On 8/12/2010 1:26 AM, Steven D'Aprano wrote:
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
<snip>
Thank you all for your help! I've added another condition to this
program, namely, in a range of 60, each 'random' number can only occur
10 times. I came up with the following:
import random
series = []
for i in range(60):
temp = [random.randint(1, 6)]
while series[-2:-1] == series[-1:] == temp:
temp = [random.randint(1, 6)]
while series.count(temp[0]) >= 10:
temp = [random.randint(1, 6)]
series.extend(temp)
print series
However, this also generates gems such as:
[4, 4, 3, 6, 3, 2, 6, 3, 4, 3, 4, 1, 4, 2, 4, 3, 4, 4, 6, 2, 1, 5, 5, 6,
5, 6, 5, 6, 3, 3, 1, 6, 6, 4, 1, 5, 2, 6, 6, 4, 2, 5, 3, 1, 5, 5, 2, 1,
_2_, _2_, _2_, 3, 3, 2, 1, 5, 1, 1, 5, 1]
[1, 4, 3, 1, 5, 3, 5, 1, 5, 6, 5, 3, 2, 6, 1, 4, 1, 5, 5, 2, 6, 2, 4, 1,
3, 1, 2, 1, 1, 3, 1, 6, 6, 3, 2, 3, 6, 4, 5, 6, 5, 6, 3, 6, 2, 4, 5, 3,
3, 4, 6, _4_, _4_, _4_, 5, 4, _2_, _2_, _2_, _2_]
I thought this needed to become the following:
import random
series = []
for i in range(60):
temp = [random.randint(1, 6)]
print "Temp", i, ":", temp
while series[-2:-1] == series[-1:] == series:
if series.count(temp[0]) >= 10:
temp = [random.randint(1, 6)]
series.extend(temp)
print series
But this just hangs whenever the while clause matches. I'm not sure what
I'm doing wrong here. I do know the random.shuffle() function, but I
can't put my conditions in there.
Any push in the right direction would be greatly appreciated :)
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor