Next Palindrome number - python-3.x

I want the final number as returned by the function, the following code is running, but not returning the correct value, the correct value is printed by the print statement above return satatement, how can return it ??
the correct answer is 22. but 13 is too printed.
def palindrome(num):
num = num+1
num = str(num)
if num[::-1]!=num:
palindrome(int(num))
else:
print(int(num))
return int(num)
palindrome(12)
>RESULT---
22
13

Seems that this could be done in a better way.
def palindrome(num):
if str(num) == str(num)[::-1]:
print(num)
return num
else:
palindrome(num+1)

Your recursive function returns 13 because this is the result of the first call to your function. The other iterations from your recursion are lost since you don't save it in your recursive call to palindrome.
You'll want to set your call to palindrome as your return also:
if num[::-1] != num:
return palindrome(int(num))

a = int(input("enter the no. of choices"))
for i in range(a):
b = int(input("enter all no."))
for j in range(b , 10000000000000000):
count = 0
pal = str(j)
b += 1
if (pal == pal[::-1]):
print(j)
break
else:
continue

Related

How to fix issue where python won't call a function from within a loop

At the yes/no loop, the program won't call the function to re-perform a calculation. Instead, it asks to compute another gcd repeatedly instead of calling the specified function.
I've tried re-inputting the whole function into the question loop if the user inputs yes, but that did not work either.
def gcd(n,m):
if(m==0):
return n
else:
return gcd(m,n%m)
n = int(input("Enter a positive whole number:"))
while True:
if n <= 0:
print ("The number entered is not a positive number!, please try again")
n = int(input("Enter a positive whole number : "))
if n > 0: break
m = int(input("Enter a second positive whole number:"))
while True:
if m <= 0:
print ("The number entered is not a positive number!, please try again")
m = int(input("Enter a positive whole number : "))
if m > 0: break
GCD = gcd(n,m)
print("The GCD of the two numbers you entered is:" ,GCD)
while True:
a = input("Compute another GCD? Enter y/n:").lower()
if a=="y":
gcd(n,m)
elif a=="n":
break
else:
print("Invalid entry. Please enter either y/n:")
print("Goodbye!")
Expected results is that it calls the function gcd(n,m) and re-performs a calculation. Actual results is that it asks to perform another calculation without having actually completed a second calculation.
The function is called. The problem is that you don't do anything with its return value.
You will also need to ask the user for new input. In order to not repeat the same code again you can have a function that does that.
Then the whole code becomes:
def get_2_numbers():
n = int(input("Enter a positive whole number:"))
while True:
if n <= 0:
print ("The number entered is not a positive number!, please try again")
n = int(input("Enter a positive whole number : "))
if n > 0: break
m = int(input("Enter a second positive whole number:"))
while True:
if m <= 0:
print ("The number entered is not a positive number!, please try again")
m = int(input("Enter a positive whole number : "))
if m > 0: break
return n, m
def gcd(n,m):
if(m==0):
return n
else:
return gcd(m,n%m)
a, b = get_2_numbers()
while True:
answer = input("Compute another GCD? Enter y/n:").lower()
if answer == "y":
print(gcd(a, b))
a, b = get_2_numbers()
elif answer == "n":
break
else:
print("Invalid entry. Please enter either y/n:")
print("Goodbye!")
A small downside is that the user will have to answer y even before the first calculation, but I'll leave that as an exercise to the reader.

Count not incrementing properly in python while loop

Can anyone tell me why when I input 1, 2, 3, and 4 into this code, my output is 6, 2, 3.00? I thought that every time my while loop evaluated to true it would increment the count by one, but the output is not making sense. It's taking the total of 3 of the numbers, but only 2 for the count? I'm probably just overlooking something so an extra pair of eyes would be awesome.
def calcAverage(total, count):
average = float(total)/float(count)
return format(average, ',.2f')
def inputPositiveInteger():
str_in = input("Please enter a positive integer, anything else to quit: ")
if not str_in.isdigit():
return -1
else:
try:
pos_int = int(str_in)
return pos_int
except:
return -1
def main():
total = 0
count = 0
while inputPositiveInteger() != -1:
total += inputPositiveInteger()
count += 1
else:
if count != 0:
print(total)
print(count)
print(calcAverage(total, count))
main()
The error with your code is that on this piece of code...
while inputPositiveInteger() != -1:
total += inputPositiveInteger()
You first call inputPositiveInteger and throw out the result in your condition. You need to store the result, otherwise one input out of two is ignored and the other is added even if it is -1.
num = inputPositiveInteger()
while num != -1:
total += num
count += 1
num = inputPositiveInteger()
Improvements
Although, note that your code can be significantly improved. See the comments in the following improved version of your code.
def calcAverage(total, count):
# In Python3, / is a float division you do not need a float cast
average = total / count
return format(average, ',.2f')
def inputPositiveInteger():
str_int = input("Please enter a positive integer, anything else to quit: ")
# If str_int.isdigit() returns True you can safely assume the int cast will work
return int(str_int) if str_int.isdigit() else -1
# In Python, we usually rely on this format to run the main script
if __name__ == '__main__':
# Using the second form of iter is a neat way to loop over user inputs
nums = iter(inputPositiveInteger, -1)
sum_ = sum(nums)
print(sum_)
print(len(nums))
print(calcAverage(sum_, len(nums)))
One detail worth reading about in the above code is the second form of iter.

Finding the logical error in my code to get first 50 primes

I'm trying to write my own formula to find a prime number, but it does not completely work and I cannot find the flaw in my logic. Bare in mind I have taken a look around but cannot find an algorithm that I find similar to mine.
My code:
#Challenge 7
prime = []
num = 0
found = False
while found == False:
if num == 0 or num == 1:
num+=1
else:
for value in range(2, num+1):
if len(prime) == 50:
print('Found all')
found = True
break
if num % value == 0:
num+=1
else:
if num not in prime:
prime.append(num)
else:
pass
print(prime)
This code works for first few primes (3, 5, 7...)
but it also gives incorrect values like 10, and I don't understand why. If someone could explain it to me so that I can understand where the logical mistake is, I'd appreciate it.
The error comes from this part
if num % value == 0:
num+=1
else:
if num not in prime:
prime.append(num)
else:
pass
You assume that the integer is a prime as soon as we find the first occurence of a non-divisor. But the def for primes is that every integer in the interval [2..prime] is a non-divisor. How do we check if any number does not have any divisors?
def isPrime(x):
for v in range(2, x):
if (x % v == 0):
return False;
return True;
Something like this would work to check if any given number is a prime or not. And since we now have taken the isPrime part out of the main loop, we no longer need a for loop inside the while. Something like this would do
def isPrime(x):
for v in range(2, x):
if (x % v == 0):
return False;
return True;
prime = [}
num = 2
found = False
while found == False:
if len(prime) == 50:
print("found all")
found = True
break
if(isPrime(num)):
print(num)
prime.append(num)
num+=1
else:
num+=1
If you set a breakpoint for when num == 10 you will see the problem clearly.
When you start doing you division check inside of for value in range(2, num + 1): the second number is 3, so num (10) modulo value (3) is 1, which is your test for determining a prime. What your test should be is that it not divisible by any number less than it (less than half is actually sufficient since you check with 2 anyway).
So, consider instead:
else:
is_indivisible = True
# loop through all numbers less than it not including itself
# (because x % x == 0)
for value in range(2, num - 1):
# it is only indivisible if it was previously indivisible
# And the check is same as before, modulo != 0
is_indivisible = is_indivisible and (num % value != 0)
if not is_indivisible:
break
# if it is indivisible and it doesn't exist in prime list yet
if is_indivisible and num not in prime:
prime.append(num)
# move on to the next number
num += 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)

What is wrong with my function? Giving me a blank output

def get_nearest_multiple(minnum, factor):
"""
function get_nearest_multiple will calculate the nearest multiple that is greater than the min. value,
Parameters are the minimum value and factor,
Will return the ans - the nearest multiple
"""
ans = 0
x = 1
while ans < minnum:
if minnum == 0:
ans = 0
else:
ans = x * factor
x += 1
return ans
get_nearest_multiple(0, 1)
if __name__ == '__main__':
get_nearest_multiple(0, 1)
Can't seem to figure out why my function doesn't print out anything. The output doesn't even show up as an error. Just blank.
Nowhere in your code do you have a print() statement which is required to produce an output in the console

Resources