【发布时间】:2021-12-09 16:59:02
【问题描述】:
问题陈述:- 给定一个由 N 个整数组成的数组和一个整数 K,找出数组中总和等于 K 的元素对的数量。
**def countpairs(x,length,sum):
count = 0
for i in range(0,length):
for j in range(i+1,length):
print(x[i],x[j])
if(x[i]+x[j]==sum):
count+=1
print(count)
x = [1, 1, 1, 1]
sum = 2
length=len(x)
countpairs(x,length,sum)
Output:= 6**
This is My solution used in VS code.
我的问题:- 每当我在 gfg 中运行相同的代码时,它不接受给我这个错误的代码。我什至在在线编译器中尝试了相同的代码,它也运行正常。
This Is the gfg code which i have written
class Solution:
def getPairsCount(self, arr, K, N):
count = 0
for i in range(0,N):
for j in range(i+1,N):
if(arr[i]+arr[j]==K):
count+=1
return count
#Initial Template for Python 3
if __name__ == '__main__':
tc = int(input())
while tc > 0:
n, k = list(map(int, input().strip().split()))
arr = list(map(int, input().strip().split()))
ob = Solution()
ans = ob.getPairsCount(arr, n, k)
print(ans)
tc -= 1
Error
if(arr[i]+arr[j]==K):
IndexError: list index out of range
【问题讨论】:
-
您将参数
arr, n, k传递给参数为arr, K, N的函数;这给出了 indexerror。 -
参数名可以不一样,如果是argumnet的问题,在vs code里就不行了。
-
我知道参数名称和参数名称可以不同。我的意思是这个问题是由拼写错误引起的。你的 'vscode' 和其他代码 sn-p 完全不同,只有一个有这种交换 n 和 k 的错字
-
@kcsquared 明白了
-
gfg代码中的gfg是什么?