![](/img/trans.png)
[英]Function digits(n) that returns how many digits the number has , returns a random value in python
[英]Trying to write a function that returns the number of digits in n that are divisble by m — Too much output - Python
我目前正在嘗試編寫一個 function ,它將n
和m
作為參數,然后返回n
中可被m
整除的位數。 這方面的一個例子可能是 n = 305689 和 m = 3。這里的答案是 4。
我的程序能夠得到這個結果,但是我正在工作的界面是說我的程序運行時間太長或產生太多 output。
到目前為止,這是我的程序:
def count_divisible_digits(n, m):
count = 0
while n != 0:
if (n % 10) % m == 0:
count += 1
#print("dbg", count, n)
n = n // 10
return count
嘗試將輸入 n 轉換為字符串數據類型並按如下方式獲取計數。 這應該更快。
def count_divisible_digits(n, m):
count = 0
string = str(n)
if n == 0 and m == 0:
return 0
elif m == 0:
return 0
elif n == 0:
return 1
elif n < 0:
x = 1
else:
x = 0
for i in range(x, len(string)):
if string[i] == '.' or 0 < int(string[i]) < m:
continue
elif int(string[i]) % m == 0:
count += 1
return count
再試一次,錯過0
✅ 立即檢查;
count =sum(1 for s in str(n) if int(s)%m==0 and int(s) >0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.