Reputation: 3
My intent is to read a list from a file, pick a random number from that list and remove it, then resave the list. Sometimes the function works fine, sometimes not.
choices=[]
with open("C:\\choices.txt", "r") as f:
for line in f:
choices.append(int(line.strip()))
if len(choices)==0:
choices=[0,1,2,3,4,5]
num=rdm.randint(0,5)
def chooseline(myList, myNum):
print("before if num= "+str(myNum))
if not myNum in myList:
myNum=rdm.randint(0,5)
chooseline(myList,myNum)
print("In NOT-IF num= "+str(myNum))#<-- Need to move before chooseline to print. ok
else:
myNum=myList.pop(myList.index(myNum))
print("in Else num= "+str(myNum))
print("end num= "+str(myNum))
return myNum
newnum= chooseline(choices,num)
with open("C:\\choices.txt", "w") as f:
for e in choices:
f.write(str(e) +"\n")
As long as the random number is in the list the function returns as expected, but if the first number is not on the list, it seems to loop back.
runfile('...')
before if num= 0
in Else num= 0
end num= 0
runfile('...')
before if num= 2
in Else num= 2
end num= 2
runfile('...')
before if num= 2 #ok not in list
before if num= 0 #ok chooses new number, but not in list
before if num= 4 # chose 4, in list
in Else num= 4 # as expected
end num= 4 #<----- expect to stop here and return 4
In NOT-IF num= 4
end num= 4 #
In NOT-IF num= 0
end num= 0
Upvotes: 0
Views: 73
Reputation: 151
Example without the recursion as mentioned in the comments:
import random
choices = []
with open("choices.txt", "r") as f:
for line in f:
choices.append(int(line.strip()))
if len(choices) == 0:
choices = [0, 1, 2, 3, 4, 5]
num = random.randint(0, 5)
def choose_num_in_list(max_attempts=100):
chosen_number = -1
attempts = 0
while chosen_number == -1 and attempts < max_attempts:
candiate_number = random.randint(0, 5)
attempts = attempts + 1
if candiate_number in choices:
chosen_number = candiate_number
return chosen_number
newnum = choose_num_in_list()
if(newnum != -1):
choices.pop(choices.index(newnum))
print(f"Removed {str(newnum)} from the list")
else:
print("Failed to remove a number from the list")
with open("choices.txt", "w") as f:
for e in choices:
f.write(str(e) + "\n")
Upvotes: 0
Reputation: 165
There is an easier and more efficient approach ...
import random
lines = []
with open('choices.txt', 'r') as file:
for line in file:
lines.append(int(line.rstrip()))
file.close()
with open('choices.txt', 'w') as file:
if len(lines) > 1:
number = lines[random.randint(0, len(lines) - 1)]
for line in lines:
if line != number:
file.write(f'{line}\n')
file.close()
Upvotes: 0