Prolog:有没有办法找到列表中最长的连续数字序列并获取其长度?
Prolog: Is there a way to find the longest consecutive number sequence in a list and get its length?
给定 5 个随机自然数的列表(数字的范围是从 1 到 13),即 [1,6,11,12,13],我如何找出最长的连续数字序列(即 [ 11,12,13]),它的长度必须大于等于3,也得到它的长度?
def longestSeq(n):
seqMax = 0
counter = 0
i = 0
while i+1 < len(n):
curr = n[i+1]
last = n[i]
sub = curr - last
if sub == 1:
if counter == 0:
counter = 2
else:
counter += 1
else:
if counter > 0:
if seqMax < counter:
seqMax = counter
counter = 0
i += 1
if seqMax < counter:
seqMax = counter
if seqMax >= 3:
return seqMax
else:
return 0
您可以遍历列表以跟踪当前序列及其长度以及目前找到的最大序列和长度。
处理完所有列表后,您可以检查最大长度是否 >= 3 和 select 正确的输出:
longest_sequence([First|L], Len1, Seq) :-
longest_sequence(L, 1, [First], 0, [], Len, RSeq),
( Len>=3
-> reverse(RSeq, Seq),
Len1=Len
; Seq=[],
Len1=0
).
longest_sequence([], CurLen, CurSeq, MaxLen, MaxSeq, Len, Seq):-
(CurLen > MaxLen -> Len-Seq=CurLen-CurSeq ; Len-Seq=MaxLen-MaxSeq).
longest_sequence([CurItem|L], CurLen, [LastItem|CurSeq], MaxLen, MaxSeq, Len, Seq):-
(
succ(LastItem, CurItem) ->
(
succ(CurLen, CurLen1),
CurSeq1=[CurItem,LastItem|CurSeq],
MaxLen1-MaxSeq1=MaxLen-MaxSeq
) ;
(
(CurLen > MaxLen -> MaxLen1-MaxSeq1=CurLen-[LastItem|CurSeq] ; MaxLen1-MaxSeq1=MaxLen-MaxSeq),
CurLen1=1,
CurSeq1=[CurItem]
)
),
longest_sequence(L, CurLen1, CurSeq1, MaxLen1, MaxSeq1, Len, Seq).
样本运行:
?- longest_sequence([1,6,11,12,13], Len, Seq).
Len = 3,
Seq = [11, 12, 13].
?- longest_sequence([1,6,11,12,13,2,3,4,5], Len, Seq).
Len = 4,
Seq = [2, 3, 4, 5].
?- longest_sequence([1,2], Len, Seq).
Len = 0,
Seq = [].
给定 5 个随机自然数的列表(数字的范围是从 1 到 13),即 [1,6,11,12,13],我如何找出最长的连续数字序列(即 [ 11,12,13]),它的长度必须大于等于3,也得到它的长度?
def longestSeq(n):
seqMax = 0
counter = 0
i = 0
while i+1 < len(n):
curr = n[i+1]
last = n[i]
sub = curr - last
if sub == 1:
if counter == 0:
counter = 2
else:
counter += 1
else:
if counter > 0:
if seqMax < counter:
seqMax = counter
counter = 0
i += 1
if seqMax < counter:
seqMax = counter
if seqMax >= 3:
return seqMax
else:
return 0
您可以遍历列表以跟踪当前序列及其长度以及目前找到的最大序列和长度。
处理完所有列表后,您可以检查最大长度是否 >= 3 和 select 正确的输出:
longest_sequence([First|L], Len1, Seq) :-
longest_sequence(L, 1, [First], 0, [], Len, RSeq),
( Len>=3
-> reverse(RSeq, Seq),
Len1=Len
; Seq=[],
Len1=0
).
longest_sequence([], CurLen, CurSeq, MaxLen, MaxSeq, Len, Seq):-
(CurLen > MaxLen -> Len-Seq=CurLen-CurSeq ; Len-Seq=MaxLen-MaxSeq).
longest_sequence([CurItem|L], CurLen, [LastItem|CurSeq], MaxLen, MaxSeq, Len, Seq):-
(
succ(LastItem, CurItem) ->
(
succ(CurLen, CurLen1),
CurSeq1=[CurItem,LastItem|CurSeq],
MaxLen1-MaxSeq1=MaxLen-MaxSeq
) ;
(
(CurLen > MaxLen -> MaxLen1-MaxSeq1=CurLen-[LastItem|CurSeq] ; MaxLen1-MaxSeq1=MaxLen-MaxSeq),
CurLen1=1,
CurSeq1=[CurItem]
)
),
longest_sequence(L, CurLen1, CurSeq1, MaxLen1, MaxSeq1, Len, Seq).
样本运行:
?- longest_sequence([1,6,11,12,13], Len, Seq).
Len = 3,
Seq = [11, 12, 13].
?- longest_sequence([1,6,11,12,13,2,3,4,5], Len, Seq).
Len = 4,
Seq = [2, 3, 4, 5].
?- longest_sequence([1,2], Len, Seq).
Len = 0,
Seq = [].