def append_combine(w, b):
for i in range (len(w)):
a.join (w)
a.append(w)
x = []
print(append_combine(x, 2))
I'm trying to work this one to return the example test case below. It's returning none. I can't even append the first integer to the list. Help me.
x = []
append_combine(x, 2) # [2]
append_combine(x, 3) # -> [2, 3]
append_combine(x, 3) # -> [2, 3, 3] -> [2, 6]
append_combine(x, 3) # -> [2, 6, 3]
append_combine(x, 3) # -> [2, 6, 3, 3] -> [2, 6, 6] -> [2, 12]
append_combine(x, 4) # -> [2, 12, 4]
append_combine(x, 3) # -> [2, 12, 4, 3]
append_combine(x, 5) # -> [2, 12, 4, 3, 5]
append_combine(x, 5) # -> [2, 12, 4, 3, 5, 5] -> [2, 12, 4, 3, 10]
# Final value of x is [2, 12, 4, 3, 10]
CodePudding user response:
You function had few errors. Correct code will be:
def append_combine(listname, element):
if len(listname) == 0 or listname[-1] != element: # This checks If the
# list is empty or last
# element is not same
listname.append(element)
else:
listname[-1] = 2*element # This is unnecessary with the loop so you can
# remove it
# This loop checks all duplicates
while len(listname)>1 and listname[-1] == listname[-2]:
listname.pop()
listname[-1] = listname[-1] * 2
return listname
x = []
x = append_combine(x, 2) # [2] Since the Function is returning a list,
# you need to assign it to the list x
x = append_combine(x, 3) # -> [2, 3]
x = append_combine(x, 3) # -> [2, 3, 3] -> [2, 6]
x = append_combine(x, 3) # -> [2, 6, 3]
x = append_combine(x, 3) # -> [2, 6, 3, 3] -> [2, 6, 6] -> [2, 12]
x = append_combine(x, 4) # -> [2, 12, 4]
x = append_combine(x, 3) # -> [2, 12, 4, 3]
x = append_combine(x, 5) # -> [2, 12, 4, 3, 5]
x = append_combine(x, 5) # -> [2, 12, 4, 3, 5, 5] -> [2, 12, 4, 3, 10]
# Final value of x is [2, 12, 4, 3, 10]
print(x)