我一直在嘗試撰寫一個概念上簡單明了的 Python 代碼,但我一直沒有成功地弄清楚如何使用優雅的代碼來做到這一點。
基本上,給定兩個升序排序的整數串列:
A = [5, 6, 7, 9, 35, 47, 88, 100]
B = [3, 12, 44, 78, 94, 122, 186]
C = []
從串列 A 開始,我想將連續串列(ABABA)中的下一個更高的數字放入一個空串列 C 中。
在執行中,這將產生
C = [5,12,35,44,47,78,88,94,100,122]
并以 122 結束,因為我們在串列 A 中找不到任何更高的數字。
uj5u.com熱心網友回復:
您可以利用itertools.cycle在兩個串列之間翻轉。一旦你能做到這一點,你就可以使用filter()從當前迭代器中獲取下一個更大的值,并跟蹤迄今為止看到的最大值。
from itertools import cycle
def get_seq(A, B):
if not A: # handle case where A is empty
return
its = cycle((iter(A), iter(B)))
current_val = A[0] - 1
for i in its:
try:
current_val = next(filter(lambda n: n > current_val, i))
except StopIteration:
return
yield current_val
A = [5, 9, 35, 47, 88, 100]
B = [3, 12, 44, 78, 94, 122, 186]
list(get_seq(A, B))
# [5, 12, 35, 44, 47, 78, 88, 94, 100, 122]
如果您知道 A不會為空,則可以稍微簡化一下。
uj5u.com熱心網友回復:
定義一個函式get_index,獲取下一個較大元素的索引,然后依次追加元素,其中sig用于區分A和B串列的順序:
def get_index(lst, value):
for i in range(len(lst)):
if lst[i] > value:
return i
def solution(a, b):
res, sig, index_a, index_b = [], True, 0, 0
while True:
if sig:
if len(res):
index_a = get_index(a, res[-1])
item = a[index_a]
res.append(item)
if item >= b[-1]:
break
sig = False
else:
index_b = get_index(b, res[-1])
item = b[index_b]
res.append(item)
if item >= a[-1]:
break
sig = True
return res
A = [5, 6, 7, 9, 35, 47, 88, 100]
B = [3, 12, 44, 78, 94, 122, 186]
print(solution(A, B))
# [5,12,35,44,47,78,88,94,100,122]
uj5u.com熱心網友回復:
我們可以加入串列并在它們之間觸發。
如果您期望一些僅使用少量元素的巨大串列,則二進制搜索方法(已注釋)可能比線性掃描更好。
#import bisect
A = [5, 6, 7, 9, 35, 47, 88, 100]
B = [3, 12, 44, 78, 94, 122, 186]
AB = [A,B]
lens = [len(A), len(B)]
C = []
curr = [0, 0]
idx = 0
while curr[idx] < lens[idx]:
val = AB[idx][curr[idx]]
C.append(val)
idx = 1 - idx
#curr[idx] = bisect.bisect_right(AB[idx], val 1, curr[idx] 1)
while curr[idx] < lens[idx] and AB[idx][curr[idx]] <= val:
curr[idx] = 1
print(C)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/435223.html
