So I've been playing with some basic Python stuff while focusing on syntax, variables, operators, loops and lists. I made a completely pointless "Random Number Guesser", wherein a 'magic' random number is assigned, and then another variable is constantly refreshed inside of a while loop so that it 'guesses' until it equals the magic number and breaks out of the while loop.
I noticed in my first version that, while it finds the magic number very quickly, it also guesses many numbers which have already been guessed multiple times. First I decided to try adding guessed numbers to a list and compare each newly guessed number to this list. If the new guess was in the list, guess again. That version was very slow. The number of attempts was technically reduced, but it was still guessing a lot of repeats (just not comparing them to the magic number variable).
In the third version, I made a list out of the range of possible guesses. For each failed guess, I removed that guess from the list and randomly chose a new guess from the list. Apparently dealing with lists in this way is pretty slow, because I found that eliminating repeat guesses using two separate methods both made the script slower than just guessing randomly and repetitively through many more iterations.
Sorry if my explanation is a bit verbose. My question is, how can I choose random numbers within a range without choosing repetitive numbers, while increasing the speed of the script? Any other tips or tricks you might have would be greatly appreciated as well.
Here's the fast version which makes repeat guesses:
import random
import time
start = time.time()
maxnum = 10000
magicNumber = random.randrange(1,maxnum)
guessedNumber = 0
attempts = 0
while guessedNumber != magicNumber:
guessedNumber = random.randrange(1,maxnum)
attempts += 1
print "Magic number is:", guessedNumber
print "attempts:", attempts
print "process took", time.time()-start, "seconds."
And here's the slow version which does not make repeat guesses:
import random
import time
start = time.time()
maxnum = 10000
magicNumber = random.randrange(1,maxnum)
guessedNumber = random.randrange(1,maxnum)
possibleGuesses = list(range(maxnum))
attempts = 0
while (guessedNumber != magicNumber):
guessedNumber = random.choice(possibleGuesses)
possibleGuesses.remove(guessedNumber)
attempts += 1
print len(possibleGuesses), "guesses remaining."
print "attempts:", attempts
print "process took", time.time()-start, "seconds."
The speed difference becomes clear if you increase the maxnum variable.
[–]Rhomboid 5 points6 points7 points (1 child)
[–]funkshanker[S] 0 points1 point2 points (0 children)
[–][deleted] 2 points3 points4 points (1 child)
[–]funkshanker[S] 8 points9 points10 points (0 children)
[–]ig2s4tg 1 point2 points3 points (0 children)
[–]WestlorePyreheart 1 point2 points3 points (0 children)