![]() |
|
|
|
Thread Tools | Display Modes |
|
|
|
|
#1 |
|
The Supreme Ruler
![]() Join Date: May 2004
Location: Houston
Posts: 1,476
Rep Power: 6
![]() |
Nested Lists
I decided to learn Python finally. I decided to play around and give myself a challenge to create a spiral, since it would get me used to working with lists and the basic concepts of python. I'm using the Quick Python Book, which says you can use nested lists to create a matrix, which is wha I tried. I wanted to create a 2-dimensional list which is initialized to 1. I tried to do:
m = [[1]*square]*square] This worked in creating the nested list, but was ineffective since it seems that each of the nested lists were simply a reference to the same list. I got around it, and did get my spiral function working, but I was wondering if there's a more effective way to initialize seperate lists to 1 value than what I did it. I'm sure the book will show me eventually, I'm just not too far in it yet. Here's what I had. >>> def spiral(square): m = [] i = 0 while i < square: m.append([]) i = i + 1 del i i = 0 while i<square: j = 0 while j<square: m[i].append(1) j = j+1 i = i+1 del j del i r = 0 c = 0 d = 1 value = square * square while value > 1: m[r][c] = value if d == 1: if c == square-1 or m[r][c+1] !=1: d = d + 1 continue else: c = c + 1 value = value - 1 elif d == 2: if r == square-1 or m[r+1][c] !=1: d = d + 1 continue else: r = r + 1 value = value - 1 elif d == 3: if c == 0 or m[r][c-1] !=1: d = d + 1 continue else: c = c - 1 value = value - 1 elif d == 4: if r == 0 or m[r-1][c] !=1: d = 1 continue else: r = r - 1 value = value - 1 r = 0 c = 0 while r<square: while c<square: print "%3d" % (m[r][c]), c = c+1 c = 0 r = r+1 print This is how I created and initialized the list: m = [] i = 0 while i < square: m.append([]) i = i + 1 del i i = 0 while i<square: j = 0 while j<square: m[i].append(1) j = j+1 i = i+1 Thanks in advance for any help.
__________________
"Every gun that is made, every warship launched, every rocket signifies, in the final sense, a theft from those who hunger and are not fed, from those who are cold and are not clothed. The world in arms is not spending money alone. It is spending the sweat of its laborers, the genius of its scientists, the hopes of its children." - Dwight D. Eisenhower |
|
|
|
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|