0

So I am the rankest of novices trying to work through the Python courses on Codeacademy. The final problem in the section on lists and dictionaries (http://www.codecademy.com/courses/python-beginner-en-IZ9Ra/1#!/exercises/3) asks you print the total value of a stock of different items at different prices, defined like this:

prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}

stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}

I had a lot of trouble thinking about how to carry over the results from one iteration of a for loop to the next, or to outside the loop, so I could sum them. I spent some time looking this up, and couldn't find good answers, which makes me think that I'm thinking about it incorrectly. But in any case I did discover the sum() function, and so I wrote the following and got the correct answer:

values = []

for items in prices:
    value = prices[items] * stock[items]
    values.append(value)

print sum(values)

The problem is that Codeacademy hasn't taught me sum() yet, so it seems like I'm missing a pretty obvious way to do this without it. Without it I could get a list of the separate values for the 4 different items, but couldn't sum them. So - can someone maybe give me a hint as to how to carry over the results from one iteration into the next? But, I think that's the wrong way to be thinking about, right? If it is, can someone give me a hint as to how I should be thinking about?

I've been stuck on the second Project Euler problem (sum the even numbers of the Fibonacci sequence up to 4 million) out of a similar confusion I think.

Thank you! (If this is a bad question to post or poorly formulated, please explain. Thank you again!)

4

2 回答 2

2
totalValue = 0

for item in prices:
     totalValue += prices[item] * stock[item]

print totalValue
于 2013-03-29T22:04:04.910 回答
2

What you have now isn't a bad solution. You could skip the list creation and just add to a sum variable:

total = 0

for item in prices:
    total += prices[item] * stock[item]

print total

Or use a generator along with sum for a one-liner:

total = sum(prices[item] * stock[item] for item in prices)
于 2013-03-29T22:07:22.540 回答