Could someone explain me what is the space complexity of beyond program, and why is it?
def is_pal_per(str):
s = [i for i in str]
nums = [0] * 129
for i in s:
nums[ord(i)] += 1
count = 0
for i in nums:
if i != 0 and i / 2 == 0:
count += 1
print count
if count > 1:
return False
else:
return True
Actually, i'm interested in this lines of code. How does it influence on space complexity of above program?
s = [i for i in str]
nums = [0] * 129
I'm unclear where you're having trouble with this. s is simply a list of individual characters in str. The space consumption is len(s).
nums is a constant size, dominated by the O(N) term.
Is this code you wrote, or has this been handed to you? The programming style is highly not "Pythonic".
As for your code, start with this collapse:
count = 0
for char in str:
val = ord[char] + 1
if abs(val) == 1:
count += 1
print count
return count == 0
First, I replaced your single-letter variables (s => char; i => val). Then I cut out most of the intermediate steps, leaving in a couple to help you read the code. Finally, I used a straightforward Boolean value to return, rather than the convoluted statement of the original.
I did not use Python's counting methods -- that would shorten the function even more. By the way, do you have to print the count of unity values, or do you just need the Boolean return? If it's just the return value, you can make this even shorter.