【发布时间】:2014-10-18 05:19:26
【问题描述】:
通过一本自学书,他们为您提供了一些代码,以找出特定数字在整数中的次数。他们是如何自动知道使用模 10 的?作为程序员,这是您在 CompSci 课程中学到的技巧吗?
def num_zero_and_five_digits(n):
count = 0
while n:
digit = n % 10 # This divides w/10 for remainder. How did they know to use 10?
if digit == 0 or digit == 5: #These can be changed to whatever digits you want.
count = count + 1
n = n / 10
return count
我理解代码,但不拥有它。我的意思是,如果我被要求“编写代码”来找出某个数字在整数中的次数,我个人会 做这样的事情:
integer = str(22342445)
looker = list(integer)
counter = 0
find = raw_input("What number are you looking for")
for num in looker:
if find == num:
print "We found it!"
counter += 1
print "There are %d, %s's in %s" % (counter, find,integer )
现在,我的主要问题是:
如果有人想查找整数“10”或更高的值怎么办?如何 我可以在第一个解决方案中解释这一点吗?
您个人会采取哪些步骤来提出第一个解决方案?你怎么会“知道”你需要做模10?
【问题讨论】:
-
这太宽泛了,可能也应该转移到数学 SO 并且也在寻找外部资源。你真的应该把它分解成多个单独的问题。
-
我会把它剪掉一点,让它不那么宽泛。
标签: python python-2.7 math logic modulo