慕田峪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

拉丁的傳說
TA貢獻1789條經驗 獲得超8個贊
如果要計算數字中“123”出現的次數,為什么不將數字從整數轉換為字符串并使用?str.count
然后你的函數將如下所示:
def onetwothree(x): return str(x).count('123')
但它也不再是遞歸的。
您也可以只使用與函數一起使用幾乎相同的行。print(str(123123999123).count('123'))
onetwothree
我希望這個答案對:)
添加回答
舉報
0/150
提交
取消