[英]How do I get my num_digit function to give me the correct output and how do I get it to return any integer value in python?
How do I get the function to return any integer such as negative numbers? 我如何获得该函数以返回任何整数,例如负数?
def num_digits(n): count = 0 while n: count = count + 1 n = abs(n) / 10 return count
I was working on question number 2 first. 我首先在研究第二个问题。 Even if I put the abs(n) in the line of code where while is, I still get an infinite loop which I still do not really understand why.
即使将abs(n)放在while所在的代码行中,我仍然会遇到一个无限循环,但我仍然不太明白为什么。 I figured if I can get my n value to always be positive and input in say -24, it would convert it to 24 and still count the number of values.
我计算出如果我可以使n值始终为正并输入“ -24”,它将把它转换为24并仍然计算值的数量。
On question 1, I do not know where to start, ive tried: 关于问题1,我不知道从哪里开始,我试过了:
def num_digits(n):
count = 0
while n:
if n == 0:
count = count + 1
n = n / 10
return count
I forgot to add I have limited tools to use since I am still learning python. 我忘了补充,因为我仍在学习python,因此我只能使用有限的工具。 I have gotten up to iterations and am studying the while loops and counters.
我已经开始迭代,正在研究while循环和计数器。 I have not gotten to break yet although I have an idea of what it does.
尽管我对它的功能有所了解,但我还没有休息。
When in doubt, brute force is always available: 如有疑问,可以随时使用蛮力:
def num_digits(n):
if n == 0:
return 1
if n < 0:
return num_digits(abs(n))
count = 0
while n:
count = count + 1
n = n / 10
return count
Process the exceptional cases first, and then you only have to deal with the regular ones. 首先处理例外情况,然后您只需要处理常规情况。
If you want to avoid the conditionals, I suggest taking abs(n)
only once, at the beginning, and using an infinite loop + break for the 0 case: 如果要避免使用条件,我建议在开始时只使用一次
abs(n)
,并在0情况下使用无限循环+中断:
def num_digits(n):
n = abs(n)
count = 0
while True:
count = count + 1
n = n / 10
if n == 0:
break
return count
For a more practical solution, you can either count the number of digits in the string (something like len(str(n))
for positive integers) or taking log
base 10, which is a mathematical way of counting digits. 对于更实际的解决方案,您可以对字符串中的位数进行计数
len(str(n))
对于正整数而言,类似于len(str(n))
)或采用log
10的对数,这是一种对位数进行数学计算的方式。
def num_digits(n):
if n == 0:
return 0
return math.floor(math.log10(math.abs(n)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.