Question

Write a python program write a function numDigits(num) which counts the digits in int num. Answer...

Write a python program

write a function numDigits(num) which counts the digits in int num. Answer code is given in the Answer tab (and starting code), which converts num to a str, then uses the len() function to count and return the number of digits.

Note that this does NOT work correctly for num < 0. (Try it and see.) Fix this in two different ways, by creating new functions numDigits2(num) and numDigits3(num) that each return the correct number of digits for all values of num.

First try modifying numDigits(num) to create numDigits2(num). Do so by checking the sign of num and returning the correct value if num < 0.

Next, try a different approach, implementing your solution in numDigits3(num). Use a while loop and accumulator variable, repeatedly dividing num by 10 (use //) and incrementing the variable, until 0 is reached. Then return the value of the variable. But... there's a flaw in this approach for num==0 and others; make sure you fix them.

#
# Given Starter Code
#


def numDigits(num):
n_str = str(num)
return len(n_str)

def numDigits2(num):
return -1

def numDigits3(num):
# use a while loop here
return -1

def main():

number = int(input("Enter a integer: "))

print (number, 'has', numDigits(number), 'digits.')

print("%s has %d digits (different output)." % (number, numDigits(number))) # alternate output
print("%s has %d digits." % (number, numDigits2(number))) # alternate output
print("%s has %d digits." % (number, numDigits3(number))) # alternate output

# in the above, % is the old Python formatting operator:
#
# fmt-string % (v1,v2,...) results in each vN substituted into % slots within
# fmt-string, with slot types %d for int, %s for str, %f for float
#

main()

0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE :

#
# Given Starter Code
#
import math
def numDigits(num):
n_str = str(num)
return len(n_str)

def numDigits2(num):
n_str = str(num)
#If number is less than 0 return one less than the string length
if num<0:
return len(n_str)-1
else:
return len(n_str)

def numDigits3(num):
# use a while loop here
ans=0
#If number is 0 return 1
if num == 0 :
return 1
#If number is less than 0 , "//" gives floor of a number and gives wrong result
#Hence we use ceil function to using normal division
if num<0:
while num != 0:
num = num/10
num = math.ceil(num)
ans+=1
#If number is greater than 0 , then its as stated in the question
else:
while num != 0:
num = num//10
ans+=1
return ans

def main():

number = int(input("Enter a integer: "))
print (number, 'has', numDigits(number), 'digits.')
print("%s has %d digits (different output)." % (number, numDigits(number))) # alternate output
print("%s has %d digits." % (number, numDigits2(number))) # alternate output
print("%s has %d digits." % (number, numDigits3(number))) # alternate output
  
# in the above, % is the old Python formatting operator:
#
# fmt-string % (v1,v2,...) results in each vN substituted into % slots within
# fmt-string, with slot types %d for int, %s for str, %f for float
#

main()

Add a comment
Know the answer?
Add Answer to:
Write a python program write a function numDigits(num) which counts the digits in int num. Answer...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Python String Product Function Name: string Multiply Parameters: sentence (str), num (int) Returns: product (int) Description:...

    Python String Product Function Name: string Multiply Parameters: sentence (str), num (int) Returns: product (int) Description: You're texting your friend when you notice that they replace many letters with numbers. Out of curiosity, you want to find the product of the numbers. Write a function that takes in a string sentence and an int num, and find the product of only the first num numbers in the sentence. If num is 0, return 0. If num > O but there...

  • Page 3 of 7 (Python) For each substring in the input string t that matches the...

    Page 3 of 7 (Python) For each substring in the input string t that matches the regular expression r, the method call re. aub (r, o, t) substitutes the matching substring with the string a. Wwhat is the output? import re print (re.aub (r"l+\d+ " , "$, "be+345jk3726-45+9xyz")) a. "be$jk3726-455xyz" c. "bejkxyz" 9. b. "be$jks-$$xyz" d. $$$" A object a- A (2) 10. (Python) What is the output? # Source code file: A.py class A init (self, the x): self.x-...

  • 1. Questions Python Code: For each line of code, write the type of error (syntax, semantics,...

    1. Questions Python Code: For each line of code, write the type of error (syntax, semantics, runt-time), cause of the error, and your fix. (1) def fun(num letter) (2) num == 7 + num (3) return 'num' - letter (4) result = fun(5, x) 2. Question Python Code: Run the code below to check the outputs of the print() call on lines 12. And : A) Analyze the application of the accumulation pattern and answer the following questions: #1. a....

  • how to add the digits of the doubled values and the digits that were not doubled...

    how to add the digits of the doubled values and the digits that were not doubled from the original number in python? The first part prints it in a list: def toDigits(g): return [int (y) for y in str(g)] print (str(toDigits(759283))) The second part: prints every number and multiplies all by 2 def doubleEveryOther(g): return [int(y) * 2 if i % 2 == 0 else int(y) for i, y in enumerate(toDigits(g))] print(str(doubleEveryOther(759283))) The third part: I'm trying to add the...

  • 1) Fix the Function #include <iostream> void print Num() { std::cout << number; }; int main()...

    1) Fix the Function #include <iostream> void print Num() { std::cout << number; }; int main() { int number = 35; printNum (number); return 0; (Give two ways to fix this code. Indicate which is preferable and why.) #include <iostream> void double Number (int num) {num = num * 2;} int main() { int num = 35; double Number (num); std::cout << num; // Should print 70 return 0; (Changing the return type of doubleNumber is not a valid solution.)

  • Please, I need help debuuging my code. Sample output is below MINN = 1 MAXX =...

    Please, I need help debuuging my code. Sample output is below MINN = 1 MAXX = 100 #gets an integer def getValidInt(MINN, MAXX):     message = "Enter an integer between" + str(MINN) + "and" + str(MAXX)+ "(inclusive): "#message to ask the user     num = int(input(message))     while num < MINN or num > MAXX:         print("Invalid choice!")         num = int(input(message))     #return result     return num #counts dupes def twoInARow(numbers):     ans = "No duplicates next to each...

  • convert the following code from python to java. def topkFrequent(nums, k): if not nums: return [...

    convert the following code from python to java. def topkFrequent(nums, k): if not nums: return [ ] if len(nums) == 1: return nums [0] # first find freq freq dict d = {} for num in nums: if num in d: d[num] -= 1 # reverse the sign on the freq for the heap's sake else: d[num] = -1 h = [] from heapq import heappush, heappop for key in di heappush(h, (d[key], key)) res = [] count = 0...

  • IN PYTHON ''' Helper func 3: checksum_ISBN Input: a list with 9 single digit number in...

    IN PYTHON ''' Helper func 3: checksum_ISBN Input: a list with 9 single digit number in it (first 9 digit in ISBN) Output: print out: "The correct checksum digit is:__. Now we have a legit ISBN: _____" Hint: just loop through 0-9, test every one with helper func1 to find out the one checksum that forms a legit ISBN with the correct ISBN in lis (10 numbers), call helper func2 to format it correctly. Then print the final result. '''...

  • Just using print not return Imodify this function to not only return but also keep printing...

    Just using print not return Imodify this function to not only return but also keep printing def reverseoigits num): Reverse the digits of an Integer using recursion Return a string that contains the reversed number Returns None lt nu . 1 num < 0 return None num >= 0 and num < 9: return str(num) return str(num110) +reverseDigits (int(num/10)) RESTART: /cs/student/rkumaran/Labos pypy = >>>reversedigits(0) >>> reverse igits (6) >>> reverseDigits (52) >>reverseDigits (5328) >>> reverseDigits (-5328) >>> a = reversedioits/5328...

  • for this code fix the smtax error this is a python code for some reason my...

    for this code fix the smtax error this is a python code for some reason my code isnt liking my returns and it bring up other symtax error so fix the following code answer should pop out the following when runned 1/ 2 + 1/ 3 + 1/ 12 = 11/12 z=' ' def math(x,y):     global z     if y==0 or x==0:         return     if y%x ==0:         z=("1/"+str(int(y/x))         return      if x%y ==0         z+=(int(x/y))    ...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT