[英]How do I count the number of specific digits in an integer
I want to make a program so that it counts the total number of 6's between two integers.我想编写一个程序,以便计算两个整数之间 6 的总数。
For example the total number of 6's that appear from 1 to 99 is 20.例如,从 1 到 99 出现的 6 的总数是 20。
How would I make this for larger numbers on python?我如何在 python 上为更大的数字做这个?
Would appreciate help!将不胜感激帮助!
I'd do it with sum
and count
:我会用sum
和count
来做:
>>> sum(str(n).count("6") for n in range(1, 100))
20
>>> sum(str(n).count("6") for n in range(1, 100000))
50000
>>> sum(str(n).count("6") for n in range(1, 10000000))
7000000
For much larger numbers you might need to come up with some clever algorithmic trick rather than actually doing it as a linear operation.对于更大的数字,您可能需要想出一些巧妙的算法技巧,而不是实际将其作为线性运算来执行。 I can roughly envision something with recursion and memoization that involves getting the answer for a smaller subset of the digits, multiplying it by 10 for each of the 10 digits that can be combined with it, and then adding 1 for the 6 that occurs in one of those possibilities, but if you don't actually need to do this for numbers that greatly exceed a million I wouldn't bother.我可以粗略地设想一些带有递归和记忆的东西,它涉及为较小的数字子集获取答案,对于可以与其组合的 10 个数字中的每个数字乘以 10,然后为出现在一个数字中的 6 个数字加 1这些可能性中的一部分,但如果您实际上不需要为远远超过一百万的数字执行此操作,我不会打扰。
这里有一些可能对你有用的东西,我不知道你想要解析多大的数字......
str(list(range(1, 1000000))).count('6')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.