python的题目在哪里_请问这道python题目错在哪里?

简单先写了一个,得到正确的结果:

def list_alg(lst):

lst1 = []

lst2 = []

for i in range(len(lst)):

if i+2 <= len(lst)-1:

if lst[i+1] - lst[i] == lst[i+2] - lst[i+1]:

lst1.extend([lst[i],lst[i+1],lst[i+2]])

else:

if len(lst1) > 2:

lst2.append(list(set(lst1)))

lst1 = []

else:

lst1 = []

else:

if len(lst1) > 2:

lst2.append(list(set(lst1)))

lst1 = []

print(lst2)

print(len(lst2))

if __name__ == '__main__':

lst = [1,2,3,4,8,9,10]

list_alg(lst)

得到结果:

[[1, 2, 3, 4], [8, 9, 10]]

2

后来重新想了下,写了一个可以判断更大量列表的代码:

def func_lst(lst_func, lst, x):

for i in range(1,len(lst)):

if lst[i]-lst[0] == x:

lst_func.append(lst[i])

func_lst(lst_func,lst[i:],x)

def list_alg(lst):

lst1 = []

lst2 = []

for i in range(len(lst)):

for j in range(1,len(lst)):

x = lst[j] - lst[i]

lst1.append(lst[i])

lst1.append(lst[j])

func_lst(lst1, lst[j:], x)

if len(lst1) > 2:

lst2.append(lst1)

lst1 = []

else:

lst1 = []

print(lst2)

print(len(lst2))

if __name__ == '__main__':

lst = [1,2,3,5,6,7,8,9,10]

list_alg(lst)

得到结果:

[[1, 2, 3], [1, 3, 5, 7, 9], [1, 5, 9], [2, 5, 8], [2, 6, 10], [3, 5, 7, 9], [3, 6, 9], [5, 6, 7, 8, 9, 10], [5, 7, 9], [6, 7, 8, 9, 10], [6, 8, 10], [7, 8, 9, 10], [8, 9, 10]]

13

发现有很多局部重复的元素。那么可以再增加一个函数进行清理,得到完全干净的结果:

def func_lst(lst_func, lst, x):

for i in range(1,len(lst)):

if lst[i]-lst[0] == x:

lst_func.append(lst[i])

func_lst(lst_func,lst[i:],x)

def func_lst_pop(lst):

lst1 = lst[:]

for n in range(len(lst)-2):

for m in range(n+1, len(lst)):

if len(lst[n]) < len(lst[m]):

if any([lst[n]==lst[m][i:i+len(lst[n])] for i in range(0,len(lst[m])-len(lst[n])+1)]):

if lst[n] in lst1:

lst1.remove(lst[n])

elif len(lst[n]) > len(lst[m]):

if any([lst[m]==lst[n][i:i+len(lst[m])] for i in range(0,len(lst[n])-len(lst[m])+1)]):

if lst[m] in lst1:

lst1.remove(lst[m])

return lst1

def list_alg(lst):

lst1 = []

lst2 = []

for i in range(len(lst)):

for j in range(1,len(lst)):

x = lst[j] - lst[i]

lst1.append(lst[i])

lst1.append(lst[j])

func_lst(lst1, lst[j:], x)

if len(lst1) > 2:

lst2.append(lst1)

lst1 = []

else:

lst1 = []

print(lst2)

print(len(lst2))

lst3 = func_lst_pop(lst2)

print(lst3)

print(len(lst3))

if __name__ == '__main__':

lst = [1,2,3,5,6,7,8,9,10]

list_alg(lst)

得到结果:

[[1, 2, 3], [1, 3, 5, 7, 9], [1, 5, 9], [2, 5, 8], [2, 6, 10], [3, 5, 7, 9], [3, 6, 9], [5, 6, 7, 8, 9, 10], [5, 7, 9], [6, 7, 8, 9, 10], [6, 8, 10], [7, 8, 9, 10], [8, 9, 10]]

13

[[1, 2, 3], [1, 3, 5, 7, 9], [1, 5, 9], [2, 5, 8], [2, 6, 10], [3, 6, 9], [5, 6, 7, 8, 9, 10], [6, 8, 10]]

8

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值