首页 > 解决方案 > 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)**

标签: python

解决方案


创建一个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)

推荐阅读