在计算两个相同的数字时得到一个空输出,并且无法更改dict w/Regex中的键名



编辑:我能够通过添加一个条件来解决这个问题的第一部分,即如果costpaid相同,并且与money中的一个键值匹配,那么它就会将其添加到dict中。

如果标题混淆了,我很抱歉。基本上,我正在编写一个函数,它将一个数字作为项目成本,将第二个数字作为您支付的金额。然后它告诉你在纸币和硬币上的零钱。

def right_change(cost, paid):
money = {
"$20 bill" : 20,
"$10 bill" : 10,
"$5 bill" : 5,
"$1 bill": 1,
"quarter": 0.25,
"dime" : 0.10,
"nickel": 0.05,
"penny": 0.01
}
amount = paid - cost
change = {}

for item in money:
while amount >= money[item]:
amount -= money[item]
amount = float(f'{amount:.2f}')
if item not in change:
change[item] = 1
else:
change[item] += 1

当我使用诸如(5.40, 20) --> {$10 bill: 1, $1 bill: 4, quarter: 2, dime: 1}之类的浮点时,我得到了预期的输出但如果我使用像(20, 20)这样的精确数字,当我想要{$20 bill: 1}时,它将返回一个空对象

如果它们的数量超过1,我也会尝试将名称更改为复数。为了减少冗余并为每个单词键入条件,我尝试使用Regex:

def plurals(dict):
new_dict = {}
for item in dict:
if dict[item] > 1 and re.match('/[^y]$/gm', item):
new_dict[item+"s"] = dict[item]
if re.match('p', item):
new_dict['pennies'] = dict[item]
else:
new_dict[item] = dict[item]
return new_dict

它仍然会输出更改,但不会更改任何内容。感谢您的帮助!我花了好几个小时想弄清楚。

对于名称更改问题:

def set_to_plural_if_more_than_one(old_dict):
new_dict = {}
for item in old_dict:
if old_dict[item] > 1:
if item[-1] == "y":
new_dict[item[:-1] + "ies"] = old_dict[item]
else:
new_dict[item + "s"] = old_dict[item]
else:
new_dict[item] = old_dict[item]
return new_dict

您可以使用regex,但在这种情况下,我觉得这太过分了,因为您只是在区分一些您知道的基本字符串,而不搜索任何高级模式。

此外,一般情况下,我会避免在代码中将Python内置的名称(如dict(重写为变量或参数名称,因为它们可能会导致奇怪的、有时很难调试的行为。

最新更新