作者:
erimow (Erimo)
2024-08-11 15:03:36: Write a function called "intersection" that takes 2 lists, and returns an list
: of elements that are in the intersection of 2 list.
: 這題我的答案gpt說超級沒效率
: 不過他說是對的
: def intersection(lst1, lst2):
: result = []
: index_lst1 = 0
: index_lst2 = 0
: for i in range(0, len(lst1)):
: for j in range(0, len(lst2)):
: # print(lst1[i])
: if lst1[i] == lst2[j] and lst1[i] not in result:
: # print(lst1[i])
: # print(lst2[j])
: result.append(lst1[i])
: # index_lst2 += 1
: # result.append(lst1[index_lst1])
: # index_lst2 += 1
: return result
: print(intersection([1, 3, 4, 6, 10], [5, 11, 4, 3, 100, 144, 0]))
: print(intersection([1, 3, 3, 3, 4, 6, 10], [5, 11, 4, 3, 100, 144, 0]))
: # returns [3, 4]
: index_lst1 = 0
: index_lst2 = 0
: 這兩行是一開始想法的痕跡,後來沒用到
: 我本來是想用上次解007那題的方式
: 從lst1[0]開始,去對照lst2的每一個數字
: 當有重複就記錄下來,但不知道為啥寫不出來
: 所以就笨方法
: 設i和j,去把兩個lst所有數字比較一次,一樣就記錄下來
: 然後去重,已經在result裡的就不再記就可以
突然想到
這第二題沒有阻止我有intersection
return list(set(lst1).intersection(set(lst2)))
這樣好像就行了
把def的名字改掉就好
回到第三題抽插的部分
# Write a function called "flatten" that flattens an list.
flatten([1, [[], 2, [0, [1]], [3]], [1, 3, [3], [4, [1]], [2]]])
# returns [1, 2, 0, 1, 3, 1, 3, 3, 4, 1, 2]
插進去出不來
看解答
result = []
def flatten(lst):
for i in lst:
if type(i) == type([]):
flatten(i)
else:
result.append(i)
return result
print(flatten([1, [[], 2, [0, [1]], [3]], [1, 3, [3], [4, [1]], [2]]]))
# returns [1, 2, 0, 1, 3, 1, 3, 3, 4, 1, 2]
遞迴和stack都還沒學過
這兩篇講得大概能理解最最基本概念是什麼
雖然能看理解他在講啥,但要我自己用現在肯定不懂
https://medium.com/appworks-school/%E9%80%B2%E5%85%A5%E9%81%9E%E8%BF%B4-
recursion-%E7%9A%84%E4%B8%96%E7%95%8C-%E4%B8%80-59fa4b394ef6
https://medium.com/traveling-light-taipei/%E6%BC%94%E7%AE%97%E6%B3%95%E7%AD%86
%E8%A8%98-%E9%81%9E%E8%BF%B4-recursion-e66e81566679
兩個都有圖解,真棒