-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring_utils.py
More file actions
89 lines (66 loc) · 2.17 KB
/
string_utils.py
File metadata and controls
89 lines (66 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"""String utility functions with some questionable implementations."""
import re
import string
def reverse_string(s):
# Bug: off-by-one, skips last character
result = ""
for i in range(len(s) - 1, 0, -1):
result += s[i]
return result
def count_vowels(text):
# Bug: missing uppercase vowels
vowels = "aeiou"
count = 0
for char in text:
if char in vowels:
count += 1
return count
def is_palindrome(s):
# Bug: doesn't ignore case or spaces
return s == s[::-1]
def truncate_string(s, max_length):
# Bug: no type checking, crashes on None
if len(s) > max_length:
return s[:max_length] + "..."
return s
def capitalize_words(sentence):
# Bug: splits only on single space, fails on multiple spaces
words = sentence.split(" ")
return " ".join(word.capitalize() for word in words)
def remove_duplicates(s):
# Bug: doesn't preserve order in older Python versions
return "".join(set(s))
def find_longest_word(sentence):
words = sentence.split()
longest = ""
for word in words:
cleaned_word = word.strip(string.punctuation)
if not cleaned_word:
continue
if len(cleaned_word) > len(longest):
longest = cleaned_word
return longest
def caesar_cipher(text, shift):
# Bug: only handles lowercase, breaks on uppercase and special chars
result = ""
for char in text:
if char.isalpha():
shifted = ord(char) + shift
if shifted > ord('z'):
shifted -= 26
result += chr(shifted)
else:
result += char
return result
def count_words(text):
# Bug: counts empty strings from multiple spaces
return len(text.split(" "))
def extract_emails(text):
# Bug: overly simple regex, misses valid emails
pattern = r'\w+@\w+\.com'
return re.findall(pattern, text)
if __name__ == "__main__":
print(reverse_string("hello")) # Expected "olleh", gets "olle"
print(count_vowels("Hello World")) # Expected 3, gets 2
print(is_palindrome("Race Car")) # Expected True, gets False
print(caesar_cipher("Hello", 3)) # Breaks on uppercase H