Ah, yes, I couldn’t see the instructions and my memory of the lesson involved returning something different if the sums were the same. I’ll take the post down.
In fact, if there is a mistake in that ‘else’ block, our function will not fail if not tested thoroughly.
return lst1
else:
return lst997 # this list is not defined, but the function didn't complain when run our test example
#Uncomment the line below when your function is done
print(larger_sum([1, 9, 5], [2, 3, 7]))
Output:
[1, 9, 5]
My solution is recursive: I had stuck trying to mimic sum() for an unknown me reason:
def larger_sum(lst1, lst2):
def additionx(lst1): # defining a helper function of my custom sum()
while len(lst1) > 0: #set the rule of allowed run
first_element = next(iter(lst1)) #a trick to find 1st element of the list, for..in works too
if len(lst1) == 1: # set the exit of recursion
return lst1[0]
return first_element + additionx(lst1[1:]) #recurse
if additionx(lst1) >= additionx(lst2): #compare by call of a custom sum()
return lst1
return lst2 #no need of else, due to only one other way out
Wow! That is a mountain of code. I hope you were trying to emulate the C program for the sum() function. It’s extreme for Python, to say the least. What, if I may ask is the lesson in that much code?
Well, d’uh? Recursion, of course. Use case analysis would be a good appendix.
Right. The recursion is another relative of the for… in loops. The very distant relative who drives Bently and drinks Rooibos tea at 420p.m. So, this sophisticated ‘madam’ who could be as simple as the:
f(n) = 1 + 2 + 3 +………+ n
would look like the:
f(n) = 1 n=1 f(n) = n + f(n-1) n>1
The main difference is that the function “ f( ) ” itself is being called inside the function, so this phenomenon is named as recursion and the function containing recursion is called recursive function, at the end this is a great tool in our hand.
I was overthinking the solution haha it worked in the end but at times im trying to put everything in ive learned so far instead of keeping it simple and clean.
def larger_sum(lst1, lst2):
if sum(a for a in lst1) >= sum(b for b in lst2):
return [a for a in lst1]
else:
return [b for b in lst2]
#Uncomment the line below when your function is done
print(larger_sum([1, 9, 5], [2, 3, 7]))