[Tutor] Need help understanding output...

Steven D'Aprano steve at pearwood.info
Thu Aug 12 01:26:48 CEST 2010


On Thu, 12 Aug 2010 07:04:15 am Laurens Vets wrote:

> 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 :)):

I can't possible do that! :)


> 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

This is probably a simpler way:


import random
reeks = []
for i in range(30):
    temp = [random.randint(1, 6)]
    while reeks[-2:-1] == reeks[-1:] == temp:
        # print "Triplet found:", reeks, temp
        temp = [random.randint(1, 6)]
    reeks.extend(temp)

print reeks

Note that you can avoid dealing with IndexError by extracting slices and 
comparing lists.


> However, I wanted to look deeper in the above script and I created
> the following:
[...]
>    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...

nummer != reeks[-1] and nummer != reeks[-2]

gives a true result if all three numbers are different, otherwise it 
gives a false result.

Negative conditions are often hard to reason with. It might be better to 
write that as:

nummer == reeks[-1] and nummer == reeks[-2]

and swap the if/else clauses. But even better is to use Python's chained 
comparisons, and write:

nummer == reeks[-1] == reeks[-2]




-- 
Steven D'Aprano


More information about the Tutor mailing list