why it is returning me only [0] - python-3.x

Why it is the filter method below returning [0]? I want all values where y[x] % 1 == 0
list1=[]
list2=[]
a=0
b=0
c=0.5
d=65
z=0
while a!=100:
list1.append(a)
a=a+1
while b!=50:
list1.append(c)
b=b+1
c=c+0.43
while d!=115:
list1.append(chr(d))
d=d+1
print(len(list1))
print(list1)
def filter(e,x,y):
while x != 200:
if y[x] % 1 == 0:
e.append(y[x])
x=x+1
return e
print(filter(list2,z,list1))
Why it is returning [0]? I want to return all values those where y[x] % 1 == 0
Why isn't the while executing first? It is returning the result of having run the loop only once.

Use isinstance to test for an integer.
Change
if y[x] % 1 == 0:
to
if isinstance(y[x], int):
But if you want to include floats that have only zeroes after the decimal point, then you need to watch out for slight errors in floating point representation. So in that case...
if isinstance(y[x], int) or abs(y[x] - int(y[x])) < .000001:
You can pick the very small number to match the precision you are working at. For instance if all your floats are sums of numbers with maximum 2 decimal places, you could use .005

Related

How to find the first odd digit in an integer recursively

I am new to python and am trying to get more comfortable with recursion. I am trying to find the first odd digit of a integer recursively. If there are no odd digits found return -1. Whenever I run this code I always get 35 instead of just 5.
This is what I have tried
def first_odd(n):
if n == 0:
return 0
elif n % 2 == 1:
return first_odd(n//10) * 10 + n%10
else:
return first_odd(n//10)
print(first_odd(2345))
If I understand your recent comment to Tarik correctly, it sounds like you want a function that will return the first odd digit scanning an integer right to left and if no odd digits are found then return -1. For example, in your original post you stated that with the integer 2345 you expected the value of 3, but based on your comment it sounds like 5 would be the correct answer scanning right to left, right? If so, then the following code should meet that description.
from random import randint
def find_rightmost_odd_digit(number):
while number:
rightmost_digit = number % 10
if rightmost_digit % 2:
return rightmost_digit
number = number // 10
return -1
for _ in range(10):
number = randint(0, 1000)
print(f"{number:>10}{find_rightmost_odd_digit(number):>4}")
Output:
387 7
88 -1
639 9
196 9
986 9
232 3
82 -1
907 7
948 9
214 1
You were basically on the correct track but just included an extra recursion you didn't need. Consider:
def first_odd(n):
if n == 0:
return -1
if n % 2 == 1: # number is odd, return last digit
return n % 10
return first_odd(n // 10)
If this works as intended, then I might implement it as follows to combine a couple of the divisions:
def first_odd(n):
if n == 0:
return -1
quotient, remainder = divmod(n, 10)
if remainder % 2 == 1: # remainder is odd, return it
return remainder
return first_odd(quotient)
Is there also a way to find the first odd digit from left to right
using 1 parameter?
from math import log10
def first_left_odd(n):
if n == 0:
return -1
power = 10 ** int(log10(n))
digit = n // power
if digit % 2 == 1:
return digit
return first_left_odd(n - digit * power)
Or if using the math library and/or log10() is an issue, then:
def first_left_odd(n):
if n < 10:
return n if n % 2 == 1 else -1
result = first_left_odd(n // 10)
if result != -1:
return result
return first_left_odd(n % 10)
Building complex programs is a matter of combining several simple programs. For this problem I would write a program that breaks a number into digits, and one that checks if any particular number is_odd -
def first_odd(n):
for d in digits(n):
if is_odd(d):
return d
return None
We can write digits and is_odd easily -
def is_odd(n):
return n & 1
def digits(n):
if n < 0:
yield from digits(n * -1)
elif n < 10:
yield n
else:
yield from digits(n // 10)
yield n % 10
print(first_odd(2345)) # 3
print(first_odd(6804721)) # 7
print(first_odd(2468)) # 9
print(first_odd(-465321)) # 5
This might do it:
def first_odd(n, digit):
if n == 0:
return None
elif n % 2 == 1:
return digit
else:
return first_odd(n//10, digit+1)
first_odd(2345, 0)
If you want the first digit to be 1, pass 1 instead of 0
Ok, this is for left to right:
def first_odd(n, digit):
if n == 0:
return None
pos = first_odd(n//10, digit+1)
if pos is None and n % 2 == 1:
return digit
else:
return pos

Python 3 for beginners Control Flow, While Loops and Break Statements

I bought a book to teach myself programming using Python.I am not taking any online course at the moment. I'm in chapter 2 and having problems with an exercise. I am to write a program that asks for 10 integers and then prints the largest odd number. If no odd number was entered, it should print a message saying so.
x = 0
largest_odd = int()
while(x < 10):
user_input = int(input('Enter an integer '))
if user_input%2 != 0 and user_input > largest_odd:
largest_odd = user_input
elif user_input%2 == 0 and x == 10:
print('no odd numbers')
x += 1
print(f'the largest odd number is {largest_odd}')
I am having a hard time entering all even numbers without printing the last print statement. I understand that the last print statement will print regardless because it is outside of the loop. But I've been on this the past few hours and can't figure out what I should change.
Please help.
If I understood the problem right you could just put a IF statement after the loop:
x = 0
largest_odd = 0
while x < 10:
user_input = int(input('Enter an integer '))
# check if x is odd and bigger than largest_odd
if user_input % 2 != 0 and user_input > largest_odd:
largest_odd = user_input
x += 1
if not largest_odd:
print('No odd numbers inputed!')
else:
print('The largest odd number is {}'.format(largest_odd))
You're on the right track with using the if-statements. What you need to do is to move the verification for if there were no odd numbers outside of the loop itself, and make an else-statement that prints out the largest if that isn't true:
x = 1
largest_odd = int()
while(x <= 10):
user_input = int(input(f'Enter an integer ({x}/10): '))
if user_input % 2 != 0 and user_input > largest_odd:
largest_odd = user_input
x += 1
if largest_odd == 0:
print('There was no odd numbers.')
else:
print(f'The largest odd number is {largest_odd}')
Because int() will default to 0 if you don't give it an argument, then we can use that as the verification, because 0 is not an even number.
I also changed the values of x changed the while-statement into x <= 10 so that we can make the representation of the input a little bit better.

Sum of odd and even digits of a number using recursion

I have currently set a code that adds the even or odd digits of a number. But when I run it, it does not add all the digits.
I know that modulus (%) and float division (//) should be used, but I cannot go on further. I only want to use recursion and while loop, since I haven't yet learned for loop.
def sum_even_digits(number):
if number == 0:
return 0
remainder = number % 10
if remainder % 2 == 1:
return 0
if remainder % 2 == 0:
return number % 10 + sum_even_digits(number // 10)
def sum_odd_digits(number):
if number == 0:
return 0
remainder = number % 10
if remainder % 2 == 0:
return 0
if remainder % 2 == 1:
return number % 10 + sum_even_digits(number // 10)
For instance, I expect the even digit sum of 256 is 8, but it only gives 6.
Your mistake is in your second case, when the remainder is not the kind of number you want to sum, you should not return 0. Returning 0 would mean not checking the rest of the number, which could still contain even/odd digits. You should just ignore the remainder and continue to recurse:
def sum_even_digits(number):
if number == 0:
return 0
remainder = number % 10
if remainder % 2 == 1:
return sum_even_digits(number // 10) # note this line
if remainder % 2 == 0:
return remainder + sum_even_digits(number // 10)
You need to loop through each digits.
Try this snippet in your function.
sum_even=0
sum_odd=0
number=123456789
while number!=0:
rem=number%10
If rem%2==0:
sum_even=sum_even+rem
else:
sum_odd+=rem
number=inte(number/10)
print("Sum of even digital is :", sun_even)
print("Sum of odd digital is :", sun_odd)

A function to manipulate strings ad numbers

I need the solution for a function that prints numbers from 1 to 100. For multiples of three print “Foo”
instead of the number and for the multiples of five print “Bar”. For numbers which are multiples of both three and five print “FooBar”. For the remaining numbers just print this number.
i = 0
while I < 100:
i += 1
print(i)
if i == 3:
print("Foo")
You will have to use mod (%) to check the remainder of a division.
See if i % 3 is equal to 0. If this is true, then print FOO.
If i % 5 equal 0, print Bar; and so on.
I would recommend using an if else statement in your while loop after the index counter. Something like...
i = 0
while i <= 100:
i += 1
if i % 15 == 0:
print("foobar")
elif i % 3 == 0;
print("foo")
elif i % 5 == 0:
print("bar")
else:
print(i)
Using % returns the remainder and if that returns a remainder of 0 then you know that it is evenly divisible by that number.
i = 0
while i < 100:
i += 1
if i%15 == 0:
print('FooBar')
elif i%3 == 0:
print('Foo')
elif i%5 == 0:
print('Bar')
else:
print(i)
Apply if and else statement to decide which is the situation during the while loop.
Also, % could return the remainder. 3 and 5 both are prime numbers, so a number which % (3*5) == 0 indicates itself is a multiples of 3 and 5.

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)

Resources