Okku
Okku

Reputation: 7819

Python for loop inside brackets syntax

So I'm trying to convert this Python function into Javascript. I'm new to Python, so some of the syntax is difficult for me to cipher. Here's both the original code and my attempt at JS-conversion. I know I've interpreted something wrong, because what I have now is an infinite loop.

Python:

graph = [[0,1,0,0,1,0],[1,0,1,0,1,0],[0,1,0,1,0,0],[0,0,1,0,1,1],[1,1,0,1,0,0],[0,0,0,1,0,0]]

def N(vertex):
    c = 0
    l = []
    for i in graph[vertex]:
        if i is 1 :
         l.append(c)
        c+=1
    return l 

def bronk(r,p,x):
    if len(p) == 0 and len(x) == 0:
        print r
        return

    for vertex in p[:]:
        r_new = r[::]
        r_new.append(vertex)
        p_new = [val for val in p if val in N(vertex)] #this and
        x_new = [val for val in x if val in N(vertex)] #this part was particularly difficult to understand 
        bronk(r_new,p_new,x_new)
        p.remove(vertex)
        x.append(vertex)

bronk([], [0,1,2,3,4,5], [])

And here's my attempt at its conversion to JS:

'use strict';
const graph = [[0,1,0,0,1,0],[1,0,1,0,1,0],[0,1,0,1,0,0],[0,0,1,0,1,1],[1,1,0,1,0,0],[0,0,0,1,0,0],];

function N(vertex){
  let c = 0;
  const l = [];
  for (let i in graph[vertex]){
      if (i){
        l.push(c);
        c++;
      }
  }
  return l;
}

function bronk(r,p,x){
  if (p.length == 0 && x.length == 0){
    console.log(r);
    return;
  }
  for (let vertex in p.slice(0)){
    const r_new = r.slice(0);
    r_new.push(vertex);
    const p_new=p.filter(val=>~~N(vertex).indexOf(val)); //here´s my best guess...
    const x_new=x.filter(val=>~~N(vertex).indexOf(val));
    bronk(r_new, p_new, x_new);
    p=p.splice(vertex,1);
    x.push(vertex);
  }
}

bronk([], [0,1,2,3,4,5], []);

I got the Python code from this question.

Edit: I'm working in an ES6 environment.

Upvotes: 0

Views: 7619

Answers (2)

danidee
danidee

Reputation: 9624

They're both List comprehensions in python

The closest you can get to a list comprehension in python in Javascript (Without ES6, babel and its relations) is to use Array.Map (Similar to python's map)

Example in python

>>> l = [2, 4, 6, 8, 10, 12]
>>> [int(i / 2) for i in l]
[1, 2, 3, 4, 5, 6]

In Javascript:

l = [2, 4, 6, 8, 10, 12]
l.map(function(i){ return i / 2 });
[1, 2, 3, 4, 5, 6]

With Arrow functions in ES6, you can get rid of the function(){}

l.map(x => x/2)
[2, 4, 6, 8, 10, 12]

So your code should look like this

const p_new = p.map(function(i){ if(i in N(vertex)){ return i } });
const x_new = x.map(function(i){ if(i in N(vertex)){ return i } });

Upvotes: 4

Dan D.
Dan D.

Reputation: 74655

It would be better to use:

p.filter(val => graph[vertex][val])

As this cuts out the useless Array creation that N does.

Also ~~ doesn't properly convert -1 to false and 0 .. n to true. Use !!~ instead.

Upvotes: 2

Related Questions