iT邦幫忙

0

目前遇到一些return不出數值的情況 ((LeetCode問題 38. Count and Say ))

  • 分享至 

  • twitterImage

問題網址: [https://leetcode.com/problems/count-and-say/]

本小弟目前已經解題完成,但是遇到一些疑問,這是我的程式碼。

class Solution(object):
        def countAndSay(self, n):
            if n == 1:  return '1'
            ans = '1'
            for _ in range(1, n):
                ans = self.DD(ans)
            return ans

        def DD(self, s:str):
            ans = ''
            curr = 1
            for i in range(1, len(s)):
                if s[i] == s[i - 1]:
                    curr += 1
                else:
                    ans += str(curr) + s[i - 1]
                    curr = 1

            ans += str(curr) + s[-1]
            return ans

在n = 5 的情況下,答案應該輸出:
https://ithelp.ithome.com.tw/upload/images/20211221/20138613i9mAJxemTS.png

而在去掉倒數第二行 ans += str(curr) + s[-1] 的情況下,輸出卻變成了:
https://ithelp.ithome.com.tw/upload/images/20211221/20138613sMQT47Jul7.png

最差的情況應該不是少了幾位數字而不是直接空白,請問有大大能夠替我解答嗎?

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

5
海綿寶寶
iT邦大神 1 級 ‧ 2021-12-22 09:00:33
最佳解答

插兩隻旗子
用以看出有沒有ans += str(curr) + s[-1]這列的差異

            print('before s=%s ans=%s' % (s, ans))
            ans += str(curr) + s[-1]
            print('after  s=%s ans=%s' % (s, ans))

測試結果如下
成功版本(原程式碼)
https://ithelp.ithome.com.tw/upload/images/20211222/20001787e9c1jOb8Py.png
失敗版本(把 ans += str(curr) + s[-1] 註解掉)
https://ithelp.ithome.com.tw/upload/images/20211222/20001787zgJDesQTUm.png

可以看出失敗版本在 n=1 得到的結果 ans = ""
因此不管再怎麼繼續往下傳
ans 都是空字串,再也不會累加

謝謝解惑

2
一級屠豬士
iT邦大師 1 級 ‧ 2021-12-21 23:34:43

另一種方式

from itertools import groupby

def cntandjoin(nums):
  return ''.join( str(len(list(g))) + k
               for k, g in groupby(nums))

def cntandsay(n):
  numstr = '1'
  for _ in range(n):
    print(numstr)
    numstr = cntandjoin(numstr)



if __name__ == '__main__':
  for i in range(1,5):
    print("i = ", i)
    print('-' * 10)
    cntandsay(i)
    print('*' * 10)

https://ithelp.ithome.com.tw/upload/images/20211221/20050647WtoSAwqqxg.png

謝謝解惑

我要發表回答

立即登入回答