A function to manipulate strings ad numbers - python-3.x

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.

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.

How do I write the fizzbuzz function in Python 3 with an input value?

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))

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)

Why this script doesn't run after the first line

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

Resources