Re: [閒聊] 自學練習

看板Marginalman作者 (阿歐伊)時間1年前 (2024/08/11 12:26), 1年前編輯推噓2(202)
留言4則, 3人參與, 1年前最新討論串4/5 (看更多)
※ 引述《erimow (阿歐伊)》之銘言: : Write a function called "factorPrime" that takes an integer as input, and : returns the prime factorization of the input. : factorPrime(120); # returns "2 x 2 x 2 x 3 x 5" : 想了大概45分鐘 : 修修改改 : 屁都沒有 : 轉頭睡大覺 : 明天再來 早上起來去超市邊買邊想 想不出來 我一開始的想法是,我先找出所有這個數字會有的因數 再從因數裡面挑出是質數的部分,並從最小的質數2開始除 一直重覆到2不能除,然後在用下一個質數去除,除到不能除 但這個想法太暴力了,而且我自己寫了幾行真的寫不出來 只好看答案 def factorPrime(n): answer = str(n) + "=" # if n cannot be divided by 2 # then n cannot be divided any mulitples of 2 p = 2 while p <= n: if n % p == 0: answer += str(p) + "x" n = n / p else: p += 1 return answer[: len(answer) - 1] 我的理解是 首先設一個answer,後面的str(n)+"=" 這行應該只是為了美觀 就是最後會變成120=2*2*2*3*5而已 第2第3行感覺是我一開始想法的具體且簡潔可行的方式 他將2設成第一個拿來被除的質數,所以當n不能再被2整除 n也不能被任何2的倍數整除 所以當p<=n的時候,如果n%p可以整除 answer就加上這個str(p)+"x" 然後n變成n/=p 如果沒辦法被2整除,p就+1 全部跑完一輪就是答案了 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裡的就不再記就可以 #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 一個大lst裡面有3個中lst 3個中lst裡面又有兩個有4個小lst 所以我要做的事應該是用力往深處抽插,插到數字按順序拔出來,一個一個排好就可以 目前卡在插進去了抽不出來,先寫研究所要的東西== 這自學比較沒壓力 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 103.131.12.26 (澳大利亞) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1723350390.A.257.html ※ 編輯: erimow (103.131.12.26 澳大利亞), 08/11/2024 12:28:19

08/11 12:30, 1年前 , 1F
那解答看起來也挺爛的
08/11 12:30, 1F

08/11 12:32, 1年前 , 2F
因為他要寫給初學者看吧 初學者用解答==
08/11 12:32, 2F

08/11 12:32, 1年前 , 3F
大師
08/11 12:32, 3F

08/11 12:33, 1年前 , 4F
寫得太好我才真的看不懂
08/11 12:33, 4F
文章代碼(AID): #1ck3rs9N (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1ck3rs9N (Marginalman)