python - Python将出现与int相乘
问题描述
代码:
from collections import Counter
class Solution(object):
def combinationSum(self, candidates, target):
result = []
unique={}
candidates = list(set(candidates))
self.solve(candidates,target,result,unique)
return result
def solve(self,candidates,target,result,unique,i = 0,current=[]):
if target == 0:
temp = [i for i in current]
temp1 = temp
temp.sort()
temp = tuple(temp)
if temp not in unique:
unique[temp] = 1
result.append(temp1)
return
if target <0:
return
for x in range(i,len(candidates)):
current.append(candidates[x])
self.solve(candidates,target-candidates[x],result,unique,i,current)
current.pop(len(current)-1)
ob1 = Solution()
X = 2500
Y = 7500
x1 = 700
y1 = 2950
sol = (ob1.combinationSum([X,Y],40000))
for i in sol:
x = (Counter(i))
print(x)
输出:
Counter({2500: 16})
Counter({2500: 13, 7500: 1})
Counter({2500: 10, 7500: 2})
Counter({2500: 7, 7500: 3})
Counter({2500: 4, 7500: 4})
Counter({7500: 5, 2500: 1})
我需要做的是多个&如果值为X,则返回x1,如果值为Y,则返回y1。我对如何获得以下输出有点坚持。有什么帮助吗?
例如:
**Counter({2500: 16}, 11,200 (700*16))
Counter({2500: 13, 7500: 1}, 12,050 ((13*700)+(1*2950)))
Counter({2500: 10, 7500: 2}, 12,900)
Counter({2500: 7, 7500: 3}, 13,750)
Counter({2500: 4, 7500: 4}, 14,600)
Counter({7500: 5, 2500: 1}, 15,450)**
解决方案
创建一个dict
来映射您的权重,通过该映射的键对计数进行加权,并将它们相加:
weights = {X: x1, Y: y1}
for i in sol:
x = Counter(i)
xsum = sum(counts * weights[key] for key, counts in x.items())
print(x, xsum)
推荐阅读
- javascript - 如何将两个内容html的总和放入jQuery脚本中
- php - 为什么我的 png 文件以 pdf 格式更新到数据库中以及如何更正?
- css - 平滑地向文本添加渐变不起作用?
- ios - 带有 Fastlane 翻译插件的 iOS 本地化
- api - 如何将图片保存到 API 以与 Expo 原生反应?
- c# - 通过类传回带有响应代码的消息
- c++ - 链接的 .so 有:未定义的对 `fminf' 的引用
- tsql - SSRS 中的数据透视列
- php - 从mysql查询到php的空白列表下拉列表
- ruby-on-rails - 迁移到 Rails 5,rails gem 问题