Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiplying in a list python

Tags:

python

list

I am doing some homework and I am stuck. I supposed to write a code in Python 3, that reads a text file that is like a bill with an amount of numbers. I am supposed to write the code so it will calculate the total amount.

I figured that a bill(simple example) will contain a number and the a prise. like:

2 10$
1 10 $
and so on

So I figured that I create a list with all numbers in it and then I want to multiply the first with the second element in the list and then jump in the list so the tird and the fourth element get multiply and so on, until there is no more numbers in my list. During this happens I want the sums of every multiplication in a new list called sums there they later will be summed.

my code looks like this so far:

file = open('bill.txt')
s = file.read()
file.close()



numbers = []
garbage = []

for x in s.split():
    try:
        numbers.append(float(x))
    except ValueEror:
        garbage.append()
print(numbers)


for n in numbers:
    sums = []
    start = 0
    nxt = start + 1
    t = numbers[start]*numbers[nxt]    
    if n <= len(numbers):
        start += 2
        nxt += 2
        summor.append(t)
    if n == len(numbers):
        print(sum(sums))
like image 732
mix Avatar asked Dec 08 '22 11:12

mix


1 Answers

The problem in your code is likely that you keep resetting sums for every number in the list. So you basically keep forgetting the sums you previously collected. The same applies to start and nxt. If you move these definition outside of the loop, and also fix the summor.append(t) to sums.append(t) it should almost work. Also note that the loop variable n does not iterate over indexes of numbers but over the actual items (i.e. the numbers). So the check at the end n == len(numbers) is unlikely to do what you expect. Instead, you can just put the print after the loop because you know that when you reached that point the loop is over and all numbers have been looked at.


A common idiom is to use zip to combine two elements with each other. Usually, you use zip on two different iterators or sequences, but you can also use zip on the same iterator for a single list:

>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> it = iter(numbers)
>>> for a, b in zip(it, it):
        print(a, b)

1 2
3 4
5 6
7 8

As you can see, this will group the numbers automatically while iterating through the list. So now you just need to collect those sums:

>>> sums = []
>>> it = iter(numbers)
>>> for a, b in zip(it, it):
        sums.append(a * b)

>>> sum(sums)
100

And finally, you can shorten that a bit more using generator expressions:

>>> it = iter(numbers)
>>> sum(a * b for a, b in zip(it, it))
100
like image 172
poke Avatar answered Dec 27 '22 19:12

poke