我编制了一个程序来称重一袋钱,并计算出袋子里是否有太多/小硬币,以及两者之间的差别。
bagWeight = 0
totalCoinsAdd = 0
totalCoinsRemoved = 0
totalBagsChecked = 0
def inputs():
global bagWeight
global totalCoinsAdd
global totalCoinsRemoved
#The above grabs the global variables for use in the function
bagWeight = int(input("How much does the bag weigh? "))
denomination = ""
denom = ['0.01', '0.02', '0.05', '0.10', '0.20', '0.50', '1', '2']
while denomination not in denom:
denomination = input("What denomination is the money? £")
idealWeight = { '2' : 120, '1' : 190, '0.50' : 160, '0.20' : 250, '0.10' : 325, '0.05' : 325, '0.02' : 356, '0.01' : 356, }
#This dictionary stores the ideal weight of each bag.
bagCoins = { '2' : 10, '1' : 20, '0.50' : 20, '0.20' : 50, '0.10' : 50, '0.05' : 100, '0.02' : 50, '0.01' : 100, }
#This dictionary stores how many coins are in each bag.
coinWeight = { '2' : 12, '1' : 9.5, '0.50' : 8, '0.20' : 5, '0.10' : 6.5, '0.05' : 3.25,'0.02' : 7.12, '0.01' : 3.56, }
#This dictionary stores how much the 1 of each coin weighs. The values are in grams.
AddCoins = True #This defines a variable for whether to add/remove coins.
differentWeight = idealWeight[denomination] - bagWeight
#This calculation works out how the difference in weight between the 'ideal' bag weight and the actual bag weight.
coinInBag = bagWeight/coinWeight[denomination]
#This calculation works out how many coins are in each bag. It does this by, dividing the bag weight by how much each coin weighs.
coinChange = bagCoins[denomination] - coinInBag
#Calculating the amount of coin difference in the bag
if differentWeight < 0:
AddCoins = False
differentWeight = differentWeight * -1
coinChange = coinChange * -1
if AddCoins == True:
print('The bag is ',str(differentWeight), 'g less than it should be')
print('Add ', int(coinChange), ' coin(s)')
totalCoinsAdd = totalCoinsAdd + coinChange
if AddCoins == False:
print('The bag is ',str(differentWeight), 'g more than it should be')
print('Remove ', int(coinChange), ' coin(s)')
totalCoinsRemoved = totalCoinsRemoved + coinChange
again = 'yes'
while again != 'no':
inputs()
totalBagsChecked = totalBagsChecked + 1
again = input('Would you like to weight another bag? ("no" to quit)')
print('Total coins added: ', int(totalCoinsAdd))
print('Total coins removed: ', int(totalCoinsRemoved))
print('Total bags checked:', int(totalBagsChecked))发布于 2016-12-05 16:35:22
您有4个数据结构(1个list和3个字典),它们的内容需要保持同步,因为列表中的值必须是字典的键,而列表中没有的字典中的键是没有意义的。
如果你只有一个真理的单一来源,事情可能会更清楚。例如,您可以有一个到idealWeight、bagCoins和coinWeight的单字典映射值(不管它的意思是什么)。Python通过元组或名称s提供了简单的实现方法。
FOr实例,您可以执行如下操作:
from collections import namedtuple
bagWeight = 0
totalCoinsAdd = 0
totalCoinsRemoved = 0
totalBagsChecked = 0
CoinInfo = namedtuple('CoinInfo', ['idealWeight', 'bagCoins', 'coinWeight'])
COINS = {
'2': CoinInfo(120, 10, 12),
'1': CoinInfo(190, 20, 9.5),
'0.50': CoinInfo(160, 20, 8),
'0.20': CoinInfo(250, 50, 5),
'0.10': CoinInfo(325, 50, 6.5),
'0.05': CoinInfo(325, 100, 3.25),
'0.02': CoinInfo(356, 50, 7.12),
'0.01': CoinInfo(356, 100, 3.36),
}
def inputs():
global bagWeight
global totalCoinsAdd
global totalCoinsRemoved
#The above grabs the global variables for use in the function
bagWeight = int(input("How much does the bag weigh? "))
denomination = ""
while denomination not in COINS:
denomination = input("What denomination is the money? £")
coin = COINS[denomination]
AddCoins = True #This defines a variable for whether to add/remove coins.
differentWeight = coin.idealWeight - bagWeight
#This calculation works out how the difference in weight between the 'ideal' bag weight and the actual bag weight.
coinInBag = bagWeight/coin.coinWeight
#This calculation works out how many coins are in each bag. It does this by, dividing the bag weight by how much each coin weighs.
coinChange = coin.bagCoins - coinInBag
#Calculating the amount of coin difference in the bagAddCoinss变量注释This defines a variable for whether to add/remove coins.非常冗长,可以是一个简单的Add/remove coins。
顺便说一句,这里有一个叫做PEP 8的风格指南,它非常值得一读,如果你没有任何理由不去读它(遗留项目、公司代码风格等等),它是值得一读的。除其他外,它还指出snake_case应该用于变量(而不是CamelCase)。
另外,我们以后检查它的方式可以改进,原因有两个:
if var (resp )。( if not var)而不是if var == True (resp.if var == False)。在现实生活中,你会说“如果下雨”,而不是“如果真的下雨”。if AddCoins == True,然后在if AddCoins == False之后检查,而不更改AddCoins的值。这正是else关键字的作用所在。它使代码对读者来说更加清晰,因为乍一看,我们将只通过一个块。到目前为止,我们已经:
add_coins = True # Whether to add/remove coins.
if differentWeight < 0:
add_coins = False
differentWeight = differentWeight * -1
coinChange = coinChange * -1
if add_coins :
print('The bag is ',str(differentWeight), 'g less than it should be')
print('Add ', int(coinChange), ' coin(s)')
totalCoinsAdd = totalCoinsAdd + coinChange
else:
print('The bag is ',str(differentWeight), 'g more than it should be')
print('Remove ', int(coinChange), ' coin(s)')
totalCoinsRemoved = totalCoinsRemoved + coinChange现在,这个变量一点也不有用,因为我们正在执行真正重要的测试(differentWeight < 0),我们可以直接在这里处理不同的处理。
此外,在这里,变量名也可以改进,您可以使用var *= -1而不是var = var * -1。
代码看起来应该是:
if different_weight < 0:
different_weight *= -1
coinChange *= -1
print('The bag is ',str(different_weight), 'g more than it should be')
print('Remove ', int(coinChange), ' coin(s)')
totalCoinsRemoved = totalCoinsRemoved + coinChange
else:
print('The bag is ',str(different_weight), 'g less than it should be')
print('Add ', int(coinChange), ' coin(s)')
totalCoinsAdd = totalCoinsAdd + coinChange正如马蒂亚斯·埃廷格的S评论所指出的,您最好完全去掉乘法,在打印时只考虑负值:
if different_weight < 0:
print('The bag is ',str(-different_weight), 'g more than it should be')
print('Remove ', int(-coinChange), ' coin(s)')
totalCoinsRemoved = totalCoinsRemoved - coinChange
else:
print('The bag is ',str(different_weight), 'g less than it should be')
print('Add ', int(coinChange), ' coin(s)')
totalCoinsAdd = totalCoinsAdd + coinChangePython提供了不同的格式化字符串的方法,向print提供多个参数并不是最喜欢的方法。您可以在网上找到关于字符串格式设置的文档,但是可以找到pyformat.info提供了一个非常好的摘要。
使用此方法,您可以编写如下内容:
if different_weight < 0:
print('The bag is {}g more than it should be'.format(-different_weight))
print('Remove {} coin(s)'.format(-coinChange))
totalCoinsRemoved = totalCoinsRemoved - coinChange
else:
print('The bag is {}g less than it should be'.format(different_weight))
print('Add {} coin(s)'.format(coinChange))
totalCoinsAdd = totalCoinsAdd + coinChange
again = 'yes'
while again != 'no':
inputs()
totalBagsChecked = totalBagsChecked + 1
again = input('Would you like to weight another bag? ("no" to quit)')
print('Total coins added: {}'.format(totalCoinsAdd))
print('Total coins removed: {}'.format(totalCoinsRemoved))
print('Total bags checked: {}'.format(totalBagsChecked))一般来说,使用全局变量是个坏主意,它往往表明代码的组织方式存在问题。
无论如何,bagWeight不需要是一个全局变量。
发布于 2016-12-06 11:49:29
我想说的是,你应该把这些清单合并成一个。例如
coins = {'1p':[356,3.56,0.01]}所有的硬币都可以这样做。最后的价值等于硬币的货币价值(以英镑为单位)。
这就是我的例子:
#A variable to count the number of bags processsed
count = 0
#The function to check the weights of the bags and display the number of coins needed to be added or removed
def check(bag_weight, coin_type, bag_weight1):
#import the variable 'count' into the function
global count
#Add 1 to the number of bags counted
count = count+1
#Find the maximum number of coins allowed in the bag
x = bag_weight1[coin_type]
y = x[1]
#Check if the bag exceeds the maximum weight allowed
if bag_weight > y:
#If it does take the maximum away from the actual weight and display how much too heavy the bag is
print("you have",int(bag_weight - y), "too many coins")
else:
#Otherwise take the actual weight from the maximum weight and display number of coins needed to be added
print("you need to add",int(y - bag_weight), "coins")
#Starting function to get all necassary information for calculation to begin
def main():
#Forever iterate through this loop
while True:
#Display the number of bags already checked
print("you have checked", count, "bags.")
#Ask if the user wants to weigh a bag
y = input('do you want to check a bag?(Y/N)')
#If answer is yes continue, other wise jump to the 'else' statement
if y.lower() == 'y':
#Get user to input the weight of the bag
weight = float(input('how heavy is the bag(grams)?'))
#Dictionary of lists containing vital information about the different types of coin the format: weight of coin, maximum number of coins allowed in the bag
coin_Weight = {'1p':[3.56, 100],'2p':[7.12, 50],'5p':[3.25,100],'10p':[6.5, 50],'20p':[5.0, 50],'50p':[8.00, 20],'£1':[9.50, 20],'£2':[12.00, 10]}
#Input the type of coin in the bag
coin_type = input('what type of coin is it?(1p, 2p, 5p, 10p, 20p, 50p, £1, £2)')
#Get the corresponding list of information from the dictionary about the coin
bag_weight1 = coin_Weight[coin_type]
#Divide the actual weight of the bag by the weight of one coin to find the number of coins in each bag
bag_weight = weight/bag_weight1[0]
#Output the number of coins in the bag allong with the type of coin
print('there are', int(bag_weight), coin_type, 'coins in the bag.')
#Initiate further calculation by passing the following arguments into the function 'check'
check(bag_weight, coin_type, coin_Weight)
#If the user answered 'no' continue into this part of the loop
else:
#Print a message thanking the user for using the program
print("Thank you for using this program.")
#Break out of the loop
break
#Call the function 'main' to begin the program
main()https://codereview.stackexchange.com/questions/148994
复制相似问题