我们都知道数学函数(PEMDAS)的标准操作顺序,但是如果我们用从左到右的表达式来计算呢?
挑战
通过标准输入或命令行args给出一个字符串,找出该表达式的传统计算(PEMDAS)和顺序(从左到右)计算之间的区别。
发布于 2014-07-16 07:09:35
d=x=input();z=2;u='('*(((len(x)-len(x.replace(' ','')))/2)+1);d=x=d.replace(r'^','**');x=x.split();p=u+''.join(")".join(x[i:i+z]) for i in range(0,len(x),z))+")";m=eval(p)-eval(d);m=m*-1 if 0>m else m;print m;卡尔文的霍布斯评论:
import re;e=input().replace('^','**');print abs(eval(e)-eval(e.count(' ')/2*'('+re.sub('(\d) ',r'\1)',e)))# variable d = x, and x = user input
d = x = input()
# variable z = 2
z = 2
# I take the length of the string 'x' (aka the equation we're solving) with
# *all* whitespaces removed (it's the 'len(x.replace(' ', '')...' part) and
# subtract that from 'len(x)' which is the vanilla length of our equation
# I divide the total by two and add one for reasons I'll explain in a minute
# the '(' * part means to make a string with as many '(' as I get from multiplying
# so '(' * 5 = '(((((', '(' * 3 = '((('
u = '(' * (((len(x) - len(x.replace(' ', ''))) / 2) + 1)
# Here I replace the caret with **, because in Python ^ == **
# I also split the string by whitespaces, but only for x;
d = x = d.replace(r'^','**'); x = x.split();
# I set the variable p = to the result of joining the list (aka array) that
# I just made with the .split() in the above section first with a ')' on every
# second character (e.g. [1,2,3,4,5,6] would be 1,2),3,4),... etc. I do it like
# this because in our math equation we'll (hopefully) follow the pattern of
# num op num op num op... etc. I insert parenthases because I'm using PEMDAS
# to my advantage by grouping each set of numbers in the order I want them
# to be completed. The initial ''.join simply rejoins all elements into a
# complete string (basically removes the commas that are left over from
# converting a list -> string). I add a '(' to the end because every 2nd
# character would skip the final one
p = u + ''.join(")".join(x[i:i + z]) for i in range(0, len(x), z)) + ")"
# I eval() both p and d. eval() will run arbitrary code, so you can pass it a
# string and it will act as if the string is code, so while print '1+1' would
# usually result in TypeError (or Value? I forget), print eval('1+1') would
# print '2', I have to do them separately because eval() thinks I wanna
# subtract two string for whatever reason
m = eval(p) - eval(d)
# Here I make use of Python's ternary operators by saying this:
# if 0 > m:
# m = m * -1
# else:
# m
# which means that if m is negative, multiply it by -1 to make it
# a positive number so we can get the absolute value. If it's not negative
# then we can just have m and not do anything with it
m = m * -1 if 0 > m else m
# Print m :)
print mhttps://codegolf.stackexchange.com/questions/34599
复制相似问题