列出python3中的问题

时间:2017-09-27 20:00:31

标签: python python-3.x list

当我运行此代码时,它表示在评论的两行中存在错误。

#!/bin/python3

import sys

def birthdayCakeCandles(n, ar):
    j=1

    for f in range(0,n):      
            b=f+1
         #   if ar[f]<ar[b]:
                if f==n:
                    break
                else:
                        m=ar[b]
                        for k in range(0,n):
                            if m==ar[k]:
                                j=j+1

    return j    

n = int(input().strip())
ar = list(map(int, input().strip().split(' ')))
  #  print(birthdayCakeCandles(n, ar))
  

错误(stderr)回溯(最近一次调用最后一次):文件&#34; solution.py&#34;,第23行,打印(birthdayCakeCandles(n,ar))文件&#34; solution.py&#34 ;,第10行,在birthdayCakeCandles中,如果ar [f]

2 个答案:

答案 0 :(得分:0)

for f in range(0,n):      
    b=f+1
    if ar[f]<ar[b]:

在这里,您引用的列表索引大于列表的长度,这就是您收到错误的原因。 n是列表的长度,因此当你为b添加1时,它将是一个不存在的索引。您可能已经意识到此代码块发生此问题:

if f==n:
    break

但是,该程序在达到该点之前已经遇到了错误。我的解决方案是在上面的代码中用n-1替换n。我不确定这是否能够应对挑战,我需要更彻底地阅读它。这是我的代码的样子。我也摆脱了上面的第二个代码块,因为它没有做任何事情。

def birthdayCakeCandles(n, ar):
    j=1
    for f in range(0,n-1):      
        b=f+1
        #if one element is less than the following
        if ar[f]<ar[b]:
            #count the number of elements equal to the following element, add to j
            m=ar[b]
            for k in range(0,n):
                if m==ar[k]:
                j+=1
    return j    

 n = int(input().strip())
 ar = list(map(int, input().strip().split(' ')))
 print(birthdayCakeCandles(n, ar))

我也用j + = 1代替j = j + 1。另外,第二个for循环可以用列表理解代替,但我不知道你是否知道它们,所以我把它保留原样。

看起来this是你要做的挑战,在这种情况下你误解了它,而上面的代码对它不起作用。再读一遍并阅读示例。它比你想象的要简单得多。

答案 1 :(得分:-1)

            else:
                    m=ar[b]
                    for k in range(0,n):
                        if m==ar[k]:
                            j=j+1

缩进不正确。它应该是:

            else:
                m=ar[b]
                for k in range(0,n):
                    if m==ar[k]:
                        j=j+1

另外,

for f in range(0,n):      
        b=f+1
     #   if ar[f]<ar[b]: <-- Your commented out line used to create a new block
            if f==n:   # <-- This line is incorrectly indented as a result
                break (and all lines after)
            else:
                m=ar[b]  # I moved this back in, not a syntax error, but is incorrect. 
                for k in range(0,n):
                    if m==ar[k]:
                        j=j+1