a couple of things I don't understand wrt lists

Dave Angel davea at davea.name
Thu Apr 18 09:23:22 EDT 2013


On 04/18/2013 09:01 AM, aaB wrote:
> Hello,
>
> I am still in the process of writing preliminary code for my CA project.
> I am now running into a behavior that I can't explain.
>
> Here is a script which, at least on my system, shows the issue (python2.7 on a
> linux system).
> The final project will be wrapping these functions (and others) into a class
> which will be in a module which can be imported into a script.
>
> #!/usr/bin/python2
>
> import sys
> import random
>
> def get_rule(rulenum):
>    bitpattern = bin(rulenum)[2:]
>    return [0]*(8-len(bitpattern)) + [int(bit) for bit in bitpattern]
>
> def populate(n):
>    random.seed()
>    return [random.randint(0,1) for i in range(n)]
>
> def get_index(thisgen, i):
>    n = len(thisgen)-1
>    cell = thisgen[i]
>    if i is 0:
>      print "i==0"
>      prev, next = thisgen[n], thisgen[i+1]
>    elif i is n:

Don't use 'is' here and above.  You're not looking for a matching 
object, you're looking for the same value.

>      print "i==%d" % n
>      prev, next = thisgen[i-1], thisgen[0]
>    else:
>      prev, next = thisgen[i-1], thisgen[i+1]
>    return prev*4 + cell*2 + next
>
> def get_nextgen(thisgen, rule):
>    return [rule[get_index(thisgen, i)] for i in range(len(thisgen))]
>
>
> if len(sys.argv) == 2:
>    n = int(sys.argv[1])
> else:
>    n = 257
>
> rule = get_rule(145)
> thisgen = populate(n)
> nextgen = get_nextgen(thisgen, rule)
> print "done for n == 257"
>
> n = 258
> thisgen = populate(n)
> nextgen = get_nextgen(thisgen, rule)
>
>
> My issue is that when n == 257, the script runs as expected, but if n >= 258, I
> get an "IndexError: list index out of range".

No, you get an exception traceback.  Please paste in the whole traceback 
instead of making everyone guess where in the code it might be getting 
the exception.

My *guess* is that somewhere you're assuming that 8 bits is enough to 
encode 258 possibilities.  I'd have expected that to fail at 256 and 
larger, but it's a place to look.

The second guess, more likely, is that you're using "is" to compare 
numbers, and that's never a safe idea.  It might happen to work for 
small numbers, but you should be using ==.

    if i == 0:
    elf i == n:


> The script is also attached to the email

Attachments aren't necessarily visible to everyone reading the mailing 
list.  Just make sure you post in text mode (which you did), and that 
should take care of spurious indentation bugs.



-- 
DaveA



More information about the Python-list mailing list