Я новичок в программировании и пишу этот код для проекта вводного курса по программированию. Он принимает вводимые пользователем данные в долларах и выводит, сколько различных способов можно создать эти вводимые данные, используя американскую валюту. Это позволяет пользователю увидеть количество способов ввода монет, купюр или их комбинации.
Недавно я изменил свои входные параметры, чтобы разрешить ввод с плавающей запятой для представления целых долларов сдачи. Кажется, это работает, за исключением случаев, когда я вводю значения 1,09–1,16, и я не могу понять, почему. Я показал это своему профессору, и он тоже не смог разобраться (за то ограниченное время, которое у нас было в классе). Итак, теперь я публикую здесь. Я правда в растерянности, как мне это исправить? Заранее спасибо
# This code aims to inform the user of the number of possible combinations of US coin currency which sum to any user input whole dollar amount less than or equal to 10
# Set recursion limit
import sys
sys.setrecursionlimit(100000)
# Spacing
print(" ")
# Input
request = 1
# Will only break if the user inputs a whole number less than or equal to 100
while request >= 0:
# Ask for user to input the whole dollar amount they wish to see sums equal to.
USDi = (input("Hello! Welcome to the Coin Sum Answer Key. Input a number less than or equal to 10 representing an amount in USD: "))
#Define sets of unacceptable inputs: letters and symbols
azck = {"a", "A", "b", "B", "c", "C", "d", "D", "e", "E", "f", "F", "g", "G", "h", "H", "i", "I", "j", "J", "k", "K", "l", "L", "m", "M", "n", "N" "o", "O", "p", "P", "q", "Q", "r", "R", "s", "S", "t", "T", "u", "U", "v", "V", "w", "W", "x", "X", "y", "Y", "z", "Z"}
symbols = {"!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "{", "}", "[", "]", ":", ";", "'", "", ",", "?", "/", "~", "`", " "}
# Spacing
print(" ")
# If the input contains any letters or symbols
if any(letter in USDi for letter in azck) or any(symbol in USDi for symbol in symbols):
print("Error! Input is invalid.")
request += 1
# If the user inputs a number without a decimal (whole number)
elif not(any(letter in USDi for letter in azck)) and not(any(symbol in USDi for symbol in symbols)):
USDf = float(USDi)
USD = round(USDf, 2)
if USD > 10:
print("Error! Input is greater than 10")
request += 1
elif isinstance(USD, (float,int)):
print(f"You entered: ${USD:.2f}")
break
else:
print("Error! Input is invalid.")
request += 1
# Catch all- if the user inputs a value which is not covered
else:
print("Unknown Error, please try again.")
request += 1
# Coin Calculation
# Establish Coin Dictionary with coin names as keys and values as values
coinsdict = {
"Penny" : 0.01,
"Nickel" : 0.05,
"Dime" : 0.10,
"Quarter" : 0.25,
"Half Dollar" : 0.50,
"Dollar" : 1.00
}
# Spacing
print(" ")
# Print Dictionary
print("We have an unlimited amount of the following coins to make our sum: ")
for coin in coinsdict:
print(f"{coin}, ${coinsdict[coin]:.2f}")
# Establish coin - cent scale
global USDc
USDc = USD * 100
# Etsablish a list of available coin values in cents
coins = [1,5,10,25,50,100]
# Create coin counting command
def change_coins():
# Create sub-command to allow for better organization
def dpc(coin, n):
# Return values for allowable inputs which do not need computation
if USD == 0:
return 1
#There is one way to make the sum zero, which is by using no coins at all
#Establish base case for tabulation
#Do not allow for index of coin list to be higher than amount of available coins
#Do not allow for computation of negative user input (backup)
if coin >= len(coins) or n = len(bills) or n = len(combos) or n 0:
preference = input(f"You may select to see the number of ways in which to make ${USD:.2f} out of coins, bills, both individually, or a combination of both. Which would you like? \nEnter 'Coins' , 'Bills' , 'Both', 'Combo', or 'All' to see all outputs: ").strip().title()
if preference == 'Coins':
change_coins()
break
elif preference == 'Bills':
change_bills()
break
elif preference == 'Both':
change_coins()
change_bills()
break
elif preference == 'Combo':
change_combo()
break
elif preference == 'All':
change_coins()
change_bills()
change_combo()
break
else:
print("Invalid input, please try again: ")
inpt += 1
Подробнее здесь: https://stackoverflow.com/questions/798 ... 1-16-and-i
Python. Мой код подсчета монет не работает для входных данных от 1,09 до 1,16 доллара, и я не знаю, почему. ⇐ Python
Программы на Python
1762914947
Anonymous
Я новичок в программировании и пишу этот код для проекта вводного курса по программированию. Он принимает вводимые пользователем данные в долларах и выводит, сколько различных способов можно создать эти вводимые данные, используя американскую валюту. Это позволяет пользователю увидеть количество способов ввода монет, купюр или их комбинации.
Недавно я изменил свои входные параметры, чтобы разрешить ввод с плавающей запятой для представления целых долларов сдачи. Кажется, это работает, за исключением случаев, когда я вводю значения 1,09–1,16, и я не могу понять, почему. Я показал это своему профессору, и он тоже не смог разобраться (за то ограниченное время, которое у нас было в классе). Итак, теперь я публикую здесь. Я правда в растерянности, как мне это исправить? Заранее спасибо
# This code aims to inform the user of the number of possible combinations of US coin currency which sum to any user input whole dollar amount less than or equal to 10
# Set recursion limit
import sys
sys.setrecursionlimit(100000)
# Spacing
print(" ")
# Input
request = 1
# Will only break if the user inputs a whole number less than or equal to 100
while request >= 0:
# Ask for user to input the whole dollar amount they wish to see sums equal to.
USDi = (input("Hello! Welcome to the Coin Sum Answer Key. Input a number less than or equal to 10 representing an amount in USD: "))
#Define sets of unacceptable inputs: letters and symbols
azck = {"a", "A", "b", "B", "c", "C", "d", "D", "e", "E", "f", "F", "g", "G", "h", "H", "i", "I", "j", "J", "k", "K", "l", "L", "m", "M", "n", "N" "o", "O", "p", "P", "q", "Q", "r", "R", "s", "S", "t", "T", "u", "U", "v", "V", "w", "W", "x", "X", "y", "Y", "z", "Z"}
symbols = {"!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "-", "+", "=", "{", "}", "[", "]", ":", ";", "'", "", ",", "?", "/", "~", "`", " "}
# Spacing
print(" ")
# If the input contains any letters or symbols
if any(letter in USDi for letter in azck) or any(symbol in USDi for symbol in symbols):
print("Error! Input is invalid.")
request += 1
# If the user inputs a number without a decimal (whole number)
elif not(any(letter in USDi for letter in azck)) and not(any(symbol in USDi for symbol in symbols)):
USDf = float(USDi)
USD = round(USDf, 2)
if USD > 10:
print("Error! Input is greater than 10")
request += 1
elif isinstance(USD, (float,int)):
print(f"You entered: ${USD:.2f}")
break
else:
print("Error! Input is invalid.")
request += 1
# Catch all- if the user inputs a value which is not covered
else:
print("Unknown Error, please try again.")
request += 1
# Coin Calculation
# Establish Coin Dictionary with coin names as keys and values as values
coinsdict = {
"Penny" : 0.01,
"Nickel" : 0.05,
"Dime" : 0.10,
"Quarter" : 0.25,
"Half Dollar" : 0.50,
"Dollar" : 1.00
}
# Spacing
print(" ")
# Print Dictionary
print("We have an unlimited amount of the following coins to make our sum: ")
for coin in coinsdict:
print(f"{coin}, ${coinsdict[coin]:.2f}")
# Establish coin - cent scale
global USDc
USDc = USD * 100
# Etsablish a list of available coin values in cents
coins = [1,5,10,25,50,100]
# Create coin counting command
def change_coins():
# Create sub-command to allow for better organization
def dpc(coin, n):
# Return values for allowable inputs which do not need computation
if USD == 0:
return 1
#There is one way to make the sum zero, which is by using no coins at all
#Establish base case for tabulation
#Do not allow for index of coin list to be higher than amount of available coins
#Do not allow for computation of negative user input (backup)
if coin >= len(coins) or n = len(bills) or n = len(combos) or n 0:
preference = input(f"You may select to see the number of ways in which to make ${USD:.2f} out of coins, bills, both individually, or a combination of both. Which would you like? \nEnter 'Coins' , 'Bills' , 'Both', 'Combo', or 'All' to see all outputs: ").strip().title()
if preference == 'Coins':
change_coins()
break
elif preference == 'Bills':
change_bills()
break
elif preference == 'Both':
change_coins()
change_bills()
break
elif preference == 'Combo':
change_combo()
break
elif preference == 'All':
change_coins()
change_bills()
change_combo()
break
else:
print("Invalid input, please try again: ")
inpt += 1
Подробнее здесь: [url]https://stackoverflow.com/questions/79817243/python-my-coin-counting-code-doesnt-work-for-inputs-between-1-09-1-16-and-i[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия