I am getting list.remove(x)
error So what am I doing here is that, am using this program to generate random numbers without duplicates from a set range and removing the number as the number has been called but somehow I am getting not in the list message even though the random has been called from the list.
import random
def checkPizza(numOfPizza):
pizzaD = []
allowed_val = list(range(0,M+1))
if numOfPizza == 2:
allowed_val = allowed_val
while True:
allowed_val = allowed_val
alpha = random.choice(allowed_val)
beta = random.choice(allowed_val)
if alpha != beta:
allowed_val.remove(alpha)
allowed_val.remove(beta)
pizzaD.append(alpha)
pizzaD.append(beta)
break
Your code runs fine for me. You did not define M here so I chose an arbitrary number:
import random
def checkPizza(numOfPizza):
pizzaD = []
allowed_val = list(range(0,10))
if numOfPizza == 2:
allowed_val = allowed_val
while True:
allowed_val = allowed_val
alpha = random.choice(allowed_val)
beta = random.choice(allowed_val)
if alpha != beta:
allowed_val.remove(alpha)
allowed_val.remove(beta)
pizzaD.append(alpha)
pizzaD.append(beta)
print(pizzaD)
break
checkPizza(2)
output:
[7, 5]
It is howevery not clear for me what allowed_val=allowed_val
is suppose to do. It appears twice in your code. Also I think you are using a while loop for the case that alpha equals beta. In my opinion the following would be prefered:
alpha,beta = random.sample(allowed_val,2)
This will asign two values from the list of allowed_val that are not the same. In this case you do not need the while True
loop
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.