0

There doesn't seem to be a way to write this type of for loop in Python because I'm trying to translate/rewrite this javascript code into Python. How do I set the inital loop index like j in the nested loop?

Here's my JS code:

// 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;
}
1

3 Answers 3

2

You can use the range built-in like the following:

for i in range(len(arr)):
    for j in range(i+1, len(arr)):
        # work with i and j as required
Sign up to request clarification or add additional context in comments.

Comments

2

You can use itertools.combinations for the purpose:

from itertools import combinations
def findGreaterNumbers(arr):
    return sum(b > a for a, b in combinations(arr, 2))

Comments

1

control of the initial loop index value:

In javascript: for (let i= 0; i < arr.length; i++){

In Python: for i in range(0, len(arr), 1) :

or: for i in range( len(arr) ) :


Loop in Loop:

In javascript:

  for (let i= 0; i < arr.length; i++){
     for (let j= i + 1; j < arr.length; j++){

In Python:

for i in range(len(arr)):
    for j in range(i+1, len(arr), 1):

Rewrite this javascript code into Python

def findGreaterNumbers(arr):
    count = 0
    for i in range(len(arr)):
        for j in range(i + 1, len(arr), 1):
            if arr[j] > arr[i]:
                count += 1
    return count

Currently, you may not see people using loop in loop in python for simple tasks, instead people often uselist comprehension. Examples :

arr = [6, 1, 2, 7]
result = [f'{x} < {i}' for c, x in enumerate(arr) for i in arr[c:] if x < i]
# ['6 < 7', '1 < 2', '1 < 7', '2 < 7']
len(result) # 4

1 Comment

Cool. Thanks so much for the detailed explanation! The list comprehension is sort of a mind-bender for me right now but I get the gist on how it works. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.