题解 | #称砝码# set去重
称砝码
http://www.nowcoder.com/practice/f9a4c19050fc477e9e27eb75f3bfd49c
除了去重主要还是算数的问题……不知如何描述……以至于我保留了calTypes
中被注释掉的逻辑。
示例:
3个74,2个185,有几种结果?
0
0,74
0,74,74*2=144
0,74,144,74*3=222
0,74,144,222,185
0,74,144,222,185,185+74=259
0,74,144,222,185,259,185+144=329
0,74,144,222,185,259,329,185+222=407
最后结果为 0,74,144,222,185,259,329,407
一共 8 个
import sys
# 计算可以称出的不同重量数
def calTypes(mx):
# 遍历字典的同时,使用set
rtn = set([0])
for key in mx.keys():
cishu = mx[key]
rtnlist = list(rtn)
for i in range(1,cishu+1):
rtn.add(key*i)
# 分别和set里已有的数字相加
for l in rtnlist:
rtn.add(key*i+l)
"""
rtnlist = list(rtn)
for i in rtnlist:
rtn.add(key*i+i)
"""
return len(rtn) # rtn
if __name__=='__main__':
lidx = 0
n=0 # 砝码种数
mList = [] # 每种砝码的重量
mx = {}
for line in sys.stdin:
if lidx==0:
n = int(line.replace("\n",""))
elif lidx==1:
mList = line.split(" ")
elif lidx==2:
idx = 0
for l in line.split(" "):
if idx<n:
mx[int(mList[idx])]=int(l)#.replace("\n",""))
idx+=1
lidx +=1
rtn = calTypes(mx)
print(rtn)