您的位置:首页 > Web前端

Leetcode Algorithm No.241 Different Ways to Add Parentheses

2015-08-31 14:24 537 查看
初识Python的浅拷贝题目来自LeetcodeGiven a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are
+
,
-
and
*
.Example 1Input:
"2-1-1"
.
((2-1)-1) = 0
(2-(1-1)) = 2
Output:
[0, 2]
Example 2Input:
"2*3-4*5"

(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10
Output:
[-34, -14, -10, -10, 10]
Program language: Python 3.4成功运行的第N版本, 并没有得到期望结果
'''calculat函数用来作 +,-,* 的运算,调用的例子为calculat([1,2],'+'),返回值3'''
def calculat(value,oper):
#print(input)
result = 0
if len(oper) == 1:
a = value[0]
b = value[1]
if oper[0] == '+':
result = (a+b)
elif oper[0] == '-':
result = (a-b)
elif oper[0] == '*':
result = (a*b)
return result
'''itercalculate接收两个list,value中是一系列数字,oper中是一系列运算符,value的长度比oper多1
函数返回最终运算结果'''
def itercalculate(value,oper,out=[]):
if len(oper) == 1:
out.append(calculat(value,oper))
return out
else:
i=0
while i<len(oper):
print ('before del',value,oper,i)
result = calculat(value[i:i+2],oper[i])
subvalue = value
suboper = oper
print (id(value),' ' , id(oper))
print (id(subvalue),' ' , id(suboper))
'''打印出上面四个变量的id发现value与subvalue其实是同一个对象,名称不同而已,
也就是说,赋值语句subvalue = value相当于浅拷贝,解释器并没有新分配内存给subvalue变量,如此对
subvalue的删除元素操作影响到了value'''
subvalue[i] = result
del subvalue[i+1]
del suboper[i]
itercalculate(subvalue,suboper)
i=i+1

'''diffWaysToCompute函数用来对输入的字符串用处理,将数字与运算符分别存储在两个list中:value
及operator.
例如输入字符串为"2*3-4*5",则最终运算结果为value=[2,3,4,5],oper=[*,-,*]
然后调用函数itercalculate,以value及operator作为参数,并将其返回结果作为自己的返回值'''
def diffWaysToCompute(input,out):
i=0
value = []
operator = []
while i<len(input):
if i%2 == 0:
value.append(int(input[i]))
else:
operator.append(input[i])
i=i+1
out=itercalculate(value,operator,out)
return out
s="2*3-4*5"
out=[]
diffWaysToCompute(s,out)
print('输出结果: ',out)
'''
输出结果为:
>>>
before del [2, 3, 4, 5] ['*', '-', '*'] 0
58214280   58213680
58214280   58213680
before del [6, 4, 5] ['-', '*'] 0
58214280   58213680
58214280   58213680
输出结果:  None
'''
'''
itercalculate 函数中的while循环中使用了 del 命令对 subvalue 及 suboper 进行处理。
del命令执行完成后打印value 及oper 的值发现它们的值改变了。
意味着对subvalue 及 suboper的del 操作在value 及oper上也生效了。
与期望结果不符。
'''
鉴于上面出现的问题,更新itercalculate函数,不再使用del命令
'''
在diffWaysToCompute 函数中对输入的字符串做处理,将数字与运算符分别存储在两个list中。
如此当某个运算出现负数时能方便处理
'''
def itercalculate(value,oper,out):
if len(oper) == 1:
out.append(calculat(value,oper))
return out
else:
i=0
while i<len(oper):
result = calculat(value[i:i+2],oper[i])
if i==0:
subvalue = value[1:]
suboper = oper[1:]
elif i==len(oper)-1:
subvalue = value[0:i+1]
suboper = oper[0:i]
else:
subvalue = value[0:i+1] + value[i+2:]
suboper = oper[0:i] + oper[i+1:]
subvalue[i] = result
itercalculate(subvalue,suboper,out)
i=i+1
输出期望结果:>>>[10, -14, -10, -10, -14, -34]

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: