Reputation: 345
I am trying to make a game where one person chooses a number and then two threads of computers try to find it with random guesses. I was trying to make the "AI" smarter by making a list of guesses the thread had already guesses so then it would cut down on total guesses. For some reason, the computers never find the number and my CPU usage spikes showing that they are looking for it. What is my flaw in the code? Thanks a bunch in advance! Also if there is any improvements to make the AI guess better would be appreciated. Code (This is just the part where the computers guess, not the full thing):
def first_computer():
global computer1_score
computer1_score=0
computer1_guess= -1
one_guess_list=[]
while computer1_guess != pick_number:
computer1_guess=random.randint(1,1000000)
if computer1_guess in one_guess_list:
pass
else:
one_guess_list.append(computer1_guess)
computer1_score+=1
print computer_name_one.upper() +" got the answer in " + str(computer1_score) + " guesses"
def second_computer():
global computer2_score
computer2_score=0
computer2_guess= -1
two_guess_list=[]
while computer2_guess != pick_number:
computer2_guess=random.randint(1,1000000)
if computer2_guess in two_guess_list:
pass
else:
two_guess_list.append(computer2_guess)
computer2_score+=1
print computer_name_two.upper() +" got the answer in " + str(computer2_score) + " guesses"
Upvotes: 0
Views: 18
Reputation: 76715
Your basic algorithm would take a long time in any event: guess a random number with a one-in-1000000 chance of the guess being correct.
Your program makes things worse by your use of a list to store the previous guesses. The more failed guesses go into the list, the slower your program gets, as Python has to search through each list, looking at one number at a time. This is called an "O(n)" complexity algorithm; the set is called an "O(1)" complexity algorithm. The larger n
becomes, the slower O(n) gets.
http://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notation/
You can speed your program up a bit by switching to a set rather than a list to store the list of incorrect guesses.
You can speed your program up a lot by giving your guesses a hint whether they were too low or too high, and using a binary search to close in on the number. Maybe that's cheating? I'm not sure what your goals are with this program.
Upvotes: 1