ulvis.paste.net

Paste Search Dynamic
Recent pastes
transform function
  1. from collections import Counter #help to sum two dictionaries with same key
  2. #initial  input
  3. A = [50, 100, 200, 500]
  4. initialMoney = 300
  5. results = []
  6. initial = {}
  7. #define a transform function
  8. def transformMoney(Array, money):
  9.     lenArray = len(Array)
  10.     B = {}
  11.     # sap xep Array giam dan
  12.     Array = sorted(Array, key = int, reverse = true)
  13.     remain = money
  14.     for i in range(lenArray):
  15.         qty = int(remain/Array[i])
  16.         remain = remain % Array[i]
  17.         if qty > 0:
  18.             B[(lenArray-1) - i] = qty
  19.     return B
  20. #get initial dictionary
  21. initial = transformMoney(A,initialMoney)
  22. # save first result
  23. results.append(initial.copy())
  24. while (len(initial) > 1):
  25.     # set dictionary
  26.     transform = {}
  27.     # get max key
  28.     key = max(initial,key=int)
  29.     initial[key] -= 1
  30.     #delete key if key = 0
  31.     if initial[key] < 1:
  32.         initial.pop(key, none)
  33.     #set to a new dict
  34.     transform = transformMoney(A[0:key],A[key])
  35.     #sum two dictionariies with same key and convert to a dict
  36.     initial = dict(Counter(initial) + Counter(transform))
  37.     results.append(initial.copy())
  38. #format result readable
  39. lenResults = len(results)
  40. for i in range(lenResults):
  41.     for key in list(results[i]):
  42.         results[i][A[key]] = results[i].pop(key)
  43. print(results)
Parsed in 0.019 seconds