Py学习  »  Python

python:如何在随后的减法中使用divmod中的值

Jakob • 6 年前 • 1419 次点击  

如何将divmod除法的结果包含到简单的减法中而不面对: 类型错误:不支持-:“int”和“tuple”的操作数类型? < /P>

这里是我的代码(用python编写):。

def discount(price,quantity):
如果(价格>100):
折扣价=价格*0.9
其他:
折扣价=价格

如果(数量>10):
扣除的数量=divmod(数量,5)
折扣数量=数量-扣除数量
其他:
折扣数量=数量

#计算哪种折扣会产生更好的结果
如果(折扣价*数量<价格*折扣量):
退货(折扣价*数量)
其他:
退货(价格*折扣数量)
< /代码> 

任何帮助都非常感谢,因为我是一个初学者,我还没有找到合适的解决方案。

仅供参考,基础任务: 编写一个函数discount(),它接受(位置)参数price和quantity,并为客户订单实现一个折扣方案,如下所示。如果价格超过100美元,我们给予10%的相对折扣。如果客户订购超过10件商品,每五件商品中就有一件是免费的。然后,该函数应返回总体成本。此外,只授予两种折扣类型中的一种,以对客户更好的为准。

.

这里是我的代码(用python编写):

def discount(price, quantity): 
if (price > 100): 
    discounted_price = price*0.9
else: 
    discounted_price = price

if (quantity > 10): 
    deducted_quantity = divmod(quantity, 5)
    discounted_quantity = quantity - deducted_quantity
else: 
    discounted_quantity = quantity

#Compute which discount yields a better outcome   
if (discounted_price*quantity < price*discounted_quantity):
    return(discounted_price*quantity)
else:
    return(price*discounted_quantity)

任何帮助都非常感谢,因为我是一个初学者,我还没有找到合适的解决方案。

仅供参考,基础任务: 编写一个函数discount(),它接受(位置)参数price和quantity,并为客户订单实现一个折扣方案,如下所示。如果价格超过100美元,我们给予10%的相对折扣。如果客户订购超过10件商品,每五件商品中就有一件是免费的。然后,该函数应返回总体成本。此外,只允许两种折扣类型中的一种,以对客户更好的为准。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/30676
 
1419 次点击  
文章 [ 1 ]  |  最新文章 6 年前
Mr Geek
Reply   •   1 楼
Mr Geek    6 年前

divmod 返回元组 (d, m) 在哪里? d 是除法的整数结果( x // y ) m 剩下的是吗( x % y )使用索引获取您想要的二者中的任何一个。( div mod ):

deducted_quantity = divmod(quantity, 5)[0]
# or:
# deducted_quantity = divmod(quantity, 5)[1]

或者,如果两者都需要,请使用解包为每个值使用一个变量:

the_div, the_mod = divmod(quantity, 5)