[ create a new paste ] login | about

Link: http://codepad.org/70jT3DCM    [ raw code | output | fork | 1 comment ]

fulano - Python, pasted on Apr 4:
1
2
3
4
5
6
7
8
#Generating the Fibonacci sequence with only a list comprehension
for index,number in enumerate (
        [(x < 2 and [[0, 1][x]] #This 'seeds' the first 2 numbers with 0, 1 
            or [locals()['_[1]'][-2] + locals()['_[1]'][-1]] #Undocumented method of gaining access to the list that is currently being built
        )[0]
        for x in range (20)]
        ):
    print "%2d: %5d" % (index, number)


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 0:     0
 1:     1
 2:     1
 3:     2
 4:     3
 5:     5
 6:     8
 7:    13
 8:    21
 9:    34
10:    55
11:    89
12:   144
13:   233
14:   377
15:   610
16:   987
17:  1597
18:  2584
19:  4181


Create a new paste based on this one


Comments:
posted by fulano on Apr 5
Thanks to Chris Perkins at code.activestate.com for the locals()['_[1]'] trick.

http://code.activestate.com/recipes/204297-the-secret-name-of-list-comprehensions/
reply