我的教授給了我一個 Python 作業來比較 2 個二維串列,如果串列中的所有物件都相似,則回傳 True,否則回傳 False。這些串列的型別是-list[list[int]]。這必須使用遞回來完成。我不允許使用回圈或切片。(但可以訪問串列中的特定索引)串列的內部劃分可能不同,但只要串列中相似位置的所有元素都相似,函式將回傳True。例如 - [[1], [2, 3, 4]] , [[1, 2], [3, 4]] - 該函式將回傳true。希望詳細說清楚,謝謝!
我的問題是找到解決這個問題的方法:)
uj5u.com熱心網友回復:
通常你做l[0]and l[1:]for carand cdr( firstand rest) 的串列。
這項任務的最大挑戰是禁止切片。
但是隨著
first, *rest = your_list
有用!不僅沒有切片,而且沒有索引。
def first(l): # traditionally in Lisp languages `CAR`
car, *cdr = l
return car
def rest(l): # traditionally in Lisp languages `CDR`
car, *cdr = l
return cdr
def comp(lol1, lol2):
if len(lol1) == len(lol2) == 0: # recursion end condition
return True
# if first elements are lists, `comp`are the firsts and the rests
elif type(first(lol1)) == type(first(lol2)) == list:
return comp(first(lol1), first(lol2)) and \
comp(rest(lol1), rest(lol2))
# if first elements are atoms (non-lists), `==` the firsts and `comp`are the rest
else: # then the firsts are atoms!
return first(lol1) == first(lol1) and \
comp(rest(lol1), rest(lol2))
# traditionally in Lisp languages, you test not for list
# but for `atom` (whether the first elements of the lists are
# non-lists -> atomar). But `atom` is not that easy test in Python.
# so it is must more easy to ask whether both first elements are lists - and
# if not - then it is clear that the first elements of non-empty lists must be non-lists => atoms.
這適用于 Python3,但不適用于 Python2。
對于 Python2 和 Python3,您可以使用函式定義:
def first(l):
return (lambda x, *y: x)(*l)
def rest(l):
return (lambda x, *y: y)(*l)
使用單一索引和 .pop()
也許你的老師想到的是:
def first(l):
return l[0]
def rest(l):
if l != []:
l.pop()
return l
else:
return []
# For definition of the `comp()` function see above
但是這個解決方案是有問題的,因為它改變了輸入串列,因為 Python 做了call-by-reference而不是call-by-value. 為避免這種情況,必須先對串列進行深度復制。可以使用切片對串列進行淺拷貝,但不允許切片......
喜歡:
q = [1, 2, [3, 4], [5, 6, 7], 8]
comp(q, q)
## True
# so far so good, but:
q
## []
uj5u.com熱心網友回復:
a1 = [[1], [2, 3, 4]]
a2 = [[1, 2], [3, 4]]
def get_next_indexes(i, j, a): # function for getting next indexes based on previous
return (i 1, 0)if j >= len(a[i]) - 1 else (i, j 1)
def compare_lists(i1, j1, i2, j2): # i1 and j1 - indexes for first array; i2 and j2 - indexes for second array
if i1 >= len(a1) or i2 >= len(a2):
print("Two lists are equal.")
exit(0)
if a1[i1][j1] != a2[i2][j2]:
print("Two lists are not equal.")
exit(0)
print(get_next_indexes(i1, j1, a1))
compare_lists(*get_next_indexes(i1, j1, a1), *get_next_indexes(i2, j2, a2))
compare_lists(0, 0, 0, 0)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/371652.html
下一篇:最長遞增子序列錯誤答案
