Author name: Vikram Chiluka

Python Program to Count Words that Appear Exactly Two Times in an Array/List of Words

In the previous article, we have discussed Python Program for Snake Case of a Given Sentence
The task is counting the words that appear exactly twice in an array/list of words in a given list in Python

Examples:

Example1:

Input:

Given List of words = ['hi', 'all', 'this', 'is', 'btechgeeks', 'hi', 'this', 'btechgeeks']

Output:

The Count of words in a given list ['hi', 'all', 'this', 'is', 'btechgeeks', 'hi', 'this', 'btechgeeks']  which are exactly repeated two times = 3

Example2:

Input:

Given List of words = ['good', 'morning', 'this', 'is', 'btechgeeks', 'good', 'is']

Output:

The Count of words in a given list ['good', 'morning', 'this', 'is', 'btechgeeks', 'good', 'is'] which are exactly repeated two times = 2

Program to Count Words that Appear Exactly Two Times in an Array/List of Words

Below are the ways to count the words that appear exactly twice in an array/list of words in a given list.

Method #1: Using For Loop (Static Input)

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the list of words as static input and store it in a variable.
  • Calculate the frequency of all the given list of words using the Counter() function which returns the element and its frequency as key-value pair and store this dictionary in a variable(say dictnry)
  • Take a variable say countt and initialize its value with 0.
  • Iterate in the above-obtained dictionary values using the for loop.
  • Check if the iterator value is equal to 2 or not using the if conditional statement.
  • If the statement is true, increase the value of countt by 1.
  • Print the count of words that appear exactly twice in an array/list of words 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 of words as static input and store it in a variable.
gvn_lst = ["hi", "all", "this", "is", "btechgeeks", "hi", "this", "btechgeeks"]
# Calculate the frequency of all the given list of words using the Counter() function
# which returns the element and its frequency as key-value pair and store this
# dictionary in a variable(say dictnry)
dictnry = Counter(gvn_lst)
# Take a variable say countt and initialize its value with 0.
countt = 0
# Iterate in the above-obtained dictionary values using the for loop.
for itr in dictnry.values():
  # Check if the iterator value is equal to 2 or not using the if conditional statement.
    if itr == 2:
       # If the statement is true, increase the value of "countt" by 1.
        countt += 1
# Print the count of words that appear exactly twice in an array/list of words in a
# given list.
print("The Count of words in a given list", gvn_lst,
      " which are exactly repeated two times =", countt)

Output:

The Count of words in a given list ['hi', 'all', 'this', 'is', 'btechgeeks', 'hi', 'this', 'btechgeeks']  which are exactly repeated two times = 3

Method #2: Using For loop (User Input)

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the list of words as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Calculate the frequency of all the given list of words using the Counter() function which returns the element and its frequency as key-value pair and store this dictionary in a variable(say dictnry)
  • Take a variable say countt and initialize its value with 0.
  • Iterate in the above-obtained dictionary values using the for loop.
  • Check if the iterator value is equal to 2 or not using the if conditional statement.
  • If the statement is true, increase the value of countt by 1.
  • Print the count of words that appear exactly twice in an array/list of words 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 of words as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvn_lst = list(input(
   'Enter some random List Elements separated by spaces = ').split())
# Calculate the frequency of all the given list of words using the Counter() function
# which returns the element and its frequency as key-value pair and store this
# dictionary in a variable(say dictnry)
dictnry = Counter(gvn_lst)
# Take a variable say countt and initialize its value with 0.
countt = 0
# Iterate in the above-obtained dictionary values using the for loop.
for itr in dictnry.values():
  # Check if the iterator value is equal to 2 or not using the if conditional statement.
    if itr == 2:
       # If the statement is true, increase the value of "countt" by 1.
        countt += 1
# Print the count of words that appear exactly twice in an array/list of words in a
# given list.
print("The Count of words in a given list", gvn_lst,
      " which are exactly repeated two times =", countt)

Output:

Enter some random List Elements separated by spaces = good morning this is btechgeeks good is
The Count of words in a given list ['good', 'morning', 'this', 'is', 'btechgeeks', 'good', 'is'] which are exactly repeated two times = 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 Count Words that Appear Exactly Two Times in an Array/List of Words Read More »

Program to Print Number in Ascending Order which contains 1, 2 and 3 in their Digits

Python Program to Print Number in Ascending Order which contains 1, 2 and 3 in their Digits

In the previous article, we have discussed Python Program to Check if Array can be Sorted with One Swap
Given a list and the task is to print the numbers with the digits 1, 2, and 3 in ascending order, which are separated by commas.

Examples:

Example1:

Input:

Given List = [67123, 1234, 985, 126, 1011]

Output:

The numbers with the digits 1, 2, and 3 in ascending order, which is separated by commas=  [1234, 67123]

Example2:

Input:

Given List = [75, 4123, 87123, 5312, 9098]

Output:

The numbers with the digits 1, 2, and 3 in ascending order, which is separated by commas= [4123, 5312, 87123]

Program to Print Number in Ascending Order which contains 1, 2, and 3 in their Digits in Python

Below are the ways to print the numbers with the digits 1, 2, and 3 in ascending order, which is separated by commas.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Take a new empty list say “numb” and store it in another variable.
  • Loop in the given list using the for loop.
  • Inside the loop, convert the iterator value to the string using the str() function and store it in another variable.
  • Check if 1 and 2 and 3 are present in the string number using the if conditional statement and ‘and’ keyword.
  • If the statement is true, then append the iterator value to the above initialized new empty list “numb”.
  • Sort the above list “numb” using the sort() function.
  • Print the list “numb” to print the numbers with the digits 1, 2, and 3 in ascending order, which is separated by commas.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gven_lst = [67123, 1234, 985, 126, 1011]
# Take a new empty list say "numb" and store it in another variable.
numb = []
# Loop in the given list using the for loop.
for itr in gven_lst:
 # Inside the loop, convert the iterator value to the string using the str() function
    # and store it in another variable.
    strng_number = str(itr)
# Check if 1 and 2 and 3 are present in the string number using the if conditional
# statement and 'and' keyword.
    if '1' in strng_number and '2' in strng_number and '3' in strng_number:
        # If the statement is true, then append the iterator value to the above initialized
        # new empty list "numb".
        numb.append(itr)
 # Sort the above list "numb" using the sort() function.
numb.sort()
# print the list "numb" to print the numbers with the digits 1, 2, and 3 in ascending order,
# which is separated by commas.
print("The numbers with the digits 1, 2, and 3 in ascending order, which is separated by commas= ", numb)

Output:

The numbers with the digits 1, 2, and 3 in ascending order, which is separated by commas=  [1234, 67123]

Method #2: Using For loop (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Take a new empty list say “numb” and store it in another variable.
  • Loop in the given list using the for loop.
  • Inside the loop, convert the iterator value to the string using the str() function and store it in another variable.
  • Check if 1 and 2 and 3 are present in the string number using the if conditional statement and ‘and’ keyword.
  • If the statement is true, then append the iterator value to the above initialized new empty list “numb”.
  • Sort the above list “numb” using the sort() function.
  • Print the list “numb” to print the numbers with the digits 1, 2, and 3 in ascending order, which is separated by commas.
  • The Exit of the Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gven_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Take a new empty list say "numb" and store it in another variable.
numb = []
# Loop in the given list using the for loop.
for itr in gven_lst:
 # Inside the loop, convert the iterator value to the string using the str() function
    # and store it in another variable.
    strng_number = str(itr)
# Check if 1 and 2 and 3 are present in the string number using the if conditional
# statement and 'and' keyword.
    if '1' in strng_number and '2' in strng_number and '3' in strng_number:
        # If the statement is true, then append the iterator value to the above initialized
        # new empty list "numb".
        numb.append(itr)
 # Sort the above list "numb" using the sort() function.
numb.sort()
# print the list "numb" to print the numbers with the digits 1, 2, and 3 in ascending order,
# which is separated by commas.
print("The numbers with the digits 1, 2, and 3 in ascending order, which is separated by commas= ", numb)

Output:

Enter some random List Elements separated by spaces = 75 4123 87123 5312 9098
The numbers with the digits 1, 2, and 3 in ascending order, which is separated by commas= [4123, 5312, 87123]

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 Print Number in Ascending Order which contains 1, 2 and 3 in their Digits Read More »

Program to Find the Sum of Digits of a Number at Even and Odd places

Python Program to Find the Sum of Digits of a Number at Even and Odd places

In the previous article, we have discussed Python Program to Check if Product of Digits of a Number at Even and Odd places is Equal
The task is to find the sum of digits of a number at even and odd places given a number N.

Examples:

Example1:

Input:

Given Number = 123456

Output:

The sum of all digits at even places in a given number{ 123456 } = 9
The sum of all digits at odd places in a given number { 123456 } = 12

Example2:

Input:

Given Number = 1787725620

Output:

The sum of all digits at even places in a given number{ 1787725620 } = 23
The sum of all digits at odd places in a given number { 1787725620 } = 22

Program to Count the Number of Odd and Even Digits of a Number at Even and Odd places in Python

Below are the ways to find the sum of digits of a number at even and odd places given a number N.

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 iterator value is even or not using the if conditional statement.
  • If the statement is true, then add the iterator value of “digtslst” to the “evn_sum” and store it in the same variable evn_sum.
  • If the statement is false, then add the iterator value of “digtslst” to the “od_sum” and store it in the same variable od_sum.
  • Print “evn_sum to get the sum of even digits in a given number.
  • Print “od_sum to get the sum of odd digits in a given number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
numb = 1787725620
# 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 iterator value is even or not using
    # the if conditional statement.
    if(itr % 2 == 0):
     # If the statement is true, then add the iterator value of "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 iterator value of "digtslst" to the "od_sum"
        # and store it in the same variable od_sum.
        od_sum += digtslst[itr]
# Print "evn_sum" to get the sum of all digits at even places in a given number.
print(
    "The sum of all digits at even places in a given number{", numb, "} =", evn_sum)
# Print "od_sum" to get the sum of all digits at odd places in a given number.
print(
    "The sum of all digits at odd places in a given number {", numb, "} =", od_sum)

Output:

The sum of all digits at even places in a given number{ 1787725620 } = 23
The sum of all digits at odd places in a given number { 1787725620 } = 22

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 iterator value is even or not using the if conditional statement.
  • If the statement is true, then add the iterator value of “digtslst” to the “evn_sum” and store it in the same variable evn_sum.
  • If the statement is false, then add the iterator value of “digtslst” to the “od_sum” and store it in the same variable od_sum.
  • Print “evn_sum to get the sum of even digits in a given number.
  • Print “od_sum to get the sum of odd digits in a given 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.
numb = int(input("Enter some random variable = "))
# 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 iterator value is even or not using
    # the if conditional statement.
    if(itr % 2 == 0):
     # If the statement is true, then add the iterator value of "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 iterator value of "digtslst" to the "od_sum"
        # and store it in the same variable od_sum.
        od_sum += digtslst[itr]
# Print "evn_sum" to get the sum of all digits at even places in a given number.
print(
    "The sum of all digits at even places in a given number{", numb, "} =", evn_sum)
# Print "od_sum" to get the sum of all digits at odd places in a given number.
print(
    "The sum of all digits at odd places in a given number {", numb, "} =", od_sum)

Output:

Enter some random variable = 123456
The sum of all digits at even places in a given number{ 123456 } = 9
The sum of all digits at odd places in a given number { 123456 } = 12

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 the Sum of Digits of a Number at Even and Odd places Read More »

Program for Maximum Distance between Two Occurrences of Same Element in ArrayList

Python Program for Maximum Distance between Two Occurrences of Same Element in Array/List

In the previous article, we have discussed Python Program for Leonardo Number Series
Dictionaries:

Python dictionaries are mutable collections of things that contain key-value pairs. The dictionary contains two main components: keys and values. These keys must be single elements, and the values can be of any data type, such as list, string, integer, tuple, and so on. The keys are linked to their corresponding values. In other words, the values can be retrieved using their corresponding keys.

A dictionary is created in Python by enclosing numerous key-value pairs in curly braces.

Given a list, the task is to find the greatest distance between two occurrences of an element in a given list of repeated elements.

Examples:

Example1:

Input:

Given List =  [1, 2, 3, 7, 8, 9, 2, 1, 4, 3]

Output:

The greatest distance between two occurrences of an element in a given list of repeated elements = 7

Example2:

Input:

Given List = [6, 7, 8, 2, 1, 6, 8, 9]

Output:

The greatest distance between two occurrences of an element in a given list of repeated elements = 5

Program for Maximum Distance between Two Occurrences of the Same Element in Array/List in Python

Below are the ways to find the greatest distance between two occurrences of an element in a given list of repeated elements:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Calculate the length of the given list using the len() function and store it in another variable.
  • Create an empty dictionary and store it in another variable.
  • Take a variable say “max_val” and initialize its value with 0.
  • Loop till the number of elements of the list using the for loop.
  • Check if the list element is present in the dictionary keys or not using the if conditional statement.
  • If the statement is true, then update the dictionary with the key as a list element and value as an iterator.
  • If it is not true, calculate the maximum value of “max_val” and iterator -dictionary of list of iterator and store it in “max_val”.
  • Print “max_val” to get the greatest distance between two occurrences of an element in a given list of repeated elements.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = [1, 2, 3, 7, 8, 9, 2, 1, 4, 3]
# Calculate the length of the given list using the len() function and store it in
# another variable.
lst_len = len(gvn_lst)
# Create an empty dictionary and store it in another variable.
new_dict = {}
# Take a variable say "max_val" and initialize its value with 0.
max_val = 0
# Loop till the number of elements of the list using the for loop.
for itr in range(lst_len):
    # Check if the list element is present in the dictionary keys or not using the
    # if conditional statement.
    if gvn_lst[itr] not in new_dict.keys():
        # If the statement is true, then update the dictionary with the key as a list element
        # and value as an iterator.
        new_dict[gvn_lst[itr]] = itr
 # If it is not true, calculate the maximum value of "max_val" and iterator -dictionary
# of list of iterator and store it in "max_val".
    else:
        max_val = max(max_val, itr-new_dict[gvn_lst[itr]])
 # Print "max_val" to get the greatest distance between two occurrences of an element
# in a given list of repeated elements.
print("The greatest distance between two occurrences of an element in a given list of repeated elements = ", max_val)

Output:

The greatest distance between two occurrences of an element in a given list of repeated elements =  7

Method #2: Using For loop (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Calculate the length of the given list using the len() function and store it in another variable.
  • Create an empty dictionary and store it in another variable.
  • Take a variable say “max_val” and initialize its value with 0.
  • Loop till the number of elements of the list using the for loop.
  • Check if the list element is present in the dictionary keys or not using the if conditional statement.
  • If the statement is true, then update the dictionary with the key as a list element and value as an iterator.
  • If it is not true, calculate the maximum value of “max_val” and iterator -dictionary of list of iterator and store it in “max_val”.
  • Print “max_val” to get the greatest distance between two occurrences of an element in a given list of repeated elements.
  • The Exit of the Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
#Store it in a variable.
gvn_lst = list(map(int, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Calculate the length of the given list using the len() function and store it in
# another variable.
lst_len = len(gvn_lst)
# Create an empty dictionary and store it in another variable.
new_dict = {}
# Take a variable say "max_val" and initialize its value with 0.
max_val = 0
# Loop till the number of elements of the list using the for loop.
for itr in range(lst_len):
    # Check if the list element is present in the dictionary keys or not using the
    # if conditional statement.
    if gvn_lst[itr] not in new_dict.keys():
        # If the statement is true, then update the dictionary with the key as a list element
        # and value as an iterator.
        new_dict[gvn_lst[itr]] = itr
 # If it is not true, calculate the maximum value of "max_val" and iterator -dictionary
# of list of iterator and store it in "max_val".
    else:
        max_val = max(max_val, itr-new_dict[gvn_lst[itr]])
 # Print "max_val" to get the greatest distance between two occurrences of an element
# in a given list of repeated elements.
print("The greatest distance between two occurrences of an element in a given list of repeated elements = ", max_val)

Output:

Enter some random List Elements separated by spaces = 6 7 8 2 1 6 8 9
The greatest distance between two occurrences of an element in a given list of repeated elements = 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 for Maximum Distance between Two Occurrences of Same Element in Array/List Read More »

Program to Find GCD of Elements in a Given Range

Python Program to Find GCD of Elements in a Given Range

In the previous article, we have discussed Python Program to Sort digits of a Number in Ascending Order
Highest Common Factor (HCF) / Greatest Common Divisor (GCD) :

When at least one of the integers is not zero, the greatest positive integer that evenly divides the numbers without a remainder is called the Highest Common Factor or Greatest Common Divisor.

The GCD of 12 and 16 is, for example, 4.

Given two numbers, n, and m, and the task is to solve the equation, Find the largest integer a(gcd) that is divisible by all integers n, n + 1, n + 2,…, m.

We only need to look at two cases here:

If a = b, the segment is made up of a single number, so the answer is a.
If a = b, then gcd(n, n + 1, n?+ 2,…, m) = gcd(n, n + 1), n + 2,…, m) = gcd(1, n + 2,…, n) = 1.

Examples:

Example1:

Input:

Given First Number =   125
Given Second Number = 125

Output:

The greatest number that divides both 125 and 125 = 125

Example2:

Input:

Given First Number = 5
Given Second Number = 8

Output:

The greatest number that divides both 5 and 8 = 1

Program to Find GCD of Elements in a Given Range in Python.

Below are the ways to Find the largest integer a(gcd) that is divisible by all integers n, n + 1, n + 2,…, m.

Method #1: Using If, Else conditional  Statements (Static Input)

Approach:

  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Check if the first number is equal to the second number using the if conditional statement.
  • If the statement is true, then print the first number.
  • If the statement is false, then print 1.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as static input and store it in a variable.
fst_numb = 125
# Give the second number as static input and store it in another variable.
secnd_numb = 125
# Check if the first number is equal to the second number using the if conditional statement.
if(fst_numb == secnd_numb):
  # If the statement is true, then print the first number.
    print("The greatest number that divides both",
          fst_numb, "and", secnd_numb, "=", fst_numb)
else:
  # If the statement is false, then print 1.
    print("The greatest number that divides both",
          fst_numb, "and", secnd_numb, "=", 1)

Output:

The greatest number that divides both 125 and 125 = 125

Method #2: Using If, Else conditional  Statements (User Input)

Approach:

  • Give the first number as user input using the int(input()) function and store it in a variable.
  • Give the second number as user input using the int(input()) function and store it in another variable.
  • Check if the first number is equal to the second number using the if conditional statement.
  • If the statement is true, then print the first number.
  • If the statement is false, then print 1.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as user input using the int(input()) function and store it in a variable.
fst_numb = int(input("Enter some random number = "))
# Give the second number as user input using the int(input()) function and store it in another variable.
secnd_numb = int(input("Enter some random number = "))
# Check if the first number is equal to the second number using the if conditional statement.
if(fst_numb == secnd_numb):
  # If the statement is true, then print the first number.
    print("The greatest number that divides both",
          fst_numb, "and", secnd_numb, "=", fst_numb)
else:
  # If the statement is false, then print 1.
    print("The greatest number that divides both",
          fst_numb, "and", secnd_numb, "=", 1)

Output:

Enter some random number = 5
Enter some random number = 8
The greatest number that divides both 5 and 8 = 1

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 GCD of Elements in a Given Range Read More »

Program to Sort digits of a Number in Ascending Order

Python Program to Sort digits of a Number in Ascending Order

In the previous article, we have discussed Python Program to Count the Number of Odd and Even Digits
The task is to sort the digits in ascending order given a number N. Print the new number after removing the leading zeroes.

join() method in python:

The join() method in Python can be used to convert a List to a String.

Iterables such as Lists, Tuples, Strings, and others are accepted as parameters for the join() process.

Examples:

Example1:

Input:

Given Number = 4561230008

Output:

The sorted digits in ascending order of a given number 4561230008 after removal of leading zeros =
1234568

Example2:

Input:

Given Number = 34879010

Output:

The sorted digits in ascending order of a given number 34879010 after removal of leading zeros =
134789

Program to Sort digits of a Number in Ascending Order in Python

Below are the ways to get sorted digits in ascending order of a given number after the removal of leading zeros:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Convert the given number into a string number using the str() function and store it in another variable.
  • Sort the above-obtained string number using the sorted() function and store it in another variable.
  • Convert this sorted list of numbers into a string using the join function and store it in another variable.
  • Convert the above obtained sorted string to an integer using the int() function (This removes the leading zeros) and store it in another variable.
  • Print the sorted digits in ascending order of a given number after removal of leading zeros.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
numb = 4561230008
# Convert the given number into a string number using the str() function and
# store it in another variable.
strng_numbr = str(numb)
# Sort the above-obtained string number using the sorted() function and store
# it in another variable.
sortdlst_num = sorted(strng_numbr)
# Convert this sorted list of numbers into a string using the join function and
# store it in another variable.
sortd_str = ''.join(sortdlst_num)
# Convert the above obtained sorted string to an integer using the int() function
# (This removes the leading zeros) and store it in another variable.
rslt = int(sortd_str)
# Print the sorted digits in ascending order of a given number after removal of
# leading zeros.
print("The sorted digits in ascending order of a given number",
      numb, "after removal of leading zeros =")
print(rslt)

Output:

The sorted digits in ascending order of a given number 4561230008 after removal of leading zeros =
1234568

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 into a string number using the str() function and store it in another variable.
  • Sort the above-obtained string number using the sorted() function and store it in another variable.
  • Convert this sorted list of numbers into a string using the join function and store it in another variable.
  • Convert the above obtained sorted string to an integer using the int() function (This removes the leading zeros) and store it in another variable.
  • Print the sorted digits in ascending order of a given number after removal of leading zeros.
  • 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 into a string number using the str() function and
# store it in another variable.
strng_numbr = str(numb)
# Sort the above-obtained string number using the sorted() function and store
# it in another variable.
sortdlst_num = sorted(strng_numbr)
# Convert this sorted list of numbers into a string using the join function and
# store it in another variable.
sortd_str = ''.join(sortdlst_num)
# Convert the above obtained sorted string to an integer using the int() function
# (This removes the leading zeros) and store it in another variable.
rslt = int(sortd_str)
# Print the sorted digits in ascending order of a given number after removal of
# leading zeros.
print("The sorted digits in ascending order of a given number",
      numb, "after removal of leading zeros =")
print(rslt)

Output:

Enter some random number = 34879010
The sorted digits in ascending order of a given number 34879010 after removal of leading zeros =
134789

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 Sort digits of a Number in Ascending Order Read More »

Program to Find the 2nd Largest Digit in a Given Number

Python Program to Find the 2nd Largest Digit in a Given Number

In the previous article, we have discussed Python Program to Find GCD of Elements in a Given Range
Given a number and the task is to find the given number’s second-largest digit.

sort() method in Python:

By default, the sort() method sorts the list in ascending order.

Examples:

Example1:

Input:

Given Number = 1732981

Output:

The given number's { 1732981 } second largest digit = 8

Example2:

Input:

Given Number = 76542316

Output:

The given number's { 76542316 } second largest digit = 6

Program to Find the 2nd Largest Digit in a Given Number in Python

Below are the ways to find the given number’s second-largest digit:

Method #1: Using sort() Function (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.
  • Sort the above-obtained list of digits using the sort() function.
  • Calculate the digit at the index length of the digitlist-2 to get the second-largest digit of a given number.
  • Store it in another variable.
  • Print the second-largest digit of a given number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
numb = 1732981
# Convert the given number to string using the str() function and store it in another variable
stringnum = str(numb)
# Create a list of digits say "digtslst" using map(),list(),int functions.
# Store it in another variable.
digtslst = list(map(int, stringnum))
# Sort the above-obtained list of digits using the sort() function.
digtslst.sort()
# Calculate the length of the list of digits of a given number using the len() function
# and store it in another variable.
len_digtslst = len(digtslst)
# Calculate the digit at the index length of the digitlist-2 to get the second-largest
# digit of a given number.
# Store it in another variable.
scnd_largst_digtt = digtslst[len_digtslst-2]
# Print the second-largest digit of a given Number.
print("The given number's {", numb,
      "} second largest digit =", scnd_largst_digtt)

Output:

The given number's { 1732981 } second largest digit = 8

The given number’s { 1732981 } second largest digit = 8

Method #2: Using sort() Function (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.
  • Sort the above-obtained list of digits using the sort() function.
  • Calculate the digit at the index length of the digitlist-2 to get the second-largest digit of a given number.
  • Store it in another variable.
  • Print the second-largest digit of a given 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.
numb = int(input("Enter some random variable = "))
# Convert the given number to string using the str() function and store it in another variable
stringnum = str(numb)
# Create a list of digits say "digtslst" using map(),list(),int functions.
# Store it in another variable.
digtslst = list(map(int, stringnum))
# Sort the above-obtained list of digits using the sort() function.
digtslst.sort()
# Calculate the length of the list of digits of a given number using the len() function
# and store it in another variable.
len_digtslst = len(digtslst)
# Calculate the digit at the index length of the digitlist-2 to get the second-largest
# digit of a given number.
# Store it in another variable.
scnd_largst_digtt = digtslst[len_digtslst-2]
# Print the second-largest digit of a given Number.
print("The given number's {", numb,
      "} second largest digit =", scnd_largst_digtt)

Output:

Enter some random variable = 76542316
The given number's { 76542316 } second largest digit = 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 the 2nd Largest Digit in a Given Number Read More »

Program to Count the Number of Odd and Even Digits

Python Program to Count the Number of Odd and Even Digits

In the previous article, we have discussed Python Program to Replace a Word with Asterisks in a Sentence
Given a number and the task is to count the number of odd and even digits in a given number.

Examples:

Example1:

Input:

Given Number = 1237891

Output:

The count of even digits in a given number{ 1237891 } = 2
The count of odd digits in a given number{ 1237891 } = 5

Example2:

Input:

Given Number = 78342186453

Output:

The count of even digits in a given number{ 78342186453 } = 6
The count of odd digits in a given number{ 78342186453 } = 5

Program to Count the Number of Odd and Even Digits in Python

Below are the ways to count the number of odd and even digits in a given number :

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_count” and initialize it with 0.
  • Take another variable say “od_count” 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 iterator value of “digtslst” is even or not using the if conditional statement.
  • If the statement is true, increment the count value of “evn_count” by 1.
  • If the statement is false, increment the count value of “od_count” by 1.
  • Print “evn_count” to get the count of even digits in a given number.
  • Print “od_count to get the count of odd digits in a given number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
numb = 1237891
# 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_count" and initialize it with 0.
evn_count = 0
# Take another variable say "od_count" and initialize it with 0.
od_count = 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 iterator value of "digtslst" is even or not using
    # the if conditional statement.
    if(digtslst[itr] % 2 == 0):
        # If the statement is true, increment the count value of "evn_count" by 1.
        evn_count += 1
    else:
        # If the statement is false, increment the count value of "od_count" by 1.
        od_count += 1
# Print "evn_count" to get the count of even digits in a given number.
print("The count of even digits in a given number{", numb, "} =", evn_count)
# Print "od_count" to get the count of odd digits in a given number.
print("The count of odd digits in a given number{", numb, "} =", od_count)

Output:

The count of even digits in a given number{ 1237891 } = 2
The count of odd digits in a given number{ 1237891 } = 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.
  • Convert the given number to string using the str() function.
  • Create a list of digits say “digtslst” using map(),list(),int functions.
  • Take a variable say “evn_count” and initialize it with 0.
  • Take another variable say “od_count” 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 iterator value of “digtslst” is even or not using the if conditional statement.
  • If the statement is true, increment the count value of “evn_count” by 1.
  • If the statement is false, increment the count value of “od_count” by 1.
  • Print “evn_count” to get the count of even digits in a given number.
  • Print “od_count to get the count of odd digits in a given 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.
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_count" and initialize it with 0.
evn_count = 0
# Take another variable say "od_count" and initialize it with 0.
od_count = 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 iterator value of "digtslst" is even or not using
    # the if conditional statement.
    if(digtslst[itr] % 2 == 0):
        # If the statement is true, increment the count value of "evn_count" by 1.
        evn_count += 1
    else:
        # If the statement is false, increment the count value of "od_count" by 1.
        od_count += 1
# Print "evn_count" to get the count of even digits in a given number.
print("The count of even digits in a given number{", numb, "} =", evn_count)
# Print "od_count" to get the count of odd digits in a given number.
print("The count of odd digits in a given number{", numb, "} =", od_count)

Output:

Enter some random number = 78342186453
The count of even digits in a given number{ 78342186453 } = 6
The count of odd digits in a given number{ 78342186453 } = 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 Count the Number of Odd and Even Digits Read More »

Program to Check Whether Sum of digits at Odd places of a Number is Divisible by K

Python Program to Check Whether Sum of digits at Odd places of a Number is Divisible by K

In the previous article, we have discussed Python Program to Find Even Digits Sum and Odd Digits Sum Divisible by 4 and 3 Respectively
The task is to check if the sum of digits at odd places of a given number is divisible by the another given input number say K.

Examples:

Example1:

Input:

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

Output:

The sum of digits at odd places of the given number{ 24689131 } is divisible by the another given number k{ 2 }

Example2:

Input:

Given Number = 12573
Given another Number (k) = 5

Output:

The sum of digits at odd places of the given number{ 12573 } is not divisible by the another given number k{ 5 }

Program to Check Whether Sum of digits at Odd places of a Number is Divisible by K in Python

Below are the ways to check if the sum of digits at odd 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 “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 iterator value is odd or not using the if conditional statement.
  • If the statement is true, then add the element of digits list at the iterator value to the “od_sum” and store it in the same variable od_sum.
  • Check if the od_sum modulus given number k is equal to 0 or not using the if conditional statement.
  • If the statement is true, then print “The sum of digits at odd places of the given number is divisible by the another given number k.
  • If the statement is false, then print “The sum of digits at odd 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 = 12573
# 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 a 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 iterator value is odd or not using
    # the if conditional statement.
    if(itr % 2 != 0):
        # If the statement is true, then add the element of digits list at iterator value to
        # the "od_sum"  and store it in the same variable od_sum.
        od_sum += digtslst[itr]
# Check if the od_sum modulus given number k is equal to 0 or not using the if conditional
# statement.
if(od_sum % gvn_k == 0):
    # If the statement is true, then print "The sum of digits at odd places of the given
    # number is divisible by the another given number k.
    print("The sum of digits at odd 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 sum of digits at odd places of the given
    # number is Not divisible by the another given number k.
    print("The sum of digits at odd places of the given number{", gvn_numb,
          "} is not divisible by the another given number k{", gvn_k, "}")

Output:

The sum of digits at odd places of the given number{ 12573 } is not 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 “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 iterator value is odd or not using the if conditional statement.
  • If the statement is true, then add the element of digits list at the iterator value to the “od_sum” and store it in the same variable od_sum.
  • Check if the od_sum modulus given number k is equal to 0 or not using the if conditional statement.
  • If the statement is true, then print “The sum of digits at odd places of the given number is divisible by the another given number k.
  • If the statement is false, then print “The sum of digits at odd 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 a 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 iterator value is odd or not using
    # the if conditional statement.
    if(itr % 2 != 0):
        # If the statement is true, then add the element of digits list at iterator value to
        # the "od_sum"  and store it in the same variable od_sum.
        od_sum += digtslst[itr]
# Check if the od_sum modulus given number k is equal to 0 or not using the if conditional
# statement.
if(od_sum % gvn_k == 0):
    # If the statement is true, then print "The sum of digits at odd places of the given
    # number is divisible by the another given number k.
    print("The sum of digits at odd 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 sum of digits at odd places of the given
    # number is Not divisible by the another given number k.
    print("The sum of digits at odd places of the given number{", gvn_numb,
          "} is not divisible by the another given number k{", gvn_k, "}")

Output:

Enter some random number = 624351
Enter some random number = 3
The sum of digits at odd places of the given number{ 624351 } is divisible by the another given number k{ 3 }

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 Sum of digits at Odd places of a Number is Divisible by K Read More »

Program to Calculate the Product of Digits of a Number at Even and Odd places

Python Program to Calculate the Product of Digits of a Number at Even and Odd places

In the previous article, we have discussed Python Program to Check Whether Product of Digits at Even places of a Number is Divisible by K
Given a number, the task is to calculate whether or not the product of its digits at even and odd places.

Examples:

Example1:

Input:

Given Number = 432172

Output:

The product of all digits at even places in a given number{ 432172 } = 56
The product of all digits at odd places in a given number { 432172 } = 6

Example2:

Input:

Given Number = 2134315

Output:

The product of all digits at even places in a given number{ 2134315 } = 90
The product of all digits at odd places in a given number { 2134315 } = 4

Program to Check if Product of Digits of a Number at Even and Odd places is Equal in Python

Below are the ways to determine whether or not the product of its digits at even and odd places is equal.

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_prodt” and initialize it with 1.
  • Take another variable say “od_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 iterator value of “digtslst” to the “evn_prodt” and store it in the same variable evn_prodt.
  • If the statement is false, then multiply the iterator value of “digtslst” to the “od_prodt” and store it in the same variable od_prodt.
  • Print “evn_prodt to get the product of all digits at even places in a given number.
  • Print “od_prodt to get the product of all digits at odd places in a given number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
numb = 432172
# 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 1.
evn_prodt = 1
# Take another variable say "od_sum" and initialize it with 1.
od_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 iterator value of "digtslst" to the "evn_prodt"
        # and store it in the same variable evn_prodt.
        evn_prodt *= digtslst[itr]
    else:
     # If the statement is false, then add the iterator value of "digtslst" to the "od_prodt"
     # and store it in the same variable od_sum.
        od_prodt *= digtslst[itr]
# Print "evn_prodt" to get the product of all digits at even places in a given number.
print(
    "The product of all digits at even places in a given number{", numb, "} =", evn_prodt)
# Print "od_prodt" to get the product of all digits at odd places in a given number.
print(
    "The product of all digits at odd places in a given number {", numb, "} =", od_prodt)

Output:

The product of all digits at even places in a given number{ 432172 } = 56
The product of all digits at odd places in a given number { 432172 } = 6

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_prodt” and initialize it with 1.
  • Take another variable say “od_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 iterator value of “digtslst” to the “evn_prodt” and store it in the same variable evn_prodt.
  • If the statement is false, then multiply the iterator value of “digtslst” to the “od_prodt” and store it in the same variable od_prodt.
  • Print “evn_prodt to get the product of all digits at even places in a given number.
  • Print “od_prodt to get the product of all digits at odd places in a given 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.
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 1.
evn_prodt = 1
# Take another variable say "od_sum" and initialize it with 1.
od_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 iterator value of "digtslst" to the "evn_prodt"
        # and store it in the same variable evn_prodt.
        evn_prodt *= digtslst[itr]
    else:
     # If the statement is false, then add the iterator value of "digtslst" to the "od_prodt"
     # and store it in the same variable od_sum.
        od_prodt *= digtslst[itr]
# Print "evn_prodt" to get the product of all digits at even places in a given number.
print(
    "The product of all digits at even places in a given number{", numb, "} =", evn_prodt)
# Print "od_prodt" to get the product of all digits at odd places in a given number.
print(
    "The product of all digits at odd places in a given number {", numb, "} =", od_prodt)

Output:

Enter some random number = 2134315
The product of all digits at even places in a given number{ 2134315 } = 90
The product of all digits at odd places in a given number { 2134315 } = 4

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 Calculate the Product of Digits of a Number at Even and Odd places Read More »