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
Related
I am writing a function fizzbuzz and what I want to do is input value and return it as fizz, buzz or fizzbuzz. However, there is a problem with my code. Whenever I run this, I just only get the first condition and it does not continue. Here is the code below for you:
a=int(input('Enter a number: '))
def fizzbuzz(a):
if a % 3 == 0:
return ('Fizz')
elif a % 5 == 0:
return ( 'Buzz' )
elif a % 15 == 0:
return ('Fizzbuzz')
else:
return a
print(fizzbuzz(a))
The problem is in the ordering of your if conditionals.
Consider that if a is divisible by 15 then it is also divisible by 3 and 5 and so your code will just enter the first conditional and not the one you want.
Arrange the conditionals in descending order of 15, 5, 3 etc. and you should see what you want.
def fizzBuzz(n):
for n in range(1,n+1):
if n % 3 == 0 and n % 5 == 0:
print('FizzBuzz')
elif n % 3 == 0:
print('Fizz')
elif n % 5 == 0:
print('Buzz')
else:
print(n)
if __name__ == '__main__':
n = int(input().strip())
fizzBuzz(n)
Be sure that your conditions are checked in the right order.
A Fizzbuzz number is also a Fizz (divisible by 3) and a Buzz (divisible by 5), just to be clear.
In the code you wrote if you ask the function if 15 is a Buzz, since it is the 1st check, you will get a positive result.
The condition you want to test here is not if a number is divisible by 15 but if a number is divisible by 3 and 5 at the same time.
Given this explanation you need to write conditions a bit differently:
a=int(input('Enter a number: '))
def fizzbuzz(a):
if a % 3 == 0 and a % 5 == 0:
return('Fizzbuzz')
elif a % 3 == 0:
return('Fizz')
elif a % 5 == 0:
return('Buzz')
else:
return a
print(fizzbuzz(a))
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)
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.
tweak = int(input("Input an integer"))
def collatz(number):
while number != 1:
if number % 2 == 0:
return int(number)
elif number % 2 != 0:
return int((3 * number) + 1)
print(number)
collatz(tweak)
If you are trying to implement a Collatz conjecture script, then your first if is wrong - you should divide the number by 2. Also, your return causes the function to end, so you get only one while loop, doesn't matter what happens inside - so you basically return the number you inputed or that number * 3 + 1.
Here is the correct code with slight modifications:
tweak = int(input("Input an integer"))
def collatz(number):
steps = 0
num = number
while number != 1:
if number % 2 == 0:
number = number / 2
else:
number = int(3 * number + 1)
steps +=1
print("Reached 1 in {} iterations for number {}.".format(steps, num))
collatz(tweak)
You also don't need the elif, because number can only be dividable by 2 or not.
Example outputs:
collatz(22)
collatz(55)
collatz(234)
Reached 1 in 15 iterations for number 22.
Reached 1 in 112 iterations for number 55.
Reached 1 in 21 iterations for number 234.
Your question has only code, but I think this is what you might be looking for:
def collatz(tweak):
while tweak != 1:
if tweak % 2 == 0:
return int(tweak)
elif tweak % 2 != 0:
return int((3 * tweak) + 1)
print(tweak)
tweak = int(input("Input an integer:"))
result = collatz(tweak)
print(result)
Your returning values in if and else so it wont print beyond..
instead assign it in variable and do print..
tweak = input("Input an integer")
def collatz(number):
while number != 1:
if number % 2 == 0:
return int(number)
elif number % 2 != 0:
return int((3 * number) + 1)
print number # this wont work.. your returned already
print "output:%s"%collatz(tweak)
output:
me#dev-007:~/Desktop$ python test.py
Input an integer10
number 10
output:10
I've been working on this for a while and I've just met the condition of not including the number itself in the addition. but it seems to notwant to get passed 3. is it my logic? And why does this list keep returning as None?
Any assistance would be appreciated
def sum_divisors(n):
div = 1
total = []
while (n % div) == 0:
if n == 0:
return 0
if (n % div) == 0:
n = int(n / div)
total.append(div)
total.append(n)
if div == 1:
total.remove(n)
div += 1
print(total) #this is to check if the list is working (it's not)
else:
return sum(total)
# Return the sum of all divisors of n, not including n
print(sum_divisors(0))
# 0
#print(sum_divisors(3)) # Should sum of 1
1
print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18
# 55
print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51
# 114
try the placeholder: "hello %s what would you like to do?" % name... hope this helps. More on placeholders: Placeholders in Python.