I’d like to implement yield and range to challenge myself and get a better understanding of both. I’m trying to use yield to loop through a function to get a random number within the list. And range used somewhere within as well. The current function below I have isn’t currently working.
JavaScript
x
9
1
NumList = [6,9,32,39,61,75,60,63,22,49,26,4,64,54,78,43,1,47,46,17,69,20,85,71,93,28,89,67,14,88,15,73,96,86,55,79,68,76,94,65]
2
3
def PenTune():
4
for NumList in range(1):
5
yield random.choice(list(enumerate(NumList)))
6
7
for pos, item in PenTune():
8
print("pos:", pos, "itemvalue:", item)
9
Advertisement
Answer
The following may hint you at what’s going on:
JavaScript
1
16
16
1
numList = [6,9,32,39,61,75,60,63,22,49,26,4,64,54,78,43,1,47,46,17,69,20,85,71,93,28,89,67,14,88,15,73,96,86,55,79,68,76,94,65]
2
3
def PenTune():
4
e = list(enumerate(numList)) # only listify it once
5
for _ in range(5): # or how many random index-value pairs you want
6
yield random.choice(e)
7
8
for pos, item in PenTune():
9
print("pos:", pos, "itemvalue:", item)
10
11
pos: 37 itemvalue: 76
12
pos: 16 itemvalue: 1
13
pos: 29 itemvalue: 88
14
pos: 32 itemvalue: 96
15
pos: 8 itemvalue: 22
16
A less wasteful implementation:
JavaScript
1
5
1
def PenTune():
2
for _ in range(5):
3
i = random.randint(0, len(numList)-1)
4
yield i, numList[i]
5