FAQ: Code Challenge: Loops - Larger Sum

if you added all the values into a, you would get the sum in a. so what then would sum1 be?
(clearly nothing since it will not run, but as you are trying to use it, that doesn’t fully make sense)

and then if you removed sum1 you’d have next contradiction, you’d be creating a list with a list comprehension, but then not using that list in any way

syntactically, you’re using a statement in place of an expression, similar to how this is not allowed:

1 + for n in range(3): n
2 Likes

Thanks for your prompt response!

Is it possible at all to have the following code in a list comprehension?

    for x in lst1:
        sum1 += x
    for y in lst2:
        sum2 += y

isn’t that picking a solution before having figured out the problem?

what problem does list comprehension solve and do you have that problem?

you can also consider if there is something redundant about that code information-wise, what could possibly be removed and what would then remain <- this is often how you would go about finding a smaller way to express something, or alternatively measure how close to minimal something is

2 Likes

what does a list comprehension do?

it creates a list.

do you want a list?

you have a list.

is there a different list that would be better?

2 Likes

Because that is a statement, albeit in place. We do not perform actions in a comprehension; we append expressions.

1 Like

Hey all!

Just hoping for some help with logic here. My initial solution was:

def larger_sum(lst1, lst2):
big_list =
if sum(lst1) > sum(lst2):
big_list.append(lst1)
elif sum(lst2) > sum(lst1):
big_list.append(lst2)
else:
big_list.append(lst1)
return big_list

how ever this would return another set of [list brackets] around the return value, which otherwise was correct. I viewed the solution to see if I could find anything obvious that I was doing incorrectly or inefficiently. My ultimate question here is surrounding the use of the for loops in this solution block of code:

def larger_sum(lst1, lst2):
sum1 = 0
sum2 = 0
for number in lst1:
sum1 += number
for number in lst2:
sum2 += number
if sum1 >= sum2:
return lst1
else:
return lst2

is this structure less prone to data loss or replication? Simply more efficient?

def larger_sum(lst1, lst2):
  big_list = []
  if sum(lst1) > sum(lst2):
    big_list.append(lst1)    #<=  appending a list to a list [[]]
  elif sum(lst2) > sum(lst1):
    big_list.append(lst2)
  else:
    big_list.append(lst1)
  return big_list

We don’t need to define an empty list, just return one or the other list.

def larger_sum(lst1, lst2):
  if sum(lst2) > sum(lst1):
    return lst2
  return lst1

The given solution does not use any built-in functions, but likewise we can still simplify it. List 2 is either larger or not.

m = 0
n = 0
for x in lst1:
    m += x
for x in lst2
    n += x
return lst2 if n > m else lst1

Thank you for your insight!

If I may, what is meant by built-in functions in regards to the given solution?

Built-in functions are ones that come with the Standard Library, such as, sum().

We can inspect the module if we are curious…

import builtins
dir(builtins)

Many of the functions are used internally by Python, but you will recognize some of the ones near the end of the list. The first that is applicable to us in the normal sense is, abs.

From this list we can also look up their syntax and usage.

>>> help(abs)
Help on built-in function abs in module builtins:

abs(x, /)
    Return the absolute value of the argument.

>>> 

BTW, we do not need to import builtins since Python does that for us. We have direct access to the functions.

2 Likes

Brilliant!

Thank you again!

2 Likes

Hey everyone,

I was just wondering if anyone knows why my code isn’t working please?

It returns 1 instead of printing out the list and I dont really understand why

Thanks so much in advance!

def larger_sum(lst1,lst2):
  for i in lst1:
    sum_lst_1 = 0   
    sum_lst_1 += i
    return sum_lst_1
  for i in lst2:
    sum_lst_2 = 0
    sum_lst_2 += i
    return sum_lst_2
  if sum_lst_1 >= sum_lst_2:
    return lst1
  if sum_lst_2 > sum_lst_1:
    return lst2

It’s worth noting that the return statement whene executed will immediately exit the function. On that note check the order in which your statements are executed to see how that particular value may have been returned earlier than expected.

1 Like

ahhh that might be it then, instead I might try using the return statements only for the if statements at the end

1 Like

Try to understand this convoluted solution:

1 Like

First, the opening line, the declaration of the function, is formatted to include type tags. The value after the parameter names is the type of the parameter. In this case, it is list. The value after the “->” is the type that the function returns.

The description in quotes is called the docstring.
You can look up information about this function using

help(larger_sum)

and it will output whatever is inside the docstring.

If you click on

show original

you will read the line:

return [lst1, lst2][-max((sum(lst1), 0), (sum(lst2), -1))[1]]

In order to break this statement down you need to understand

  • how indexing works

  • that max picks the largest of two values and returns it. In this case max returns the largest tuple.

  • That sum() computes and returns the sum of an iterator.

  • that tuples have ranked ordering (which means that if the first index in both tuples have the same value, the next value in the tuple will be compared. Think of the later values in the tuple as being potential tie breakers.)

  • the second value in the tuples is the index for the list [lst1, lst2]

  • I had to make the 1 negative because max will always return the largest tuple and '1 is greater than 0, yet in this function I needed the first list to always be returned in the sum of the insides equaled each other, so in order to make this happen I had to make the result of max() negative to counterbalance the negative 1.

If you have any questions, please feel free to ask.

assert just raises an assertionError if the the values on both sides of the ‘==’ are not equal. It is a testing feature of python.

1 Like

Here is my code:

def larger_sum(lst1, lst2):
  if sum(lst1) < sum(lst2):
    print("lst2")
    return lst2
  else:
    print("lst1")
    return lst1
print(larger_sum([1, 9, 5], [2, 3, 7]))

Is this a bad way to do it? I’m not seeing any other solutions that did this…

It’s the author’s call, but I prefer to not print anything in a function unless that is the role that it serves… Output formatting. Otherwise only during debugging would one ever find a print statement in a function body. Return the stuff you want printed and print it at the caller.

print (larger_sum(lst1, lst2))

If we want to print AND save the result, we can package it in the return statement.

return x, f"sum({x}) = {y}"

As in,

    a, b = sum(lst1), sum(lst2)
    if b > a:
        y, x = b, lst2
    else:
        y, x = a, lst1
    return  x, f"sum({x}) = {y}"

a, b = larger_sum([1, 9, 5], [2, 3, 7])
print (b)
# sum([1, 9, 5]) = 15

At any length, plan to print at the caller as much as can be done. Only print inside a function if it is unavoidable. The speed of a function is greatly diminished by intermittent print operations which are very expensive in terms of clock ticks. Run the function, get the resulting output and then print.

print (a)
# [1, 9, 5]

Here is how I wrote the code to solve the problem. I figured out that print needed to be return. However Id like to know why, my code prints NONE… where does return got too??

According to the description it says: If the sum of the elements of each list are equal, return lst1 .
So, I think in your code in the if clause should be something like:

if x >= y

i just realized that we can put an if else loop inside the return :grinning:

opened a hole new world

can i use this for any kind of function?

def larger_sum(lst1, lst2):
  a = sum(lst1)
  b = sum(lst2)
  return lst1 if a >= b else lst2
print(larger_sum([1, 9, 5], [2, 3, 7]))