Author name: Vikram Chiluka

Python Program to Perform Addition

Given two numbers and the task is to find the addition of two numbers.

Also, given a list and the task is to find the addition of all the elements in a given list.

Examples:

Example1:

Input:

Given first number = 2
Given second number = 3

Output:

The addition of given two numbers { 2 + 3 } =  5

Example2:

Input:

Given List = [4, 7, 3, 1, 5]

Output:

The sum of all the elements of a given list [4, 7, 3, 1, 5] = 
20

Program to Perform Addition in Python

Method #1: Using + Operator (Static Input)

1) Addition using Functions

Approach:

  • Create a function say Additionof_2numbers() which accepts the given two numbers as the arguments and returns the addition of given two numbers.
  • Inside the function, add the given two numbers and store it in a variable.
  • Return the above result.
  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Pass the given two numbers as the arguments to the Additionof_2numbers() function and store it in another variable.
  • Print the addition of given two numbers
  • The Exit of the program.

Below is the implementation:

# Create a function say Additionof_2numbers() which accepts the given two numbers
# as the arguments and returns the addition of given two numbers.


def Additionof_2numbers(gvn_num1, gvn_num2):
    # Inside the function, add the given two numbers and store it in a variable.
    rsltsum = gvn_num1 + gvn_num2
    # Return the above result.
    return(rsltsum)

# Give the first number as static input and store it in a variable.
gvn_num1 = 2
# Give the second number as static input and store it in another variable.
gvn_num2 = 3
# Pass the given two numbers as the arguments to the Additionof_2numbers() function 
# and store it in another variable.
fnl_summ = Additionof_2numbers(gvn_num1, gvn_num2)
# Print the addition of given two numbers
print("The addition of given two numbers {",gvn_num1,"+",gvn_num2,"} = ",fnl_summ)

Output:

The addition of given two numbers { 2 + 3 } =  5

2)Addition of list Elements using for loop

Approach:

  • Give the list as static input and store it in a variable.
  • Take a variable and initialize its value to 0.
  • Loop in the given list using the for loop.
  • Add the element of the given list to the above declared rslt_sum variable and store it in the same variable.
  • Print the sum of all the elements of a given list.
  •  The Exit of the program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = [4, 7, 3, 1, 5]
# Take a variable and initialize its value to 0.
rslt_sum = 0
# Loop in the given list using the for loop.
for elemnt in gvn_lst:
    # Add the element of the given list to the above declared rslt_sum variable
        # and store it in the same variable.
    rslt_sum = rslt_sum+elemnt
# Print the sum of all the elements of a given list.
print("The sum of all the elements of a given list", gvn_lst, "= ")
print(rslt_sum)

Output:

The sum of all the elements of a given list [4, 7, 3, 1, 5] = 
20

Method #2: Using + Operator (User Input)

Approach:

  • Create a function say Additionof_2numbers() which accepts the given two numbers as the arguments and returns the addition of the given two numbers.
  • Inside the function, add the given two numbers and store it in a variable.
  • Return the above result.
  • Give the first number as user input using the int(input()) function and store it in a variable.
  • Give the second number as user input using the int(input()) function and store it in another variable.
  • Pass the given two numbers as the arguments to the Additionof_2numbers() function and store it in another variable.
  • Print the addition of two numbers.
  • The Exit of the program.

Below is the implementation:

# Create a function say Additionof_2numbers() which accepts the given two numbers
# as the arguments and returns the addition of given two numbers.


def Additionof_2numbers(gvn_num1, gvn_num2):
    # Inside the function, add the given two numbers and store it in a variable.
    rsltsum = gvn_num1 + gvn_num2
    # Return the above result.
    return(rsltsum)

# Give the first number as user input using the int(input()) fucntion and store it in a variable.
gvn_num1 = int(input("Enter some random number = "))
# Give the second number as user input using the int(input()) fucntion and store it in another variable.
gvn_num2 = int(input("Enter some random number = "))
# Pass the given two numbers as the arguments to the Additionof_2numbers() function 
# and store it in another variable.
fnl_summ = Additionof_2numbers(gvn_num1, gvn_num2)
# Print the addition of given two numbers
print("The addition of given two numbers {",gvn_num1,"+",gvn_num2,"} = ",fnl_summ)

Output:

Enter some random number = 55
Enter some random number = 45
The addition of given two numbers { 55 + 45 } = 100

2)Addition of list Elements using for loop

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Take a variable and initialize its value to 0.
  • Loop in the given list using the for loop.
  • Add the element of the given list to the above declared rslt_sum variable and store it in the same variable.
  • Print the sum of all the elements of a given list.
  •  The Exit of the program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))

# Take a variable and initialize its value to 0.
rslt_sum = 0
# Loop in the given list using the for loop.
for elemnt in gvn_lst:
    # Add the element of the given list to the above declared rslt_sum variable
        # and store it in the same variable.
    rslt_sum = rslt_sum+elemnt
# Print the sum of all the elements of a given list.
print("The sum of all the elements of a given list", gvn_lst, "= ")
print(rslt_sum)

Output:

Enter some random List Elements separated by spaces = 6 7 3 1 2
The sum of all the elements of a given list [6, 7, 3, 1, 2] = 
19

Python Program to Perform Addition Read More »

Python Program to Find the Smallest Number in 3 Easy Methods

Given a list and the task is to find the smallest number in the given list.

Let us see this python code in 3 easy methods. They are

  1. Using the min() function in Python.
  2. Using sort() function in Python.
  3. Using the for loop.

min() function:

min() is a Python built-in function that takes a list as an argument and returns the number with the smallest value in the list.

sort() Function:

sort() is another Python built-in method that does not return the smallest number in the list. Instead, it arranges the items in ascending order.
So, by sorting the list, we can use indexing to access the first element of the list, which will be the smallest number in the list.

Examples:

Example1:

Input:

Given list = [9, 6, -3, -20, 4]

Output:

The given list's [9, 6, -3, -20, 4] smallest value =  -20

Example2:

Input:

Given list =  [3, 7, 8, 1, 0]

Output:

The given list's [3, 7, 8, 1, 0] smallest value = 0

Program to Find the Smallest Number in 3 Easy Methods

Method #1: Using Built-in Functions (Static Input)

1)Using the min() function in Python.

Approach:

  • Give the list as static input and store it in a variable.
  • Pass the given list to the min() function that gives the smallest value in the given list.
  • Store it in another variable.
  • Print the smallest value in the given list.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = [9, 6, -3, -20, 4]
# Pass the given list to the min() function that gives the smallest value in
# the given list.
# Store it in another variable.
small_numbr = min(gvn_lst)
# Print the smallest value in the given list.
print("The given list's", gvn_lst, "smallest value = ", small_numbr)

Output:

The given list's [9, 6, -3, -20, 4] smallest value =  -20

2)Using sort() function in Python.

Approach:

  • Give the list as static input and store it in a variable.
  • Apply sort() function to the given list that sorts the given list in ascending order.
  • Get the first element(smallest value) of the given list and store it in another variable.
  • Print the smallest value in the given list.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = [9, 6, -3, -20, 4]
# Apply sort() function to the given list that sorts the given list in
# ascending order
gvn_lst.sort()
# Get the first element(smallest value) of the given list and store it in
# a variable.
small_numbr = gvn_lst[0]
# Print the smallest value in the given list.
print("The given list's", gvn_lst, "smallest value = ", small_numbr)

Output:

The given list's [-20, -3, 4, 6, 9] smallest value =  -20

3) Using the for loop.

Approach:

  • Give the list as static input and store it in a variable.
  • Take a variable say smalest_elemnt and initialize it with the first element of the given list.
  • Calculate the length of the given list using the len() function and store it in a variable.
  • Loop till the length of the given list using the for loop.
  • Check if the iterator value of the given list is less than the above-initialized variable value.
  • If it is true, then assign the iterator value of the given list to the above-initialized variable(smalest_elemnt).
  • Print the variable smalest_elemnt which is the smallest element in the given list.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = [2, 3, 9, -10, -11, 2, 4]
# Take a variable say smalest_elemnt and initialize it with the first element
# of the given list
smalest_elemnt = gvn_lst[0]
# Calculate the length of the given list using the len() function and store it
# in a variable.
lst_len = len(gvn_lst)
# Loop till the length of the given list using the for loop.
for itr in range(lst_len):
    # Check if the iterator value of the given list is less than the above-initialized
        # variable value.
    if gvn_lst[itr] < smalest_elemnt:
        # If it is true, then assign the iterator value of the given list to the
        # above-initialized variable(smalest_elemnt).
        # (Now this becomes the smallest element)
        smalest_elemnt = gvn_lst[itr]
# Print the variable smalest_elemnt which is the smallest element in the given list.
print("The given list's smallest element = ", smalest_elemnt)

Output:

The given list's smallest element =  -11

Method #2: Using Built-in Functions (User Input)

1)Using the min() function in Python.

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Pass the given list to the min() function that gives the smallest value in the given list.
  • Store it in another variable.
  • Print the smallest value in the given list.
  • The Exit of the Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Pass the given list to the min() function that gives the smallest value in
# the given list.
# Store it in another variable.
small_numbr = min(gvn_lst)
# Print the smallest value in the given list.
print("The given list's", gvn_lst, "smallest value = ", small_numbr)

Output:

Enter some random List Elements separated by spaces = 3 7 8 1 0
The given list's [3, 7, 8, 1, 0] smallest value = 0

2)Using sort() function in Python.

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Apply sort() function to the given list that sorts the given list in ascending order.
  • Get the first element(smallest value) of the given list and store it in another variable.
  • Print the smallest value in the given list.
  • The Exit of the Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Apply sort() function to the given list that sorts the given list in
# ascending order
gvn_lst.sort()
# Get the first element(smallest value) of the given list and store it in
# a variable.
small_numbr = gvn_lst[0]
# Print the smallest value in the given list.
print("The given list's", gvn_lst, "smallest value = ", small_numbr)

Output:

Enter some random List Elements separated by spaces = 5 7 8 3 9
The given list's [3, 5, 7, 8, 9] smallest value = 3

3) Using the for loop.

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Take a variable say smalest_elemnt and initialize it with the first element of the given list.
  • Calculate the length of the given list using the len() function and store it in a variable.
  • Loop till the length of the given list using the for loop.
  • Check if the iterator value of the given list is less than the above-initialized variable value.
  • If it is true, then assign the iterator value of the given list to the above-initialized variable(smalest_elemnt).
  • Print the variable smalest_elemnt which is the smallest element in the given list.
  • The Exit of the Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Take a variable say smalest_elemnt and initialize it with the first element
# of the given list
smalest_elemnt = gvn_lst[0]
# Calculate the length of the given list using the len() function and store it
# in a variable.
lst_len = len(gvn_lst)
# Loop till the length of the given list using the for loop.
for itr in range(lst_len):
    # Check if the iterator value of the given list is less than the above-initialized
        # variable value.
    if gvn_lst[itr] < smalest_elemnt:
        # If it is true, then assign the iterator value of the given list to the
        # above-initialized variable(smalest_elemnt).
        # (Now this becomes the smallest element)
        smalest_elemnt = gvn_lst[itr]
# Print the variable smalest_elemnt which is the smallest element in the given list.
print("The given list's smallest element = ", smalest_elemnt)

Output:

Enter some random List Elements separated by spaces = -7 5 6 10 -12 12
The given list's smallest element = -12

Python Program to Find the Smallest Number in 3 Easy Methods Read More »

Python Program for Multi-Conditional If Statement

Python If Statement :

The ‘If’ statement is a conditional statement that is used to determine whether or not a specific expression is true. The program control first checks the condition written with’if ‘, and if the condition is true, the if block is executed. Otherwise, the program control is transferred to the else block and executed.

Syntax:

if(condition):
    block code 1
else:
    block code 2

If the condition is met, block code 1 is executed. If this is not the case, block code 2 is executed.

We all use a basic if statement, which is an if statement with only one condition. This is used to compare one variable to another or to determine whether a variable is true or false.

For Example:

gvn_num = int(input("Enter some random number = "))
# condition to check whether the given number is even or odd.
if((gvn_num % 2) == 0):
    print("The given number is an Even Number")
else:
    print("The given number is an Odd Number")

Output:

Enter some random number = 10
The given number is an Even Number

Multiple Conditions in If Statement

Multiple conditions can be used in a single if statement by using AND, OR, or BOTH.

Syntax:

if ((condition1) AND/OR (condition2)) :
    block code 1
else :
    block code 2

Program for Multi-Conditional If Statement

Method #1: Using If statement (Static Input)

1)Using AND

Approach:

  • Give the age as static input and store it in a variable.
  • Give the experience as static input and store it in another variable.
  • Check if the given age is greater than 25 and less than 55 and experience is greater than 3 using the if conditional statement.
  • If it is true, then print “congrats you are selected”.
  • Else print “You are not qualified sorry”.
  • The Exit of the Program.

Below is the implementation:

# Give the age as static input and store it in a variable.
gvn_age = 32
# Give the experience as static input and store it in another variable.
gvn_expernce = 5
# Check if the given age is greater than 25 and less than 55 and experience is
# greater than 3 using the if conditional statement
if (gvn_age > 25 and gvn_age < 55) and (gvn_expernce > 3):
    # If it is true, then print "congrats you are selected".
    print("congrats you are selected")
else:
    # Else print "You are not qualified sorry".
    print("You are not qualified sorry")

Output:

congrats you are selected

2) Using OR

When you want at least one condition to be satisfied, you use the OR condition.

Approach:

  • Give the number as static input and store it in a variable.
  • Get the remainder by dividing the given number by 10 and store it in another variable.
  • Check if the above-obtained remainder is equal to 0 or 5 using the if conditional statement and or condition.
  • If it is true, then print “The given number is divisible by 5”.
  • Else, print “The given number is NOT divisible by 5”.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_num = 45
# Get the remainder by dividing the given number by 10 and store it in another
# variable.
remaindr = gvn_num % 10
# Check if the above-obtained remainder is equal to 0 or 5 using the if
# conditional statement and or condition.
if (remaindr == 0) or (remaindr == 5):
    #If it is true, then print "The given number is divisible by 5".
    print("The given number{", gvn_num, "} is divisible by 5")
else:
    #Else, print "The given number is NOT divisible by 5".
    print("The given number{", gvn_num, "} is NOT divisible by 5")

Output:

The given number{ 45 } is divisible by 5

Method #2: Using If statement (User Input)

1)Using AND 

Approach:

  • Give the age as user input using the int(input()) function and store it in a variable.
  • Give the experience as user input using the int(input()) function and store it in another variable.
  • Check if the given age is greater than 25 and less than 55 and experience is greater than 3 using the if conditional statement.
  • If it is true, then print “congrats you are selected”.
  • Else print “You are not qualified sorry”.
  • The Exit of the Program.

Below is the implementation:

# Give the age as user input using the int(input()) function and store it in a variable.
gvn_age = int(input("Enter some random number(age) = "))
# Give the experience as user input using the int(input()) function and 
# store it in another variable.
gvn_expernce = int(input("Enter some random number(experience) = "))
# Check if the given age is greater than 25 and less than 55 and experience is
# greater than 3 using the if conditional statement
if (gvn_age > 25 and gvn_age < 55) and (gvn_expernce > 3):
    # If it is true, then print "congrats you are selected".
    print("congrats you are selected")
else:
    # Else print "You are not qualified sorry".
    print("You are not qualified sorry")

Output:

Enter some random number(age) = 22
Enter some random number(experience) = 3
You are not qualified sorry

2) Using OR

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Get the remainder by dividing the given number by 10 and store it in another variable.
  • Check if the above-obtained remainder is equal to 0 or 5 using the if conditional statement and or condition.
  • If it is true, then print “The given number is divisible by 5”.
  • Else, print “The given number is NOT divisible by 5”.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function and store it in a variable.
gvn_num = int(input("Enter some random number = "))
# Get the remainder by dividing the given number by 10 and store it in another
# variable.
remaindr = gvn_num % 10
# Check if the above-obtained remainder is equal to 0 or 5 using the if
# conditional statement and or condition.
if (remaindr == 0) or (remaindr == 5):
    #If it is true, then print "The given number is divisible by 5".
    print("The given number{", gvn_num, "} is divisible by 5")
else:
    #Else, print "The given number is NOT divisible by 5".
    print("The given number{", gvn_num, "} is NOT divisible by 5")

Output:

Enter some random number = 28
The given number{ 28 } is NOT divisible by 5

Python Program for Multi-Conditional If Statement Read More »

Python Program for Computing Parity of a Word.

Parity of a Word:

A binary word’s parity is:

  • If the word contains an odd number of ones, it is assigned a value of 1.
  • If the word contains an even number of ones, it is assigned a value of 0.

For Example:

Given word = 0111 (7)

No of 1’s = 3

The given word has an odd number of 1’s. Hence the parity is 1.

Examples:

Example1:

Input:

Given Number =7

Output:

 The parity of the given number = 1

Example2:

Input:

Given Number =10

Output:

 The parity of the given number = 0

Program for Computing Parity of a Word in Python

Method #1: Using XOR Operator (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Take a variable and initialize its value with 0.
  • Loop until the given number is not equal to 0 using the while loop.
  • Check if the AND operation of the given number and 1 is equal to 1 using the And operator and if conditional statement. (Determine whether the current LSB is 1 or 0.)
  • If it is true, then perform the XOR operation for the above-initalized variable and 1 and store it in the same variable. It will alternately change the parity from 0 to 1 and vice versa.
  • Right shift the given number and store it in the same variable.
  • Print the parity of the given number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_num = 7
# Take a variable and initialize its value with 0.
rslt_parityy = 0
# Loop until the given number is not equal to 0 using the while loop.
while(gvn_num != 0):

    # Check if the AND operation of the given number and 1 is equal to 1 using the
        # And operator and if conditional statement.
        # (Determine whether the current LSB is 1 or 0.)
    if((gvn_num & 1) == 1):
        # If it is true, then perform the XOR operation for the above-initalized
        # variable and 1 and store it in the same variable.
        # It will alternately change the parity from 0 to 1 and vice versa.
        rslt_parityy ^= 1

    # Right shift the given number and store it in the same variable.
    gvn_num >>= 1
# Print the parity of the given number.
print("The  parity of the given number = ", rslt_parityy)

Output:

The parity of the given number = 1

Method #2: Using XOR Operator (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Take a variable and initialize its value with 0.
  • Loop until the given number is not equal to 0 using the while loop.
  • Check if the AND operation of the given number and 1 is equal to 1 using the And operator and if conditional statement. (Determine whether the current LSB is 1 or 0.)
  • If it is true, then perform the XOR operation for the above-initalized variable and 1 and store it in the same variable. It will alternately change the parity from 0 to 1 and vice versa.
  • Right shift the given number and store it in the same variable.
  • Print the parity of the given number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input and store it in a variable.
gvn_num = int(input('Enter some random number = '))
# Take a variable and initialize its value with 0.
rslt_parityy = 0
# Loop until the given number is not equal to 0 using the while loop.
while(gvn_num != 0):

    # Check if the AND operation of the given number and 1 is equal to 1 using the
        # And operator and if conditional statement.
        # (Determine whether the current LSB is 1 or 0.)
    if((gvn_num & 1) == 1):
        # If it is true, then perform the XOR operation for the above-initalized
        # variable and 1 and store it in the same variable.
        # It will alternately change the parity from 0 to 1 and vice versa.
        rslt_parityy ^= 1

    # Right shift the given number and store it in the same variable.
    gvn_num >>= 1
# Print the parity of the given number.
print("The  parity of the given number = ", rslt_parityy)

Output:

Enter some random number = 10 
The parity of the given number = 0

Python Program for Computing Parity of a Word. Read More »

Python Program to Find Number of Possible Strings With No Consecutive 1s

Given an integer n, which represents the length of the string, or the number of bits in the final string.

The task is to obtain a string with n bits and no consecutive 1s, which means that 11(binary) is prohibited in the string.

There are two possibilities for any string:
If the first element is zero, the second element can be either zero or one.
In the other instance, if the initial element is 1, the sole option for the next element is 0.

Our task is to count the number of such possible strings that match the above-mentioned requirement.

Examples:

Example1:

Input:

Given number = 2

Output:

The total number of possible strings for the given number { 2 } =  3

Example2:

Input:

Given number = 3

Output:

The total number of possible strings for the given number { 3 } = 5

Program to Find Number of Possible Strings With No Consecutive 1s in Python

This can be solved manually or via the recursion method. The recursion method is a superior, more efficient, and faster method of solving the problem.

Before going into the problem just have a glance over the recursion.

The two things are as follows:

The first digit is 1, then the second bit is set to 0 and we check for n-2 places left in the final string.
The first digit is 0, and we next look for n-1 places left in the string.

                                      n                          number of possible strings

0                            0

1                             2   (0, 1)

2                            3   (00, 01, 10)

We will consider the two cases in all circumstances when n is bigger than 2.

Method #1: Using Recursion (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Create a recursive function say numberof_ways() which accepts the given number as an argument and returns the number of possible strings with no consecutive 1’s.
  • Inside the function, check if the given number is equal to 0 using the if conditional statement.
  • If it is true, then return 0.
  • Check if the given number is less than 3 using the if conditional statement.
  • If it is true, then return the value given number+1.
  • Return the value numberof_ways(gvn_n-1) + numberof_ways(gvn_n-2) (Recursive Logic).
  • Pass the given number as an argument to the numberof_ways() function and store it in a variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function say numberof_ways() which accepts the given number
# as an argument and returns the number of possible strings with no
# consecutive 1's


def numberof_ways(gvn_n):
     # Inside the function, check if the given number is equal to 0 using the if
     # conditional statement.
    if(gvn_n == 0):
        # If it is true, then return 0.
        return 0
    # Check if the given number is less than 3 using the if
    # conditional statement.
    if(gvn_n < 3):
        # If it is true, then return the value given number+1
        return gvn_n+1
    # Return the value numberof_ways(gvn_n-1) + numberof_ways(gvn_n-2).
    # (Recursive Logic)
    return numberof_ways(gvn_n-1) + numberof_ways(gvn_n-2)


# Give the number as static input and store it in a variable.
gvn_n = 2
# Pass the given number as an argument to the numberof_ways() function and
# store it in a variable.
rslt = numberof_ways(gvn_n)
# Print the above result.
print(
    "The total number of possible strings for the given number {", gvn_n, "} = ", rslt)

Output:

The total number of possible strings for the given number { 2 } =  3

Method #2: Using Recursion (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Create a recursive function say numberof_ways() which accepts the given number as an argument and returns the number of possible strings with no consecutive 1’s.
  • Inside the function, check if the given number is equal to 0 using the if conditional statement.
  • If it is true, then return 0.
  • Check if the given number is less than 3 using the if conditional statement.
  • If it is true, then return the value given number+1.
  • Return the value numberof_ways(gvn_n-1) + numberof_ways(gvn_n-2) (Recursive Logic).
  • Pass the given number as an argument to the numberof_ways() function and store it in a variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function say numberof_ways() which accepts the given number
# as an argument and returns the number of possible strings with no
# consecutive 1's


def numberof_ways(gvn_n):
     # Inside the function, check if the given number is equal to 0 using the if
     # conditional statement.
    if(gvn_n == 0):
        # If it is true, then return 0.
        return 0
    # Check if the given number is less than 3 using the if
    # conditional statement.
    if(gvn_n < 3):
        # If it is true, then return the value given number+1
        return gvn_n+1
    # Return the value numberof_ways(gvn_n-1) + numberof_ways(gvn_n-2).
    # (Recursive Logic)
    return numberof_ways(gvn_n-1) + numberof_ways(gvn_n-2)


# Give the number as user input using the int(input()) function and store it in a variable.
gvn_n = int(input("Enter some random number = "))
# Pass the given number as an argument to the numberof_ways() function and
# store it in a variable.
rslt = numberof_ways(gvn_n)
# Print the above result.
print(
    "The total number of possible strings for the given number {", gvn_n, "} = ", rslt)

Output:

Enter some random number = 3
The total number of possible strings for the given number { 3 } = 5

 

 

Python Program to Find Number of Possible Strings With No Consecutive 1s Read More »

Python Program to Convert a Number to Words (digit by digit)

Given a number and the task is to convert the given number into words.

For Example:

Let number = 15

The output  will be = “one-five”

Implementation Tips:

Make a global list with words for each digit from 0 to 9. The entries in the list will be mapped to the index, as shown in the table below.

global list = [ ‘zero’,  ‘one’, ……………’Nine’]

index:                0          1 ……………..     9

Examples:

Example1:

Input:

Given number = 15

Output:

The conversion of given number{ 15 } into words = 
one five

Example2:

Input:

Given number = 678

Output:

The conversion of given number{ 678 } into words = 
six seven eight

Program to Convert a Number to Words (digit by digit) in Python

Method #1: Using Recursion (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Give the global list with words for each digit from 0 to 9 and store it in another variable.
  • Create a recursive function say convert_numbrtoword() which accepts the given number as an argument and returns the conversion of the given number into words.
  • Inside the function, check if the given number is equal to 0 using the if conditional statement.
  • If it is true, then return an empty string.
  • Else get the spelling for the last digit by giving the index of the global list as given number modulus 10 which gives the last digit of the given number.
  • Store it in a variable.
  • Add the above result and call the convert_numbrtoword() function itself by dividing the number by 10 (Recursive Logic).
  • Store it in another variable.
  • Return the above result.
  • Pass the given number as an argument to the above convert_numbrtoword() function and print it.
  • The Exit of the Program.

Below is the implementation:

# Give the global list with words for each digit from 0 to 9 and
# store it in another variable.
globl_lst = ['zero', 'one', 'two', 'three', 'four',
             'five', 'six', 'seven', 'eight', 'nine']

# Create a function say convert_numbrtoword() which accepts the given number as
# an argument and returns the conversion of the given number into words.


def convert_numbrtoword(gvn_num):

    # Inside the function, check if the given number is equal to 0 using the if
        # conditional statement.
    if(gvn_num == 0):
        # If it is true, then return an empty string.
        return ""

    else:
        # Else get the spelling for the last digit by giving the index of the global
        # list as given number modulus 10 which gives the last digit of the given
        # number.
        # Store it in a variable.
        rslt = globl_lst[gvn_num % 10]

        # Add the above result and call the convert_numbrtoword() function itself by
        # dividing the number by 10 (Recursive Logic).
        # Store it in another variable.
        fnl_rslt = convert_numbrtoword(int(gvn_num/10)) + rslt + " "

    # Return the above result.
    return fnl_rslt


# Give the number as static input and store it in a variable.
gvn_num = 15
print("The conversion of given number{", gvn_num, "} into words = ")
# Pass the given number as an argument to the above convert_numbrtoword()
# function and print it.
print(convert_numbrtoword(gvn_num))

Output:

The conversion of given number{ 15 } into words = 
one five

Method #2: Using Recursion (User Input)

Approach:

  • Give the number as user input using the int(input()) function.
  • Store it in a variable.
  • Give the global list with words for each digit from 0 to 9 and store it in another variable.
  • Create a recursive function say convert_numbrtoword() which accepts the given number as an argument and returns the conversion of the given number into words.
  • Inside the function, check if the given number is equal to 0 using the if conditional statement.
  • If it is true, then return an empty string.
  • Else get the spelling for the last digit by giving the index of the global list as given number modulus 10 which gives the last digit of the given number.
  • Store it in a variable.
  • Add the above result and call the convert_numbrtoword() function itself by dividing the number by 10 (Recursive Logic).
  • Store it in another variable.
  • Return the above result.
  • Pass the given number as an argument to the above convert_numbrtoword() function and print it.
  • The Exit of the Program.

Below is the implementation:

# Give the global list with words for each digit from 0 to 9 and
# store it in another variable.
globl_lst = ['zero', 'one', 'two', 'three', 'four',
             'five', 'six', 'seven', 'eight', 'nine']

# Create a function say convert_numbrtoword() which accepts the given number as
# an argument and returns the conversion of the given number into words.


def convert_numbrtoword(gvn_num):

    # Inside the function, check if the given number is equal to 0 using the if
        # conditional statement.
    if(gvn_num == 0):
        # If it is true, then return an empty string.
        return ""

    else:
        # Else get the spelling for the last digit by giving the index of the global
        # list as given number modulus 10 which gives the last digit of the given
        # number.
        # Store it in a variable.
        rslt = globl_lst[gvn_num % 10]

        # Add the above result and call the convert_numbrtoword() function itself by
        # dividing the number by 10 (Recursive Logic).
        # Store it in another variable.
        fnl_rslt = convert_numbrtoword(int(gvn_num/10)) + rslt + " "

    # Return the above result.
    return fnl_rslt


# Give the number as user input using the int(input()) function.
# store it in a variable.
gvn_num = int(input("Enter some random number = "))
print("The conversion of given number{", gvn_num, "} into words = ")
# Pass the given number as an argument to the above convert_numbrtoword()
# function and print it.
print(convert_numbrtoword(gvn_num))

Output:

Enter some random number = 678
The conversion of given number{ 678 } into words = 
six seven eight

Python Program to Convert a Number to Words (digit by digit) Read More »

Python Program for Friends-Travel Problem

In this article, we’ll look at The Friends-Travel Problem, which is highly interesting.

Friends-Travel Problem:

Assume n friends want to go to a party; they can travel alone or with another friend as a couple. We presume that n motorbikes are offered for n buddies.

We need to figure out how many different ways the n friends can get to the party, either individually or in pairs of two as a couple.

Answer:

One can either manually implement the naive technique using loops and if-else statements or use the quicker Recursion approach.

Before going into the problem just have a glance over the recursion.

To solve a larger problem, it is necessary to divide it into smaller difficulties.

Let us consider the lower values of n like ( 1, 2, and 3).

There are only one and two viable options for n = 1 and n = 2, respectively. And for n = 3, there are four alternative outcomes. How?

For each value of n, a friend has two options: either travel alone or search for n-1 friends.

Alternatively, the friend might choose a friend from the n-1 friends to travel with, and we will then look for n-2 friends.

Examples:

Example1:

Input:

Given number of friends = 3

Output:

Different ways the 3 friends can get to the party =  4

Example2:

Input:

Given number of friends = 5

Output:

Different ways the 5 friends can get to the party = 26

Program for Friends-Travel Problem in Python

Method #1: Using Recursion (Static Input)

Approach:

  • Give the number(no of friends) as static input and store it in a variable.
  • Create a recursive function say numberof_ways() which accepts the given number as an argument and returns the total number of ways friends can get to the party.
  • Inside the function, check if the given number is less than 3 using the if conditional statement.
  • If it is true, then return the given number.
  • Return the value of {numberof_ways(no_frnds-1)) + ((no_frnds-1) * numberof_ways(no_frnds-2)} (Recursive Logic).
  • Pass the given number as an argument to the numberof_ways() function and store it in a variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function say numberof_ways() which accepts the given number
# as an argument and returns the total number of ways friends can get to the party.


def numberof_ways(no_frnds):
    # Inside the function, check if the given number is less than 3 using the if
        # conditional statement.
    if(no_frnds < 3):
        # If it is true, then return the given number.
        return no_frnds
    # Return the value of count_no_ways(no_frnds-1)) + ((no_frnds-1) *
        # count_no_ways(no_frnds-2) (Recursive Logic).
    return (numberof_ways(no_frnds-1)) + ((no_frnds-1) * numberof_ways(no_frnds-2))


# Give the number(no of friends) as static input and store it in a variable.
no_frnds = 3
# Pass the given number as an argument to the numberof_ways() function and
# store it in a variable.
rslt = numberof_ways(no_frnds)
# Print the above result.
print("Different ways the", no_frnds, "friends can get to the party = ", rslt)

Output:

Different ways the 3 friends can get to the party =  4

Method #2: Using Recursion (User Input)

Approach:

  • Give the number(no of friends) as user input using the int(input()) function and store it in a variable.
  • Create a recursive function say numberof_ways() which accepts the given number as an argument and returns the total number of ways friends can get to the party.
  • Inside the function, check if the given number is less than 3 using the if conditional statement.
  • If it is true, then return the given number.
  • Return the value of {numberof_ways(no_frnds-1)) + ((no_frnds-1) * numberof_ways(no_frnds-2)} (Recursive Logic).
  • Pass the given number as an argument to the numberof_ways() function and store it in a variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function say numberof_ways() which accepts the given number
# as an argument and returns the total number of ways friends can get to the party.


def numberof_ways(no_frnds):
    # Inside the function, check if the given number is less than 3 using the if
        # conditional statement.
    if(no_frnds < 3):
        # If it is true, then return the given number.
        return no_frnds
    # Return the value of count_no_ways(no_frnds-1)) + ((no_frnds-1) *
        # count_no_ways(no_frnds-2) (Recursive Logic).
    return (numberof_ways(no_frnds-1)) + ((no_frnds-1) * numberof_ways(no_frnds-2))


# Give the number(no of friends) as user input using the int(input()) function and store it in a variable.
no_frnds = int(input("Enter some random number = "))
# Pass the given number as an argument to the numberof_ways() function and
# store it in a variable.
rslt = numberof_ways(no_frnds)
# Print the above result.
print("Different ways the", no_frnds, "friends can get to the party = ", rslt)

Output:

Enter some random number = 5
Different ways the 5 friends can get to the party = 26

Python Program for Friends-Travel Problem Read More »

Python Program to Convert Text to Acronyms

What is Acronym?

An acronym is a shorter version(short form) of a longer phrase; for example, ML stands for Machine Learning.

Let us see how the Python application converts text to acronyms.

While saying or writing the first initial of each word or an abbreviated form of the complete word takes longer, saying or writing the first initial of each word or an abbreviated form of the entire word takes less time. As a result, using acronyms and abbreviations in everyday speech facilitates communication.

Our goal in implementing acronyms is to construct a short form of a word from a given text. The same thing can be accomplished by splitting and indexing to obtain the first word and then combining it.

Examples:

Example1:

Input:

Given string = "Artificial Intelligence"

Output:

The Acronym for the given string =  AI
A  stands for -  Artificial
I  stands for -  Intelligence

Example2:

Input:

Given string = "Indian Space Research Organization"

Output:

The Acronym for the given string = ISRO
I stands for - Indian
S stands for - Space
R stands for - Research
O stands for - Organization

Program to Convert Text to Acronyms in Python

Method #1: Using For loop (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Split the given string into a list of words using the split() function and store it in another variable.
  • Take a variable and initialize it with an empty string.
  • Loop in the above word list using the for loop.
  • Inside the loop, convert the first character of the iterator into an upper case using the upper() function and concatenate it with the above declared empty string.
  • Store it in the same variable.
  • Print the Acronym for the given string.
  • Loop till the length of the above-obtained result acronym string using the for loop.
  • Inside, the loop print the iterator value of result acronym string and word list separated by spaces.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = "Artificial Intelligence"
# Split the given string into a list of words using the split() function and
# store it in another variable.
word_lst = gvn_str.split()
# Take a variable and initialize it with an empty string.
rslt_acrnym = ""
# Loop in the above word list using the for loop.
for itr in word_lst:
    # Inside the loop, convert the first character of the iterator into an upper
        # case using the upper() function and concatenate it with the above declared
        # empty string.
    # Store it in the same variable.
    rslt_acrnym += itr[0].upper()

# Print the Acronym for the given string.
print("The Acronym for the given string = ", rslt_acrnym)
# Loop till the length of the above-obtained result acronym string using the for loop.
for itr in range(len(rslt_acrnym)):
    # Inside, the loop print the iterator value of result acronym string and word list
        # separated by spaces.
    print(rslt_acrnym[itr], " stands for - ", word_lst[itr])

Output:

The Acronym for the given string =  AI
A  stands for -  Artificial
I  stands for -  Intelligence

Method #2: Using For loop (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Split the given string into a list of words using the split() function and store it in another variable.
  • Take a variable and initialize it with an empty string.
  • Loop in the above word list using the for loop.
  • Inside the loop, convert the first character of the iterator into an upper case using the upper() function and concatenate it with the above declared empty string.
  • Store it in the same variable.
  • Print the Acronym for the given string.
  • Loop till the length of the above-obtained result acronym string using the for loop.
  • Inside, the loop print the iterator value of result acronym string and word list separated by spaces.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Split the given string into a list of words using the split() function and
# store it in another variable.
word_lst = gvn_str.split()
# Take a variable and initialize it with an empty string.
rslt_acrnym = ""
# Loop in the above word list using the for loop.
for itr in word_lst:
    # Inside the loop, convert the first character of the iterator into an upper
        # case using the upper() function and concatenate it with the above declared
        # empty string.
    # Store it in the same variable.
    rslt_acrnym += itr[0].upper()

# Print the Acronym for the given string.
print("The Acronym for the given string = ", rslt_acrnym)
# Loop till the length of the above-obtained result acronym string using the for loop.
for itr in range(len(rslt_acrnym)):
    # Inside, the loop print the iterator value of result acronym string and word list
        # separated by spaces.
    print(rslt_acrnym[itr], " stands for - ", word_lst[itr])

Output:

Enter some random string = Indian Space Research Organization
The Acronym for the given string = ISRO
I stands for - Indian
S stands for - Space
R stands for - Research
O stands for - Organization

 

Python Program to Convert Text to Acronyms Read More »

Python Itertools.zip_longest() Function with Examples

Itertools Module:

Itertools is a Python module that contains a collection of functions for dealing with iterators. They make it very simple to iterate through iterables such as lists and strings.

Itertools in Python refers to a Python module that allows the creation of iterators, which aids in efficient looping, as well as time and space efficiency. itertools enable us to solve complex problems quickly and easily. Iterators are classified into three types.

This module provides the following types of iterators:

  1. Combinatorics Generators
  2. Infinite Iterators
  3. Terminating Iterators

itertools.zip_longest() Function :

This iterator is classified as a terminating iterator. It alternately prints the values of iterables in sequence. If one of the iterables is completely printed, the values supplied to the fillvalue argument are used to fill in the gaps.

Note:

 If no fillvalue is given it prints 'None'  to fill in the gaps.

Syntax:

zip_longest( iterable1, iterable2, fillvalue)

Parameters

iterable1, iterable2: This is Required. These are the iterables like list, string, and so on.

fillvalue: This is Optional. If the iterables are of various lengths, use this value to pad the outputs.

Examples:

Example1:

Input:

Given first List = [25, 35, 45]
Given second List = [100, 200, 300, 400, 500]

Output:

The result is : 
[(25, 100), (35, 200), (45, 300), (None, 400), (None, 500)]

Explanation:

Here it takes 25 from the first list and 100 from the second list, similarly 
it alternately prints the values of lists in sequence. But first list has 
only 3 items whereas 2 list has 5 items. Hence it fills the gaps with 'None'
as default if no fillvalue is specified.

Example2:

Input:

Given first List = "hello"
Given second List = "all"
fillvalue = '@'

Output:

The result is : 
[('h', 'a'), ('e', 'l'), ('l', 'l'), ('l', '@'), ('o', '@')]

itertools.zip_longest() Function with Examples in Python

Method #1: Using Built-in Functions (Static Input)

Approach:

  • Import zip_longest() function from itertools module using the import keyword.
  • Give the first list as static input and store it in a variable.
  • Give the second list as static input and store it in another variable.
  • Pass the given first and second lists as the arguments to the zip_longest() function and store it in a variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import zip_longest() function from itertools module using the import keyword.
from itertools import zip_longest
# Give the first list as static input and store it in a variable.
gvn_fstlst = [25, 35, 45]
# Give the second list as static input and store it in another variable.
gvn_scndlst = [100, 200, 300, 400, 500]
# Pass the given first and second lists as the arguments to the zip_longest()
# function and store it in a variable.
rslt = zip_longest(gvn_fstlst, gvn_scndlst)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print("The result is : ")
print(rslt_lst)

Output:

The result is : 
[(25, 100), (35, 200), (45, 300), (None, 400), (None, 500)]

For Strings by giving fillvalue

Approach:

  • Import zip_longest() function from itertools module using the import keyword.
  • Give the first string as static input and store it in a variable.
  • Give the second string as static input and store it in another variable.
  • Give the fill value as static input and store it in another variable.
  • Pass the given first and second strings, and given fill value as the arguments to the zip_longest() function, and store it in a variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import zip_longest() function from itertools module using the import keyword.
from itertools import zip_longest
# Give the first string as static input and store it in a variable.
gvn_fststr = "hello"
# Give the second string as static input and store it in another variable.
gvn_scndstr = 'all'
# Give the fill value as static input and store it in another variable.
gvn_filvalu = "@"
# Pass the given first and second strings and fill value as the arguments to
# the zip_longest() function and store it in a variable.
rslt = zip_longest(gvn_fststr, gvn_scndstr, fillvalue=gvn_filvalu)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print("The result is : ")
print(rslt_lst)

Output:

The result is : 
[('h', 'a'), ('e', 'l'), ('l', 'l'), ('l', '@'), ('o', '@')]

Method #2: Using Built-in Functions (User Input)

Approach:

  • Import zip_longest() function from itertools module using the import keyword.
  • Give the first list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the second list as user input using list(),map(),input(),and split() functions.
  • Store it in another variable.
  • Pass the given first and second lists as the arguments to the zip_longest() function and store it in a variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import zip_longest() function from itertools module using the import keyword.
from itertools import zip_longest
# Give the first list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_fstlst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Give the second list as user input using list(),map(),input(),and split() functions.
# Store it in another variable.
gvn_scndlst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
   
# Pass the given first and second lists as the arguments to the zip_longest() function
# and store it in a variable.
rslt = zip_longest(gvn_fstlst, gvn_scndlst)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print("The result is : ")
print(rslt_lst)

Output:

Enter some random List Elements separated by spaces = 9 8 7 6 5
Enter some random List Elements separated by spaces = 1 2 3
The result is : 
[(9, 1), (8, 2), (7, 3), (6, None), (5, None)]

For Strings by giving fillvalue

Approach:

  • Import zip_longest() function from itertools module using the import keyword.
  • Give the first string as user input using the input() function and store it in a variable.
  • Give the second string as user input using the input() function and store it in another variable.
  • Give the fill value as user input using the input() function and store it in another variable.
  • Pass the given first and second strings, and given fill value as the arguments to the zip_longest() function, and store it in a variable.
  • Convert the above result into a list using the list() function and store it in another variable.
  • Print the above result.
  • The Exit of the Program.

Below is the implementation:

# Import zip_longest() function from itertools module using the import keyword.
from itertools import zip_longest
# Give the first string as user input using the input() function and store it in a variable.
gvn_fststr = input("Enter some random string = ")
# Give the second string as user input using the input() function and store it in another variable.
gvn_scndstr = input("Enter some random string = ")
# Give the fill value as user input using the input() function and store it in another variable.
gvn_filvalu = input("Enter some random character = ")
# Pass the given first and second strings and fill value as the arguments to
# the zip_longest() function and store it in a variable.
rslt = zip_longest(gvn_fststr, gvn_scndstr, fillvalue=gvn_filvalu)
# Convert the above result into a list using the list() function and store it in
# another variable.
rslt_lst = list(rslt)
# Print the above result.
print("The result is : ")
print(rslt_lst)

Output:

Enter some random string = btechgeeks
Enter some random string = hello
Enter some random character = #
The result is : 
[('b', 'h'), ('t', 'e'), ('e', 'l'), ('c', 'l'), ('h', 'o'), ('g', '#'), ('e', '#'), ('e', '#'), ('k', '#'), ('s', '#')]

Python Itertools.zip_longest() Function with Examples Read More »

FizzBuzz Algorithm and Its Code in Python

The FizzBuzz algorithm is a common coding interview topic. Fizz and Buzz are numbers that are multiples of three and five, respectively.

In this article, we see how to develop the FizzBuzz algorithm using Python.

FizzBuzz Algorithm

A children’s game inspired the FizzBuzz algorithm. This method has long been one of the most popular coding interview tasks.

You are given a range of numbers and must generate output using the following rules:

  • If the given number is divisible by three, the output must be “Fizz.”
  • If the given number is divisible by five, the output must be “Buzz.”
  • If the given number is divisible by three and five, the output must be “FizzBuzz.”

This coding challenge is commonly encountered with digits 3 and 5, but the principle for solving the problem stays the same.

Python Program for FizzBuzz Algorithm

Method #1:Using For loop(Static Input)

Approach:

  • Give the number (upper limit) as static input and store it in a variable.
  • Loop from 1 to the given number using the for loop.
  • Check if the iterator value is divisible by 3 and 5 using the modulus operator and if conditional statement.
  • If it is true, then print “FizzBuzz”.
  • Again Check if the iterator value is divisible by 3 using the modulus operator and elif conditional statement.
  • If it is true, then print “Fizz”.
  • Check if the iterator value is divisible by 5 using the modulus operator and elif conditional statement.
  • If it is true, then print “Buzz”.
  • Else print the iterator value.
  • The Exit of the Program.

Below is the implementation:

# Give the number(upper limit) as static input and store it in a variable.
gvn_numb = 8
# Loop from 1 to the given number using the for loop.
for itr in range(1, gvn_numb+1):
    # Check if the iterator value is divisible by 3 and 5 using the modulus operator
        # and if conditional statement.
    if itr % 3 == 0 and itr % 5 == 0:
        # If it is true, then print "FizzBuzz".
        print(itr, " - FizzBuzz")
    # Again Check if the iterator value is divisible by 3 using the modulus operator
        # and elif conditional statement.
    elif itr % 3 == 0:
        # If it is true, then print "Fizz".
        print(itr, " - Fizz")
    # Check if the iterator value is divisible by 5 using the modulus operator
        # and elif conditional statement.
    elif itr % 5 == 0:
        # If it is true, then print "Buzz".
        print(itr, " - Buzz")
    else:
        # Else print the iterator value.
        print(itr)

Output:

1
2
3  - Fizz
4
5  - Buzz
6  - Fizz
7
8

Method #2:Using For loop(User Input)

Approach:

  • Give the number (upper limit) as user input using the int(input()) function and store it in a variable.
  • Loop from 1 to the given number using the for loop.
  • Check if the iterator value is divisible by 3 and 5 using the modulus operator and if conditional statement.
  • If it is true, then print “FizzBuzz”.
  • Again Check if the iterator value is divisible by 3 using the modulus operator and elif conditional statement.
  • If it is true, then print “Fizz”.
  • Check if the iterator value is divisible by 5 using the modulus operator and elif conditional statement.
  • If it is true, then print “Buzz”.
  • Else print the iterator value.
  • The Exit of the Program.

Below is the implementation:

# Give the number(upper limit) as user input using the int(input()) function 
# and store it in a variable.
gvn_numb = int(input("Enter some random number = "))
print("The output is :")
# Loop from 1 to the given number using the for loop.
for itr in range(1, gvn_numb+1):
    # Check if the iterator value is divisible by 3 and 5 using the modulus operator
        # and if conditional statement.
    if itr % 3 == 0 and itr % 5 == 0:
        # If it is true, then print "FizzBuzz".
        print(itr, " - FizzBuzz")
    # Again Check if the iterator value is divisible by 3 using the modulus operator
        # and elif conditional statement.
    elif itr % 3 == 0:
        # If it is true, then print "Fizz".
        print(itr, " - Fizz")
    # Check if the iterator value is divisible by 5 using the modulus operator
        # and elif conditional statement.
    elif itr % 5 == 0:
        # If it is true, then print "Buzz".
        print(itr, " - Buzz")
    else:
        # Else print the iterator value.
        print(itr)

Output:

Enter some random number = 15
The output is :
1
2
3 - Fizz
4
5 - Buzz
6 - Fizz
7
8
9 - Fizz
10 - Buzz
11
12 - Fizz
13
14
15 - FizzBuzz

 

 

FizzBuzz Algorithm and Its Code in Python Read More »