-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdynamicprograming.py
75 lines (58 loc) · 1.85 KB
/
dynamicprograming.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 22 15:13:59 2016
@author: pengcheng
"""
def moveTower(height, fromPole, toPole, withPole):
if height>=1:
moveTower(height-1,fromPole,withPole,toPole)
moveDisk(fromPole,toPole)
moveTower(height-1,withPole,toPole,fromPole)
def moveDisk(fp,tp):
print ("moving disk from",fp,"to",tp)
moveTower(3,"A","B","C")
def recDC(coinValueList,change,knownResults):
minCoins=change
if change in coinValueList:
knownResults[change]=1
return 1
elif knownResults[change]>0:
return knownResults[change]
else:
for i in [c for c in coinValueList if c<change]:
numCoins=1+recDC(coinValueList,change-i,knownResults)
if numCoins<minCoins:
minCoins=numCoins
knownResults[change]=minCoins
# print(knownResults)
return minCoins
#print(recDC([1,5,10,25],52,[0]*64))
def dpMakeChange(coinValueList,change,minCoins,coinUsed):
for cents in range (change+1):
coinCount =cents
newCoin = 1
for j in [c for c in coinValueList if c<change]:
if minCoins[cents-j]+1<coinCount:
coinCount=minCoins[cents-j]+1
newCoin=j
minCoins[cents]=coinCount
coinUsed[cents]=newCoin
return minCoins[change]
def printCoins(coinsUsed,change):
coin = change
while coin>0:
thisCoin=coinsUsed[coin]
print(thisCoin)
coin=coin-thisCoin
def main():
amt=63
clist=[1,5,10,21,25]
coinUsed=[0]*(amt+1)
coinCount=[0]*(amt+1)
print("Making change for",amt,"requires")
print(dpMakeChange(clist,amt,coinCount,coinUsed),"coins")
print("They are:")
printCoins(coinUsed,amt)
print("The used list is as follows:")
print(coinUsed)
main()