简体   繁体   中英

Space complexity of list creation

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

You have found the only two lines that allocate memory:

s = [i for i in str]
nums = [0] * 129

The first grows linearly with len(str) , the second is a constant. Therefore, the space complexity of your function is O(N), N=length of str .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM