这两个功能之间的区别是什么

时间:2014-01-22 05:49:35

标签: php python

我首先在PHP中创建了一个函数,然后尝试在Python中创建相同的东西。以下是我的代码

Python:

def bfs(my_data):
      my_queue = []
      my_queue.insert(0, my_data[0]); 
      my_data[0]['visited'] = '1';
      while my_queue:
                vertex = my_queue.pop()
                print(vertex['letter'])

      for n_vertex in vertex['neighbors']:
                int_vertex = int(n_vertex)-1
                if my_data[int_vertex]['visited'] is '0':
                          my_data[int_vertex]['visited'] = '1'
                          test.insert(0, my_data[int_vertex])
                          my_queue = str(test)

PHP:

function bfs($my_data)
{
    $my_queue = array(); //array to store vertices
    array_unshift($my_queue, $my_data[0]); // pass the first value to the first index of queue
    $my_data[0]['visited'] = true; // value for visited is set to true for the first vertix
    //print_r($my_queue);
    while(!empty($my_queue))
    {
        $vertex = array_pop($my_queue); // passing the last value of queue to vertex
        echo $vertex['letter'];

        $msg = $vertex['letter'];
        $output_file = $_POST["output_file_name"];
        $output_file_path = "../SPA/" . $output_file;
        $outfile = fopen($output_file_path, 'aw'); //writing output to the file
        fwrite($outfile, $msg);
        fclose($outfile);         
        // fwrite($outfile, $msg);


        foreach($vertex['neighbours'] as $n_vertex)
        {
            //print_r($n_vertex);
            if(!$my_data[$n_vertex-1]['visited'])
            {
                $my_data[$n_vertex-1]['visited'] = true; // set visited true after visiting each neighbour
                array_unshift($my_queue, $my_data[$n_vertex-1]); //pass the neighbours to queue
            }
        } 




    }

}

我相信两者都是相同的功能,但由于我得到不同的结果,我试图找出差异。你怎么看?另外,如果它们不同,你能告诉我怎么样吗?

1 个答案:

答案 0 :(得分:2)

这是一个相当广泛的问题(你看到了什么结果,你怀疑什么?)但是,首先,Python中的for循环不会缩进到while之内,而在PHP中它位于while循环内。