如何在列表中使用python查找从上到下的所有方法

时间:2014-02-02 11:19:29

标签: python python-3.x

Python v.3.2.3:
需要找到此list[]中的所有路径,但请仅接受(↓, ↓+right)。在完成需要时,从list(all paths)up([0][0])创建down([6][x])列表。

示例(列表):

[[30], [27, 84], [25, 33, 11], [31, 54, 79, 95], [98, 27, 61, 90, 52], 
 [12, 72, 29, 64, 27, 81], [90, 23, 24, 73, 69, 63, 47]]

示例list([all paths][.][.][.][.][.][.][.])

 [[30, 27, 25, 31, 98, 12, 90], [30, 27, 25, 31, 98, 12, 23].............]

代码:

from random import randint


col_str=randint(6,10)

'''create pyramid 2d array'''
def newpyramid():
    masiv=[]
    index = 0

    for i in range(0,col_str):

        masiv.append([])
        index+=1
        #print(index)
        for j in range(0,index):
            masiv[i].append(randint(10,99))
    return masiv

b=newpyramid()  
print(b)

'''function that find nodes (↓, ↓+right) '''
def get_list_subnodes(depth, width):

    try:
        pyramid[depth+1]
    except IndexError:
        return False
    else:
        subnodes = []
        subnodes1 = []
        subnodes2 = []
        subnodes1.append(depth + 1)
        subnodes1.append(width)
        subnodes2.append(depth + 1)
        subnodes2.append(width + 1)
        subnodes.append(subnodes1)
        subnodes.append(subnodes2)

        return subnodes


'''function go by 2 nodes from get_list_subnodes'''
def go_pyramid(depth, width, way):

    way1.append(pyramid[depth][width])
    way2.append(pyramid[depth][width]) 

    #print(depth)
    list_subnodes = get_list_subnodes(depth, width)

    print(list_subnodes)
    if list_subnodes==False:
        ways.append(way1)
        ways.append(way2)
        return

    go_pyramid(list_subnodes[1][0], list_subnodes[1][1], way1)
    go_pyramid(list_subnodes[0][0], list_subnodes[0][1], way2)

ways=[]
go_pyramid(0, 0, way1)
print(ways)

1 个答案:

答案 0 :(得分:1)

您要实现的目标是一系列列表的笛卡尔积。 python itertools.product中已经有了一个库支持。

lst=[[30], [27, 84], [25, 33, 11], [31, 54, 79, 95], [98, 27, 61, 90, 52], 
 [12, 72, 29, 64, 27, 81], [90, 23, 24, 73, 69, 63, 47]]
from itertools import product
result = map(list, product(*lst))