Python

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 »

Python Program to Calculate the Dot Product?

Dot Product:

The dot product, commonly known as the scalar product in mathematics, is an algebraic operation that takes two equal-length sequences of numbers and produces a single number.

Given two vectors A and B, we must find the dot product of the two vectors.

For Example :

Let A = a1i+a2j+a3k

B= b1i+b2j+b3k

Where

i is the unit vector along the x-axis.

j is the unit vector along the y-axis.

k is the unit vector along the z-axis.

The Formula to calculate the dot product

Dot product = a1*b1+a2*b2+a3*b3

Calculating Dot Product of Two Vectors in Python

The numpy.dot() method of the numpy library provides an efficient way to find the dot product of two sequences.

numpy.dot() is a method that accepts two sequences as arguments, whether they are vectors or multidimensional arrays, and displays the output, which is the dot product. To use this approach, we must first import Python’s numpy module.

Syntax:

numpy.dot(vector_a, vector_b, out = None )

Parameters

vector_a: It is an array. If a is complex, its complex conjugate is utilized to compute the dot product.

vector_b: It is an array. If b is complex, its complex conjugate is utilized to compute the dot product.

out: It is an array. This is optional. The output parameter must be C-contiguous, and its datatype must be the same as the datatype returned by dot (a,b).

Return Value:

Returns the Dot Product of given vectors a and b. Scalar is returned if vector a and vector b are both 1D.

How to find the Dot Product of Scalars?

Given two scalar values and use numpy.dot() function to display their dot product.

Approach:

  • Import numpy library using the import keyword.
  • Give the first scalar value as static input and store it in a variable.
  • Give the second scalar value as static input and store it in another variable.
  • Calculate the dot product of the given two scalar values using the numpy.dot() function by passing the given first and second scalar values as the arguments.
  • Store it in another variable.
  • Print the dot product of the given two scalar values.
  • The Exit of the Program.

Below is the implementation:

# Import numpy library using the import keyword
import numpy as np
# Give the first scalar value as static input and store it in a variable.
x = 4
# Give the second scalar value as static input and store it in another variable.
y = 6
# Calculate the dot product of the given two scalar values using the numpy.dot()
# function by passing the given first and second scalar values as the arguments.
# Store it in another variable.
dot_prdct = np.dot(x, y)
# Print the dot product of the given two scalar values.
print("The dot product of given scalars x{", x, "} and y {", y, "} = ")
print(dot_prdct)

Output:

The dot product of given scalars x{ 4 } and y { 6 } = 
24

How to find the Dot Product of Arrays?

Given two arrays, and the task is to calculate the dot product of the given two vectors.

These arrays might be one-dimensional, two-dimensional, or multi-dimensional. And we’ll compute their dot product with the help of dot(). For the dot product, we are evaluating two 2-D arrays.

Matrix multiplication is used to compute the dot product for 2-D arrays.

Approach:

  • Import numpy library using the import keyword
  • Give the 2- Dimensional array as static input and store it in a variable.
  • Give the other 2- Dimensional array as static input and store it in another variable.
  • Calculate the dot product of the given two arrays using the numpy.dot() function by passing the given two 2-D arrays as the arguments.
  • Store it in another variable.
  • Print the dot product of the given two 2- Dimensional arrays.
  • The Exit of the Program.

Below is the implementation:

# Import numpy library using the import keyword
import numpy as np
# Give the 2- Dimensional array as static input and store it in a variable.
x = [[3, 1], [5, 2]]
# Give the other 2- Dimensional array as static input and store it in another
# variable.
y = [[8, 5], [2, 4]]
# Calculate the dot product of the given two arrays using the numpy.dot()
# function by passing the given two 2-D arrays as the arguments.
# Store it in another variable.
dot_prdct = np.dot(x, y)
# Print the dot product of the given two 2- Dimensional arrays
print("The dot product of given two 2-D arrays x ", x, " and y ", y, " = ")
print(dot_prdct)

Output:

The dot product of given two 2-D arrays x [[3, 1], [5, 2]] and y [[8, 5], [2, 4]] = 
[[26 19]
[44 33]]

Note:

The dot product is not commutative for two-dimensional or multi-dimensional arrays. That means a.b does not equal b.a.

If we calculated dot product as a.b rather than b.a, the output is not the same for both of them. It is different for both.

 

Python Program to Calculate the Dot Product? Read More »

Python Program to Solve the Tiling Problem

What is Tiling Problem?

In the Tiling Problem, we would be given a wall of size 4*n, which means that the wall’s height is 4 and its length is n. ( given as the input).

Now we have an endless number of little 4*1 tiles that can be put on the wall in two distinct ways. Look at the below figure for more clarity:

 

Our goal is to fill the entire wall with all of the possible patterns using the small tiles in any of the approaches described above.

Tiling Problem Solution in Python:

One can either manually implement the naive technique using loops and if-else statements or use the quicker Recursion approach. If you want to learn about recursion, just have a glance over it what the recursion is? before going to the code.

We will use recursion to divide a large problem into smaller ones. Now, let’s look at the minor problems with both arrangements.

1st Arrangement: The first tile is placed using Method 1, reducing the length of the wall by 4, and the space above the present tile can only be filled in one way ( 3 tiles according to Method 1 )
2nd Arrangement: Next, using Method 2, we may place the first tile, reducing the length of the wall by one.

After the first arrangement has been completed. We call the same method but with a lower number of n to recursively call the same operations for the remaining wall.

The ultimate solution will be the sum of the possible ways in both the arrangements in each recursive call.

Program to Solve the Tiling Problem in Python

Recursion is used to simplify the code implementation. Just make sure you understand the solution that is given below:

Method #1: Using Recursion (Static Input)

Approach:

  • Give the n value as static input and store it in a variable.
  • Create a recursive function say total_possiblearrangements() which accepts the given n value as an argument that returns the total number of possible arrangements in both ways.
  • Inside the function, Check if the given n value is less than or equal to 3 using the if conditional statement.
  • If it is true, then return 1.
  • Return the value of total_possiblearrangements(gvn_n_val-1) + total_possiblearrangements(gvn_n_val-4) (Recursive Logic).
  • Pass the given n value as an argument to the total_possiblearrangements() 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 total_possiblearrangements() which accepts the
# given n value as an argument that returns the total number of possible
# arrangements in both ways.


def total_possiblearrangements(gvn_n_val):
        # Inside the function, Check if the given n value is less than or equal to 3
        # using the if conditional statement.

    if(gvn_n_val <= 3):
        # If it is true, then return 1.
        return 1
        # Return the value of total_possiblearrangements(gvn_n_val-1) +
        # total_possiblearrangements(gvn_n_val-4) (Recursive Logic).
    return total_possiblearrangements(gvn_n_val-1) + total_possiblearrangements(gvn_n_val-4)


# Give the n value as static input and store it in a variable.
gvn_n_val = 3
# Pass the given n value as an argument to the total_possiblearrangements()
# function and store it in a variable.
rslt = total_possiblearrangements(gvn_n_val)
# Print the above result.
print("The total number of possible arrangements in both ways = ")
print(rslt)

Output:

The total number of possible arrangements in both ways = 
1

Method #2: Using Recursion (User Input)

Approach:

  • Give the n value as user input using the int(input()) function and store it in a variable.
  • Create a recursive function say total_possiblearrangements() which accepts the given n value as an argument that returns the total number of possible arrangements in both ways.
  • Inside the function, Check if the given n value is less than or equal to 3 using the if conditional statement.
  • If it is true, then return 1.
  • Return the value of total_possiblearrangements(gvn_n_val-1) + total_possiblearrangements(gvn_n_val-4) (Recursive Logic).
  • Pass the given n value as an argument to the total_possiblearrangements() 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 total_possiblearrangements() which accepts the
# given n value as an argument that returns the total number of possible
# arrangements in both ways.


def total_possiblearrangements(gvn_n_val):
        # Inside the function, Check if the given n value is less than or equal to 3
        # using the if conditional statement.

    if(gvn_n_val <= 3):
        # If it is true, then return 1.
        return 1
        # Return the value of total_possiblearrangements(gvn_n_val-1) +
        # total_possiblearrangements(gvn_n_val-4) (Recursive Logic).
    return total_possiblearrangements(gvn_n_val-1) + total_possiblearrangements(gvn_n_val-4)


# Give the n value as user input using the int(input()) function and store it in a variable.
gvn_n_val = int(input("Enter n value = "))
# Pass the given n value as an argument to the total_possiblearrangements()
# function and store it in a variable.
rslt = total_possiblearrangements(gvn_n_val)
# Print the above result.
print("The total number of possible arrangements in both ways = ")
print(rslt)

Output:

Enter n value = 4
The total number of possible arrangements in both ways = 
2

 

 

Python Program to Solve the Tiling Problem Read More »