I have a function that sums the elements of a nested list.
data = [1, 2, [3, 4], [5, 6]]
#Big O for this is O(N)?
def sum_list_recursive(data):
if len(data) == 0:
return 0
current_number = 0
if isinstance(data[0], list):
current_number = sum_list_recursive(data[0])
else:
current_number = data[0]
data.remove(data[0])
return current_number + sum_list_recursive(data)
if __name__ == "__main__":
print("Recursive sum: ", sum_list_recursive(data))
What would be the Big O for this? I think it's O(N), because even though there's an if statement to go inside the nested list, it's still just calculating through the N
elements. Also, what would be the Big Theta and Big Omega. Are they also just Theta(N) and Omega(N), because you can just multiply N by K?
答案 0 :(得分:1)
You're right as far as your argument goes. However, look at what happens with arbitrary list nesting. How many calls do you make if the input is as below?
data = [[[[[1]], [[[[2]]]]], [3, [[[4]]]], [[[5, 6]]]]]
It's still linear, but I believe it's linear on N+P, where N is the quantity of numbers to add, and P is the quantity of lists (left brackets, for example).