[Tutor] Need help understanding output...
Laurens Vets
laurens at daemon.be
Wed Aug 11 23:04:15 CEST 2010
Hello list,
I'm learning Python and I'm currently facing an issue with a small
script I'm writing.
I need to generate a list of 30 numbers randomly chosen from 1, 2, 3, 4,
5 & 6. However, I cannot have more than 2 numbers which are the same
next to each other. I came up with the following (Please ignore the fact
that I'm trying to avoid an IndexError in a stupid way :)):
import random
reeks = []
while len(reeks) <= 1:
number = random.randrange(1, 7, 1)
reeks.append(number)
while len(reeks) <= 29:
nummer = random.randrange(1, 7, 1)
if nummer != reeks[-1] and nummer != reeks[-2]:
reeks.append(nummer)
print reeks
So far so good (I think). From what I can see from the output, I get 30
numbers, without more than 2 being the same next to each other.
However, I wanted to look deeper in the above script and I created the
following:
import random
iteraties = 5
cijferreeks = 6
aantal_cijfers = iteraties * cijferreeks
reeks = []
while len(reeks) <= 1:
nummer = random.randrange(1, cijferreeks + 1, 1)
print 'Nummer: ', nummer
print 'Reeks: ', reeks
reeks.append(nummer)
print '\n'
while len(reeks) <= aantal_cijfers:
nummer = random.randrange(1, cijferreeks + 1, 1)
print 'Nummer: ', nummer
print 'Voorlaatste vd reeks (-2): ', reeks[-2]
print 'Laatste vd reeks (-1): ', reeks[-1]
print 'Reeks: ', reeks
if nummer != reeks[-1] and nummer != reeks[-2]:
reeks.append(nummer)
else:
print 'Nummer: ', nummer, 'is gelijk aan vorige 2 nummers: ',
reeks[-1], '&', reeks[-2], '!'
print '\n'
print reeks
When I run that, I can see there's something wrong with my if statement,
it triggers the else condition even when the 2 previous numbers in my
list are not the same... I'm not sure what is happening here...
More information about the Tutor
mailing list