That for loop is impressively bad. You could delete lines 3 and 4 entirely and the code would have exactly the same output, but in O(n) instead of O(n2).
Complete novice (so I’ve probably miss understood) but would it not be O(x)? The for loop would execute for x and the if statement has constant complexity.
That won't do anything as written. replace returns a new string, it doesn't modify the old string (strings in Python are immutable and cannot be modified in place). You need user_input = user_input.replace(",", "").
Thanks for the reply! I understand the notation, I’m not sure why it’s complexity is quadratic.
My understanding is that the if statement has constant complexity, I believe replace() has constant complexity and the variable assignments have constant complexity. Only the for loop is dependent on X, so the complexity is dependent on the size of X - O(n).
I believe .replace() can also be considered to have within it a for loop of length n: iterate through the string, compare to ',' and replace if matches
The language spec in Python gives way less details about how the interpreter is supposed to behave, but I assume a bit similarly.
It wouldn't really be quadratic, since it only has to do the replace once since python's replace is like js replaceAll so it can't every be run multiple times. or...I guess it could, since the initial loop won't be on the actual newly changed string will it?
user_input = input("Enter: ")
for x in user_input:
if "," in x:
x = user_input.replace(",", "")
user_input = x
a = ("['" + user_input.replace(" ", "', '") + "']")
print(a)
166
u/TinyBreadBigMouth Mar 11 '23
That
forloop is impressively bad. You could delete lines 3 and 4 entirely and the code would have exactly the same output, but in O(n) instead of O(n2).11
u/UltimatePeace05 Mar 11 '23
sl_pit()?
5
u/doubleslashTNTz Mar 11 '23
oh yeah they now have a string that prints to the repr of a list !! ?!?!
25
u/nubatpython Mar 11 '23
What's .trainpit()?
9
u/NUTTA_BUSTAH Mar 11 '23
Doesnt this just break completely? First comma found replaces entire input with empty string, during iteration of said input
5
u/popdemtech Mar 11 '23
slpitwould have taken this to 117
u/TinyBreadBigMouth Mar 11 '23
Image Transcription: Code
I'm a human volunteer content transcriber and you could be too! If you'd like more information on what we do and why we do it, click here!
3
u/thekwoka Mar 11 '23
Pretty sure this would fail on
,,1
u/Fermi-4 Mar 11 '23
Use Regex
1
u/[deleted] Mar 11 '23
been doing this for 3 years