Author name: Vikram Chiluka

Program to Find Even Digits Sum and Odd Digits Sum Divisible by 4 and 3 Respectively

Python Program to Find Even Digits Sum and Odd Digits Sum Divisible by 4 and 3 Respectively

In the previous article, we have discussed Python Program to Find the 2nd Largest Digit in a Given Number
Given a number, and the task is to check if the sum of even digits of a number is divisible by 4 and the sum of odd digits of a given number is divisible by 3.

Examples:

Example1:

Input:

Given Number = 123452

Output:

yes, the even digits sum and odd digits sum of a given number{ 123452 } is divisible by 4 and 3 respectively.

Example2:

Input:

Given Number = 4532176

Output:

No, the even digits sum and odd digits sum of a given number{ 4532176 } is not divisible by 4 and 3 respectively.

Program to Find Even Digits Sum and Odd Digits Sum Divisible by 4 and 3 Respectively in Python:

Below are the ways to check if the sum of even digits of a number is divisible by 4 and the sum of odd digits of a given number is divisible by 3.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Convert the given number to a string using the str() function and store it in another variable.
  • Create a list of digits say “digtslst” using map(),list(),int functions.
  • Store it in another variable.
  • Take a variable say “evn_sum” and initialize it with 0.
  • Take another variable say “od_sum” and initialize it with 0.
  • Loop in the above list of digits until the length of the “digtslst” using the for loop.
  • Check if the element of the “digtslst” is even or not using the if conditional statement.
  • If the statement is true, then add the element of the “digtslst” to the “evn_sum” and store it in the same variable evn_sum.
  • If the statement is false, then add the element of the “digtslst” to the “od_sum ” and store it in the same variable od_sum.
  • Check if the evn_sum modulus 4 is equal to 0 and od_sum modulus 3 is equal to 0 using the if conditional statement.
  • If the statement is true, print “yes, the even digits sum and odd digits sum of a given number are divisible by 4 and 3 respectively.
  • If the statement is false, print “No, the even digits sum and odd digits sum of a given number are not divisible by 4 and 3 respectively.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
numb = 123452
# Convert the given number to string using the str() function.
stringnum = str(numb)
# Create a list of digits say "digtslst" using map(),list(),int functions.
digtslst = list(map(int, stringnum))
# Take a variable say "evn_sum" and initialize it with 0.
evn_sum = 0
# Take another variable say "od_sum" and initialize it with 0.
od_sum = 0
# Loop in the above list of digits until the length of the "digtslst" using the for loop.
for itr in range(len(digtslst)):
    # Check if the element of the "digtslst" is even or not using the if conditional statement.
    if(digtslst[itr] % 2 == 0):
     # If the statement is true, then add the element of the "digtslst" to the "evn_sum"
        # and store it in the same variable evn_sum.
        evn_sum += digtslst[itr]
    else:
        # If the statement is false, then add the element of the "digtslst" to the "od_sum"
        # and store it in the same variable od_sum.
        od_sum += digtslst[itr]
# Check if the evn_sum modulus 4 is equal to 0 and od_sum modulus 3 is equal to 0
# using the if conditional statement.
if(evn_sum % 4 == 0 and od_sum % 3 == 0):
  # If the statement is true, print "yes, the even digits sum and odd digits sum of a
    # given number are divisible by 4 and 3 respectively.
    print(
        "yes, the even digits sum and odd digits sum of a given number{", numb, "} is divisible by 4 and 3 respectively.")
else:
 # If the statement is false, print "No, the even digits sum and odd digits sum
    # of a given number are not divisible by 4 and 3 respectively.
    print(
        "No, the even digits sum and odd digits sum of a given number{", numb, "} is not divisible by 4 and 3 respectively.")

Output:

yes, the even digits sum and odd digits sum of a given number{ 123452 } is divisible by 4 and 3 respectively.

Method #2: Using For loop (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Convert the given number to a string using the str() function and store it in another variable.
  • Create a list of digits say “digtslst” using map(),list(),int functions.
  • Store it in another variable.
  • Take a variable say “evn_sum” and initialize it with 0.
  • Take another variable say “od_sum” and initialize it with 0.
  • Loop in the above list of digits until the length of the “digtslst” using the for loop.
  • Check if the element of the “digtslst” is even or not using the if conditional statement.
  • If the statement is true, then add the element of the “digtslst” to the “evn_sum” and store it in the same variable evn_sum.
  • If the statement is false, then add the element of the “digtslst” to the “od_sum ” and store it in the same variable od_sum.
  • Check if the evn_sum modulus 4 is equal to 0 and od_sum modulus 3 is equal to 0 using the if conditional statement.
  • If the statement is true, print “yes, the even digits sum and odd digits sum of a given number are divisible by 4 and 3 respectively.
  • If the statement is false, print “No, the even digits sum and odd digits sum of a given number are not divisible by 4 and 3 respectively.
  • 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.
numb = int(input("Enter some random number = "))
# Convert the given number to string using the str() function.
stringnum = str(numb)
# Create a list of digits say "digtslst" using map(),list(),int functions.
digtslst = list(map(int, stringnum))
# Take a variable say "evn_sum" and initialize it with 0.
evn_sum = 0
# Take another variable say "od_sum" and initialize it with 0.
od_sum = 0
# Loop in the above list of digits until the length of the "digtslst" using the for loop.
for itr in range(len(digtslst)):
    # Check if the element of the "digtslst" is even or not using the if conditional statement.
    if(digtslst[itr] % 2 == 0):
     # If the statement is true, then add the element of the "digtslst" to the "evn_sum"
        # and store it in the same variable evn_sum.
        evn_sum += digtslst[itr]
    else:
        # If the statement is false, then add the element of the "digtslst" to the "od_sum"
        # and store it in the same variable od_sum.
        od_sum += digtslst[itr]
# Check if the evn_sum modulus 4 is equal to 0 and od_sum modulus 3 is equal to 0
# using the if conditional statement.
if(evn_sum % 4 == 0 and od_sum % 3 == 0):
  # If the statement is true, print "yes, the even digits sum and odd digits sum of a
    # given number are divisible by 4 and 3 respectively.
    print(
        "yes, the even digits sum and odd digits sum of a given number{", numb, "} is divisible by 4 and 3 respectively.")
else:
 # If the statement is false, print "No, the even digits sum and odd digits sum
    # of a given number are not divisible by 4 and 3 respectively.
    print(
        "No, the even digits sum and odd digits sum of a given number{", numb, "} is not divisible by 4 and 3 respectively.")

Output:

Enter some random number = 4532176
No, the even digits sum and odd digits sum of a given number{ 4532176 } is not divisible by 4 and 3 respectively.

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Find Even Digits Sum and Odd Digits Sum Divisible by 4 and 3 Respectively Read More »

Program to Check Whether Product of Digits at Even places of a Number is Divisible by K

Python Program to Check Whether Product of Digits at Even places of a Number is Divisible by K

In the previous article, we have discussed Python Program to Check Whether Sum of digits at Odd places of a Number is Divisible by K
The task is to check if the product of digits at even places of a given number is divisible by the another given input number say K.

Examples:

Example1:

Input:

Given  Number =  693214
Given  another Number (k) = 2

Output:

The Product of digits at even places of the given number{ 693214 } is divisible by the another given number k{ 2 }

Example2:

Input:

Given Number =  2578
Given another Number (k) = 4

Output:

The Product of digits at even places of the given number{ 2578 } is not divisible by the another given number k{ 4 }

Program to Check Whether Product of Digits at Even places of a Number is Divisible by K in Python

Below are the ways to check if the product of digits at even places of a given number is divisible by the another given input number say K:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Give the other number k as static input and store it in another variable.
  • Convert the given number to a string using the str() function and store it in another variable.
  • Create a list of digits say “digtslst” using map(),list(),int functions.
  • Store it in another variable.
  • Take another variable say “evn_prodt” and initialize it with 1.
  • Loop in the above list of digits until the length of the “digtslst” using the for loop.
  • Check if the iterator value is even or not using the if conditional statement.
  • If the statement is true, then multiply the element of digits list at the iterator value to the “evn_prodt” and store it in the same variable evn_prodt.
  • Check if the evn_prodt modulus given number k is equal to 0 or not using the if conditional statement.
  • If the statement is true, then print “The product of digits at even places of the given number is divisible by the another given number k.
  • If the statement is false, then print “The product of digits at even places of the given number is Not divisible by the another given number k.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb = 123456
# Give the other number k as static input and store it in another variable.
gvn_k = 5
# Convert the given number to a string using the str() function and store it in
# another variable.
stringnum = str(gvn_numb)
# Create a list of digits say "digtslst" using map(),list(),int functions.
digtslst = list(map(int, stringnum))
# Take another variable say "evn_prodt" and initialize it with 1.
evn_prodt = 1
# Loop in the above list of digits until the length of the "digtslst" using the for loop.
for itr in range(len(digtslst)):
    # Check if the iterator value is even or not using
    # the if conditional statement.
    if(itr % 2 == 0):
        # If the statement is true, then multiply the element of digits list at iterator value to
        # the "evn_prodt" and store it in the same variable evn_prodt.
        evn_prodt *= digtslst[itr]
# Check if the evn_prodt modulus given number k is equal to 0 or not using the if conditional
# statement.
if(evn_prodt % gvn_k == 0):
    # If the statement is true, then print "The product of digits at even places of the given
    # number is divisible by the another given number k.
    print("The Product of digits at even places of the given number{", gvn_numb,
          "} is divisible by the another given number k{", gvn_k, "}")
else:
    # If the statement is false, then print "The product of digits at even places of the given
    # number is Not divisible by the another given number k.
    print("The Product of digits at even places of the given number{", gvn_numb,
          "} is not divisible by the another given number k{", gvn_k, "}")

Output:

The Product of digits at even places of the given number{ 123456 } is divisible by the another given number k{ 5 }

Method #2: Using For loop (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Give the other number k as user input using the int(input()) function and store it in another variable.
  • Convert the given number to a string using the str() function and store it in another variable.
  • Create a list of digits say “digtslst” using map(),list(),int functions.
  • Store it in another variable.
  • Take another variable say “evn_prodt” and initialize it with 1.
  • Loop in the above list of digits until the length of the “digtslst” using the for loop.
  • Check if the iterator value is even or not using the if conditional statement.
  • If the statement is true, then multiply the element of digits list at the iterator value to the “evn_prodt” and store it in the same variable evn_prodt.
  • Check if the evn_prodt modulus given number k is equal to 0 or not using the if conditional statement.
  • If the statement is true, then print “The product of digits at even places of the given number is divisible by the another given number k.
  • If the statement is false, then print “The product of digits at even places of the given number is Not divisible by the another given number k.
  • 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_numb = int(input("Enter some random number = "))
#Give the other number k as user input using the int(input()) function and store it in another variable.
gvn_k = int(input("Enter some random number = ")) 
# Convert the given number to a string using the str() function and store it in
# another variable.
stringnum = str(gvn_numb)
# Create a list of digits say "digtslst" using map(),list(),int functions.
digtslst = list(map(int, stringnum))
# Take another variable say "evn_prodt" and initialize it with 1.
evn_prodt = 1
# Loop in the above list of digits until the length of the "digtslst" using the for loop.
for itr in range(len(digtslst)):
    # Check if the iterator value is even or not using
    # the if conditional statement.
    if(itr % 2 == 0):
        # If the statement is true, then multiply the element of digits list at iterator value to
        # the "evn_prodt" and store it in the same variable evn_prodt.
        evn_prodt *= digtslst[itr]
# Check if the evn_prodt modulus given number k is equal to 0 or not using the if conditional
# statement.
if(evn_prodt % gvn_k == 0):
    # If the statement is true, then print "The product of digits at even places of the given
    # number is divisible by the another given number k.
    print("The Product of digits at even places of the given number{", gvn_numb,
          "} is divisible by the another given number k{", gvn_k, "}")
else:
    # If the statement is false, then print "The product of digits at even places of the given
    # number is Not divisible by the another given number k.
    print("The Product of digits at even places of the given number{", gvn_numb,
          "} is not divisible by the another given number k{", gvn_k, "}")

Output:

Enter some random number = 693214
Enter some random number = 2
The Product of digits at even places of the given number{ 693214 } is divisible by the another given number k{ 2 }

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Check Whether Product of Digits at Even places of a Number is Divisible by K Read More »

Program to Check Trimorphic Number or Not

Python Program to Check Trimorphic Number or Not

In the previous article, we have discussed Python Program to Check Abundant Number or Not
Trimorphic Number:

Cube the number you’ve been given. If the given number appears in the cube number in the last means, it is referred to as a trimorphic number.

For example:

Let the given number =25

The cube of the number = 25*25*25= 15625

The Given number 25 is present at the end.

Therefore, 25 is a Trimorphic Number.

The examples of the first few Trimorphic Numbers are 1, 4, 5, 6, 9, 24, 25, 49, 51, 75, 76, 99, 125, 249, 251, 375, 376, 499, and so on.

Given the number and the task is to check whether the given number is a Trimorphic Number or not.

Examples:

Example1:

Input:

Given Number = 75

Output:

The given number { 75 } is a Trimorphic number

Example2:

Input:

Given Number = 30

Output:

The given number { 30 } is Not a Trimorphic number

Program to Check Trimorphic Number or Not in Python

Below are the ways to check whether the given number is a Trimorphic Number or not:

Method #1: Using Slicing (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Calculate the cube root of the given number and convert it into the string using the str() function.
  • Store it in another variable.
  • Convert the given number to a string using the str() function and store it in another variable.
  • Calculate the length of the above-obtained string number using the len() function and store it in another variable.
  • Check if the cube_root[-len_string:](negative slicing)  is equal to the string number using the if conditional statement and slicing.
  • If the statement is true, then print “The given number is a Trimorphic Number”.
  • If it is false, then print “The given number is Not a Trimorphic Number”.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb = 75
# Calculate the cube root of the given number and convert it into the string using the str() function.
# Store it in another variable.
cube_numb = str(gvn_numb**3)
# Convert the given number to a string using the str() function and store it in
# another variable.
str_numb = str(gvn_numb)
# Calculate the length of the above-obtained string number using the len() function
# and store it in another variable.
len_str = len(str_numb)
# Check if the cube_root[-len_string:](negative slicing)  is equal to the string number using the
# if conditional statement and slicing.
if(cube_numb[-len_str:] == str_numb):
  # If the statement is true, then print "The given number is a Trimorphic Number".
    print("The given number {", gvn_numb, "} is a Trimorphic number")
else:
  # If it is false, then print "The given number is Not a Trimorphic Number".
    print("The given number {", gvn_numb, "} is Not a Trimorphic number")

Output:

The given number { 75 } is a Trimorphic number

Method #2: Using Slicing (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Calculate the cube root of the given number and convert it into the string using the str() function.
  • Store it in another variable.
  • Convert the given number to a string using the str() function and store it in another variable.
  • Calculate the length of the above-obtained string number using the len() function and store it in another variable.
  • Check if the cube_root[-len_string:](negative slicing) is equal to the string number using the if conditional statement and slicing.
  • If the statement is true, then print “The given number is a Trimorphic Number”.
  • If it is false, then print “The given number is Not a Trimorphic Number”.
  • 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_numb = int(input("Enter some random number = "))
# Calculate the cube root of the given number and convert it into the string using the str() function.
# Store it in another variable.
cube_numb = str(gvn_numb**3)
# Convert the given number to a string using the str() function and store it in
# another variable.
str_numb = str(gvn_numb)
# Calculate the length of the above-obtained string number using the len() function
# and store it in another variable.
len_str = len(str_numb)
# Check if the cube_root[-len_string:](negative slicing) to the string number using the
# if conditional statement and slicing.
if(cube_numb[-len_str:] == str_numb):
  # If the statement is true, then print "The given number is a Trimorphic Number".
    print("The given number {", gvn_numb, "} is a Trimorphic number")
else:
  # If it is false, then print "The given number is Not a Trimorphic Number".
    print("The given number {", gvn_numb, "} is Not a Trimorphic number")

Output:

Enter some random number = 30
The given number { 30 } is Not a Trimorphic number

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Check Trimorphic Number or Not Read More »

Program to Check Abundant Number or Not

Python Program to Check Abundant Number or Not

In the previous article, we have discussed Python Program to Reverse the Order of Palindrome Words in a Sentence
Abundant Number:

An abundant number is one in which the sum of the number’s proper divisors is greater than the number itself.

To check for an Abundant number, find and add the number’s proper divisors, then compare the sum to the number; if the sum is greater than the number, the number is an Abundant number; otherwise, the number is not an Abundant number. The difference between the sum and the number is referred to as abundant.

For example :

Let Number = 18

The proper divisors are:

1*18

6*3

9*2

The sum=1+6+9+3+2= 21 >18

Therefore 18 is an Abundant Number.

Some of the examples of Abundant Numbers are:

12, 18, 20, 24, 30, 36, 40, 42, 48, 54, 56, 60, 66…..and so on.

Examples:

Example1:

Input:

Given Number = 24

Output:

The given Number { 24 } is an Abundant Number

Example2:

Input:

Given Number = 25

Output:

The given Number { 25 } is Not an Abundant Number

Program to Check Abundant Number or Not in Python

Below are the ways to check whether the given number is an Abundant Number or not in Python

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Take a variable say “divisrs_sum” and initialize it with 1.
  • Iterate from 2 to the given number using the for loop.
  • Check if the given number modulus iterator value is equal to 0 or not using the if conditional statement.
  • If the statement is true, then add the iterator with the sum of divisors “divisrs_sum” and store it in the same variable “divisrs_sum”.
  • Check if the sum of divisors (divisrs_sum) is greater than the given number using the if conditional statement.
  • If the statement is true, then print “The given Number is an Abundant Number”.
  • If it is false, then print “The given Number is Not an Abundant Number”.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb = 24
# Take a variable say "divisrs_sum" and initialize it with 1.
divisrs_sum = 1
# Iterate from 2 to the given number using the for loop.
for itr in range(2, gvn_numb):
  # Check if the given number modulus iterator value is equal to 0 or not using the
    # if conditional statement.
    if(gvn_numb % itr == 0):
        # If the statement is true, then add the iterator with the sum of divisors "divisrs_sum"
        # and store it in the same variable "divisrs_sum".
        divisrs_sum = divisrs_sum + itr
# Check if the sum of divisors (divisrs_sum) is greater than the given number using the
# if conditional statement.
if(divisrs_sum > gvn_numb):
  # If the statement is true, then print "The given Number is an Abundant Number".
    print("The given Number {", gvn_numb, "} is an Abundant Number")
else:
  # If it is false, then print "The given Number is Not an Abundant Number".
    print("The given Number {", gvn_numb, "} is Not an Abundant Number")

Output:

The given Number { 24 } is an Abundant Number

Method #2: Using For loop (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Take a variable say “divisrs_sum” and initialize it with 1.
  • Iterate from 2 to the given number using the for loop.
  • Check if the given number modulus iterator value is equal to 0 or not using the if conditional statement.
  • If the statement is true, then add the iterator with the sum of divisors “divisrs_sum” and store it in the same variable “divisrs_sum”.
  • Check if the sum of divisors (divisrs_sum) is greater than the given number using the if conditional statement.
  • If the statement is true, then print “The given Number is an Abundant Number”.
  • If it is false, then print “The given Number is Not an Abundant Number”.
  • 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_numb = int(input("Enter some random Number = "))
# Take a variable say "divisrs_sum" and initialize it with 1.
divisrs_sum = 1
# Iterate from 2 to the given number using the for loop.
for itr in range(2, gvn_numb):
  # Check if the given number modulus iterator value is equal to 0 or not using the
    # if conditional statement.
    if(gvn_numb % itr == 0):
        # If the statement is true, then add the iterator with the sum of divisors "divisrs_sum"
        # and store it in the same variable "divisrs_sum".
        divisrs_sum = divisrs_sum + itr
# Check if the sum of divisors (divisrs_sum) is greater than the given number using the
# if conditional statement.
if(divisrs_sum > gvn_numb):
  # If the statement is true, then print "The given Number is an Abundant Number".
    print("The given Number {", gvn_numb, "} is an Abundant Number")
else:
  # If it is false, then print "The given Number is Not an Abundant Number".
    print("The given Number {", gvn_numb, "} is Not an Abundant Number")

Output:

Enter some random Number = 48
The given Number { 48 } is an Abundant Number

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Check Abundant Number or Not Read More »

Python Program to Reverse the Order of Palindrome Words in a Sentence

In the previous article, we have discussed Python Program to Sort Palindrome Words in a Sentence
Given a string and the task is to reverse the order of all the palindromic words in a given sentence in Python

Palindrome:

If the reverse of the given string is the same as the given original string, it is said to be a palindrome.

Examples:

Example1:

Input:

Given string/sentence = 'good bob how are you dod mom'

Output:

The given string before reversing the order of paindromic words is =  good bob how are you dod mom
The given string after reversing the order of paindromic words is =  good mom how are you dod bob

Example2:

Input:

Given string/sentence = 'hello madam how are yoou mom'

Output:

The given string before reversing the order of paindromic words is = hello madam how are yoou mom
The given string after reversing the order of paindromic words is = hello mom how are yoou madam

Program to Reverse the Order of Palindrome Words in a Sentence in Python

Below are the ways to reverse the order of all the palindromic words in a given sentence:

Method #1: Using reverse() function (Static input)

Approach:

  • Give the sentence/string as static input and store it in a variable.
  • Convert the given sentence to a list of words using list() and split() functions and store it another variable.
  • Take an empty list to say palindromicwordslist that stores all the palindromic words in the given string and initialize it to null/empty using the list() function or [].
  • Traverse the given list of words using a for loop.
  • Check if the word is palindrome or not using the slicing and if conditional statement.
  • If it is true then append this word to the palindromicwordslist using the append() function.
  • Reverse the palindromicwordslist using the reverse() function.
  • Take a variable say tempo and initialize its value to 0(Here it acts as a pointer to palindromicwordslist ).
  • Traverse the list of words of the given sentence using the For loop.
  • Check if the word is palindrome or not using the slicing and if conditional statement.
  • If it is true then modify the word with the palindromicwordslist[tempo] word.
  • Increment the tempo value by 1.
  • Convert this list of words of the given sentence to the string using the join() function.
  • Print the final string after sorting the palindromic words.
  • The Exit of the Program.

Below is the implementation:

# Give the sentence/string as static input and store it in a variable.
gvnstrng = 'good bob how are you dod mom'
# Convert the given sentence to a list of words using list()
# and split() functions and store it another variable.
strngwrdslst = list(gvnstrng.split())
# Take an empty list to say palindromicwordslist
# that stores all the palindromic words in the given string
# and initialize it to null/empty using the list() function or [].
palindromicwordslist = []
# Traverse the given list of words using a for loop.
for wrd in strngwrdslst:
        # Check if the word is palindrome or not using the slicing
    # and if conditional statement.
    if(wrd == wrd[::-1]):
        # If it is true then append this word to the palindromicwordslist
        # using the append() function.
        palindromicwordslist.append(wrd)

# Reverse the palindromicwordslist using the reverse() function.
palindromicwordslist.reverse()
# Take a variable say tempo and initialize its value to 0
# (Here it acts as a pointer to palindromicwordslist ).
tempo = 0
# Traverse the list of words of the given sentence using the For loop.
for wrditr in range(len(strngwrdslst)):
  # Check if the word is palindrome or not using the slicing
    # and if conditional statement.
    if(strngwrdslst[wrditr] == strngwrdslst[wrditr][::-1]):
        # If it is true then modify the word with the palindromicwordslist[tempo] word.
        strngwrdslst[wrditr] = palindromicwordslist[tempo]
        tempo = tempo+1
        # Increment the tempo value by 1.


# Convert this list of words of the given sentence
# to the string using the join() function.
finalstrng = ' '.join(strngwrdslst)
print('The given string before reversing the order of paindromic words is = ', gvnstrng)
# Print the final string after reversing the palindromic words.
print('The given string after reversing the order of paindromic words is = ', finalstrng)

Output:

The given string before reversing the order of paindromic words is =  good bob how are you dod mom
The given string after reversing the order of paindromic words is =  good mom how are you dod bob

Method #2: Using reverse() function (User input)

Approach:

  • Give the sentence/string as user input using the input() function and store it in a variable.
  • Convert the given sentence to a list of words using list() and split() functions and store it another variable.
  • Take an empty list to say palindromicwordslist that stores all the palindromic words in the given string and initialize it to null/empty using the list() function or [].
  • Traverse the given list of words using a for loop.
  • Check if the word is palindrome or not using the slicing and if conditional statement.
  • If it is true then append this word to the palindromicwordslist using the append() function.
  • Reverse the palindromicwordslist using the reverse() function.
  • Take a variable say tempo and initialize its value to 0(Here it acts as a pointer to palindromicwordslist ).
  • Traverse the list of words of the given sentence using the For loop.
  • Check if the word is palindrome or not using the slicing and if conditional statement.
  • If it is true then modify the word with the palindromicwordslist[tempo] word.
  • Increment the tempo value by 1.
  • Convert this list of words of the given sentence to the string using the join() function.
  • Print the final string after sorting the palindromic words.
  • The Exit of the Program.

Below is the implementation:

# Give the sentence/string as user input using input() function
# and store it in a variable.
gvnstrng = input('Enter some random string = ')
# Convert the given sentence to a list of words using list()
# and split() functions and store it another variable.
strngwrdslst = list(gvnstrng.split())
# Take an empty list to say palindromicwordslist
# that stores all the palindromic words in the given string
# and initialize it to null/empty using the list() function or [].
palindromicwordslist = []
# Traverse the given list of words using a for loop.
for wrd in strngwrdslst:
        # Check if the word is palindrome or not using the slicing
    # and if conditional statement.
    if(wrd == wrd[::-1]):
        # If it is true then append this word to the palindromicwordslist
        # using the append() function.
        palindromicwordslist.append(wrd)


# Reverse the palindromicwordslist using the reverse() function.
palindromicwordslist.reverse()
# Take a variable say tempo and initialize its value to 0
# (Here it acts as a pointer to palindromicwordslist ).
tempo = 0
# Traverse the list of words of the given sentence using the For loop.
for wrditr in range(len(strngwrdslst)):
  # Check if the word is palindrome or not using the slicing
    # and if conditional statement.
    if(strngwrdslst[wrditr] == strngwrdslst[wrditr][::-1]):
        # If it is true then modify the word with the palindromicwordslist[tempo] word.
        strngwrdslst[wrditr] = palindromicwordslist[tempo]
        tempo = tempo+1
        # Increment the tempo value by 1.


# Convert this list of words of the given sentence
# to the string using the join() function.
finalstrng = ' '.join(strngwrdslst)
print('The given string before reversing the order of paindromic words is = ', gvnstrng)
# Print the final string after reversing the palindromic words.
print('The given string after reversing the order of paindromic words is = ', finalstrng)

Output:

Enter some random string = hello madam how are yoou mom
The given string before reversing the order of paindromic words is = hello madam how are yoou mom
The given string after reversing the order of paindromic words is = hello mom how are yoou madam

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Reverse the Order of Palindrome Words in a Sentence Read More »

Program for Snake Case of a Given Sentence

Python Program for Snake Case of a Given Sentence

In the previous article, we have discussed Python Program to Check Trimorphic Number or Not
The task is to remove spaces from a sentence and rewrite it in the Snake case. It is a writing style in which spaces are replaced with underscores and all words begin with small letters.

 The lower() method in Python:

lower() returns a string with all characters in lower case.

Examples:

Example1:

Input:

Given string/sentence = Hello this is Btechgeeks

Output:

The given sentence { Hello this is Btechgeeks } after Converting into Snake case :
hello_this_is_btechgeeks

Example2:

Input:

Given string/sentence = Good morning This is Btechgeeks

Output:

The given sentence { Good morning This is Btechgeeks } after Converting into Snake case :
good_morning_this_is_btechgeeks

Program for Snake Case of a Given Sentence in Python

Below are the ways to remove spaces from a sentence and rewrite it in the Snake case:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string/sentence as static input and store it in a variable.
  • Calculate the length of the given string using the len() function and store it in another variable.
  • Convert the given string into a list of characters using the list() function and store it in another variable say lst_strng.
  • Iterate up to the length of the given string using the for loop.
  • Check if the element of the list of characters ( lst_strng ) is equal to space ( ‘ ‘ ) using the if conditional statement.
  • If the statement is true, then replace the space with the underscore( _ ).
  • If the statement is false, then convert the elements of the list of characters ( lst_strng ) into the lower case using the lower() function.
  • Convert the above list lst_strng into the string using the join function.
  • Store it in the same variable lst_strng.
  • Print the lst_strng to remove spaces from a given sentence and rewrite it in the Snake case.
  • The Exit of the Program.

Below is the implementation:

# Give the string/sentence as static input and store it in a variable.
gvn_strng = "Hello this is Btechgeeks"
# Calculate the length of the given string using the len() function and
# store it in another variable.
str_lengt = len(gvn_strng)
# Convert the given string into a list of characters using the list() function and
# store it in another variable say lst_strng.
lst_strng = list(gvn_strng)
# Iterate up to the length of the given string using the for loop.
print("The given sentence {", gvn_strng,
      "} after Converting into Snake case :")
for itr in range(str_lengt):
 # Check if the element of the list of characters ( lst_strng ) is equal to space ( ' ' )
    # using the if conditional statement.
    if (lst_strng[itr] == ' '):
      # If the statement is true, then replace the space with the underscore( _ ).
        lst_strng[itr] = '_'
    else:
        # If the statement is false, then convert the elements of the list of characters ( lst_strng )
        # into lower case using the lower() function.
        lst_strng[itr] = lst_strng[itr].lower()
# Convert the above list lst_strng into the string using the join function.
# Store it in the same variable lst_strng.
lst_strng = "".join(lst_strng)
# Print the lst_strng to remove spaces from a given sentence and rewrite it in the
# Snake case.
print(lst_strng)

Output:

The given sentence { Hello this is Btechgeeks } after Converting into Snake case :
hello_this_is_btechgeeks

Method #2: Using For loop (User Input)

Approach:

  • Give the string/sentence as user input using the input() function and store it in a variable.
  • Calculate the length of the given string using the len() function and store it in another variable.
  • Convert the given string into a list of characters using the list() function and store it in another variable say lst_strng.
  • Iterate up to the length of the given string using the for loop.
  • Check if the element of the list of characters ( lst_strng ) is equal to space ( ‘ ‘ ) using the if conditional statement.
  • If the statement is true, then replace the space with the underscore( _ ).
  • If the statement is false, then convert the elements of the list of characters ( lst_strng ) into the lower case using the lower() function.
  • Convert the above list lst_strng into the string using the join function.
  • Store it in the same variable lst_strng.
  • Print the lst_strng to remove spaces from a given sentence and rewrite it in the Snake case.
  • The Exit of the Program.

Below is the implementation:

# Give the string/sentence as user input using the input() function
# and store it in a variable.
gvn_strng = input("Enter some random string= ")
# Calculate the length of the given string using the len() function and
# store it in another variable.
str_lengt = len(gvn_strng)
# Convert the given string into a list of characters using the list() function and
# store it in another variable say lst_strng.
lst_strng = list(gvn_strng)
# Iterate up to the length of the given string using the for loop.
print("The given sentence {", gvn_strng,
      "} after Converting into Snake case :")
for itr in range(str_lengt):
 # Check if the element of the list of characters ( lst_strng ) is equal to space ( ' ' )
    # using the if conditional statement.
    if (lst_strng[itr] == ' '):
      # If the statement is true, then replace the space with the underscore( _ ).
        lst_strng[itr] = '_'
    else:
        # If the statement is false, then convert the elements of the list of characters ( lst_strng )
        # into lower case using the lower() function.
        lst_strng[itr] = lst_strng[itr].lower()
# Convert the above list lst_strng into the string using the join function.
# Store it in the same variable lst_strng.
lst_strng = "".join(lst_strng)
# Print the lst_strng to remove spaces from a given sentence and rewrite it in the
# Snake case.
print(lst_strng)

Output:

Enter some random string= Good morning This is Btechgeeks
The given sentence { Good morning This is Btechgeeks } after Converting into Snake case :
good_morning_this_is_btechgeeks

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program for Snake Case of a Given Sentence Read More »

Program to Find Two Odd Occurring Elements in an ArrayList

Python Program to Find Two Odd Occurring Elements in an Array/List

In the previous article, we have discussed Python Program to Count Words that Appear Exactly Two Times in an Array/List of Words
Counter function in Python:

The counter is a set and dict subset. Counter() takes an iterable entity as an argument and stores the elements as keys and the frequency of the elements as a value. So, in collections, if we transfer a string. When you call Counter(), you’ll get a Counter class object with characters as keys and their frequency in a string as values.

Counter() returns a Counter type object (a subclass of dict) with all characters in the string as keys and their occurrence count as values. We’ll use the [] operator to get the occurrence count of the characters from it.

Given a list, and the task is to find two odd occurring elements in a given list.

Examples:

Example1:

Input:

Given list = [5, 2, 3, 2, 3, 4, 6, 4]

Output:

The Two odd Occuring elements in a given list [5, 2, 3, 2, 3, 4, 6, 4] are :
5 6

Example2:

Input:

Given list = [2, 1, 2, 3, 1, 2, 3, 5, 5, 6]

Output:

The Two odd Occuring elements in a given list [2, 1, 2, 3, 1, 2, 3, 5, 5, 6] are :
2 6

Program to Find Two Odd Occurring Elements in an Array/List in Python

Below are the ways to find two odd occurring elements in a given list:

Method #1: Using Counter Function (Static Input)

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the list as static input and store it in a variable.
  • Calculate the frequency of all the given list elements using the Counter() function which returns the element and its frequency as key-value pair and store this dictionary in another variable (say lstfreqelements).
  • Traverse in this frequency dictionary using the for loop.
  • Inside the loop, check if any Key has the value odd using the if conditional statement.
  • If the statement is true, then print the key for getting the two odd occurring elements in a given list.
  • The Exit of the program.

Below is the implementation:

# Import the Counter() function from collections using the import keyword.
from collections import Counter
# Give the list as static input and store it in a variable.
gvn_lst = [5, 2, 3, 2, 3, 4, 6, 4]
# Calculate the frequency of all the given list elements using the Counter() function
# which returns the element and its frequency as key-value pair and
# store this dictionary in another variable (say lstfreqelements).
lstfreqelements = Counter(gvn_lst)
print("The Two odd Occuring elements in a given list", gvn_lst, "are :")
# Traverse in this frequency dictionary using the for loop.
for key in lstfreqelements:
    # Inside the loop, check if any ley has the value odd using the if conditional statement.
    if lstfreqelements[key] % 2 != 0:
        # If the statement is true, then print the key for getting the two odd occurring elements
        # in a given list.
        print(key, end=" ")

Output:

The Two odd Occuring elements in a given list [5, 2, 3, 2, 3, 4, 6, 4] are :
5 6

Method #2: Using Counter Function (User Input)

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Calculate the frequency of all the given list elements using the Counter() function which returns the element and its frequency as key-value pair and store this dictionary in another variable (say lstfreqelements).
  • Traverse in this frequency dictionary using the for loop.
  • Inside the loop, check if any key has the value odd using the if conditional statement.
  • If the statement is true, then print the key for getting the two odd occurring elements in a given list.
  • The Exit of the program.

Below is the implementation:

# Import the Counter() function from collections using the import keyword.
from collections import Counter
# 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()))
# Calculate the frequency of all the given list elements using the Counter() function
# which returns the element and its frequency as key-value pair and
# store this dictionary in another variable (say lstfreqelements).
lstfreqelements = Counter(gvn_lst)
print("The Two odd Occuring elements in a given list", gvn_lst, "are :")
# Traverse in this frequency dictionary using the for loop.
for key in lstfreqelements:
    # Inside the loop, check if any ley has the value odd using the if conditional statement.
    if lstfreqelements[key] % 2 != 0:
        # If the statement is true, then print the key for getting the two odd occurring elements
        # in a given list.
        print(key, end=" ")

Output:

Enter some random List Elements separated by spaces = 2 1 2 3 1 2 3 5 5 6
The Two odd Occuring elements in a given list [2, 1, 2, 3, 1, 2, 3, 5, 5, 6] are :
2 6

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Find Two Odd Occurring Elements in an Array/List Read More »

Program to Check if All Characters have Even Frequency

Python Program to Check if All Characters have Even Frequency

In the previous article, we have discussed Python Program to Find Two Odd Occurring Elements in an Array/List
The task is to check whether all characters in the given string made up entirely of lowercase letters have an even frequency.

Counter function in Python:

The counter is a set and dict subset. Counter() takes an iterable entity as an argument and stores the elements as keys and the frequency of the elements as a value. So, in collections, if we transfer a string. When you call Counter(), you’ll get a Counter class object with characters as keys and their frequency in a string as values.

Counter() returns a Counter type object (a subclass of dict) with all characters in the string as keys and their occurrence count as values. We’ll use the [] operator to get the occurrence count of the characters from it.

For example:

let given string = “pqrspqrspp”.

In this p occurred 4 times, q,r,s occurred 2 times.

Therefore the frequency of all the characters in a given string is Even.

Examples:

Example1:

Input:

Given String = "pqrspqrstutu"

Output:

Yes,the given string { pqrspqrstutu } contains all characters at even intervals

Example2:

Input:

Given String = "btechgeeks"

Output:

No,the given string { btechgeeks } does not contains all characters at even intervals

Program to Check if All Characters have Even Frequency in Python

Below are the ways to check whether all characters in the given string made up entirely of lowercase letters have an even frequency:

Method #1: Using For Loop (Static Input)

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the string as static input and store it in a variable.
  • Pass the given string as an argument to the function determine.
  • Calculate the frequency of all the given string elements using the Counter() function which returns the element and its frequency as a key-value pair and stores this dictionary in another variable (say strngfreqelements).
  • Traverse in this frequency dictionary using the for loop.
  • Inside the loop, check if the Key has a value even or odd using the modulus operator and if conditional statement.
  • If the statement is true, then return False.
  • Return true after the for loop.
  • Check if the function returns true or false using the if conditional statement.
  • If it is true, print “yes, the given string contains all characters at even intervals”.
  • Else print “No, the given string does not contain all characters at even intervals”.
  • The Exit of the program.

Below is the implementation:

# Import the Counter() function from collections using the import keyword.
from collections import Counter
# Pass the given string as an argument to the function determine.


def determine(gvn_strng):
  # Calculate the frequency of all the given string elements using the Counter() function
    # which returns the element and its frequency as a key-value pair and stores this
    # dictionary in another variable (say strngfreqelements).

    strngfreqelements = Counter(gvn_strng)
 # Traverse in this frequency dictionary using the for loop.
    for key in strngfreqelements:
        # Inside the loop, check if the Key has a value even or odd using the modulus operator
        # and if conditional statement.
        if (strngfreqelements[key] % 2 == 1):
           # If the statement is true, then return False.
            return False
  # Return true after the for loop.
    return True


# Give the string as static input and store it in a variable.
gvn_strng = "pqrspqrstutu"
# Check if the function returns true or false using the if conditional statement.
if(determine(gvn_strng)):
  # If it is true, print "yes, the given string contains all characters at even intervals".
    print("Yes,the given string {", gvn_strng,
          "} contains all characters at even intervals")
else:
  # Else print "No, the given string does not contain all characters at even intervals".
    print("No,the given string {", gvn_strng,
          "} does not contains all characters at even intervals")

Output:

Yes,the given string { pqrspqrstutu } contains all characters at even intervals

Method #2: Using For loop (User Input)

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the string as user input using the input() function and store it in a variable.
  • Pass the given string as an argument to the function determine.
  • Calculate the frequency of all the given string elements using the Counter() function which returns the element and its frequency as a key-value pair and stores this dictionary in another variable (say strngfreqelements).
  • Traverse in this frequency dictionary using the for loop.
  • Inside the loop, check if the Key has a value even or odd using the modulus operator and if conditional statement.
  • If the statement is true, then return False.
  • Return true after the for loop.
  • Check if the function returns true or false using the if conditional statement.
  • If it is true, print “yes, the given string contains all characters at even intervals”.
  • Else print “No, the given string does not contain all characters at even intervals”.
  • The Exit of the program

Below is the implementation:

# Import the Counter() function from collections using the import keyword.
from collections import Counter
# Pass the given string as an argument to the function determine.


def determine(gvn_strng):
  # Calculate the frequency of all the given string elements using the Counter() function
    # which returns the element and its frequency as a key-value pair and stores this
    # dictionary in another variable (say strngfreqelements).

    strngfreqelements = Counter(gvn_strng)
 # Traverse in this frequency dictionary using the for loop.
    for key in strngfreqelements:
        # Inside the loop, check if the Key has a value even or odd using the modulus operator
        # and if conditional statement.
        if (strngfreqelements[key] % 2 == 1):
           # If the statement is true, then return False.
            return False
  # Return true after the for loop.
    return True


# Give the string as user input using the input() function and store it in a variable.
gvn_strng = input("Enter some random String = ")
# Check if the function returns true or false using the if conditional statement.
if(determine(gvn_strng)):
  # If it is true, print "yes, the given string contains all characters at even intervals".
    print("Yes,the given string {", gvn_strng,
          "} contains all characters at even intervals")
else:
  # Else print "No, the given string does not contain all characters at even intervals".
    print("No,the given string {", gvn_strng,
          "} does not contains all characters at even intervals")

Output:

Enter some random String = btechgeeks
No,the given string { btechgeeks } does not contains all characters at even intervals

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Check if All Characters have Even Frequency Read More »

Program to Compute the Area and Perimeter of Pentagon

Python Program to Compute the Area and Perimeter of Pentagon

In the previous article, we have discussed Python Program to Compute the Area and Perimeter of Octagon
Pentagon:

A pentagon (from the Greek v Pente and gonia, which mean five and angle) is any five-sided polygon or 5-gon. A simple pentagon’s internal angles add up to 540°.

A pentagon can be simple or complex, and it can be self-intersecting. A pentagram is a self-intersecting regular pentagon (or a star pentagon).

Formula to calculate the area of a pentagon:

 In which, a= The Pentagon’s side length

Formula to calculate the perimeter of a pentagon:

perimeter = 5a
Given the Pentagon’s side length and the task is to calculate the area and perimeter of the given Pentagon.
Examples:

Example1:

Input:

Given The Pentagon's side length = 10

Output:

The Pentagon's area with given side length { 10 } = 172.0477400588967
The Pentagon's Perimeter with given side length { 10 } = 50

Example2:

Input:

Given The Pentagon's side length = 5.5

Output:

The Pentagon's area with given side length { 5.5 } = 52.04444136781625
The Pentagon's Perimeter with given side length { 5.5 } = 27.5

Program to Compute the Area and Perimeter of Pentagon in Python

Below are the ways to Calculate the area and perimeter of a pentagon with the given Pentagon’s side length:

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Import the math module using the import keyword.
  • Give the Pentagon’s side length as static input and store it in a variable.
  • Calculate the area of the given pentagon using the above given mathematical formula and math.sqrt() function.
  • Store it in another variable.
  • Calculate the perimeter of the given pentagon using the above given mathematical formula.
  • Store it in another variable.
  • Print the Pentagon’s area with the given side length.
  • Print the Pentagon’s perimeter with the given side length.
  • The Exit of the program.

Below is the implementation:

# Import the math module using the import keyword.
import math
# Give the Pentagon's side length as static input and store it in a variable.
side_len = 10
# Calculate the area of the given pentagon using the above given mathematical formula and
# math.sqrt() function.
# Store it in another variable.
pentgn_area = (math.sqrt(5*(5+2*math.sqrt(5)))*pow(side_len, 2))/4.0
# Calculate the perimeter of the given pentagon using the above given mathematical formula.
# Store it in another variable.
pentgn_perimtr = (5*side_len)
# Print the Pentagon's area with the given side length.
print(
    "The Pentagon's area with given side length {", side_len, "} =", pentgn_area)
# Print the Pentagon's perimeter with the given side length.
print(
    "The Pentagon's Perimeter with given side length {", side_len, "} =", pentgn_perimtr)

Output:

The Pentagon's area with given side length { 10 } = 172.0477400588967
The Pentagon's Perimeter with given side length { 10 } = 50

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Import the math module using the import keyword.
  • Give the Pentagon’s side length as user input using float(input()) function and store it in a variable.
  • Calculate the area of the given pentagon using the above given mathematical formula and math.sqrt() function.
  • Store it in another variable.
  • Calculate the perimeter of the given pentagon using the above given mathematical formula.
  • Store it in another variable.
  • Print the Pentagon’s area with the given side length.
  • Print the Pentagon’s perimeter with the given side length.
  • The Exit of the program.

Below is the implementation:

# Import the math module using the import keyword.
import math
# Give the Pentagon's side length as user input using float(input()) function and
# store it in a variable.
side_len = float(input('Enter some random number = '))
# Calculate the area of the given pentagon using the above given mathematical formula and
# math.sqrt() function.
# Store it in another variable.
pentgn_area = (math.sqrt(5*(5+2*math.sqrt(5)))*pow(side_len, 2))/4.0
# Calculate the perimeter of the given pentagon using the above given mathematical formula.
# Store it in another variable.
pentgn_perimtr = (5*side_len)
# Print the Pentagon's area with the given side length.
print(
    "The Pentagon's area with given side length {", side_len, "} =", pentgn_area)
# Print the Pentagon's perimeter with the given side length.
print(
    "The Pentagon's Perimeter with given side length {", side_len, "} =", pentgn_perimtr)

Output:

Enter some random number = 5.5
The Pentagon's area with given side length { 5.5 } = 52.04444136781625
The Pentagon's Perimeter with given side length { 5.5 } = 27.5

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Compute the Area and Perimeter of Pentagon Read More »

Program to Compute the Area and Perimeter of Heptagon

Python Program to Compute the Area and Perimeter of Heptagon

In the previous article, we have discussed Python Program to Check if All Characters have Even Frequency
Math Module :

Python’s math module is a built-in module. By importing this module, we can perform mathematical computations.

Numerous mathematical operations like ceil( ),floor( ),factorial( ),mod( ),value of pi ,…..etc .can be computed with the help of math module.

Heptagon:

A heptagon is a seven-sided polygon or 7-gon in geometry. The heptagon is also known as the septagon, which is formed by combining “sept-” (an elision of septua-, a Latin-derived numerical prefix, rather than hepta-, a Greek-derived numerical prefix; both are cognate) and the Greek suffix “-agon” meaning angle.

Formula to calculate the area of a Heptagon:

 

 

In which  a is the Heptagon’s side length

Formula to calculate the perimeter of a Heptagon:

Perimeter = 7a

Given the Heptagon’s side length and the task is to calculate the area and perimeter of the given Heptagon.

Examples:

Example1:

Input:

Given The Heptagon's side length = 8

Output:

The Heptagon's Area with given side length { 8 } = 232.576
The Heptagon's Perimeter with the given side length { 8 } = 56

Example2:

Input:

Given The Heptagon's side length = 15

Output:

The Heptagon's Area with given side length { 15 } = 817.65
The Heptagon's Perimeter with the given side length { 15 } = 105

Program to Compute the Area and Perimeter of Heptagon

Below are the ways to Calculate the area and perimeter of a heptagon with the given heptagon’s side length:

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Import the math module using the import keyword.
  • Give the heptagon’s side length as static input and store it in a variable.
  • Calculate the area of the given heptagon using the above given mathematical formula and pow() function.
  • Store it in another variable.
  • Calculate the perimeter of the given heptagon using the above given mathematical formula.
  • Store it in another variable.
  • Print the heptagon’s area with the given side length.
  • Print the heptagon’s perimeter with the given side length.
  • The Exit of the program.

Below is the implementation:

# Import the math module using the import keyword.
import math
# Give the heptagon's side length as static input and store it in a variable.
side_len = 8
# Calculate the area of the given heptagon using the above given mathematical formula
# and pow() function.
# Store it in another variable.
heptagn_area = 3.634*pow(side_len, 2)
# Calculate the perimeter of the given heptagon using the above given mathematical formula.
# Store it in another variable.
heptagn_perimetr = (7*side_len)
# Print the heptagon's area with the given side length.
print(
    "The Heptagon's Area with given side length {", side_len, "} =", heptagn_area)
# Print the heptagon's perimeter with the given side length.
print(
    "The Heptagon's Perimeter with the given side length {", side_len, "} =", heptagn_perimetr)

Output:

The Heptagon's Area with given side length { 8 } = 232.576
The Heptagon's Perimeter with the given side length { 8 } = 56

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Import the math module using the import keyword.
  • Give the Heptagon’s side length as user input using float(input()) function and store it in a variable.
  • Calculate the area of the given heptagon using the above given mathematical formula and pow() function.
  • Store it in another variable.
  • Calculate the perimeter of the given heptagon using the above given mathematical formula.
  • Store it in another variable.
  • Print the heptagon’s area with the given side length.
  • Print the heptagon’s perimeter with the given side length.
  • The Exit of the program.

Below is the implementation:

# Import the math module using the import keyword.
import math
# Give the Heptagon's side length as user input using float(input()) function and
# store it in a variable.
side_len = float(input("Enter some random variable = "))
# Calculate the area of the given heptagon using the above given mathematical formula
# and pow() function.
# Store it in another variable.
heptagn_area = 3.634*pow(side_len, 2)
# Calculate the perimeter of the given heptagon using the above given mathematical formula.
# Store it in another variable.
heptagn_perimetr = (7*side_len)
# Print the heptagon's area with the given side length.
print(
    "The Heptagon's Area with given side length {", side_len, "} =", heptagn_area)
# Print the heptagon's perimeter with the given side length.
print(
    "The Heptagon's Perimeter with the given side length {", side_len, "} =", heptagn_perimetr)

Output:

Enter some random variable = 15
The Heptagon's Area with given side length { 15.0 } = 817.65
The Heptagon's Perimeter with the given side length { 15.0 } = 105.0

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Compute the Area and Perimeter of Heptagon Read More »