avoid_frustration
avoid_frustration

Reputation: 85

How to sum the selected elements from an array in python? (Multiple Inputs)

Here's the code:

PRICE = [1000, 1100, 1200, 1300, 1400, 1500]
x = raw_input() 

for i, v in enumerate(PRICE):

print total price

For example the user inputs "1 3 2 2" So the x is the multiple inputs I get from the user. How do I sum them up? With the answer should be 1100 + 1300 + 1200 + 1200 = 4800 I want to create a code that even if I change the inputs I will still be able to sum them up. Like if I change x to 2 2 2 1 it would sum for me to 4700.

Upvotes: 1

Views: 4408

Answers (2)

TessellatingHeckler
TessellatingHeckler

Reputation: 29048

PRICE = [1000, 1100, 1200, 1300, 1400, 1500]
x = raw_input() 

for i, v in enumerate(PRICE):

print total price

Hmm, I'm stuck, I can't answer it, but can I do anything at all?

maybe I can just print some stuff to give me more ideas.

PRICE = [1000, 1100, 1200, 1300, 1400, 1500]
x = raw_input() 
print x

for i, v in enumerate(PRICE):
    print i, v

>>>
you said 2
0 1000
1 1100
2 1200
3 1300
4 1400
5 1500

So i counts from 0 to 5, v is the prices, and they said 2. Now what?

Maybe I can just add them all up for now? v is the price, so I'll just add them all up...

PRICE = [1000, 1100, 1200, 1300, 1400, 1500]

x = raw_input() 
print "you said", x

for i, v in enumerate(PRICE):
    v = v + v

print v

>>> 
you said 3
3000

3000? What's 3000? Oh, it's coming from the last one, 1500 + 1500. So I can't use v like that.

Well I know about lists, what about if I do this...

PRICE = [1000, 1100, 1200, 1300, 1400, 1500]
TOTAL = []

x = raw_input() 
print "you said", x

for i, v in enumerate(PRICE):
    TOTAL = TOTAL + v

print TOTAL

>>>
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list

No, that's an error. Uhhh...

PRICE = [1000, 1100, 1200, 1300, 1400, 1500]
TOTAL = []

x = raw_input() 
print "you said", x

for i, v in enumerate(PRICE):
    TOTAL = TOTAL + [v]

print TOTAL

>>>
you said 2
[1000, 1100, 1200, 1300, 1400, 1500]

That's not added anything up, that's just copied it! What a waste of time!

Hmm. Now what. I dunno, maybe I'll just print everything I have and see what's happening:

PRICE = [1000, 1100, 1200, 1300, 1400, 1500]
TOTAL = []

x = raw_input() 
print "you said", x

for i, v in enumerate(PRICE):
    TOTAL = TOTAL + [v]
    print "x:", x, "i:", i, "v:", v, "TOTAL: ", TOTAL


print TOTAL

>>> 
you said 2
x: 2 i: 0 v: 1000 TOTAL:  [1000]
x: 2 i: 1 v: 1100 TOTAL:  [1000, 1100]
x: 2 i: 2 v: 1200 TOTAL:  [1000, 1100, 1200]
x: 2 i: 3 v: 1300 TOTAL:  [1000, 1100, 1200, 1300]
x: 2 i: 4 v: 1400 TOTAL:  [1000, 1100, 1200, 1300, 1400]
x: 2 i: 5 v: 1500 TOTAL:  [1000, 1100, 1200, 1300, 1400, 1500]
[1000, 1100, 1200, 1300, 1400, 1500]

Look at that, at some point x is 2 and i is 2. That's what they typed in matching what I'm looking at. I want that.

PRICE = [1000, 1100, 1200, 1300, 1400, 1500]
TOTAL = []

x = raw_input() 
print "you said", x

for i, v in enumerate(PRICE):
    if x == i:
        TOTAL = TOTAL + [v]

print TOTAL

>>> 
you said 2
[]

What? I just saw them equal and it didn't work. That's ridiculous I hate it.

>>> i = 1
>>> print i
1
>>> x = raw_input()
>>> print x
2
>>> raw_input() == 2
False

>>> help(raw_input)
Help on built-in function raw_input in module __builtin__:

raw_input(...)
    raw_input([prompt]) -> string

    Read a string from standard input.  The trailing newline...

Oh that reminds me, I've heard of strings.

>>> x = raw_input()
>>> help(x)
no Python documentation found for '2'
>>> help(i)
Help on int object:
...

... hmm Googles raw_input, int object, python, compare, reads

>>> raw_input() == str(i)
True

Yes!

Now where was I?

PRICE = [1000, 1100, 1200, 1300, 1400, 1500]
TOTAL = []

x = raw_input() 
print "you said", x

for i, v in enumerate(PRICE):
    if x == str(i):
        TOTAL = TOTAL + [v]

print TOTAL

>>>
you said 2
[1200]

This is the coolest thing ever.

*Googles 'python add list', finds sum a list of numbers in Python sees sum()

>>> sum(PRICE)
7500
>>> sum(TOTAL)
1200

Oh but I don't want to use sum, I want to add them up in the loop.

But at least now I've got something the user selected.

What else can I do? I'm stuck.

*thinks

I found str() a moment ago. What about

>>> help(str)
[gibberish]

I don't know what any of this stuff means :(

Hey waitaminute

>>> help(str)
Help on class str in module __builtin__:

class str(basestring)
 |  str(object='') -> string
 |
 |  Return a nice string representation of the object.
 |  If the argument is a string, the return value is the same object.
 |
 |  __eq__(...)
 |      x.__eq__(y) <==> x==y
 |

I just used == and now this is full of ==.

|  count(...)
|      S.count(sub[, start[, end]]) -> int
|
|      Return the number of non-overlapping occurrences of substring sub in
|      string S[start:end].  Optional arguments start and end are interpreted
|      as in slice notation.

Hey what's count() doing inside str? I want to count things! Return the number of non-overlapping yawn skip.

|  find(...)
|      S.find(sub [,start [,end]]) -> int
|
|      Return the lowest index in S where substring sub is found,
|      such that sub is contained within S[start:end].  Optional
|      arguments start and end are interpreted as in slice notation.
|

find, that's a word I recognise, and I just saw int earlier. Why? Oh right, help(i) said something about int.

str find something something an int? Return the lowest index in S where substring is found.

and .. and I had to str(i) before I could compare it with x

what if I

>>> x = raw_input()
>>> print x
2
>>> x.find
<built-in method find of str object at 0x0000000001E680A8>

googles built-in method

Glances at the results

Sees "If x is not a Python int object, it has to define an index() method"

Doesn't read it, just notices the ()

>>> x.find()
{error}
>>> x.find(2)
{error}
>>> x.find(str(2))
0

I hate this it sucks.

etc.

Hours later.

PRICE = [1000, 1100, 1200, 1300, 1400, 1500]
TOTAL = []

x = raw_input() 
print "you said", x

for i, v in enumerate(PRICE):
    if x.find(str(i)) > -1:
        TOTAL = TOTAL + [v]

print TOTAL

>>>
you said 23
[1200, 1300]

OH MY WORD I FOUND THE THINGS THE USER ENTERED MORE THAN ONE OF THEM!

*hours later

PRICE = [1000, 1100, 1200, 1300, 1400, 1500]
TOTAL = []

x = raw_input() 
print "you said", x

for i, v in enumerate(PRICE):
    if x.find(str(i)) > -1:
        TOTAL = TOTAL + [v]

print TOTAL

add_total = 0
for i, v in enumerate(TOTAL):
    add_total = int(add_total) + int(v)

print "Total is:", str(add_total)

>>> 
you said 14
[1100, 1400]
Total is: 2500

!!!!!!!!!!!!!!!!

This is what really happens behind all the "try this: {neat solution} :)" that goes on.

The people who know the answer, know it because they've gone through a lot of this kind of stuff. (or maybe that's just me? D:). And doing that a lot leads to a lot of familiarity and half remembered things you saw somewhere else, and "that won't work, I've tried it before, and here's why..." moments.

Don't avoid_frustration, go right for it. Learn to love it.

Upvotes: 1

skamsie
skamsie

Reputation: 2726

You can turn the user input into indexes like this:

print sum(PRICE[int(a)] for a in x.split())

But it will only work if the raw_input has the format you said: integers split by whitespace and of course it's prone to IndexError: list index out of range if values greater than the list length are provided.

EDIT: removed intermediary list creation as martineau suggested in the comments

Upvotes: 7

Related Questions