Mhcg233366
Mhcg233366

Reputation: 57

Python multiplying occurrence with int

Code:

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)

Output:

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})

What I need to do is multiple & return the occurrence by x1 if the value is X, or by y1 if the value is Y. I am a little stuck on this on how to get the following output. any assistance?

for ex:

**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)**

Upvotes: 0

Views: 53

Answers (1)

Jan Christoph Terasa
Jan Christoph Terasa

Reputation: 5935

Create a dict to map your weights, weight the counts by key from that map, and sum them up:

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)

Upvotes: 1

Related Questions