Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make toInt.py shorter and safer #1

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 6 additions & 28 deletions TelegramBot/toInt.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,11 @@

Eval,Abs,Pow = eval,abs,pow
# use ast to prevent evil stuff
from ast import literal_eval

# separate file to prevent the usage
# of unwanted eval features
from math import *

# Lambert W-function (why?! XD)
# inverted function to f(x)=x*e^x
def W(x):
# y-result, d-10-exponent, s-y*e^y, t-previous s
y,d,s,t = 0,-2,0,-1
# relation of s to x
f = r = 1 if y*Pow(e,y)<x else -1

while d<17: # python calculates with 16 float digits
while r==f: # if relation of s to x changed - calc next digit
if s==t:return y # return if y*e^y == result
t = s
if Abs(y) > 10000:return "NaN" # x not in W(x)
y += f*Pow(10, -d) # in/decrease a digit dependent on f
s = y*Pow(e, y) # calculate x of current y value
f = 1 if s < x else -1 # recalculate relation of s to x

r, d = f, d+1
return y

# calculate int from string via eval
# calculate int from string via literal_eval
def toInt(s):
try: return Eval(s)
# convert to lower case to allow things like "Abs" or "SQRT"
try: return ast.literal_eval(s.lower())
except ZeroDivisionError:
return 'division by zero!'
return 'Division by 0!'
except: return 'Error!'