Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #43823

Re: a couple of things I don't understand wrt lists

Date 2013-04-18 15:01 +0200
From aaB <mecagonoisician@gmail.com>
Subject Re: a couple of things I don't understand wrt lists
References <20130416153701.GA18377@gmail.com> <CAPTjJmqRB0eiG9peDOU+Ow_1rqq2u=xXcUduyxUm3gAhrzMjHg@mail.gmail.com> <20130417102537.GA19967@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.766.1366290071.3114.python-list@python.org> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

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:
    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".
The script is also attached to the email in case someone would like to try it on
their machine.
The print statements in the get_index() function's branching show me that, when I
get the "out of range" error, the program doesn't enter the "elif i is n"
condition, although it does for lower values of n.
I'm sorry, but I still haven't found a way to copy/paste from the terminal to
vim.
This behaviour occurred previously and had stopped when I used an other version
of the get_index() function. At that time, get_index() wasn't a function and was
just conditional branching inside get_nextgen, I wanted to use the list
comprehension syntax to build nextgen, and this got me into seperating the
get_index() routine. 

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: a couple of things I don't understand wrt lists aaB <mecagonoisician@gmail.com> - 2013-04-18 15:01 +0200

csiph-web