有人能指出我逻辑上的错误吗。(编码练习)

2024-05-19 12:24:26 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个来自HackerRank网站的问题。我已经尽了最大努力,但我一辈子都不知道自己做错了什么。问题如下:

“今天是元旦,人们排队乘坐仙境过山车。每个人都戴着一张贴纸,表明他们在从1n的队列中的初始位置。”.任何人都可以贿赂直接在他们面前的人来交换职位,但他们仍然穿着他们原来的贴纸。一个人最多可以贿赂另外两个人

确定进入给定队列顺序所发生的最小贿赂数量。打印贿赂数量,或者,如果任何人贿赂了两人以上,打印Too chaotic。”

这是我的尝试:

def minimumBribes(q):
    bribes = 0
    sorted_q  = sorted(q)
    total_moves = 0
    for i in range(len(q)):
        origin = sorted_q[i]
        current = q[i]
        moved = current - origin
        if moved > 0:
            if moved > 2:
                print("Too chaotic")
                return
            else:
                total_moves += moved
    print(total_moves)

我意识到这有点罗嗦,但我想让我的逻辑尽可能清晰

如果我输入q = [1,2,5,3,7,8,6,4],预期的输出是7,但我得到6

为什么


Tags: 数量if队列网站origincurrent排队too
1条回答
网友
1楼 · 发布于 2024-05-19 12:24:26

q=[1,2,5,3,7,8,6,4]

正如你在问题中看到的,没有提到贿赂的顺序,一个人可以贿赂2 一次一个人或一次一个人

如果你被某人贿赂,你就不能行贿,这是没有限制的

让我们反转空穴过程,像“q”中那样创建这种情况

'''

   sorted_q=[1,2,3,4,5,6,7,8]
   5 bribed 3 and 4 
   total_moved = 2
   
   sorted_q=[1,2,5,3,4,6,7,8]
   7 bribed 4 and 6 
   total_moved = 4
    
   sorted_q=[1,2,5,3,7,4,6,8]
   8 bribed 4 and 6
   total_moved = 6

   sorted_q=[1,2,5,3,7,8,4,6]
   here at this bribe by 6 to 4 just make your logic fail
   total_moved = 7
   

   sorted_q=[1,2,5,3,7,8,6,4]
    

'''

相关问题 更多 >