Spaceship purchase

本文探讨了一个关于讨价还价的算法问题,通过逐步分析和调整,解决了算法中的错误。文章详细解释了原始算法的问题所在,并给出了修正后的正确算法。

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.

总是出错的一段代码:

<!-- lang: python -->
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

修改后的代码如下:

<!-- lang: python -->
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的关系就行了。

转载于:https://my.oschina.net/scroll/blog/120793

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值