m used to program in statistical programs like Stata and R but I’ve recently picked up on Python and I’m trying to teach myself. One thing that puzzles me is perhaps a simple (or maybe complex, I don’t know) is how to loop my scripts and write the result of each script to an excel file. I’ve been playing with this script that is heavily inspired by scripts that does the same (just to learn); the infinite monkey script, where I try to simulate a monkey on a typewriter trying to guess words that I define. I’ve succeeded in making a script that runs..... somewhat okay with shorter words (words above 7 letters takes quite some time) but I would like to take the result, write it to an excel-file and rerun to do the same estimate maybe 100 times more and writing the last line to the excel-file. Okay, enough chat. This is the code I’d like to loop (sorry for the bad formatting - something is being weird when I copy-paste the code):
import numpy as np class Best: def __init__(self): self.iBestScore = 0 self.sBestGuess = None def getScore(self): return self.iBestScore def getGuess(self): return self.sBestGuess def setScore(self, new): self.iBestScore = new def setGuess(self, new): self.sBestGuess = new def randString(iStrLen): sGuess = np.random.randint(97, 123, iStrLen, dtype=np.uint8).tostring().decode('ascii') return sGuess def goalCheck(sGiven, sGuess, iStrLen, best): iScore = 0 for i in range(iStrLen): if sGuess[i] == sGiven[i]: iScore += 1 if(iScore >= best.iBestScore or best.iBestScore == 0): best.iBestScore = iScore best.sBestGuess = sGuess return best #@profile def begin(sGiven): best = Best() iTries = 0 iBestScore = 0 sGuess = randString(len(sGiven)) iTries += 1 best = goalCheck(sGiven, sGuess, len(sGiven), best) while(best.iBestScore != (len(sGiven))): sGuess = randString(len(sGiven)) iTries += 1 best = goalCheck(sGiven, sGuess, len(sGiven), best) if iTries % 100000 == 0 and iTries != 0: print("Tries: %d Best Score: %d Best Guess: %s" %(iTries, best.iBestScore, best.sBestGuess)) return best.sBestGuess, iTries def main(): print("Done! Found '{:s}' in {:d} tries.".format(*begin("hat"))) if __name__ == "__main__": main()