[問題] python新手問題

看板Python作者 (雞爪)時間7年前 (2018/07/29 02:09), 編輯推噓2(209)
留言11則, 4人參與, 7年前最新討論串3/4 (看更多)
各位先進好 小弟在刷leetcode 796題 Rotate String碰到了一個問題 以下是小弟的code (寫法不是很concise,Discuss中有很多更好的寫法,不過我想知道自己錯在哪) class Solution(object): def rotateString(self, A, B): """ :type A: str :type B: str :rtype: bool """ if A == B: return True return self.detector(A,B,0) def detector(self,A,B,count): if count == len(B): return False if A == B: # print("here") return True index = 0 b = list(B) bcopy = list(B) for i in range(0,len(b)): if i == len(b)-1: index = index-5 b[i] = bcopy[index+1] index +=1 C = "".join(b) self.detector(A,C,count+1) 邏輯上是沒問題的,我試著用print在函式detector中檢查過,有print出來 但最後回到函式rotateString中,return的卻是null 請問程式該怎麼改才會return True呢? 感謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.170.46.205 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1532801340.A.016.html

07/29 02:29, 7年前 , 1F
沒認真想過解法的邏輯 不過為什麼要index-5呀 寫這樣很
07/29 02:29, 1F

07/29 02:29, 7年前 , 2F
magic number 的感覺
07/29 02:29, 2F

07/29 02:29, 7年前 , 3F
另外這題一行就可以搞定 可以多多熟悉寫法~
07/29 02:29, 3F

07/29 02:32, 7年前 , 4F
抱歉 沒看到是rotate 不過也是幾行就可以
07/29 02:32, 4F

07/29 03:10, 7年前 , 5F
應該是寫index-len(b)才對
07/29 03:10, 5F

07/29 03:11, 7年前 , 6F
不過為何return的是null?
07/29 03:11, 6F

07/29 04:27, 7年前 , 7F
在最後一行前面加上return
07/29 04:27, 7F

07/29 04:28, 7年前 , 8F
會接到 None 就表示 function 沒有回傳值
07/29 04:28, 8F

07/29 06:35, 7年前 , 9F
善用slice,一行就搞定。此外,會收到 Null,因為
07/29 06:35, 9F

07/29 06:36, 7年前 , 10F
detector() 函式中沒有 return。
07/29 06:36, 10F

07/29 19:51, 7年前 , 11F
懂了,謝
07/29 19:51, 11F
文章代碼(AID): #1RNB4y0M (Python)
文章代碼(AID): #1RNB4y0M (Python)