this question has answer here:
- how create variable number of variables? 12 answers
when writing code found myself doing lot of repetitive stuff , wondering if there easier or simpler or shorter way repetitive task such this.
here relevant code:
random import randint randomnumber = zeroes = ones = twos = threes = fours = fives = sixes = = 0 while < 1000000: randomnumber = (randint(0,6)) if randomnumber == 0: zeroes = zeroes + 1 if randomnumber == 1: ones = ones + 1 if randomnumber == 2: twos = twos + 1 if randomnumber == 3: threes = threes + 1 if randomnumber == 4: fours = fours + 1 if randomnumber == 5: fives = fives + 1 if randomnumber == 6: sixes = sixes + 1 = + 1
rather taking named variables each random output, can take dictionary each possible value key. shorten code , made extendable random range
from random import randint randommax = 6 randomlist= {i:0 in range(0,randommax+1)} totaliterations = 10000 while totaliterations >0: randomlist[randint(0,randommax)]+=1 totaliterations-=1
sample output:
{0: 1400, 1: 1400, 2: 1500, 3: 1400, 4: 1500, 5: 1000, 6: 1800}
Comments
Post a Comment