473,703 Members | 3,036 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help with small program

Hello, I am a newbie with python, though I am having a lot of fun using
it. Here is one of the excersizes I am trying to complete:
the program is supposed to find the coin combination so that with 10
coins you can reach a certain amoung, taken as a parameter. Here is the
current program:

coins = (100,10,5,1,0.5 )
anslist = []
def bar(fin, hist = {100:0,10:0,5:0 ,1:0,0.5:0}):
s = sum(x*hist[x] for x in hist)
l = sum(hist.values ())
if s < fin and l < 10:
for c in coins:
if (s+c) <= fin:
hist[c] += 1
bar(fin, hist)
hist[c] -= 1
elif l==10 and s==fin and not hist in anslist:
#p1
anslist.append( hist)

bar(50)
print anslist

The problem is that if I run it, anslist prints as [{0.5: 0, 1: 0, 10:
0, 100: 0, 5: 0}], which doesnt even add up to 50. When I check how
many times the program has reached the #p1 by sticking a print there,
it only reaches it once, and it comes out correct. why is it that this
result is replaced by the incorrect final one?

Dec 24 '06 #1
9 2094
smartbei schrieb:
Hello, I am a newbie with python, though I am having a lot of fun using
it. Here is one of the excersizes I am trying to complete:
the program is supposed to find the coin combination so that with 10
coins you can reach a certain amoung, taken as a parameter. Here is the
current program:

coins = (100,10,5,1,0.5 )
anslist = []
def bar(fin, hist = {100:0,10:0,5:0 ,1:0,0.5:0}):
s = sum(x*hist[x] for x in hist)
l = sum(hist.values ())
if s < fin and l < 10:
for c in coins:
if (s+c) <= fin:
hist[c] += 1
bar(fin, hist)
hist[c] -= 1
elif l==10 and s==fin and not hist in anslist:
#p1
anslist.append( hist)

bar(50)
print anslist

The problem is that if I run it, anslist prints as [{0.5: 0, 1: 0, 10:
0, 100: 0, 5: 0}], which doesnt even add up to 50. When I check how
many times the program has reached the #p1 by sticking a print there,
it only reaches it once, and it comes out correct. why is it that this
result is replaced by the incorrect final one?
hist is stored in anslist as a pointer only, therfore the hist[c] -= 1
operates on the same dict as is stored in the anslist. Try the following
in the python interpreter:

a = { 'key' : 1 }
l = [a]
l[0]['key'] -= 1
a

instead use:

anslist.append( dict(hist.items ))

which will copy the dict.
Dec 24 '06 #2

Felix Benner wrote:
smartbei schrieb:
Hello, I am a newbie with python, though I am having a lot of fun using
it. Here is one of the excersizes I am trying to complete:
the program is supposed to find the coin combination so that with 10
coins you can reach a certain amoung, taken as a parameter. Here is the
current program:

coins = (100,10,5,1,0.5 )
anslist = []
def bar(fin, hist = {100:0,10:0,5:0 ,1:0,0.5:0}):
s = sum(x*hist[x] for x in hist)
l = sum(hist.values ())
if s < fin and l < 10:
for c in coins:
if (s+c) <= fin:
hist[c] += 1
bar(fin, hist)
hist[c] -= 1
elif l==10 and s==fin and not hist in anslist:
#p1
anslist.append( hist)

bar(50)
print anslist

The problem is that if I run it, anslist prints as [{0.5: 0, 1: 0, 10:
0, 100: 0, 5: 0}], which doesnt even add up to 50. When I check how
many times the program has reached the #p1 by sticking a print there,
it only reaches it once, and it comes out correct. why is it that this
result is replaced by the incorrect final one?

hist is stored in anslist as a pointer only, therfore the hist[c] -= 1
operates on the same dict as is stored in the anslist. Try the following
in the python interpreter:

a = { 'key' : 1 }
l = [a]
l[0]['key'] -= 1
a

instead use:

anslist.append( dict(hist.items ))

which will copy the dict.
Thanks!
BTW - its hist.items(), after that it worked.

Dec 24 '06 #3
smartbei wrote:
Felix Benner wrote:
>smartbei schrieb:
>>Hello, I am a newbie with python, though I am having a lot of fun using
it. Here is one of the excersizes I am trying to complete:
the program is supposed to find the coin combination so that with 10
coins you can reach a certain amoung, taken as a parameter. Here is the
current program:

coins = (100,10,5,1,0.5 )
anslist = []
def bar(fin, hist = {100:0,10:0,5:0 ,1:0,0.5:0}):
s = sum(x*hist[x] for x in hist)
l = sum(hist.values ())
if s < fin and l < 10:
for c in coins:
if (s+c) <= fin:
hist[c] += 1
bar(fin, hist)
hist[c] -= 1
elif l==10 and s==fin and not hist in anslist:
#p1
anslist.append( hist)

bar(50)
print anslist

The problem is that if I run it, anslist prints as [{0.5: 0, 1: 0, 10:
0, 100: 0, 5: 0}], which doesnt even add up to 50. When I check how
many times the program has reached the #p1 by sticking a print there,
it only reaches it once, and it comes out correct. why is it that this
result is replaced by the incorrect final one?
hist is stored in anslist as a pointer only, therfore the hist[c] -= 1
operates on the same dict as is stored in the anslist. Try the following
in the python interpreter:

a = { 'key' : 1 }
l = [a]
l[0]['key'] -= 1
a

instead use:

anslist.append (dict(hist.item s))

which will copy the dict.

Thanks!
BTW - its hist.items(), after that it worked.
An alternative.

cointypes = (100, 10, 5, 1, 0.5)
needed = {}

def coins(fin):
cur = fin
for c in cointypes:
v = int(cur / c)
if v 0:
needed[c] = v
cur -= v * c

if __name__ == '__main__':
coins(51)
print needed
coins(127)
print needed
Dec 25 '06 #4
Better alternative.

cointype = (100, 10, 5, 1, 0.5)

def coins(fin):
needed = {}
for c in cointypes:
v, r = divmod(fin, c)
if v 0:
needed[c] = v
fin = r
return needed

if __name__ == '__main__':
print coins(51)
print coins(127)
print coins[12.5)
Dec 25 '06 #5

"Paul Watson д
<snip>

Interesting impl in Python! I am wondering what if the requirement is
to find the minimum number of coins which added to the "fin" sum...

Dec 28 '06 #6
go****@yahoo.co m wrote:
>
Interesting impl in Python! I am wondering what if the requirement is
to find the minimum number of coins which added to the "fin" sum...
Given the set of coins in the original problem (100, 10, 5, 1, 0.5), the
solution it provides will always be optimal. Even if we change this to
American coinage (50, 25, 10, 5, 1), I believe it is still optimal.

It is certainly possible to construct a set of denominations for which the
algorithm occasionally chooses badly. For example, if you give it the set
(40,35,10) and ask it to make change for 70, it will be suboptimal.
--
Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
Dec 30 '06 #7
Tim Roberts wrote:
go****@yahoo.co m wrote:
>Interesting impl in Python! I am wondering what if the requirement is
to find the minimum number of coins which added to the "fin" sum...

Given the set of coins in the original problem (100, 10, 5, 1, 0.5), the
solution it provides will always be optimal. Even if we change this to
American coinage (50, 25, 10, 5, 1), I believe it is still optimal.

It is certainly possible to construct a set of denominations for which the
algorithm occasionally chooses badly. For example, if you give it the set
(40,35,10) and ask it to make change for 70, it will be suboptimal.
Tim,

Unless I am missing the point, the minimum number of coins from the set
available will be chosen. Surely this homework is past due by now.

$ cat coins.py
#!/usr/bin/env python
import sys

cointypes = (100, 10, 5, 1, 0.5)

def coins(fin, cointypes):
needed = {}
for c in cointypes:
v, r = divmod(fin, c)
if v 0:
needed[c] = int(v)
fin = r
return needed

def doit(fin, cointypes = cointypes):
h = coins(fin, cointypes)
print '%.1f requires %d coins in hash ' % (fin, sum(h.values()) ), h

if __name__ == '__main__':
doit(51)
doit(127)
doit(12.5)
doit(70, (40,35,10))

sys.exit(0)

$ ./coins.py
51.0 requires 6 coins in hash {1: 1, 10: 5}
127.0 requires 6 coins in hash {1: 2, 10: 2, 100: 1, 5: 1}
12.5 requires 4 coins in hash {0.5: 1, 1: 2, 10: 1}
70.0 requires 4 coins in hash {40: 1, 10: 3}
Jan 1 '07 #8
Paul Watson wrote:
It is certainly possible to construct a set of denominations for which the
algorithm occasionally chooses badly. For example, if you give it the set
(40,35,10) and ask it to make change for 70, it will be suboptimal.

Unless I am missing the point, the minimum number of coins from the set
available will be chosen. Surely this homework is past due by now.

[...]

doit(70, (40,35,10))
70.0 requires 4 coins in hash {40: 1, 10: 3}
The point was that "minimum number of coins" in this case is actually
two, but the provided algorithm yields four.

-tom!

--
Jan 1 '07 #9
"Paul Watson д
"
Tim Roberts wrote:
go****@yahoo.co m wrote:
Interesting impl in Python! I am wondering what if the requirement is
to find the minimum number of coins which added to the "fin" sum...
Given the set of coins in the original problem (100, 10, 5, 1, 0.5), the
solution it provides will always be optimal. Even if we change this to
American coinage (50, 25, 10, 5, 1), I believe it is still optimal.

It is certainly possible to construct a set of denominations for which the
algorithm occasionally chooses badly. For example, if you give it the set
(40,35,10) and ask it to make change for 70, it will be suboptimal.

Tim,

Unless I am missing the point, the minimum number of coins from the set
available will be chosen. Surely this homework is past due by now.

$ cat coins.py
#!/usr/bin/env python
import sys

cointypes = (100, 10, 5, 1, 0.5)

def coins(fin, cointypes):
needed = {}
for c in cointypes:
v, r = divmod(fin, c)
if v 0:
needed[c] = int(v)
fin = r
return needed

def doit(fin, cointypes = cointypes):
h = coins(fin, cointypes)
print '%.1f requires %d coins in hash ' % (fin, sum(h.values()) ), h

if __name__ == '__main__':
doit(51)
doit(127)
doit(12.5)
doit(70, (40,35,10))

sys.exit(0)

$ ./coins.py
51.0 requires 6 coins in hash {1: 1, 10: 5}
127.0 requires 6 coins in hash {1: 2, 10: 2, 100: 1, 5: 1}
12.5 requires 4 coins in hash {0.5: 1, 1: 2, 10: 1}
70.0 requires 4 coins in hash {40: 1, 10: 3}

To be explicit, the min coins question could be resolved with "dynamic
programming". So it is not a pure python question. No, this is not a
homework question. Well, it is somewhat academic:
http://www.topcoder.com/tc?module=St...als&d2=dynProg

I wrote the following Python implementation akin to topcoder algorithm:

#!/usr/bin/env python
default_cointyp es = (1, 3, 5)

def mincoins(fin, cointypes = default_cointyp es):
needed = {}
for c in cointypes:
needed[c] = 0
min = {}
for item in range(1, fin+1):
min[item] = 2007 # suppose 2007 is the "infinity"
min[0] = 0

for i in range(1, fin+1):
for c in cointypes:
if (c <= i and min[i-c] + 1 < min[i]):
min[i] = min[i-c] + 1
needed[c] += 1

print fin, "==>", min[fin]
print needed

if __name__ == '__main__':
mincoins(11)

Probably there are things to be improved and there could be the
pythonic way(s): Welcome your comments and ideas!
Happy new year!
Wenjie

Jan 1 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
3456
by: abcd | last post by:
kutthaense Secretary Djetvedehald H. Rumsfeld legai predicted eventual vicmadhlary in Iraq mariyu Afghmadhlaistmadhla, kaani jetvedehly after "a ljetvedehg, hard slog," mariyu vede legai pressed Pentagjetvedeh karuvificials madhla reachathe strategy in karkun campaign deshatinst terrorism. "mudivae maretu winning or losing karkun global varti jetvedeh terror?" Mr. Rumsfeld adugued in a recent memormariyuum. vede velli jetvedeh madhla...
5
2833
by: titan0111 | last post by:
#include<iostream> #include<iomanip> #include<cstring> #include<fstream> using namespace std; class snowfall { private: int ft;
5
2315
by: SStory | last post by:
Hi all, I really needed to get the icons associated with each file that I want to show in a listview. I used the follow modified code sniplets found on the internet. I have left in commented code for anyone else who may be looking to do the same.
11
1896
by: abico | last post by:
Write a program that reads in a sequence of words and prints them in reverse order.Using STACK.
21
2316
by: c | last post by:
Hi everybody. I'm working on converting a program wriiten on perl to C, and facing a problem with concatenate strings. Now here is a small program that descripe the problem, if you help me to solve in this small code, I can solve it on my own program...you don't want to have head-ache :-) So, the problem excatly is, I built an array..just like this one.
1
3135
by: Unebrion | last post by:
Alright im working on a program that prints out user imput in a frame, along with a barcode.. it is like the front of an envelope. Here is the description for the program. This part just explains a check digit.. i think this part in my program is alright These barcodes actually have four parts: a tall line as the first bar, a series of tall and short lines corresponding to the digits in the ZIP code, a check digit,...
15
2574
by: Jay | last post by:
I have a multi threaded VB.NET application (4 threads) that I use to send text messages to many, many employees via system.timer at a 5 second interval. Basically, I look in a SQL table (queue) to determine who needs to receive the text message then send the message to the address. Only problem is, the employee may receive up to 4 of the same messages because each thread gets the recors then sends the message. I need somehow to prevent...
5
2560
by: weidongtom | last post by:
Hi, I tried to implement the Universal Machine as described in http://www.boundvariable.org/task.shtml, and I managed to get one implemented (After looking at what other's have done.) But when I use to run a UM program, I kept on getting error messages. I have used someone else's implementation and it runs fine. I have compared my code with other's and I still can't figure it out what's wrong with mine. So please help me out, after 3...
0
8759
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
8670
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9122
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
6588
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5922
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4687
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3125
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2455
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2070
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.