[Tutor] Need help understanding output...
Emile van Sebille
emile at fenx.com
Thu Aug 12 00:02:15 CEST 2010
On 8/11/2010 2:04 PM Laurens Vets said...
> 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]:
You're testing here if nummer is niet gelijk van _both_ vorige twee
nummers, maar je wil testen als het niet gelijk is van _either_ nummer:
if nummer != reeks[-1] _or_ nummer != reeks[-2]:
For then it is true that
nummer == reeks[-1] and nummer == reeks[-2]
You should review/create or/and truth tables to determine the validity
of your logical tests. Also, particularly when starting, it is known
that negatives often lead to confusion, with use of multiple negatives
leading to even more confusion. Next time, try eliminating the
negatives and look for a positive test when you have this kind of issue.
Then you might have written:
if nummer == reeks[-1] and nummer == reeks[-2]:
print "it's the same as the prior two"
else:
reeks.append(nummer)
HTH,
Emile
> 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...
>
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list