亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

遞歸函數,用于計算某個序列出現的次數

遞歸函數,用于計算某個序列出現的次數

慕田峪4524236 2022-08-02 16:52:35
我正在編寫一個遞歸函數,該函數將整數作為輸入,它將返回整數中出現123的次數。例如:打?。ㄒ欢?23123999123))將打印出 3,因為序列 123 在我輸入到函數中的數字中出現 3 次。這是我到目前為止的代碼:def onetwothree(x):    count = 0    while(x > 0):        x = x//10        count = count + 1    if (count < 3):  #here i check if the digits is less than 3, it can't have the sequence 123 if it doesn't have 3 digits        return 0    if (x%10==1 and x//10%10 == 2 and x//10//10%10==3):        counter += 1    else:        return(onetwothree(x//10))這會繼續打印“0”。
查看完整描述

2 回答

?
慕標琳琳

TA貢獻1830條經驗 獲得超9個贊

我認為你過度思考遞歸。像這樣的解決方案應該有效:


def onetwothree(n, count=0):

    if n <= 0:

        return count


    last_three_digits = n % 1000

    n_without_last_number = n // 10


    if last_three_digits == 123:

        return onetwothree(n_without_last_number, count + 1)

    else:

        return onetwothree(n_without_last_number, count)


print(onetwothree(123123999123))

輸出:


3


查看完整回答
反對 回復 2022-08-02
?
拉丁的傳說

TA貢獻1789條經驗 獲得超8個贊

如果要計算數字中“123”出現的次數,為什么不將數字從整數轉換為字符串并使用?str.count

然后你的函數將如下所示:

def onetwothree(x):
    return str(x).count('123')

但它也不再是遞歸的。

您也可以只使用與函數一起使用幾乎相同的行。print(str(123123999123).count('123'))onetwothree

我希望這個答案對:)


查看完整回答
反對 回復 2022-08-02
  • 2 回答
  • 0 關注
  • 132 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號