在python中递归地为列表的左侧分配标签“ left”,向右侧分配标签“ right”

时间:2019-10-01 01:47:50

标签: python algorithm

这是我在准备面试时正在研究的一个问题。请提供逻辑建议。 如果给我一个包含字符串或列表的列表,总是2个元素,那么元素order = 0或element order = 1,我如何递归地分配左侧并将其与“ left =” + element和右侧与“ right连接在一起=“ + element ..例如

l7 = [1,[[2,3],4]]
[left=1,right=[left=[left=2,right=3],right=4]]

我设法使用以下算法递归求和。但是,分配标签有点挑战。

def addList(l:list):
    sumValues = 0
    for x in range(len(l)):
        print("\nx: " +str(x)+" data:"+str(l[x]))
        if type(l[x]) == list:
            print("type is list")
            sumValues+=addList(l[x])
            print("sumValues = "+str(sumValues))
        else:
            sumValues+=l[x]
            print("sumValues = "+str(sumValues))
    return sumValues

我将其更改为:

def addList(l:list):
    sumValues = ""
    for x in range(len(l)):
        print("\nx: " +str(x)+" data:"+str(l[x]))
        if type(l[x]) == list:
            print("type is list")
            if x ==0:
                sumValues += "left = "+ str(l[x])+str(sumValues)
                #print("left = "+str(sumValues))
            if x ==1:
                sumValues += "right = "+ str(l[x])+str(sumValues)
                print("right = "+str(sumValues))
        else:
            if x ==0:
                sumValues += "left = "+ str(l[x])+str(sumValues)
                #print("left = "+str(sumValues))
            if x ==1:
                sumValues += "right = "+ str(l[x])+str(sumValues)
                #print("right = "+str(sumValues))
    return sumValues

l7 = [1,[[2,3],4]]
addList(l7)

我得到的结果是: '左= 1右= [[2,3],4]左= 1'

1 个答案:

答案 0 :(得分:0)

您可以这样做

def addList(l:list,sumValues):
    for x in range(len(l)):
        #print("\nx: " +str(x)+" data:"+str(l[x]))
        if type(l[x]) == list:
            #print("type is list")
            sumValues += "[left = "
            sumValues = addList(l[x],sumValues)
            if x==0:
                sumValues += ", right = "
        else:
            if x ==0:
                sumValues += str(l[x])+", right = "

            if x ==1:
                sumValues += str(l[x])+"]"
    return sumValues

l7 = [1,[[2,3],4]]
sumValues = "[left = "
print(addList(l7,sumValues))