Python Forum
Using print with calculation
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using print with calculation
#1
Hey guys.

I'm pretty new to Python but not to statistics and general programming. I have a very specific problem that I can't seem to be able to solve. I posted 1 time before and figured it out but the general gist of my small script is that I am simulating someone randomly pressing ascii-characters until they randomly guess a defined string. Now I want to do a small calculation in the end where I convert the number of characters typed into amount of time used. The formula I've decided is this: (((((number_characters/4)/60)/60)/24)/365.25). My problem is, that I don't know how to use {:d} as a number to be calculated in a print-function. The full code is below, but here are the parts I can't figure out:

I do this:

		if iTries%10000 ==0 and iTries!=0:
			print("Tries: %d Best Score: %d Best Guess: %s" %(iTries, best.iBestScore, best.sBestGuess))

	return best.sBestGuess, iTries
And then the regular script is:

def main():
	print("Done! Found '{:s}' in {:d} tries.".format(*begin("fish")))
if __name__ == "__main__":
	main()
But when I try to add the calculation, I thought I could do it directly in main like:

def main():
	print("Done! Found '{:s}' in {:d} tries.".format(*begin("fish")))
    print("The person used '{:d}((((({:d}/4)/60)/60)/24)/365.25)' years)
if __name__ == "__main__":
	main()
What did I do wrong?
Reply
#2
I would write something like
def main():
    found, cnt = begin("fish")
    print("Done! Found '{:s}' in {:d} tries.".format(found, cnt))
    print("The person used {:.2f} years".format(cnt/(4*60*60*24*365.25)))
Reply
#3
you just cannot have calculations within the string
Reply
#4
With the new format-strings, you can do this...
user = 'andre müller'
total = 35.0
products = ['Apple', 'Battery', 'Charger']

print(f'Hello {user.title()}. You have to pay {total * 1.19:.2f} €.')
print(f'You get following products: {", ".join(products)}')
Sometimes it's more readable, sometimes it's not.

Calculations like this cnt/(4*60*60*24*365.25) should not be done in the f-strings and/or formatting method.
Make a helper function. It can look like this one:

def cnt_per_years(cnt):
    return cnt / (4*60*60*24*365.25)
Later you just call cnt_per_years(cnt) and you get your result.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
I’ve been trying to make the helper function but I cant figure out how to use {:d} as a value in the equation. Let’s say I want to do this:

{:d}+1
How do I make it realize what value d is? Full code below.

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%10000 ==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("trips")))
if __name__ == "__main__":
	main()
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020