0

Can't think of a fitting title for my question.

So anyway, I've been looking for an algorithm to find out if a list is balanced or not and I've came across this question: Algorithm for finding if an array is balanced

One of the answers is spot-on to what I need to accomplish. I would however, like to understand what happens if I change line 2 from the below code.

def balanced(numbers):
    left_total, right_total = 0, sum(numbers)
    for pivot, value in enumerate(numbers):
       if left_total == right_total:
        return pivot
    left_total += value
    right_total -= value
    return None

I would like to know why it throws a TypeError: 'int' object is not iterable if I do this to line 2:

left_total = 0
right_total = 0
sum(numbers)

Hope someone can help me understand. Thanks!

BlueHam
  • 37
  • 4
  • 1
    `right_total` is being assigned with the value of `sum(numbers)`. Not 0 – byxor Oct 10 '17 at 11:05
  • Those three lines *won't* throw that error. They also don't do the same thing as the one they're replacing. – jonrsharpe Oct 10 '17 at 11:05
  • and numbers is a list , that's what the error is saying – Israel-abebe Oct 10 '17 at 11:06
  • 1
    `left_total, right_total = 0, sum(numbers)` will assign `left_total` -> 0 and `right_total` -> sum(numbers) – bhansa Oct 10 '17 at 11:08
  • I wasn't actually asking about the TypeError but rather the way the variables were declared. My assumption was: `left_total, right_total = 0, sum(numbers)` Is equivalent to: `left_total = 0 right_total = 0 sum(numbers)` – BlueHam Oct 10 '17 at 11:16

1 Answers1

3

The "numbers" variable you're passing in is an int.

You can't do sum(1) for example but you can do sum([1,2]) or sum((1,2))

The variable you pass to balanced must be an iterable type. AKA a list, a tuple, a set, etc.

Unrelated to your error:

You should not be doing

left_total = 0
right_total = 0
sum(numbers)

but rather

left_total = 0
right_total = sum(numbers)

If you want to mimic what the function was doing.

For more on the left_total, right_total issue see: Is there a standardized method to swap two variables in Python?

https://docs.python.org/3/reference/expressions.html#evaluation-order

FredMan
  • 861
  • 7
  • 19