Say I had the following function:
def findNumVowels(s):
vowels = ['a', 'e', 'i', 'o', 'u']
numVowels = 0
for char in s:
if char in vowels:
numVowels += 1
return numVowels
print(findNumVowels("hello world")) # 3
Would the for ... in
loop add to the space complexity of this function by creating a new string for each char
in s
, or is this syntactic sugar that abstracts away the fact that we are accessing a specific index of a string?
No, the loop by itself does not. Consider:
for char in some_string:
print(char)
It only requires one extra object of constant size. This is constant with respect to the size of the string. So, it doesn't matter if my string is 10 or 1000 characters long, it always requires one extra str
to loop over it. Therefore, it takes constant space.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With