Counting Characters in a String
Need to know: Dictionary
, for loopÂ
def count_characters(string):
counts = {}
for char in string:
if char in counts:
counts[char] = counts[char] + 1
else:
counts[char] = 1
return counts
# Example usage:
input_string = "hello world"
result = count_characters(input_string)
print("Character counts:")
for char, count in result.items():
print(f"'{char}': {count}")
If you need to keep a counter of characters, a common mistake is to say that the space complexity required for the counter is O(n). The space required for a counter of a string of latin characters is O(1) not O(n). This is because the upper bound is the range of characters, which is usually a fixed constant of 26. The input set is just lowercase Latin characters.
No Comments