alexeyhaidamaka
alexeyhaidamaka

Reputation: 178

Generating list sequence with a custom step in Python

Okay, i'm really stuck with that one-liner.

Yet tried to accomplish my task with zip and map, but none of it worked i want. So my question is: can i generate a list with a custom step like this?

>>wicked cool code snippet
>>[101, 105, 109, 115, 121]

The idea behind this is that i have the start of a sequence X equal to 101. Then i add 4, then again adding 4. Then i add 6 to the previous result and again i add 6.

I believe it should look like this mathematically speaking:

An = A1+4d,A2+4d,A3+6d, A4+6d.

UPD

Ok, let me make it more clear.

range(101, 120, 3) <-Classical arithmetical progression

[101, 104, 107, 110, 113, 116, 119] < - The output

What i need is a combination of two of them. Like add +4 to each element n-times, then add +6 to the last element of add 4 sequence n-times.

Hope, it's clearer now.

Upvotes: 1

Views: 585

Answers (3)

Dmytro Sirenko
Dmytro Sirenko

Reputation: 5083

This works for me:

>>> reduce(lambda acc, i: acc + [acc[-1] + i], [4,4,6,6], [101])
[101, 105, 109, 115, 121]

Unfortunately, it is not exactly what you've asked for and I am afraid it just can't be done with map and zip alone, because these operations do not involve any kind of accumulator.

Upvotes: 1

Alex Reynolds
Alex Reynolds

Reputation: 96927

Not sure if this is a wicked cool code snippet, but it returns your answer with one line of code:

 >>> map(lambda x: x+100 if x == 1 else (x+103 if x == 2 else (x+106 if x == 3 else (x+111 if x == 4 else x+116))), range(1,6))
 [101, 105, 109, 115, 121]

Upvotes: 1

Fredrik Pihl
Fredrik Pihl

Reputation: 45634

A bit hardcoded:

In [42]: step=[0,3,6,11,16]

In [43]: [i+step[n] for n, i in enumerate(range(101, 106))]
Out[43]: [101, 105, 109, 115, 121]

Upvotes: 2

Related Questions