Recursion function for counting the number of digits in a number? - python

So I know that this is something simple that can be done without a recursion function but I need to know the backside to this as I can't seem to figure out how to write this using recursion. im using this so far
n = int(raw_input("What is n? "))
def digit(n):
if n< 10:
return 1
else:
new = n/10
print 1 + digit(new/10)
return 1 + digit(new/10)
digit(n)
Now if I type in a number such as 33 then it outputs 2 but if I do a longer number then it doesn't print it properly and I was unsure as to what exactly it wrong with it.

The problem is,
new = n/10
return 1 + digit(new/10)
You are already dividing the number by 10, in new = n / 10, which reduces the last digit and you are again dividing it by 10 before calling digit. So, you are ignoring 1 digit in every recursive call.
Instead, you can simply do
return 1 + digit(n / 10)
or
new = n / 10
return 1 + digit(new)

#!/usr/bin/python
n = int(raw_input("What is n? "))
def digit(n):
if n < 10:
return 1
else:
return 1 + digit(n/10)
print digit(n)

You can do like this too.
def counter(number):
if(number == 0):
return 0
return counter(int(number/10)) + 1
number = 1998
print(counter(number)) // it will print 4

Related

Finding the last digits sum with recursion

I'm attempting to create a function that will sum all the digits
and will return the sum of the summarized number.
Example:
For Input getNumValue(1589)
The Output will be: 5
Becuase: 1 + 5 + 8 + 9 = 23
And 2 + 3 = 5
So the output will be 5
Because we can't split it into more digits.
I did managed to create a recursion function that summarize the digits:
def getNumValue(number: int):
if number == 0:
return 0
return (number % 10 + getNumValue(int(number / 10)))
But I can't seem to utilize it to my cause.
Btw
I don't want to use any strings
And I'm trying to use recursion so far no luck.
I bet this is a known mathematic problem I'm just unfamiliar with.
Any advice?
Even shorter:
def getNumValue(number: int): return ((number-1) % 9) + 1
The digit sum is always in the same remainder class mod 9 as the original decimal number, this applies recursively, and thus reducing it to one digit just is the remainder under division by 9.
The shift by 1 just serves the purpose that the remainder class 0 is represented by 9.
you can make a final check before returning the answer.
def getNumValue(number: int):
if number == 0:
return 0
answer = (number % 10 + getNumValue(int(number // 10)))
if answer < 10:
return answer
return getNumValue(answer)
print(getNumValue(15899999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999))
OUTPUT :
9
You can check if number is greater than 9. If yes, then call the function again:
def getNumValue(number: int):
if number == 0:
return 0
j=(number % 10 + getNumValue(int(number // 10)))
if j>9:
return getNumValue(j)
return j
print(getNumValue(getNumValue(1589)))
Without recursion:
def getNumValue(number: int) -> int:
while True:
total = 0
while number:
total += number % 10
number //= 10
number = total
if total <= 9:
return total
>>> getNumValue(number)
5
pythonic recursion :)
def getNumValue(number=1589):
ans = number % 10 + getNumValue(int(number / 10)) if number else 0
return getNumValue(ans) if ans > 10 else ans
output
5

Don't understand why code for digit sum isn't working

I tried to do the codewars Sum of Digits/Digital Root problem, where you have to:
Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.
So passing through 52 would return 7, as 5 + 2 is 7 and passing through 942 would return 6, as 9 + 4 + 2 = 15 and then 1 + 5 = 6.
I came up with this code:
def digital_root(n):
n_str = str(n)
digit_total = 0
while len(n_str) != 1:
for digit in n_str:
digit_total += int(digit)
n_str = str(digit_total)
return(n_str)
But it only works for 2 digit numbers and it won't work for higher digit numbers, it just endlessly runs. This code is probably a bad way to do it and I've looked over other people's answers and I get their solution but I just don't get why this won't work for higher digit numbers.
You have got your program almost right. The only challenge I see is with resetting the variable digit_total = 0 after each iteration.
def digital_root(n):
n_str = str(n)
while len(n_str) != 1:
digit_total = 0 #move this inside the while loop
for digit in n_str:
digit_total += int(digit)
n_str = str(digit_total)
return(n_str)
print (digital_root(23485))
The output for print (digital_root(23485)) is 4
2 + 3 + 4 + 8 + 5 = 22
2 + 2 = 4
If the digit_total = 0 is not inside the while loop, then it keeps getting added and you get a never ending loop.
While you have a lot of code, you can do this in a single line.
def sum_digits(n):
while len(str(n)) > 1: n = sum(int(i) for i in str(n))
return n
print (sum_digits(23485))
You don't need to create too many variables and get lost in keeping track of them.
Alex,
running a recursive function would always be better than a while loop in such scenarios.
Try this :
def digital_root(n):
n=sum([int(i) for i in str(n)])
if len(str(n))==1:
print(n)
else:
digital_root(n)

Factors of a number using Python recursive function

I've got an assignment which requires me to use a Python recursive function to output the factors of a user inputted number in the form of below:
Enter an integer: 6 <-- user input
The factors of 6 are:
1
2
3
6
I feel like a bit lost now and have tried doing everything myself for the past 2 hours but simply cannot get there. I'd rather be pushed in the right direction if possible than shown where my code needs to be changed as I'd like to learn
Below is my code:
def NumFactors(x):
for i in range(1, x + 1):
if x == 1:
return 1
if x % i == 0:
return i
return NumFactors(x-1)
x = int(input('Enter an integer: '))
print('The factors of', x, 'are: ', NumFactors(x))
In your code the problem is the for loop inside the method. The loop starts from one and goes to the first if condition and everything terminates there. That is why it only prints 1 as the output this is a slightly modified version of your own code. This should help. If you have any queries feel free to ask.
def factors(x):
if x == 1:
print(1 ,end =" ")
elif num % x == 0:
factors(x-1)
print(x, end =" ")
else:
factors(x-1)
x = num = int(input('Enter an integer: '))
print('The factors of', x, 'are: ',end =" ")
factors(x)
Since this question is almost 3 years old, I'll just give the answer rather than the requested push in the right direction:
def factors (x,c=1):
if c == x: return x
else:
if x%c == 0: print(c)
return factors(x,c+1)
Your recursion is passing down x-1 which will not give you the right value. For example: the number of factors in 6 cannot be obtained from the number of factors in 5.
I'm assuming that you are not looking for the number of prime factors but only the factors that correspond to the multiplication of two numbers.
This would not normally require recursion so you can decide on any F(n) = F(n-1) pattern. For example, you could use the current factor as a starting point for finding the next one:
def NumFactors(N,F=1):
count = 1 if N%F == 0 else 0
if F == N : return count
return count + NumFactors(N,F+1)
You could also optimize this to count two factors at a time up to the square root of N and greatly reduce the number of recursions:
def NumFactors(N,F=1):
count = 1 if N%F == 0 else 0
if N != F : count = count * 2
if F*F >= N : return count
return count + NumFactors(N,F+1)

Sum of all prime numbers between 1 and N in Python

I'm new to programming. While trying to solve this problem, I'm getting the wrong answer. I checked my code a number of times but was not able to figure out the mistake. Please, help me on this simple problem. The problem is as follows:
Given a positive integer N, calculate the sum of all prime numbers between 1 and N (inclusive). The first line of input contains an integer T denoting the number of test cases. T testcases follow. Each testcase contains one line of input containing N. For each testcase, in a new line, print the sum of all prime numbers between 1 and N.
And my code is:
from math import sqrt
sum = 0
test = int(input())
for i in range(test):
max = int(input())
if max==1:
sum = 0
elif max==2:
sum += 2
else:
sum = sum + 2
for x in range(3,max+1):
half = int(sqrt(max)) + 1
for y in range(2,half):
res = x%y
if res==0:
sum = sum + x
break
print(sum)
For input 5 and 10, my code is giving output 6 and 48 respectively, while the correct answer is 10 and 17 respectively. Please, figure out the mistake in my code.
Here, I implemented simple program to find the sum of all prime numbers between 1 to n.
Consider primeAddition() as a function and ip as an input parameter. It may help you to solve your problem.Try it.
Code snippet:
def primeAddition(ip):
# list to store prime numbers...
prime = [True] * (ip + 1)
p = 2
while p * p <= ip:
# If prime[p] is not changed, then it is a prime...
if prime[p] == True:
# Update all multiples of p...
i = p * 2
while i <= ip:
prime[i] = False
i += p
p += 1
# Return sum of prime numbers...
sum = 0
for i in range (2, ip + 1):
if(prime[i]):
sum += i
return sum
#The program is ready... Now, time to call the primeAddition() function with any argument... Here I pass 5 as an argument...
#Function call...
print primeAddition(5)
This is the most broken part of your code, it's doing the opposite of what you want:
res = x%y
if res==0:
sum = sum + x
break
You only increment sum if you get through the entire loop without breaking. (And don't use sum as you're redefining a Python built-in.) This can be checked using the special case of else on a for loop, aka "no break". I've made that change below as well as corrected some inefficiencies:
from math import sqrt
T = int(input())
for _ in range(T):
N = int(input())
sum_of_primes = 0
if N < 2:
pass
elif N == 2:
sum_of_primes = 2
else:
sum_of_primes = 2
for number in range(3, N + 1, 2):
for odd in range(3, int(sqrt(number)) + 1, 2):
if (number % odd) == 0:
break
else: # no break
sum_of_primes += number
print(sum_of_primes)
OUTPUT
> python3 test.py
3
5
10
10
17
23
100
>
A slight modification to what you have:
from math import sqrt
sum = 0
test = int(input())
max = int(input())
for x in range(test,max+1):
if x == 1:
pass
else:
half = int(sqrt(x)) + 1
for y in range(2,half):
res = x%y
if res==0:
break
else:
sum = sum + x
print(sum)
Your biggest error was that you were doing the sum = sum + x before the break rather than outside in an else statement.
PS: (although you can) I'd recommend not using variable names like max and sum in your code. These are special functions that are now overridden.
Because your logic is not correct.
for y in range(2,half):
res = x%y
if res==0:
sum = sum + x
break
here you check for the factors and if there is a factor then adds to sum which is opposite of the Primes. So check for the numbers where there is no factors(except 1).
from math import sqrt
test = int(input())
for i in range(test):
sum = 0
max = int(input())
if max==1:
sum = 0
elif max==2:
sum += 2
else:
sum = sum + 2
for x in range(3,max+1):
half = int(sqrt(x)) + 1
if all(x%y!=0 for y in range(2,half)):
sum = sum + x
print(sum)
First of all, declare sum to be zero at the beginning of the for i loop.
The problem lies in the if statement at almost the very end of the code, as you add x to the sum, if the res is equal to zero, meaning that the number is indeed not a prime number. You can see that this is the case, because you get an output of 6 when entering 5, as the only non-prime number in the range 1 to and including 5 is 4 and you add 2 to the sum at the beginning already.
Last but not least, you should change the
half = int(sqrt(max)) + 1
line to
half = int(sqrt(x)) + 1
Try to work with my information provided and fix the code yourself. You learn the most by not copying other people's code.
Happy coding!
I believe the mistake in your code might be coming from the following lines of code:
for x in range(3,max+1):
half = int(sqrt(max)) + 1
Since you are looping using x, you should change int(sqrt(max)) to int(sqrt(x)) like this:
for x in range(3,max+1):
half = int(sqrt(x)) + 1
Your code is trying to see if max is prime N times, where you should be seeing if every number from 1-N is prime instead.
This is my first time answering a question so if you need more help just let me know.

Integer returned as sum of digits?

Here is what I'm supposed to write:
a function, countDigits, which will take an integer as a parameter and return the sum of its digits (you must use a for loop). For instance, the number 123 would return 6 (1 + 2 + 3)
a main function which will count numbers starting at one, and ending when the total digits (for all the numbers) exceeds 1,000,000. So, if you want the total digits for the number 5, you would add:
1 = 1
2 = 2 + 1
3 = 3 + 3
4 = 6 + 4
5 = 10 + 5, so 15 would be the total digit count.
your program will print both the number and the digit count before it exceeds 1,000,000. This is easiest with a while loop.
I've written the code for the function countDigits, which is:
def countDigits():
value=int(input('Enter Integer: '))
str_num= str(value)
total = 0
for ch in str_num:
total += int(ch)
print(total)
However, I'm stuck as to how to write the main function. Can anyone point me in the right direction?
EDIT
Here is my revised countDigits function:
def countDigits(value):
str_num= str(value)
total = 0
for ch in str_num:
total += int(ch)
print(total)
a one-liner:
factorial_digit_sum = lambda x: sum( sum(map(int, str(a))) for a in range(1,x+1) )
If you EVER write real code like this, Guido will hunt you down. Was kind of a fun brain teaser to golf, though.
For a real answer:
def countDigits(number):
return sum(map(int, str(number)))
def main():
total = 0
count = 1
while total <= 1000000:
total += countDigits(count)
total -= countDigits(count) # you want the number BEFORE it hits 1000000
print("Summing the digits of {}! yields {}".format(count, total))
main()
The problem in your code is that your countDigits function requests user input. You should change that to accepting the integer as a parameter. It also prints the result instead of returning it.
As #Blorgbeard mentioned in the comments, change countDigits to accept an integer as input. Also, return the total from it.
In the main function, read input, call countDigits and add them in a while loop until the total is greater than 1,000,000
def countDigits(value):
str_num= str(value)
total = 0
for ch in str_num:
total += int(ch)
return total
grandTotal = 0
while ( grandTotal < 1000000 ):
value=int(input('Enter Integer: '))
grandTotal += countDigits(value)

Categories

Resources