Advertisement
Guest User

Algorithms Question 5

a guest
Jul 21st, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.32 KB | None | 0 0
  1. import sys
  2. import random
  3.  
  4. # My solution from the exam
  5. def calc(coins, total):
  6.     c = [1] + [0] * total
  7.     for coin in coins:
  8.         for j in range(total-coin+1):
  9.             c[j+coin]+=c[j]
  10.     return c[total]
  11.  
  12.  
  13. # Solution from Extended Intro to Computer Science
  14. # http://nbviewer.jupyter.org/github/taucsrec/recitations/blob/master/2018a/Michal/rec7/rec7_new.ipynb
  15. def change_fast(amount, coins):
  16.     d = {}
  17.     return change_mem(amount, coins, d)
  18.  
  19. def change_mem(amount, coins, d):
  20.     if amount == 0:
  21.         return 1
  22.     elif amount < 0 or coins == []:
  23.         return 0
  24.     #if (amount, tuple(coins)) not in d:
  25.     if (amount, len(coins)) not in d:
  26.         #d[(amount, tuple(coins))] = \
  27.         d[(amount, len(coins))] = \
  28.             change_mem(amount, coins[:-1], d) +\
  29.             change_mem(amount - coins[-1], coins, d)
  30.     #return d[(amount, tuple(coins))]
  31.     return d[(amount, len(coins))]
  32.  
  33.  
  34. # Comparison function
  35. def compare(amt, coins):
  36.     return calc(coins, amt) == change_fast(amt, coins)
  37.  
  38. sys.setrecursionlimit(20000)
  39.  
  40. # Samples
  41. for k in range(25):
  42.     test = (random.randint(1,20000), sorted(random.sample(range(1, 100), random.randint(1,10))))
  43.     print("Running test: " + str(test))
  44.     r = compare(test[0], test[1])
  45.     print("\tResult: " + str(r))
  46.     if (not r):
  47.         break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement