Quote:
Originally Posted by mv2devnull
Surely Python has a loop syntax that steps an integer i from 0 to n.
|
Yes, it does, but not so directly as some languages: you even said it and didn't know it.
It's, "one those things," with Python. 'For' iterates, so to step through a range of integers, you use an iterator that generates those integers, in order.
If the language is going to be slow, it should be able to do fancy stuff, to make that worthwhile.
Code:
# Python 2:
# range returns a list. Big lists can cause problems.
# xrange returns an iterator, so won't chew up so much RAM.
for i in xrange( 0, n+1 ):
...
# Python 3:
for i in range( 0, n+1 ):
...
# If stuck in Python 3, and needing to generate a list...
# because no matter how many times others say you
# shouldn't do it that way, sometimes it's the best
# way to make what you need with very little code:
my_list = list( range( begin, end[, step ]) )
However, for the OP's problem, the right way to do it is to iterate over an actual list, as given in the problem description.
Quote:
Originally Posted by lemonhead71
My problem is i don't know exactly how to sum up the values that has to be summed up. I know I should use a for loop for this but I'm not sure how to get the for loop to iterate in such a way that: list_number[0][0]*list_number[0][1]+list_number[1][0]*list_number[1][1]....list_number[n][0]*list_number[n][1], where n is an integer.
|
Use an over variable and an under variable. Update them each iteration through the loop. After the loop, divide for the result.