r/shittyprogramming • u/life_goes_on_23 • Aug 21 '22
Please tell me the complexity of this code
Hi Guys,
def EN(numbers):
for ind in range(len(numbers)):
if numbers[ind] > 10:
return ""
if len(numbers) == 2:
ans = str(numbers[0]) + str(numbers[1])
return ans
ans_lst = []
while len(ans_lst) != 2:
ans_lst = []
for i in range(len(numbers) - 1):
lst_two = (numbers[i] + numbers[i + 1]) % 10
ans_lst.append(lst_two)
numbers = ans_lst
if len(ans_lst) == 2:
ans = str(ans_lst[0]) + str(ans_lst[1])
return ans
Can anyone please tell me the complexity of this code?
0
Upvotes
32
u/souldeux Aug 21 '22
3
11
u/xecow50389 Aug 21 '22
O(n)
1st loop : O(n)
2nd loop while inside it : 2 x O(n) = O(n)
Total : O(n) + O(n) = O(n)
1
u/Wat5ups Aug 21 '22
Let n = len(numbers) and focus on the while loop :
At step k of the loop, we have len(ans_lst) = n-k
We then iterate over ans_lst to do a simple addition and append to a list which are both O(1) in python.
We stop when len(ans_lst) = 2
Therefore the complexity is O( (n - 1) + (n - 2) + ... + 2 + 1) = O(n2)
3
u/BBQGiraffe_ Aug 21 '22
4
1
u/xecow50389 Aug 21 '22
O(n) ^ Infinite
1st loop : O(n)
2nd loop [while] : it got a ans_list condition. But it breaking point is in another forloop.
Consider, breaking surpasses length 2 then while goes in Infinite loops.
For the inner loop, its O(n)
Total : O(n) + O(n)Infinite = O(n)Infinite = Infinite = memory crashes.
1
u/nuc540 Aug 21 '22
I think it’s just N, because the complexity of every loop is only the size of each array, regardless of how big you’re making N or how often you iterate. (That just changes N, but not your complexity)
I don’t see any nested loops or methods that don’t work at N complexity.
I might be wrong!
0
u/xecow50389 Aug 21 '22
O(n)
Sorry I am on mobile and missed some conditions gave wrong answers before.
This is the final one.
1st loop : O(n)
2nd loop : while loops and numbers changes and it will be fixed.
Total : O(n)