[Tutor] Need help understanding output...
Dave Angel
davea at ieee.org
Wed Aug 18 16:48:53 CEST 2010
Laurens Vets wrote:
> <snip>
>
> Yes of course :) That's a typo on my part. I came up with the
> following which I think works as well?
>
> import random
> reeks = []
> for i in range(60):
> temp = [random.randint(1, 6)]
> while reeks[-2:-1] == reeks[-1:] == temp:
> temp = [random.randint(1, 6)]
> if reeks.count(temp[0]) >= 10:
> temp = [random.randint(1, 6)]
> reeks.extend(temp)
> print reeks
>
> <snip>
Without actually trying it, I think you've got a problem in the
reeks.count code.
You only check the count if you've already match temp with the last
two list items.
I'd add the reeks.count logic as a compound "or" in the test of the
while loop. And since that makes a pretty long line, I might then make
a separate function of the "is temp a valid item to add to this list"
*untested* :
def is_valid(item, thelist):
if len(list) >1 and (thelist[-2] == thelist[-1] == item):
return False
if thelist.count(item) >= 10:
return False
return True
import random
reeks = []
for i in range(60):
temp = random.randint(1, 6)
while not is_valid(temp):
temp = random.randint(1, 6)
reeks.append(temp)
print reeks
I also fixed the indentation to 4, and made temp a scalar instead of a list.
DaveA
More information about the Tutor
mailing list