tags:

views:

84

answers:

6

task: {x*y such that x belongs to S & y is iteration count } where S is some other set something like this:

j=0
[i*j for j++ and i in S]

[s1*1, s2*2, s3*3...]

+4  A: 

for your edited question, you want

[i * j for j, i in enumerate(S)]

python doesn't have ++ because it keeps a clear distinction between statements and expressions. use

[(i + 40) * i for i in xrange(60)]

another way to do this is

[i * j for i, j in enumerate(xrange(60), start=40)]

and yet another way is

[i * j for i, j in zip(xrange(40, 100), xrange(60))]

I think that the first is the best way to do it because it reduces function calls and is the most readable.

Also, if you don't know that you absolutely need a list, use a generator expression

((i + 40) * i for i in xrange(60))

This will allow you to process the results one at a time and never store a whole list in memory. You can pass a generator expression to stuff like sum, max, min and most other builtins.

aaronasterling
+1  A: 
S = range(40,100)
[i*j for i,j in enumerate(S)]
Tim Pietzcker
There is a `start` parameter for `enumerate()` so you could use `enumerate(S, start=1)` instead.
KennyTM
OP has `j` start at 0
aaronasterling
@Aaron: Right. In his first example (since deleted), he had started at 1, throwing me off there. @KennyTM: Thanks, that's much better (if so desired).
Tim Pietzcker
+1  A: 

One way to do this would be to use enumerate in conjunction with range:

[x * (count + 1) for count, x in enumerate(range(40, 100))]

Look at other answers for (a lot of) other ways to do this :) :)

Manoj Govindan
+1  A: 

I'd do it in a generator:

def fooGen(S):
    j = 1
    for i in S:
        yield i * j
        J += 1
Douglas Leeder
OP has `j` start at 0 and a generator function is overkill for what a generator expression can trivially do.
aaronasterling
A: 

"""
task: {x*y such that x belongs to S & y is iteration count } where S is some other set
[snip unfortunate introduction of i and j]
[s1*1, s2*2, s3*3...]
"""

a very simple translation:

[x * y for y, x in enumerate(S, start=1)]

or

[x * (y + 1) for y, x in enumerate(S)]
John Machin
but OP has the index starting at 0, not 1.
aaronasterling
@Aaron: What are you calling "the index", y (the iteration count)? Look at his last line: [s1*1, s2*2, s3*3...] ... I see no zero.
John Machin
A: 

you can use the current element index as an incrementor

>>> S=[2,4,6,8]
>>> [i*(S.index(i)+1) for i in S]
[2, 8, 18, 32]
>>> 

so your c-ish "j++" is S.index(i)+1

adirau
-1 this is so incredibly fugly. `index` traverses the list to find the index of `i` so you just took an O(n) operation and turned it into an O(n**2) operation! also, try `S=[2, 3, 3, 3, 4]`
aaronasterling
the question was about using list comprehensions, nor "a fast way to" or "a beautiful way to"
adirau
1) that's just a (lame) excuse for crappy code and 2) your crappy code doesn't even work.
aaronasterling
there's your O(n): [S[i]*(i+1) for i in range(0,len(S))]
adirau