首页 > 解决方案 > Python 中的新年混沌挑战

问题描述

我正在应对这个挑战:新年混沌挑战。我已经走了很远,并意识到我的代码不适用于所有测试用例,通常是较大的输入

我知道我写的代码很糟糕,但这就是我要学习的方式。所以这是我的算法:

1. Take i = len(a)-1
2. Check whether the last element is at place or not a[i] not equals len(a)(which is anyway the nth element)
3. Find how far it is from it's actual place
4. If the value is more than 2, then Chaotic and exit
5. Else if the value is positive, which means the guy has to move to the right and bribe would be taken into consideration, else not valuable
6. Add the number of value the element has
7. Swap the values using normal swapping 
8. Print the statement according to the situation 

我的代码:

def minimumBribes(a):
  min_bribe = 0
  isChaotic = False
  i = len(a)-1
  #for chaos check
  while i >= 0:
    posVal = 0
    if a[i] != len(a):
      #if the value comes more than two with respect to any position then chaotic
      posVal = i - a.index(i+1)
      if abs(posVal) > 2:
        isChaotic = True
        break
      elif posVal > 0:
        min_bribe += posVal
        #swapping them to their place original place
        temp = i+1
        a[a.index(i+1)] = a[i]
        a[i] = temp

     i -= 1
    print("Too Chaotic" if isChaotic else min_bribe-1, end="")

因此,对于某些测试用例,我的算法完全可以正常工作,例如:

1. [2 1 5 3 4]
2. [2 5 1 3 4]
3. [5 1 2 3 7 8 6 4]
4. [1 2 5 3 7 8 6 4]

错误捕获在这样的测试用例之一中: 输入

预期输出: 966,但我的代码没有通过它。花了很多时间。

我的算法失败:

  1. 大输入耗时
  2. 空间消耗

任何可以告诉我的帮助:

  1. 用于解决我的代码或错误纠正的有效代码
  2. 你如何看待这个解决方案,以及我需要什么才能达到这个水平。

我是一个学习者,我会学习。我对那些能够真正流畅地编码并具有出色逻辑的人着迷。也请指导我。谢谢 :)

标签: pythonarrays

解决方案


导入数学导入操作系统导入随机导入重新导入系统

完成下面的 minimumBribes 函数。

def minimumBribes(q): q = [i-1 for i in q] # 设置队列从 0 开始

bribes = 0



for i, o in enumerate(q):

    cur = i 

    if o - cur > 2:

        print("Too chaotic")

        return

    for k in q[max(o - 1, 0):i]:

        if k > o:

            bribes += 1


print(bribes)

如果名称== '主要': t = int(input())

for t_itr in range(t):
    n = int(input())
    q = list(map(int, input().rstrip().split()))

    print(minimumBribes(q))

推荐阅读