ale
ale

Reputation: 11820

Generating a simple mathematical sequence in Python

I'm new to Python and coming from a PHP background.. I'm impressed. Is there a way of getting a list of numbers from this sequence:

i^2, i^2 + i, i^2 + 2i, ..., n

i.e. if i=2 and n=30:

4, 6, 8, ..., 30

Okay, this is a really simple sequence but is what's a more general way to do this sort of thing functionally?

Maybe there's some nice functional programming way of doing this? In PHP I think I would make some function some variables and interaction but Python might be able to do it more elegantly?

Many thanks.

Upvotes: 0

Views: 115

Answers (2)

zmbq
zmbq

Reputation: 39013

Python has a cool feature called List Comprehension. You can use it to do something like this:

[i*i+2*n for n in range(30) if (i*i+2*n)<=30]

Upvotes: 0

unutbu
unutbu

Reputation: 879621

You can do this with range:

In [186]: i = 2; n = 30; range(i**2, n+1, i)
Out[186]: [4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30]

Upvotes: 6

Related Questions