0

I am trying to convert some python code into JavaScript code.

I have a python list comprehension that take the paramente a as input. a is a string such as "bac".

asubstring = [a[i:i + j] for j in range(1, len(a) + 1) for i in range(len(a) - j + 1)]

The output is: ['b', 'a', 'c', 'ba', 'ac', 'bac']

I converted it into JavaScript by doing:

let j = 1
let i = 0
while(j < aTrimmed.length+1) {
    while(i < aTrimmed.length - j + 1) {
       aSubstring.push(aTrimmed.slice(i, i+j))
       i++
    }
    j++
}

However, my output is: [ 'b', 'a', 'c' ]

I am not sure what I am missing in the two while loops.

1
  • 2
    You didn't reset i = 0 in the inner loop. I would suggest writing this using nested for loops, then it's harder to make that mistake. Commented Feb 7, 2020 at 11:44

3 Answers 3

1

The issue is that you are not resetting the i variable in the inner loop. In the Python version, for i in range(...) always makes i start from 0. Additionally, declaring an iteration variable, then using a while loop which ends in incrementing that variable is a bit weird, why not just use a for loop?

let aTrimmed = "abc";
let aSubstring = [];

for (let j = 1; j <= aTrimmed.length; j++) {
  for (let i = 0; i <= aTrimmed.length - j; i++) {
    aSubstring.push(aTrimmed.slice(i, i + j));
  }
}

console.log(aSubstring);

Also note the <= instead of < ... + 1.

Sign up to request clarification or add additional context in comments.

Comments

1

Use for loop instead of while because you are forgetting reset you i index to 0 at the end of the second loop.

let aTrimmed = "bac";
let aSubstring = [];


for(let j = 1; j < aTrimmed.length+1; j++) {
    for(let i = 0; i < aTrimmed.length - j + 1; i++) {
       aSubstring.push(aTrimmed.slice(i, i + j));
    }
}
alert(aSubstring);

Comments

0

This version works more favourably with characters outside of the Unicode Basic Multilingual Plane. Although there remain issues with grapheme clusters.

let s1 = "abc"
let s2 = "🧽🍿🛥"

function substrings(s) {
    let us = [...s]
    let result = []

    for (let j = 1; j <= us.length; j++) {
      for (let i = 0; i <= us.length - j; i++) {
        result.push(us.slice(i, i + j).join(''))
      }
    }

    return result
}

console.log(substrings(s1))
console.log(substrings(s2))

Comments

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.