Remove Friends hackerearth:运行时错误-NZEC:IndexError:双端队列索引超出范围

问题描述 投票:0回答:1

问题陈述(https://www.hackerearth.com/problem/algorithm/remove-friends-5

我被这个问题困扰。请指出什么是错误的,可以做什么才能获得正确的输出。

谢谢您的帮助

[获得博士学位后,克里斯蒂(Christie)成为了她大学的名人,她的Facebook个人资料充满了朋友的要求。克里斯蒂(Christie)是个好女孩,她接受了所有要求。

现在Kuldeep嫉妒她从其他人那里得到的所有关注,因此他要求她从她的朋友列表中删除其中一些人。为了避免发生“场景”,克里斯蒂决定从她的朋友列表中删除一些朋友,因为她知道自己所拥有的每个朋友的受欢迎程度,因此她使用以下算法删除了一个朋友。

删除算法(朋友):

         DeleteFriend=false

 for i = 1 to Friend.length-1

 if (Friend[i].popularity < Friend[i+1].popularity)

    delete i th friend

    DeleteFriend=true

    break
if(DeleteFriend == false)

delete the last friend

输入:第一行包含T个测试用例。每个测试用例的第一行包含N,科视Christie当前拥有的朋友数和K,科视Christie决定删除的朋友数。接下来的几行包含了她的朋友的受欢迎程度,并用空格隔开。

输出:为每个测试案例打印N-K个数字,这些数字代表删除K个朋友后科视Christie朋友的受欢迎程度。

注意删除确切的K个朋友后的朋友顺序,应保持输入中给出的顺序。

样本输入:

3

3 1

3 100 1

5 2

19 12 3 4 17

5 3

23 45 11 77 18

样本输出

100 1

19 12 17

77 18

我的独奏:

import collections as col

def delete(n, k, frnd):

    temp = []

    while k!=0:   

        for f in frnd:

            if f<f+1:

                del frnd[f]

                k -= 1

    temp.append(frnd)

print(" ".join(map(str, temp))) 

for i in range(int(input())):

  n, k = (map(int, input().split()))

  frnd = col.deque(list(map(int, input().split())))

  delete(n, k, frnd)
python python-3.x runtime-error indexoutofboundsexception
1个回答
0
投票

要解决该错误,请使用for循环替换为

for idx, f in enumerate(frnd):
    if f<f+1:
        del frnd[idx]
        break # <------

您收到错误是因为您使用值而不是索引来删除deque中的条目

© www.soinside.com 2019 - 2024. All rights reserved.