Reputation: 11
I'm trying to make a four digit long list, with no repeated digits. However, the code i am running is only generating one digit, and then closing. Can anybody see why?
import random
complist = [0,1,2,3,4,5,6,7,8,9]
compnum = []
userlist = []
usernum = []
def compnumber(compnum):
for i in range(4):
compx = random.randint(0,9)
if compx in compnum:
compx = 0
return compx, compnum
else:
compnum.append(compx)
compx = 0
return compx, compnum
compnumber(compnum)
print(compnum)
thanks!
Upvotes: 0
Views: 99
Reputation: 4606
import random
complist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
compnum = []
userlist = []
usernum = []
def compnumber(compnum):
for i in range(4):
compx = random.randint(0, 9)
while compx in compnum:
compx = random.randint(0, 9)
compnum.append(compx)
compnumber(compnum)
print(compnum)
You could set a while
condition that won't allow the randint
to be used if it already has been added to compnum
Output
(xenial)vash@localhost:~/python$ python3.7 helpin.py [1, 4, 2, 3] [4, 2, 1, 8] [2, 0, 4, 1] [4, 6, 2, 3] [1, 2, 0, 9] [6, 4, 9, 3] [2, 8, 7, 0] [7, 5, 4, 0] [0, 9, 7, 3] [4, 9, 2, 1]
Results for 10 iterations
I would consider when defining your function to use a different variable name, not the actual variable you are passing, Ex. def compnumber(list_to_append)
Upvotes: 1
Reputation: 61930
There are a few issues with your code:
for-loop
compnum
having 4 values, so it might return a compnum
with less than 4 values.You can write it like this:
import random
complist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
compnum = []
userlist = []
usernum = []
def compnumber(compnum):
while len(compnum) != 4:
compx = random.randint(0, 9)
if compx not in compnum:
compnum.append(compx)
return compx, compnum
compnumber(compnum)
print(compnum)
Output
[9, 7, 8, 2] # as an example
But the best way to do it is to use the sample function of random module, like this:
import random
complist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
compnum = random.sample(complist, 4)
print(compnum)
Upvotes: 0
Reputation: 1879
The most Pythonic way to do it is Daniel's answer, using sample()
.
Using loops (your approach) is also fine.
Here's my take on how to do it with a loop:
import random
compnum = []
def compnumber(ur_list):
while len(ur_list) < 4:
compx = random.randint(0,9)
if compx not in ur_list:
ur_list.append(compx)
return ur_list
print(compnumber(compnum))
Upvotes: 0
Reputation: 42778
You have a return in your for-loop, so only one number is generated.
numbers = random.sample(range(10),4)
Upvotes: 3