sofi想要买个飞船,所以需要跟卖船的老头讨价还价。
Write a program that, depending on Sofia and the old man’s initial bargaining sums–the steps by which they will increase or decrease the price during their negotiations, will calculate which price they will agree upon. If Sofia's offer is lower than or equal to the old man's offer, she will accept the old man's price (and vice versa).
Sofi makes her proposition first. She never proposes an amount higher than what is proposed to her. On the other hand, the old man never proposes an amount lower than what is proposed to him.
Input data: Contains four integer numbers: Sofia's initial offer, Sofia's raise to his offer, the initial counteroffer from the old man, and the old man's reduction in his offer;
Output data: The amount of money that Sofia will pay for the spaceship.
总是出错的一段代码:
def checkio(offers):
'''
the amount of money that Petr will pay for the ride
'''
sofi, raised, oldman, reduction = offers
while(1):
# oldman was thinking...
if(sofi > oldman):
return sofi
elif(sofi > oldman - reduction):
return sofi
# sofi was thinking...
elif(sofi + raised > oldman):
return oldman
# a circle was ended
else:
sofi = sofi + raised
oldman = oldman - reduction
以下是算法运行步骤:
1.sofi出价,老头考虑。转2
2.老头觉得自己的报价会比sofi低,则接受sofi的价格。否则,转3
3.老头觉得自己下一轮的报价会比sofi低,则接受sofi的价格。否则,转4
4.老头报价,sofi考虑。转5
5.sofi觉得自己下一轮的报价会比老头高,则sofi接受老头的价格。否则,转1
看起来也没问题啊,但是总是出错。看到出错的用例之后,再回过头去考虑,我发现主要还是错在第3轮——这一步好像不该有。
修改算法步骤如下:
1.sofi出价,老头考虑。转2
2.老头觉得自己的报价会比sofi低,则接受sofi的价格。否则,转3
3.老头报价,sofi考虑。转4
4.sofi觉得自己下一轮的报价会比老头高,则sofi接受老头的价格。否则,转1
修改后的代码如下:
def checkio(offers):
'''
the amount of money that Petr will pay for the ride
'''
sofi, raised, oldman, reduction = offers
while(1):
# oldman was thinking...
if(sofi > oldman):
return sofi
# sofi was thinking...
elif(sofi + raised > oldman):
return oldman
# a circle was ended
else:
sofi = sofi + raised
oldman = oldman - reduction
通过了。
注释有点问题。老头思考的时候,只是针对sofi当前的出价。出价高于老头打算出的价格,则接受sofi的报价。老头不会在自己还没报出的价格上打折,所以第二个判断是多余的,只需要考虑sofi和oldman的关系就行了。