Python for循环括号语法

时间:2016-12-10 11:34:07

标签: javascript python

所以我试图将这个Python函数转换为Javascript。我是Python的新手,所以有些语法很难用来加密。这是原始代码和我尝试JS转换的原因。我知道我已经解释了错误,因为我现在所拥有的是一个无限循环。

的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], [])

这是我尝试转换为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], []);

我从this问题获得了Python代码。

编辑:我在ES6环境中工作。

2 个答案:

答案 0 :(得分:3)

他们在python中都是List comprehensions

在Javascript(没有ES6,babel及其关系)中最接近python中的列表理解是使用Array.Map(类似于python的地图)

python中的示例

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

在Javascript中:

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

在ES6中使用Arrow functions,您可以摆脱function(){}

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

所以你的代码应该是这样的

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 } });

答案 1 :(得分:2)

最好使用:

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

因为这会削减N所做的无用数组创建。

同时~~无法将-1正确转换为false0 .. n转换为true。请改用!!~