Lesson 40/48 ยท ๐ฏ Problem Solving
๐ฏ Problem SolvingLesson 40/48
Phase 6 ยท Problem Solving25 min
String Problems
Reversal, anagrams, character counting, patterns you'll see everywhere
Strings are the most common data type in real-world programming. Log files, API responses, user input, config values, all strings. These 4 patterns cover 80% of string problems.
Pattern 1: Reversal
s[::-1], that's it. Python's slice with step -1 reverses any sequence.String reversalpython
s = "Hello, World!"
print(s[::-1]) # !dlroW ,olleH
# Check palindrome
def is_palindrome(s):
s = s.lower().replace(" ", "") # normalize
return s == s[::-1]
print(is_palindrome("racecar")) # True
print(is_palindrome("A man a plan a canal Panama")) # TruePattern 2: Anagram checkTwo words are anagrams if they have the same characters in different order. Sort both and compare.
Anagram checkpython
def is_anagram(s1, s2):
return sorted(s1.lower()) == sorted(s2.lower())
print(is_anagram("listen", "silent")) # True
print(is_anagram("hello", "world")) # FalsePattern 3: Character countingUse a dictionary or
collections.Counter.Character frequencypython
def char_count(s):
counts = {}
for ch in s:
counts[ch] = counts.get(ch, 0) + 1
return counts
print(char_count("hello")) # {'h': 1, 'e': 1, 'l': 2, 'o': 1}
# Most common character
s = "programming"
counts = char_count(s)
most_common = max(counts, key=counts.get)
print(f"Most common: '{most_common}' ({counts[most_common]}x)")How would you approach this? Think first, then expand.
Practice Exercises
0/4 solvedExercise 1 of 4easy
โฑ 00:00Reverse Words
Reverse the ORDER of words in a sentence (not the characters).
Given: sentence = "Hello World Python"Expected output:
Given: sentence = "Hello World Python"Expected output:
Python World Hellosolution.py
1 / 4
Exercise 2 of 4easy
โฑ 00:00Find All Vowels
Count how many vowels (a,e,i,o,u) are in the string.
Given: text = "Python Programming"Expected output:
Given: text = "Python Programming"Expected output:
Vowels: 5solution.py
2 / 4
Exercise 3 of 4medium
โฑ 00:00First Non-Repeated Character
Find the first character that appears only once.
Given: s = "swiss"Expected output:
(s appears twice, so skip it. w appears once, that's the answer)
Given: s = "swiss"Expected output:
First unique: w(s appears twice, so skip it. w appears once, that's the answer)
solution.py
3 / 4
Exercise 4 of 4hard
โฑ 00:00Compress a String
Compress consecutive repeated characters into char+count format.
Given: s = "aabbbccdddd"Expected output:
Given: s = "aabbbccdddd"Expected output:
a2b3c2d4solution.py
4 / 4
Solve all 4 exercises to unlock completion