I want to return the sum of all indexes in n via recursion. How do I do this? - python-3.x

def final_sum(n):
n = str(n)
if int(n) == 0:
return 0
else:
x = int(n[0])
return x + int(final_sum(n[1:]))
print(final_sum(123))
For example, if my n is 123, I should be getting 6. But I am having an error in this code. Can anyone help? I have to use recursive function. So tell me what's wrong with the code.

in return x + int(final_sum(n[1:])), n[1:] is str type
in the beginning of the function, with n = str(n), you assume the input is an int
Besides, you did not consider the case that n[1:] can be empty in return x + int(final_sum(n[1:])).
Here is an anwser based on your code
def final_sum(n):
if n == 0:
return 0
n = str(n)
x = int(n[0])
if len(n)==1:
return x
else:
return x + final_sum(int(n[1:]))
Here is another version using % operation
def final_sum(n):
if n < 10:
return n
return n % 10 + final_sum(n // 10)

First of all, at the beggining I would do this instead of casting back and forth:
def final_sum(n):
if n<10:
return n
You see, the problem is, in the last recursive iteration, you are passing this to the function:
final_sum("")
When you should be passing an int. I think this is happening because your last cast is backwards and you never check how many digits the number has. So the code should look like this:
def final_sum(n):
if n<10:
return n
n = str(n)
x = int(n[0])
return x + final_sum(int(n[1:]))
print(final_sum(123))

Related

How to sort a list into even then odd numbers using recursion when the function can only call itself and use basic list manipulations

The function takes in a list of integers and returns a list of the same elements sorted into the order of even integers then odd ones. Im struggling with implementing a recursive function to complete it even though I am able to solve this using a for loop.
def sort(lst: list[int]) -> list[int]:
l1 = []
l2 = []
for i in lst:
if i % 2 == 0:
l1.append(i)
else:
l2.append(i)
x = l1 + l2
return x
def eto(lst: list[int]) -> list[int]:
if len(lst) == 1
return lst
else:
y = lst[0]
x = lst[1:]
return(eto(x))
I'm not sure how to proceed from here.
I suppose we are allowed to reorder the odd numbers, as long as they are in the second part of the list. I completed your proposition:
def eto(lst: list[int]) -> list[int]:
if len(lst) <= 1:
return lst
head = lst[0]
tail = lst[1:]
if head % 2 == 0:
return [head] + eto(tail)
return eto(tail) + [head]

Why does my number reverser function produce an infinite loop

Whenever i try print the number reverser function i always get an infinite loop,instead of my expected output 54321. Can someone help find the problem? Thanks.
def order(num):
x=str(num)
if x==False:
return None
else:
return order(x[1:])+(x[0])
print (order(12345))
Welcome to your community.
There are some problems with your code:
First:
A string never will be equal to False.
for instance:
'0' is not equal to False.
'' is not equal to False.
Second:
You cannot add a String to None.
This Error will be thrown: TypeError: can only concatenate str (not "NoneType") to str
Modify your code like this:
def order(num):
x=str(num)
if x=='':
return ''
else:
return order(x[1:])+(x[0])
print (order(12345))
Tip 1: A string can be equal to '' (empty string).
In your function, you compare the string x with the boolean False. This is not a correct way to test whether string x is an empty string or not.
In addition, if string x is empty, then you shouldn't return None, but an empty string: reversing an empty string should logically return an empty string.
Here I present two ways to fix your function, which I implemented under the names reverse0 and reverse1. I also present a few other alternatives to achieve the same result using python features, under the names reverse2 to reverse6. Finally I present three other ways to reverse nonnegative integers, under the names reverse7 to reverse9.
def reverse0(num):
x = str(num)
if len(x) == 0:
return ''
else:
return reverse0(x[1:]) + x[0]
def reverse1(num):
x = str(num)
if not x:
return ''
else:
return reverse1(x[1:]) + x[0]
def reverse2(num):
return str(num)[::-1]
def reverse3(num):
return ''.join(reversed(str(num)))
def reverse4(num):
x = str(num)
return ''.join(x[len(x)-1-i] for i in range(len(x)))
def reverse5(num):
x = str(num)
return ''.join(x[-i] for i in range(1, len(x)+1))
def reverse6(num):
y = ''
for c in str(num):
y = c + y
return y
# reverse7 only works for nonnegative integers
def reverse7(num):
if num < 10:
return str(num)
else:
return str(num % 10) + reverse7(num // 10)
# reverse8 only works for nonnegative integers
def reverse8(num):
l = []
while num > 9:
l.append(num % 10)
num = num // 10
l.append(num)
return ''.join(str(d) for d in l)
# reverse9 only works for nonnegative integers
# reverse9 returns an int, not an str
def reverse9(num):
y = 0
while num > 0:
y = 10 * y + (num % 10)
num = num // 10
return y
Relevant documentation:
builtin reversed;
str.join;
An informal introduction to string slices such as x[::-1].

Using Recursive Functions in Python to find Factors of a Given Number

Have tried searching for this, but can't find exactly what I'm looking for.
I want to make a function that will recursively find the factors of a number; for example, the factors of 12 are 1, 2, 3, 4, 6 & 12.
I can write this fairly simply using a for loop with an if statement:
#a function to find the factors of a given number
def print_factors(x):
print ("The factors of %s are:" % number)
for i in range(1, x + 1):
if number % i == 0: #if the number divided by i is zero, then i is a factor of that number
print (i)
number = int(input("Enter a number: "))
print (print_factors(number))
However, when I try to change it to a recursive function, I am getting just a loop of the "The factors of x are:" statement. This is what I currently have:
#uses recursive function to print all the letters of an integer
def print_factors(x): #function to print factors of the number with the argument n
print ("The factors of %s are:" % number)
while print_factors(x) != 0: #to break the recursion loop
for i in range(1,x + 1):
if x % i == 0:
print (i)
number = int(input("Enter a number: "))
print_factors(number)
The error must be coming in either when I am calling the function again, or to do with the while loop (as far as I understand, you need a while loop in a recursive function, in order to break it?)
There are quite many problems with your recursive approach. In fact its not recursive at all.
1) Your function doesn't return anything but your while loop has a comparision while print_factors(x) != 0:
2) Even if your function was returning a value, it would never get to the point of evaluating it and comparing due to the way you have coded.
You are constantly calling your function with the same parameter over and over which is why you are getting a loop of print statements.
In a recursive approach, you define a problem in terms of a simpler version of itself.
And you need a base case to break out of recursive function, not a while loop.
Here is a very naive recursive approach.
def factors(x,i):
if i==0:
return
if x%i == 0:
print(i)
return factors (x,i-1) #simpler version of the problem
factors(12,12)
I think we do using below method:
def findfactor(n):
factorizeDict
def factorize(acc, x):
if(n%x == 0 and n/x >= x):
if(n/x > x):
acc += [x, n//x]
return factorize(acc, x+1)
else:
acc += [x]
return acc
elif(n%x != 0):
return factorize(acc, x+1)
else:
return acc
return factorize(list(), 1)
def factors(x,i=None) :
if i is None :
print('the factors of %s are : ' %x)
print(x,end=' ')
i = int(x/2)
if i == 0 :
return
if x % i == 0 :
print(i,end=' ')
return factors(x,i-1)
num1 = int(input('enter number : '))
print(factors(num1))
Recursion is a functional heritage and so using it with functional style yields the best results. This means avoiding things like mutations, variable reassignments, and other side effects. That said, here's how I'd write factors -
def factors(n, m = 2):
if m >= n:
return
if n % m == 0:
yield m
yield from factors(n, m + 1)
print(list(factors(10))) # [2,5]
print(list(factors(24))) # [2,3,4,6,8,12]
print(list(factors(99))) # [3,9,11,33]
And here's prime_factors -
def prime_factors(n, m = 2):
if m > n:
return
elif n % m == 0:
yield m
yield from prime_factors(n // m, m)
else:
yield from prime_factors(n, m + 1)
print(list(prime_factors(10))) # [2,5]
print(list(prime_factors(24))) # [2,2,2,3]
print(list(prime_factors(99))) # [3,3,11]
def fact (n , a = 2):
if n <= a :
return n
elif n % a != 0 :
return fact(n , a + 1 )
elif n % a == 0:
return str(a) + f" * {str(fact(n / a , a ))}"
Here is another way. The 'x' is the number you want to find the factors of. The 'c = 1' is used as a counter, using it we'll divide your number by 1, then by 2, all the way up to and including your nubmer, and if the modular returns a 0, then we know that number is a factor, so we print it out.
def factors (x,c=1):
if c == x: return x
else:
if x%c == 0: print(c)
return factors(x,c+1)

The result is coming back correct but not in correct format

I am doing an assignment and the answers are coming back correctly but I would need them to say 5! = 120 instead of just = 120. How would I go about that?
def getInt():
getInt = int
done = False
while not done:
print("This program calcultes N!")
# get input for "N
N = int(input("Please enter a non-negative value for N: "))
if N < 0:
print("Non-Negative integers, please!")
else:
done = True
return N
def main():
n = getInt()
for i in range(n-1):
n = n * (i+1)
print("=" ,n)
main()
I hope this code will help.
print('Enter a positive integer')
a = int(input())
def factorial(n):
if n == 0:
return(1)
if n == 1:
return(1)
if n > 1:
return(n * factorial(n-1))
if a < 0:
print('Non-Negative integers, please!')
if a >= 0:
print(str(a) + '! = ' + str(factorial(a)))
In the for i in range(n-1)you could use another integer instead of n just to be sure things don't mess up and you can print like joel said print(i,"!=", n) but instead of n the integer you will use.
can you show me your homework instructions?
i'm not sure what the first value is in your example.. the current iteration or the original number entered?
# declare getInt()
def getInt():
getInt = int
done = False
while not done:
# write "this program calculates N!"
print("This program calcultes N!")
# get input for "N
N = int(input("Please enter a non-negative value for N: "))
# if N < 0 then
if N < 0:
print("Non-Negative integers, please!")
# else
else:
# done = true
done = True
# return N
return N
# main
def main():
n = entry = getInt()
for i in range(n-1):
n = n * (i+1)
print("{0}! = {1}".format(entry, n))
main()
results:
/*
This program calcultes N!
Please enter a non-negative value for N: 5
5! = 120
*/

Invalid Syntax; nth prime number

def primetest(x):
if x < 2:
return False
if x == 2:
return True
if x % 2 == 0:
return False
for i in range(3,(x**0.5)+1):
if x % i == 0:
return False
return True
def nthprime(n):
primes = []
x = 2
while len(primes) < n:
if primetest(x) == True:
primes.append(x)
x = x + 1
return list(-1)
print nthprime(10001)
Whenever I try to run this it says that "print nthprime(10001)" is invalid syntax.
-prime test is to test wether a number is prime and nthprime creates a list of prime numbers a certain lengths and then return the last element of the list.
print is a function in Python 3, not a statement. You should change your last line of code to:
print(nthprime(10001))
In your code:
def nthprime(n):
primes = []
x = 2
while len(primes) < n:
if primetest(x) == True:
primes.append(x)
x = x + 1
return list(-1) // this is the error
I think you meant primes[-1], like this:
def nthprime(n):
primes = []
x = 2
while len(primes) < n:
if primetest(x) == True:
primes.append(x)
x = x + 1
return primes[-1] // this is now correct
You're also going to need to specify a range in integers, not float. So this:
for i in range(3,(x**0.5)+1):
Becomes this:
for i in range(3,int((x**0.5)+1)): // note the "int"

Resources