Python if condition for print or not print - python

Here is a basic math problem. I want to calculate least amount of banknotes to be paid.
Here is my code and working well.
total_payment = int(input("Please enter the total amount: "))
Dollar50 = int(total_payment // 50)
remaining_money = total_payment % 50
Dollar20 = int(remaining_money // 20)
remaining_money = remaining_money % 20
Dollar10 = int(remaining_money // 10)
remaining_money = remaining_money % 10
Dollar5 = int(remaining_money // 5)
remaining_money = remaining_money % 5
Dollar1 = int(remaining_money // 1)
print("We need {0} 50 dollar.".format(Dollar50))
print("We need {0} 20 dollar.".format(Dollar20))
print("We need {0} 10 dollar.".format(Dollar10))
print("We need {0} 5 dollar.".format(Dollar5))
print("We need {0} 1 dollar.".format(Dollar1))
But i want to print only if that type of banknote is used. For example if total amount is 101 dollar than program prints
We need 2 50 dollar.
We need 0 20 dollar.
We need 0 10 dollar.
We need 0 5 dollar.
We need 1 1 dollar.
But i dont want to print the ones with 0 value. I only want it to print
We need 2 50 dollar.
We need 1 1 dollar.
This was an example of my struggle. I can not code this kind of loops or conditions. Thank you very much for any help.

Instead of writing an if statement for all of these just zip them together and use a for loop:
counts = [Dollar50, Dollar20, Dollar10, Dollar5, Dollar1]
ammounts = [50, 20, 10, 5, 1]
for i, j in zip(counts, ammounts):
if i:
print("We need {} {} dollar.".format(i, j))

All you need is an if condition.
As an exercise, you should try to write DRY code. Using loops and lists would look like this
face_values = [50, 20, 10, 5, 1]
amounts = [0]*5
remaining_money = int(input("Please enter the total amount: "))
# While you have money left, calculate the next most 'dollar_value' you can use
i = 0 # This is an index over the 'dollars' list
while remaining_money > 0:
d = face_values[i]
amounts[i] = remaining_money // d
remaining_money %= d
i+=1
denomination = "dollar bill"
denomination_plural = denomination + "s"
# Iterate both values and amounts together and print them
for val, amount in zip(face_values, amounts):
if amount == 1: # Filter out any non-positive amounts so you don't show them
print("We need {} {} {}.".format(val, amount, denomination))
else if amount > 1:
print("We need {} {} {}.".format(val, amount, denomination_plural))

Use
if Dollar50:
print("We need {0} 50 dollar.".format(Dollar50))
if the value is 0, it won't print anything.

Speaking simplistically, just add an if statement around each print statement checking for a 0.
if Dollar50 != 0:
print("We need {0} 50 dollar.".format(Dollar50))
if Dollar20 != 0:
print("We need {0} 20 dollar.".format(Dollar20))
Continue that for each item.

Related

Check if variable changes in for loop in Python

I have this code here and I'm looking for a way to check if min_score and max_score changes, and count how many times it changes. I can't seem to find a way to do it:
games = int(input())
score = list(input().split())
score = [int(x) for x in score]
for y in range(1, len(score) + 1):
min_score = (str(min(score[:y])) + " MIN")
max_score = (str(max(score[:y])) + " MAX")
print(min_score)
print(max_score)
This is a sample test case for reference:
9
10 5 20 20 4 5 2 25 1
First number is the size of the array, which in my code I never use because I make an array just from the string of numbers below ( in fact I don't even know why they give the size).
Basically I need to find how many times the max and min values change. I'm still a beginner in programming and I don't really know what to do..
you could just keep track of the lowest and highest number encountered and check if the current score is just below or above. A simple script could look like this:
scores = [10,5,20,20,4,5,2,25,1]
countChanges = 0
limitLow = float("inf")
limitHigh = -float("inf")
for s in scores:
if(s < limitLow):
countChanges += 1
limitLow = s
if(s > limitHigh):
countChanges += 1
limitHigh = s
print("current score: %3d limits: [%2d .. %2d] changes:%d" % (s, limitLow, limitHigh, countChanges))
spam = [10, 5, 20, 20, 4, 5, 2, 25, 1]
print(sum(n < min(spam[:idx]) for idx, n in enumerate(spam[1:], start=1)))
print(sum(n > max(spam[:idx]) for idx, n in enumerate(spam[1:], start=1)))
output
4
2
if you also want to account for initial value - add 1.
Looks like a hankerrank problem? They often give the length of the input to allow solutions without knowing about built-in methods like len().
Anyway,
You can initialise min and max to the first element of the array (if it exists, check the specification), or some suitably small and large values (again, check the possible values).
Then you can count the number of times min and max changes as you go.
Should be easy enough to adapt for the case that you just want to track any change, not min and max separately. It wasn't clear from your question.
scores = [10, 5, 20, 20, 4, 5, 2, 25, 1]
min_score = scores[0]
max_score = scores[0]
min_score_changes = 0
max_score_changes = 0
for score in scores:
if score < min_score:
min_score = score
min_score_changes += 1
if score > max_score:
max_score = score
max_score_changes += 1
I solved it like this after some thinking:
games = int(input())
score = list(input().split())
score = [int(x) for x in score]
min_score_list, max_score_list = [] , []
for y in range(1, len(score) + 1):
min_score = (min(score[:y]))
max_score = (max(score[:y]))
if min_score not in min_score_list:
min_score_list.append(min_score)
if max_score not in max_score_list:
max_score_list.append(max_score)
print((len(max_score_list) - 1), len(min_score_list) - 1)
I know it's not perfect code but at least I did myself :D

How to change this code to not printing unused coin=0?

I am trying to build a function that after people entering the amount of money, it will show the minimum number of coins or notes that they need. But this there any methods for me to change it so that it will not print the name and the number of the unused coin? (as a beginner) Thanks for helping! (Will it be possible to deal with it by using for loop?)
Instead of keeping a variable for every demonmation, keep a dict and update key: val based on the denominations used. See the code
amount=int(input('Enter an amount: '))
denominations = dict()
print('Total number of notes/coins=')
if amount>=1000:
denominations['1000'] = amount//1000
amount%=1000
if amount>=500:
denominations['500'] = amount//500
amount= amount%500
if amount>=100:
denominations['100'] = amount//100
amount= amount%100
if amount>=50:
denominations['50'] = amount//50
amount= amount%50
if amount>=20:
denominations['20'] = amount//20
amount= amount%20
if amount>=10:
denominations['10'] = amount//10
amount= amount%10
if amount>=5:
denominations['5'] = amount//5
amount= amount%5
if amount>=2:
denominations['2'] = amount//2
amount= amount%2
if amount>=1:
denominations['1'] = amount//1
for key, val in denominations.items():
print(f"{key}: {val}")
Enter an amount: 523
Total number of notes/coins=
500: 1
20: 1
2: 1
1: 1
You can reduce the number of lines of code if you use a simple logic like shown below,
def find_denominations():
amount=int(input('Enter an amount: '))
denominations = dict()
DENOMINATIONS = [1000, 500, 100, 50, 20, 10, 5, 2, 1]
print('Total number of notes/coins=')
for d in DENOMINATIONS:
if amount >= d:
denominations[d] = amount // d
amount %= d
for key, val in denominations.items():
print(f"{key}: {val}")
A similiar implementation to Sreerams using a while loop instead a for loop:
amount = int(input("Enter an amount: "))
counter = amount
pos = 0
notes = [1000, 500, 100, 50, 20, 10, 5, 2, 1]
output = []
while counter > 0:
remainder = counter % notes[pos]
sub = counter - remainder
num = int(sub / notes[pos])
counter -= sub
output.append({notes[pos]: num})
pos += 1
print("Total number of notes/coins=")
for r in output:
for k,v in r.items():
if v > 0:
print("{}: {}".format(k, v))
Please note Sreerams code is superior to mine, it's easier to read and would be more performant at scale.
Loop can be used iterate through a list of notes and inside the loop, if any note is found to be counted, that can be printed.
notes=[1000,500,100,50,20,10,5,2,1]
amount=int(input('Enter an amount: '))
print('Total number of notes/coins=')
for notesAmount in notes:
if amount>=notesAmount:
notesCount=amount//notesAmount
amount%=notesAmount
if notesCount>0:
print(notesAmount, ":", notesCount)

Trying to find how often a dice roll result occurs in a list of randomly rolled n-sided dice

I am trying to find the occurrences of each number for sides going 1 up to the number of sides on a dice roll. I would like the program to find the number of occurrences for each number that is in listRolls.
Example: if there were a 6 sided dice then it would be 1 up to 6 and the list would roll the dice x amount of times and I would like to find how many times the dice rolled a 1 so on and so forth.
I am new to python and trying to learn it! Any help would be appreciated!
import random
listRolls = []
# Randomly choose the number of sides of dice between 6 and 12
# Print out 'Will be using: x sides' variable = numSides
def main() :
global numSides
global numRolls
numSides = sides()
numRolls = rolls()
rollDice()
counterInputs()
listPrint()
def rolls() :
# for rolls in range(1):
###################################
## CHANGE 20, 50 to 200, 500 ##
##
x = (random.randint(20, 50))
print('Ran for: %s rounds' %(x))
print ('\n')
return x
def sides():
# for sides in range(1):
y = (random.randint(6, 12))
print ('\n')
print('Will be using: %s sides' %(y))
return y
def counterInputs() :
counters = [0] * (numSides + 1) # counters[0] is not used.
value = listRolls
# if value >= 1 and value <= numSides :
# counters[value] = counters[value] + 1
for i in range(1, len(counters)) :
print("%2d: %4d" % (i, value[i]))
print ('\n')
# Face value of die based on each roll (numRolls = number of times die is
thrown).
# numSides = number of faces)
def rollDice():
i = 0
while (i < numRolls):
x = (random.randint(1, numSides))
listRolls.append(x)
# print (x)
i = i + 1
# print ('Done')
def listPrint():
for i, item in enumerate(listRolls):
if (i+1)%13 == 0:
print(item)
else:
print(item,end=', ')
print ('\n')
main()
Fastest way (I know of) is using Counter() from collections (see bottom for dict-only replacement):
import random
from collections import Counter
# create our 6-sided dice
sides = range(1,7)
num_throws = 1000
# generates num_throws random values and counts them
counter = Counter(random.choices(sides, k = num_throws))
print (counter) # Counter({1: 181, 3: 179, 4: 167, 5: 159, 6: 159, 2: 155})
collections.Counter([iterable-or-mapping])) is a specialized dictionary that counts the occurences in the iterable you give it.
random.choices(population, weights=None, *, cum_weights=None, k=1) uses the given iterable (a range(1,7) == 1,2,3,4,5,6 and draws k things from it, returning them as list.
range(from,to[,steps]) generates a immutable sequence and makes random.choices perform even better then when using a list.
As more complete program including inputting facecount and throw-numbers with validation:
def inputNumber(text,minValue):
"""Ask for numeric input using 'text' - returns integer of minValue or more. """
rv = None
while not rv:
rv = input(text)
try:
rv = int(rv)
if rv < minValue:
raise ValueError
except:
rv = None
print("Try gain, number must be {} or more\n".format(minValue))
return rv
from collections import Counter
import random
sides = range(1,inputNumber("How many sides on the dice? [4+] ",4)+1)
num_throws = inputNumber("How many throws? [1+] ",1)
counter = Counter(random.choices(sides, k = num_throws))
print("")
for k in sorted(counter):
print ("Number {} occured {} times".format(k,counter[k]))
Output:
How many sides on the dice? [4+] 1
Try gain, number must be 4 or more
How many sides on the dice? [4+] a
Try gain, number must be 4 or more
How many sides on the dice? [4+] 5
How many throws? [1+] -2
Try gain, number must be 1 or more
How many throws? [1+] 100
Number 1 occured 22 times
Number 2 occured 20 times
Number 3 occured 22 times
Number 4 occured 23 times
Number 5 occured 13 times
You are using python 2.x way of formatting string output, read about format(..) and its format examples.
Take a look at the very good answers for validating input from user: Asking the user for input until they give a valid response
Replacement for Counter if you aren't allowed to use it:
# create a dict
d = {}
# iterate over all values you threw
for num in [1,2,2,3,2,2,2,2,2,1,2,1,5,99]:
# set a defaultvalue of 0 if key not exists
d.setdefault(num,0)
# increment nums value by 1
d[num]+=1
print(d) # {1: 3, 2: 8, 3: 1, 5: 1, 99: 1}
You could trim this down a bit using a dictionary. For stuff like dice I think a good option is to use random.choice and just draw from a list that you populate with the sides of the dice. So to start, we can gather rolls and sides from the user using input(). Next we can use the sides to generate our list that we pull from, you could use randint method in place of this, but for using choice we can make a list in range(1, sides+1). Next we can initiate a dictionary using dict and make a dictionary that has all the sides as keys with a value of 0. Now looks like this d = {1:0, 2:0...n+1:0}.From here now we can use a for loop to populate our dictionary adding 1 to whatever side is rolled. Another for loop will let us print out our dictionary. Bonus. I threw in a max function that takes the items in our dictionary and sorts them by their values and returns the largest tuple of (key, value). We can then print a most rolled statement.
from random import choice
rolls = int(input('Enter the amount of rolls: '))
sides = int(input('Enter the amound of sides: '))
die = list(range(1, sides+1))
d = dict((i,0) for i in die)
for i in range(rolls):
d[choice(die)] += 1
print('\nIn {} rolls, you rolled: '.format(rolls))
for i in d:
print('\tRolled {}: {} times'.format(i, d[i]))
big = max(d.items(), key=lambda x: x[1])
print('{} was rolled the most, for a total of {} times'.format(big[0], big[1]))
Enter the amount of rolls: 5
Enter the amound of sides: 5
In 5 rolls, you rolled:
Rolled 1: 1 times
Rolled 2: 2 times
Rolled 3: 1 times
Rolled 4: 1 times
Rolled 5: 0 times
2 was rolled the most, for a total of 2 times

How to turn money (in pence) to its individual coins?

My task was to
'Write a function selectCoins that asks the user to enter an amount of money
(in pence) and then outputs the number of coins of each denomination (from £2 down
to 1p) that should be used to make up that amount exactly (using the least possible
number of coins). For example, if the input is 292, then the function should report:
1 × £2, 0 × £1, 1 × 50p, 2 × 20p, 0 × 10p, 0 × 5p, 1 × 2p, 0 × 1p. (Hint: use integer
division and remainder).'
def selectCoins():
twopound = 200
onepound = 100
fiftyp = 50
twentyp = 20
tenp = 10
fivep = 5
twop = 2
onep = 1
a = 0
b = 0
c = 0
d = 0
e = 0
f = 0
g = 0
h = 0
money = int(input('Enter how much money you have in pence'))
while True:
if money >= twopound:
money = money - twopound
a = a + 1
elif money >= onepound:
money = money - onepound
b = b + 1
elif money >= fiftyp:
money = money - fiftyp
c = c + 1
elif money >= twentyp:
money = money - twentyp
d = d + 1
elif money >= tenp:
money = money - tenp
e = e + 1
elif money >= fivep:
money = money - fivep
f = f + 1
elif money >= twop:
money = money - twop
g = g + 1
elif money >= onep:
money = money - onep
h = h + 1
else:
money = 0
break
print(a,b,c,d,e,f,g,h)
I am new to programming so when I run this code it just inputs
'1 0 0 0 0 0 0 0' when I type 292 instead of what it should output.
Since you're new to coding, you should start writing the procedure you'd follow on paper, and then find out which tools you can use to automate this process.
Important
Read the full answer in order!
Don't fall for the temptation of reading the code right away.
The solutions I provide are hidden, but you can read them hovering your mouse over them or clicking on them (if you're using StackExchange mobile app, touch the "spoiler" link in each block).
The algorithm
What I'd do is:
Assume I have bins with coins, each bin labeled with the coin denomination.
The bins are sorted from the largest to the lowest denomination, and I always pick as much coins as I need from the highest denomination bin before moving to the next bin.
Write in a piece of paper the value for which I need to calculate the number of coins of each denomination I need.
Start with the first bin (the one holding the highest denomination).
Pick as many coins I need from that bin, in such a way that I don't "overshoot" the amount written on the piece of paper (notice that this number can be zero).
This can be done with an integer division; for example, if your value is 700 and the bin has denomination 200, you calculate the integer division 700 ÷ 200 = 3 (plus a remainder of 100)
Calculate the total amount of the coins I've picked.
Strike the value calculated in step 5 and write the remainder as a "new" value.
Since you've already calculated the integer division in step 4, you can calculate the remainder. You can also consider that there's a "Modulo" operator in most programming languages that will give you the remainder of an integer division right away. Using the above example, 700 mod 200 = 100, which reads "700 modulo 200 is 100", or "The remainder of the integer division 700 ÷ 200 is 100".
Move on to the next bin of coins.
Repeat from step 4 until I use all the bins or the value is zero.
Example
Suppose I start with a value of 292 and I have bins with the following denominations (already sorted from highest to lowest denominations):
| 200 | 100 | 50 | 20 | 10 | 5 | 2 | 1 |
+------+------+------+------+------+------+------+------+
| I | II | III | IV | V | VI | VII | VIII |
So, let's see what happens if I apply the algorithm above:
Write the value: 292
Start with the first bin (denomination: 200)
Pick 1 coin from the bin
The total amount picked from the bin is 200
The remainder is 92
Strike the previous value
The new value is 92
Move to the next bin (denomination: 100)
Pick 0 coins from the bin
The total amount picked from the bin is 0
The remainder is 92
Strike the previous value
The new value is 92
Move to the next bin (denomination: 50)
Pick 1 coin from the bin
The total amount picked from the bin is 50
The remainder is 42
Move to the next bin (denomination: 20)
Pick 2 coins from the bin
The total amount picked from the bin is 20
The remainder is 2
Move to the next bin (denomination: 10)
Pick 0 coins from the bin
The total amount picked from the bin is 0
The remainder is 2
Move to the next bin (denomination: 10)
Pick 0 coin from the bin
The total amount picked from the bin is 0
The remainder is 2
Move to the next bin (denomination: 5)
Pick 0 coin from the bin
The total amount picked from the bin is 0
The remainder is 2
Move to the next bin (denomination: 2)
Pick 1 coin from the bin
The total amount picked from the bin is 2
The remainder is 0
Done
Implementing this in Python
Python is an amazingly clear language, and makes this sort of tasks easy. So let's try to translate our algorithm to Python.
The toolbox
Assuming you're using Python 3.x, you'll need to know some operators:
The integer division operator (//): If you divide with just a single slash, you'll get the "real division" (e.g. 3 / 2 == 1.5), but if you use a double slash, you'll get the "integer division (e.g. 3 // 2 = 1)
The modulo operator (%): As explained above, this operator returns the remainder of a division (e.g. 7 % 4 == 3)
Used together, these operators will give you what you need on each step:
292 // 200 == 2
292 % 200 == 92
92 // 100 == 0
92 % 100 == 92
...
One useful characteristic of Python is that you can perform a "multiple assignment": You can assign multiple values to multiple variables in one single step:
# Initialize the value:
value = 292
# Initialize the denomination:
denomination = 200
# Calculate the amount of coins needed for the specified denomination
# and get the remainder (overwriting the value), in one single step:
coins, value = value // denomination, value % denomination
# ^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^
# | The remainder
# The number of coins
# (using integer division)
With this knowledge, we can write the solution:
Correcting your code
Remember: Read all of the above before revealing the solutions below.
def selectCoins():
twopound = 200
onepound = 100
fiftyp = 50
twentyp = 20
tenp = 10
fivep = 5
twop = 2
onep = 1
a = 0
b = 0
c = 0
d = 0
e = 0
f = 0
g = 0
h = 0
money = int(input('Enter how much money you have in pence')) # Example: 292
# Calculate the number of coins needed and the remainder
# The remainder will "overwrite" the value previously held in the "money" variable
a, money = money // twopound, money % twopound # a = 1, money = 92
b, money = money // onepound, money % onepound # b = 0, money = 92
c, money = money // fiftyp, money % fiftyp # c = 1, money = 42
d, money = money // twentyp, money % twentyp # d = 2, money = 2
e, money = money // tenp, money % tenp # e = 0, money = 2
f, money = money // fivep, money % fivep # f = 0, money = 2
g, money = money // twop, money % twop # g = 1, money = 0
e, money = money // onep, money % onep # e = 0, money = 0
print(a,b,c,d,e,f,g,h)
This solution uses both integer division and remainder to perform the calculations.
Let's do it the right way: with a loop
Let's face it: the above code is verbose. There must be a better way... and there is! Use a loop.
Consider the algorithm: you repeat the steps jumping from one bin to the next and getting the number of coins you need and the remainder. This can be written in a loop.
So, let's add a list to our toolbox:
denominations = [200, 100, 50, 20, 10, 5, 2, 1]
And let's store the results of each step in a second list:
coins = [] # We'll use the '.append()' method to add elements to this list
So, starting in the first "bin":
n, money = money // denominations[0] , money % denominations[0]
coins.append(n)
Let's put this in a loop:
def select_coins_v2():
denominations = [200, 100, 50, 20, 10, 5, 2, 1]
coins = []
money = int(input('Enter how much money you have in pence'))
for i in range(len(denominations)):
n, money = money // denominations[i], money % denominations[i]
coins.append(n)
print(coins)
And that's it!
Another improvement: get the denomination only once and use it twice
Notice that the code above still has an issue: you read denominations twice. It would be nice if the denomination value could be read only once.
Of course, there is a way:
def select_coins_v3():
denominations = [200, 100, 50, 20, 10, 5, 2, 1]
coins = []
money = int(input('Enter how much money you have in pence'))
for d in denominations: # 'd' will hold the value of the denomination
n, money = money // d, money % d
coins.append(n)
print(coins)
As a friend of mine says: "Fast, precise and concise; not slow, difuse and confusing"
TL;DR
In Python 3.x, the "integer division" operator is // and the remainder (modulo) operator is %.
You can perform multiple assignement in a single line of code:
a, b = 1, 2
You can store the denominations in a list:
denominations = [200, 100, 50, 20, 10, 5, 2, 1]
You can read from the denominations list and get both the integer division and the remainder in a single step:
n, money = money // denominations[0], money % denominations[0]
You can write a loop that does all of the above:
for d in denominations: n, money = money // d, money % d
Bonus: Use a dictionary
What if I want to print both the denominations and the number of coins of each denomination I used? You can traverse both lists with a loop, but you can also keep it simple by using a dictionary:
def select_coins_v4():
denominations = [200, 100, 50, 20, 10, 5, 2, 1]
coins = []
money = int(input('Enter how much money you have in pence'))
for d in denominations: # 'd' will hold the value of the denomination
n, money = money // d, money % d
coins.append(n)
number_of_coins = dict(zip(denominations, coins))
print(number_of_coins)
Python offers a great deal of flexibility. Feel free to try different ways of getting what you need... and choose the easier one.
Hope this helps.
the cool thing about using real denominations is that the greedy solution will always find the optimal solution ... this stops holding true with weird denominations... but these problems are always easiest if you break them into parts
def get_one_change(amt_due):
# find how many of the largest denomination that you can use is
# ie for 60 = 1x50p is the count and number of largest
# for 4 = 4x1p ; 21 = 2x10p ; etc
return pence,count # ie 50,1 would be 1 50p coin
once you have this you just need to repeatedly call it and adjust your result until you have no change due
def get_change(amount_due):
changes_due = [] # to keep track
while amount_due:
pence,qty_of_coin = get_one_change(amount_due)
changes_due.append({"coin":pence,"qty":qty_of_coin})
amount_due = amount_due - (pence*qty_of_coin)
return changes_due
now you can just call your get_change method with your users input

Python-Modulus-Stuck with a coin-for-given-dollar-amount scenario

Specs: Ubuntu 13.04, Python 3.3.1
General Background: total beginner to Python;
Question-specific background: I'm exhausted trying to solve this problem, and I'm aware that, besides its instructional value for learning Python, this problem is boring and does not in any way make this world a better place :-( So I'd be even more grateful if you could share some guidance on this exhausting problem. But really don't want to waste your time if you are not interested in this kind of problems.
What I intended to do: "Calculate the number of basic American coins given a value less than 1 dollar. A penny is worth 1 cent, a nickel is worth 5 cents, a dime is worth 10 cents,
and a quarter is worth 25 cents. It takes 100 cents to make 1 dollar. So given an amount less than 1 dollar (if using floats, convert to integers for this exercise), calculate the number of each type of coin necessary to achieve the amount, maximizing the number of larger denomination coins. For example, given $0.76, or 76 cents, the correct output would be "3 quarters and 1 penny." Output such as "76 pennies" and "2 quarters, 2 dimes, 1 nickel, and 1 penny" are not acceptable."
What I was able to come up with:
penny = 1
nickel = 5
dime = 10
quarter = 25
i = input("Please enter an amount no more than 1 dollar(in cents): ")
i = int(i)
if i > 100:
print ("Please enter an amount equal or less than 100. ")
elif i >= quarter:
quarter_n = i % quarter
i = i - quarter * quarter_n
if i >= dime:
dime_n = i % dime
i = i - dime * dime_n
if i >= nickel:
nickel_n = i % nickel
i = i - nickel * nickel_n
if i >= penny:
penny_n = i % penny
print (quarter_n,"quarters,",dime_n,"dimes",nickel_n,"nickels",penny_n,"pennies")
else:
if i >= penny:
penny_n = i % penny
print (quarter_n,"quarters,",dime_n,"dimes",penny_n,"pennies")
else:
if i >= nickel:
nickel_n = i % nickel
i = i - nickel * nickel_n
if i >= penny:
penny_n = i % penny
print (quarter_n,"quarters,",nickel_n,"nickels",penny_n,"pennies")
else:
if i >= penny:
penny_n = i % penny
print (quarter_n,"quarters,",penny_n,"pennies")
else:
if i >= dime:
dime_n = i % dime
i = i - dime * dime_n
if i >= nickel:
nickel_n = i % nickel
i = i - nickel * nickel_n
if i >= penny:
penny_n = i % penny
print (dime_n,"dimes",nickel_n,"nickels",penny_n,"pennies")
else:
if i >= penny:
penny_n = i % penny
print (dime_n,"dimes",penny_n,"pennies")
else:
if i >= nickel:
nickel_n = i % nickel
i = i - nickel * nickel_n
if i >= penny:
penny_n = i % penny
print (nickel_n,"nickels",penny_n,"pennies")
else:
if i >= penny:
penny_n = i % penny
print (penny_n,"pennies")
This solution, though the best I could come up with, does not work as expected when fed with actual input numbers. And I'm unable to figure out why. Besides, I know that even from sheer size of the code that something is wrong. I searched for similar questions but the closest I got was one that dealt with very difficult math which I couldn't understand.
My question: I know I can't ask for a complete solution because that's down to me to figure it out. I'll appreciate either a) general pointer on the correct line of thinking b) critiques to my current code/line of thinking so that I might be able to improve it.
Thank you for taking the time, even just reading this!
I think your solution may actually be working if you do a "find and replace" for all the mod operators %, switching in integer division //.
Say you have 76 cents and want to find the number of quarters. Using 76 % 25 results in 1 whereas 76 // 25 is 3.
With regard to the code, you should probably be thinking in terms of iterating over the possible coin values rather than a huge if, elif mess.
Try something like this. The only part that may need some explaining is using divmod but its really just a tuple of the integer division, modulo result. You can use that to get the number of coins and the new amount, respectively.
def coins_given(amount):
coins = [(25, 'quarter'), (10, 'dime'), (5, 'nickel'), (1, 'penny')]
answer = {}
for coin_value, coin_name in coins:
if amount >= coin_value:
number_coin, amount = divmod(amount, coin_value)
answer[coin_name] = number_coin
return answer
print coins_given(76)
# {'quarter': 3, 'penny': 1}
i think your algorithm is too complicated,
you don't need all the elifs and the elses
just check with and if and then modidy the remaining amount until you get to zero
something like this
penny = 1
nickel = 5
dime = 10
quarter = 25
q = 0
d = 0
n = 0
p = 0
i = input("Please enter an amount no more than 1 dollar(in cents): ")
i = int(i)
if i>=25:
q = i/quarter
i %= quarter
if i>=10:
d = i/dime
i%=dime
if i>=5:
n = i/nickel
i %= nickel
if i>0:
p = i/penny
i = 0
print "The coins are %i quarters, %i dimes, %i nickels and %i pennys." %(q , d, n, p)
>>>
Please enter an amount no more than 1 dollar(in cents): 99
The coins are 3 quarters, 2 dimes, 0 nickels and 4 pennys.
>>>
Please enter an amount no more than 1 dollar(in cents): 76
The coins are 3 quarters, 0 dimes, 0 nickels and 1 pennys.
dime=10
nickel=5
penny=1
quarter=25
def change(cents):
changeIs = ""
qs = cents/quarter
cents %= quarter
if qs > 0 :
changeIs += str(qs) + " quarter(s)"
ds = cents/dime
cents %= dime
if ds > 0 :
changeIs += " " + str(ds) + " dime(s)"
ns = cents/nickel
cents %= nickel
if ns > 0 :
changeIs += " " + str(ns) + " nickel(s)"
if cents > 0 :
changeIs += " " + str(cents) + " cent(s)"
return changeIs
if __name__ == '__main__':
cents=int(raw_input("Enter the change: "))
print change(cents)

Categories

Resources