On 04/16/2013 11:37 AM, aaB wrote:
hello,

I am a beginner programmer. I started learning programming about a year and a
half ago, using C. I picked up python a few months ago, but only wrote very few
scripts.

I am currently trying to learn more about the python way of doing things by
writing a script that generates png images using a 1D cellular automaton.

While writing preliminary code for that project, I ran into a behaviour that I
don't understand.
I am using python 2.7 on a linux system.

I represent the CA's rule with a list of integers, of value 1 or 0.
Here is the function I use to generate the list:

def get_rule(rulenum):
   rule = []
   while rulenum > 0:
     rule.append(rulenume % 2)
     rulenum /= 2
   while len(rule) < 8:
     rule.append(0)
   rule.reverse()
   return rule

if i call it by writing:

rule = getrule(int(8))

and then call:

print rule

the output is good:

[0, 0, 0, 0, 1, 0, 0, 0]


I then tried to print each item of the list using a for loop:


There are copy/paste errors in your following pieces. Did you retype them instead of using the clipboard?

for i in range(rule):
   print rule[i]

the output is, as expected:
0
0
0
0
1
0
0
0


Here's what I get, and how I fix it:

>>> rule = [0,0,0,0,1,0,0,0]
>>> for i in range(rule):
...     print i
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: range() integer end argument expected, got list.
>>> for i in range(len(rule)):
...     print rule[i]
...
0
0
0
0
1
0
0
0


but when I do:

for i in rule:
   print rule[i]
You should be printing i here, not rule[i]


I get the "complement":
1
1
1
1
0
1
1
1

I don't.  And don't expect to.  It's nothing like the complement.

>>> for i in rule:
...     print rule[i]
...
0
0
0
0
0
0
0
0

Anyway, to fix it, just print the value, don't try to use it as a subscript.

>>> for value in rule:
...     print value
...
0
0
0
0
1
0
0
0


There must be something I didn't understand correctly in the for statement, but
I really can't think of a reason why the output is what it is.
I tried this using the interactive console, and the results are the same,
whatever the length of the list, i always get the complement of my bit pattern.

You should never get the complement of the bit pattern with any code you've shown above.


Hope that helps.


--
DaveA
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to