This program is supposed to compute a numeric palindrome, when data is input via a web form. It did run properly on localhost environment using just python and the web.py framework. But since then, I ported it to the google app engine, using webapp2 framework, so that I can launch this on a public server. When I refactored code for this new framework, something got off in the lines of code dealing with the computation. Hoping someone can help solve this.
Below is the class that handles getting the input from browser. I've tested and it seems to get that input fine. Then it sends it to compute_palintip, which is supposed to solve the palindrome (final amount). It is hanging here.
class result(webapp2.RequestHandler):
def post(self):
form = self.request.get_all('entries', default_value = None)
if form[0]:
if form[1]:
orig_dollar_amount = cgi.escape(form[0])
tip_percent = cgi.escape(form[1])
final_amount = compute_palintip(float(orig_dollar_amount),
float(tip_percent))
actual_tip_percent = final_amount - orig_dollar_amount
actual_tip_percent = actual_tip_percent*100/orig_dollar_amount
This is the compute_palintip code and its helper function:
def compute_palintip(orig_dollar_amount, tip_percent):
orig_amount_cents = orig_dollar_amount*100
final_amount = orig_amount_cents*(1.0 + tip_percent/100.0)
while(is_palindrome(final_amount) == False):
final_amount += 1
final_amount = final_amount/100
final_amount = round(final_amount, 2)
return final_amount
def is_palindrome(num):
num_str = str(num)
num_str_len = len(num_str)
for i in range(num_str_len):
if num_str[i] != num_str[num_str_len-i-1]:
return False
return True
A few notes:
I had to convert the input into floats in order to send them to the compute_palintip function.
Couldn't convert to ints because they do not allow decimal places (cents are needed for these inputs related to restaurant dollar amounts).
I also have to use the float type I'm pretty sure, because neither Strings nor Ints will be able to operate with the formulas which are also floats. Python wants them all the same.
However, it seems that the math is now wonky since the floats and ints got mixed up, and it is not terminating.
The math was written by a colleague, whereas I was writing the UI type stuff, which is why I'm not really able to debug it at this point, so I am hoping someone else can spot a solution I'm not seeing. Thanks.
Perhaps you can set some logging to see the flow of the program. When dealing in floats, be consistent in your arithmetic, and use decimals after each number:
orig_dollar_amount*100.0
final_amount/100.0
final_amount += 1.0
actual_tip_percent*100.0/orig_dollar_amount
Also, you failed to cast orig_dollar_amount to a float
What are the numbers you've input? There are cases where is_palindrome never returns True. e.g. 1234567890. It will go through the entire string, and return False for every test.
I solved the issues, thanks for the help everyone. The decimal places had to be exact, and I had to be sure in each place of choosing whether to use ints / floats / strings, etc. in order to get the proper outcome. Line by line debugging, testing various examples, and correcting the flaws one by one was the only way to go.
The prototype app of this code is up and running at http://third-fire-595.appspot.com/ , by the way, for anyone interested in playing with it. please feel free to test out some combinations and let me know any feedback.
Related
So, really I'm just confused, I've been learning python, and I was given an exercise to find the performance speed of a function, however after finishing the code I received an error in the time output, it was 3.215000000000856e-06, this value varies with every time I run the program though so you probably won't get the same output.(in reality it was less then a second.) I went through the video where it explained how to write how they did it and changed a how I wrote a statement, now my code is Identical, to theirs but with different variable names, I ran the program and the same problem, however they didn't experience this issue, heres the code:
import time
SetContainer = {I for I in range(1002)}
ListContainer = [I for I in range(1002)]
def Search(Value, Container):
if Value in Container:
return True
else:
return False
def Function_Speed(Func, HMT = 1, **arg):
sum = 0
for I in range(HMT):
start = time.perf_counter()
print (Func(**arg))
end = time.perf_counter()
sum = sum + (end - start)
return (sum, )
print (Function_Speed(Search, Value = 402,
Container = SetContainer))
Possible Answers?:
Could it be my hardware? My version of Python is no longer supported(The video is over a year old I'm using 3.6) or it turns out I screwed up.
(Edit:) By the way it does work when the function is printed so this example works, but without print (Func(**arg)) and instead Func(**arg) it doesn't work.
First, your capitalization of variable and function violates convention. Though not a syntax error, it makes it difficult for Python programmers to follow your code.
Second, the result you got makes sense. A single iteration of the search on a modern computer takes very little time. If your printed result was in the form 1.23456e-05, then that is a valid number so small that the default representation shifted to scientific notation.
Add a value for HMT, starting with 100000, and see what is output.
I already read the other questions and answers but couldn't implement any of the solutions to my code. I'm still clueless about the reason why this code gives a runtime error.
I'm trying to submit the code on CodeChef, yet it gives the Runtime Error(NZEC), although the code runs flawlessly on my console for some inputs. Here's my code:
def GetSquares(base):
if not base or base < 4:
return 0
else:
x = (base - 4) - (base % 2) + 1
return x + GetSquares(base - 4)
num_test = int(input())
for test in range(num_test):
base = int(input())
print (int(GetSquares(base)))
Codechef's explanation for NZEC:
NZEC stands for Non Zero Exit Code. For C users, this will be
generated if your main method does not have a return 0; statement.
Other languages like Java/C++ could generate this error if they throw
an exception.
The problem I'm trying to solve:
https://www.codechef.com/problems/TRISQ
The problem description says that the input is constrained to be < 10^4. That's 10,000! Your code will need to make 10,000/4 = 2500 recursive calls to GetSquares, that's a lot! In fact, it's so much that it's going to give you, fittingly, this error:
RuntimeError: maximum recursion depth exceeded
You're going to have to think of a better way to solve the problem that doesn't involve so much recursion! Because you're doing this coding challenge, I'm not going to give a solution in this answer as that would sort of defeat the purpose, but if you'd like some prodding towards an answer, feel free to ask.
The question puts a constraint on the value of 'B' which is 10000 at max, which means there are a lot of recursive calls and giving a runtime error. Try solving using iteration.
Just got one other question for my python plugin.
Here is the code:
def cmd_give(self, data, client=None, cmd=None):
"""
^3<player> <money> - Give someone however much money you want.
"""
input = self._adminPlugin.parseUserCmd(data)
if not data:
client.message('^7 correct syntax is !give <player> <money>')
return False
else:
if len([x for x in data if x.isspace()]) < 1:
client.message('^7 correct syntax is !give <player> <money>')
return False
else:
input_data = data.split(' ',1)
scname = input_data[0]
ammount = int(input_data[1])
sclient = self._adminPlugin.findClientPrompt(scname, client)
if not sclient: return False
self.earn_money(sclient, ammount)
return True
Now this obviously adds the value given in the command to the user inputting into mysql.
I'm also wanting a command to subtract any value given in the command as well.
So this command above is a give and I also want a take.
My problem is I don't know what the change is to minus the amount off the value input instead of adding.
Hope someone can help,
Thanks guys.
Without modifying the function that does the actual addition, the suggestion by Rob Watts in a comment will work:
ammount = -int(input_data[1])
You can either create a new function, cmd_take, and do that there, or have a more general function (cmd_transaction?) that takes an extra argument (eg give) and has the appropriate logic:
if not give:
ammount = -int(input_data[1])
In the first case, it would be good practice to extract most of the code to a helper function, to avoid repetition, but if you don't know python and this is just a one time thing, having a cmd_take function that is exactly like command_give, except for that one line, is the simplest solution.
I'm a fairly new Python programmer (started 3 days ago). I'm working as a apprentice for a civil engineer and he asked me to do some simpler tasks for his program, as of the objective I should work with is to not allow numbers from inputs in certain glade objects.
The code I've been struggling with creating is as such:
def testOmHeltal (self, number1):
textviewResultat = self.builder.get_object("textviewResultat")
text = gtk.TextBuffer()
try:
#print number1.get_text()
#temp = number1.get_text() + number1.get_text()
temp = float(number1.get_text())
except ValueError:
text.set_text("ERROR: Endast Nummer")
self.builder.get_object("hboxWarning").show()
self.builder.get_object("image12").show()
self.builder.get_object("textviewResultat").set_buffer(text)
return 0
self.builder.get_object("hboxWarning").hide()
self.builder.get_object("image12").hide()
def quit(self, widget):
sys.exit(0)
This code is called upon at the location of the glade object with this line:
self.testOmHeltal(entryGladeObject)
Now to the problem at hand, I allways get an Float error as such:
File "bvf.py", line 393, in utfora
+float(entryTjockleksskyddslager.get_text<>>>>
ValueError: invalid literal for float<>: 0.04e
0.04e is the invalid input and line 393 is a piece of my Chiefs code, since all he uses is float all the time and I shouldn't meddle with it too much I'm kind of panicking alittle..
I understand that float can only start and end with a number to not give an error, but since my "code" bit wants an error(or rather, an exception) to start the 'hboxWarning' and 'image12' of someone using a letter instead of the supposed number, I'm at a loss at what to do ><
Instead of showing my error with hboxWarning and image12, nothing happens at all...
Any hints or advice would help alot.
I don't know if I understood correctly, but the error is not on your code, right?
All I can assume is that there's a piece of code trying to convert the value to float before your verification. If that's the case, you should verify the value before any processing is done on it, or move the try-except code around the faulty code, depending on the processing itself (for example, if the processing implies database manipulation, it would be safer to do all the verifications previously).
If the error is happening before the line where you run self.testOmHeltal(entryGladeObject), the execution of the signal/method stops right away and your code is never excecuted; that's why the warning isn't showing.
I have this script file in python running on S60:
import location
def current_location():
gsm_loc = location.gsm_location()
print gsm_loc
current_location()
instead of printing a tuple of mcc, mnc, lac and cellId it prints None.
on top of my python shell I see location between the capabilities included.
what can be the problem?
Development of the situation:
I thought maybe nevertheless, my problem is lack of capabilities. So I went to sign the PythonScriptShell file.
I used OPDA website - I know they sign all the capabilities but three - which I don't use.
I installed the signed PythonScriptShell file on my phone (N95). On the top the list of capabilities didn't change. tried to run the script again:
same result - prints None.
If anyone can help me with this, it's really important.
thank you.
I think I can answer now one part of the problem:
the reason for printing None is because there needed another capability: ReadDeviceData which wasn't included in the capabilities list on top of python shell.
still, remaining the other part of the problem, why this capability wasn't included when I signed PythonScriptShell file? It is not one of the three restricted capabilities.
I have same issue with all necessary scriptshell capabilities: 'PowerMgmnt', 'ReadDeviceData', 'WriteDeviceData', 'TrustedUI', 'ProtServ', 'SwEvent', 'Network services', 'LocalServices', 'ReadUserData', 'WriteUserData', 'Location', 'SurroundingsDD', 'UserEnviroment'.
Let's take a look at source code from PythonForS60/module-repo/dev-modules/location.py:
import e32
import _location
def gsm_location():
if e32.s60_version_info>=(3,0):
ret = _location.gsm_location()
if ret[4]==1: # relevant information ?
return (int(ret[0]),int(ret[1]),ret[2],ret[3])
else:
return None # information returned by _location.gsm_location() not relevant
else:
return _location.gsm_location()
On my Nokia E71 e32.s60_version_info == (3,1) and I get None value too.
I don't really know what means 'not relevant', but direct calling
>>> import _location
>>> _location.gsm_location()
(u'257', u'01', 555, 11, 0)
returns something close to my objective reality.