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 num_digit function return 1 instead of 0 whenever put in 0 parameter in function?
how function return integer such negative numbers?
def num_digits(n): count = 0 while n: count = count + 1 n = abs(n) / 10 return count
i working on question number 2 first. if put abs(n) in line of code while is, still infinite loop still not understand why. figured if can n value positive , input in -24, convert 24 , still count number of values.
on question 1, not know start, ive tried:
def num_digits(n): count = 0 while n: if n == 0: count = count + 1 n = n / 10 return count
i forgot add have limited tools use since still learning python. have gotten iterations , studying while loops , counters. have not gotten break yet although have idea of does.
when in doubt, brute force 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 exceptional cases first, , have deal regular ones.
if want avoid conditionals, suggest taking abs(n)
once, @ beginning, , using infinite loop + break 0 case:
def num_digits(n): n = abs(n) count = 0 while true: count = count + 1 n = n / 10 if n == 0: break return count
for more practical solution, can either count number of digits in string (something len(str(n))
positive integers) or taking log
base 10, mathematical way of counting digits.
Comments
Post a Comment