[英]Trying to write a function that returns the number of digits in n that are divisble by m — Too much output - Python
I'm currently trying to write a function that will take n
and m
as an argument and then will return the number of digits in n
that are divisible by m
.我目前正在尝试编写一个 function ,它将
n
和m
作为参数,然后返回n
中可被m
整除的位数。 An example of this could be n = 305689 and m = 3. The answer here would be 4.这方面的一个例子可能是 n = 305689 和 m = 3。这里的答案是 4。
My program is able to get this result, but the interface I'm working is is saying that my program is running for too long or producing too much output.我的程序能够得到这个结果,但是我正在工作的界面是说我的程序运行时间太长或产生太多 output。
Here's my program so far:到目前为止,这是我的程序:
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
Try converting the input n to string datatype and getting the count as follows.尝试将输入 n 转换为字符串数据类型并按如下方式获取计数。 This should be faster.
这应该更快。
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
Try this again, miss the 0
✅ check now;再试一次,错过
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.