似乎没有一种方法可以用Python编写这种类型的for循环,因为我正在尝试将这段javascript代码转换/重写为Python。如何在嵌套循环中设置初始循环索引,如j?
下面是我的JS代码:
// Write a function called findGreaterNumbers which accepts an array and returns the number of times a number is followed by a larger number.
// Examples:
// findGreaterNumbers([1,2,3]) // 3 (2 > 1, 3 > 2, and 3 > 1)
// findGreaterNumbers([6,1,2,7]) // 4
// findGreaterNumbers([5,4,3,2,1]) // 0
// findGreaterNumbers([]) // 0
function findGreaterNumbers(arr) {
let count = 0
for (let i= 0; i < arr.length; i++){
for (let j= i + 1; j < arr.length; j++){
if(arr[j] > arr[i]){
count++;
}
}
}
return count;
}发布于 2020-02-05 08:19:38
您可以使用itertools.combinations来实现以下目的:
from itertools import combinations
def findGreaterNumbers(arr):
return sum(b > a for a, b in combinations(arr, 2))https://stackoverflow.com/questions/60067300
复制相似问题