我正在尝试从我传递的python列表中找到最长的递增子序列。最终的字典结构应如下所示:
Expected structure
subsequence_dict={ 0:[15], 1:[15,27], 2:[14],3:[15,27,38],4:[14,26],5:[15,27,38,55],6:[15,27,38,46],7:[15, 27, 38, 55, 65, 85]}
Output:
{0: [15, 27, 38, 55, 65, 85], 1: [15, 27, 38, 55, 65, 85], 2: [14, 26, 46], 3: [15, 27, 38, 55, 65, 85], 4: [14, 26, 46], 5: [15, 27, 38, 55, 65, 85], 6: [14, 26, 46], 7: [15, 27, 38, 55, 65, 85], 8: [15, 27, 38, 55, 65, 85]}
在我的输出中查看键0时,看起来存在一些可变性问题。
对于主函数中i的每个值,字典中应该有一个新键,该键的值来自longest_subsequence函数。
from copy import deepcopy
def longest_subsequence(dict_elent,subsequence_dict):
"""
:param dict_elent: Dictionary element to which the longest list last element to be compared
:param subsequence_dict:
:return: List
"""
x=subsequence_dict.values()
sorted_list = sorted(x, reverse=True)
flag=False
for sublist in sorted_list:
if sublist[-1]<dict_elent:
sublist.append(dict_elent)
flag=True
break
if flag==True:
return sublist
else:
return [dict_elent]
def main(d,subsequence_dict):
for i in range(len(d)):
if i==0 :
subsequence_dict[i]=[d[i]]
else:
subsequence_dict.update({i: longest_subsequence(d[i],subsequence_dict)})
if __name__ == '__main__':
d=[15,27,14,38,26,55,46,65,85]
subsequence_dict={}
main(d,subsequence_dict)
print(subsequence_dict)