Author name: Vikram Chiluka

Python Program to Find the Position of an Element in a Matrix

In the previous article, we have discussed Python Program to Find the Maximum Element in the Matrix
Given a matrix and a number(element) the task is to find the position of the given element in the given matrix in Python.

If the element does not exist in the given matrix then print the given element doesn’t exist in the given matrix.

If there are multiple answers we print all of them.

What is a matrix:

A matrix is a rectangular sequence of numbers divided into columns and rows. A matrix element or entry is a number that appears in a matrix.

Example:

Above is the matrix which contains 5 rows and 4 columns and having elements from 1 to 20.

In this order, the dimensions of a matrix indicate the number of rows and columns.

Here as there are 5 rows and 4 columns it is called a 5*4 matrix.

Examples:

Example1:

Input:

Given Matrix :
2   9   1
11 4   5 
9   2   3
1   2   3
Given Element = 9

Output:

The given element { 9 } is present at row {1} and column {2}
The given element { 9 } is present at row {3} and column {1}

Example2:

Input:

Given Matrix :
1   2
3   4
Given Element =5

Output:

The given element doesnot exist in the given matrix.

Example3:

Input:

Given Matrix :
2   5   6
1   2   3
Given Element = 5

Output:

The given element { 5 } is present at row {1} and column {2}

Program to Find the Position of an Element in a Matrix in Python

Below are the ways to find the position of the given element in the given matrix in Python.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the matrix as static input and store it in a variable.
  • Calculate the number of rows of the given matrix by calculating the length of the nested list using the len() function and store it in a variable mtrxrows.
  • Calculate the number of columns of the given matrix by calculating the length of the first list in the nested list using the len() function and store it in a variable mtrxcolums.
  • Give the number/element as static input and store it in a variable to say gvnele.
  • Take a variable to say tempo and initialize its value to 0 (Here tempo as temp variable which says whether the element is present or not in matrix at the end).
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of rows using another Nested For loop(Inner For loop).
  • Check if the gvnmatrix[n][m] value (where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop) is equal to gvnele using the if conditional statement.
  • If it is true then print the iterator value of parent for loop+1(Here it acts as row number) and also print the inner loop iterator value+1(Here it acts as column number).
  • Set the value of tempo to 1.
  • After the end of loops check if the value of tempo is 0 or not using the if conditional statement.
  • If it is true then print the given element doesn’t exist in the given matrix.
  • The Exit of the Program.

Below is the implementation:

# Give the matrix as static input and store it in a variable.
mtrx = [[2, 9, 1], [11, 4, 5], [9, 2, 3], [1, 2, 3]]
# Calculate the number of rows of the given matrix by
# calculating the length of the nested list using the len() function
# and store it in a variable mtrxrows.
mtrxrows = len(mtrx)
# Calculate the number of columns of the given matrix by
# calculating the length of the first list in the nested list
# using the len() function and store it in a variable mtrxcols.
mtrxcols = len(mtrx[0])
# Give the number/element as static input and store it in a variable to say gvnele.
gvnele = 9
# Take a variable to say tempo and initialize its value to 0
# (Here tempo as temp variable which says whether the element is present
# or not in matrix at the end).
tempo = 0
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
    # Inside the For loop, Iterate till the given number of rows using another
    # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
        # Check if the gvnmatrix[n][m] value
        # (where n is the iterator value of the parent For loop and
        # m is the iterator value of the inner For loop)
        # is equal to gvnele using the if conditional statement.
        if(mtrx[n][m] == gvnele):
            # If it is true then print the iterator value of parent for loop+1
            # (Here it acts as row number)
            # and also print the inner loop iterator value+1
            # (Here it acts as column number).
            print('The given element {', gvnele, '} is present at row {' +
                  str(n+1)+'} and column {'+str(m+1)+'}')
            # Set the value of tempo to 1.
            tempo = 1
# After the end of loops check if the value of tempo is 0
# or not using the if conditional statement.
if(tempo == 0):
        # If it is true then print the given element doesn't exist in the given matrix.
    print('the given element doesnot exist in the given matrix.')

Output:

The given element { 9 } is present at row {1} and column {2}
The given element { 9 } is present at row {3} and column {1}

Here element 9 is present in two positions so we print two of them.

Method #2: Using For loop (User Input)

Approach:

  • Give the number of rows of the matrix as user input using the int(input()) function and store it in a variable.
  • Give the number of columns of the matrix as user input using the int(input()) function and store it in another variable.
  • Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
  • Loop till the given number of rows using the For loop
  • Inside the For loop, Give all the row elements of the given Matrix as a list using the list(),map(),int(),split() functions and store it in a variable.
  • Add the above row elements list to gvnmatrix using the append() function.
  • Take a variable to say tempo and initialize its value to 0 (Here tempo as temp variable which says whether the element is present or not in matrix at the end).
  • Give the number/element as user input using the int(input()) function and store it in a variable to say gvnele.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of rows using another Nested For loop(Inner For loop).
  • Check if the gvnmatrix[n][m] value (where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop) is equal to gvnele using the if conditional statement.
  • If it is true then print the iterator value of parent for loop+1(Here it acts as row number) and also print the inner loop iterator value+1(Here it acts as column number).
  • Set the value of tempo to 1.
  • After the end of loops check if the value of tempo is 0 or not using the if conditional statement.
  • If it is true then print the given element doesn’t exist in the given matrix.
  • The Exit of the Program.

Below is the implementation:

# Give the number of rows of the matrix as user input using the int(input()) function
# and store it in a variable.
mtrxrows = int(input('Enter some random number of rows of the matrix = '))
# Give the number of columns of the matrix as user input using the int(input()) function
# and store it in another variable.
mtrxcols = int(input('Enter some random number of columns of the matrix = '))
# Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
mtrx = []
# Loop till the given number of rows using the For loop
for n in range(mtrxrows):
    # Inside the For loop, Give all the row elements of the given Matrix as a list using
    # the list(),map(),int(),split() functions and store it in a variable.
    l = list(map(int, input(
        'Enter {'+str(mtrxcols)+'} elements of row {'+str(n+1)+'} separated by spaces = ').split()))
    # Add the above row elements list to gvnmatrix using the append() function.

    mtrx.append(l)
# Give the number/element as user input using the int(input()) function
# and store it in a variable to say gvnele.
gvnele = int(input('Enter some random element = '))
# Take a variable to say tempo and initialize its value to 0
# (Here tempo as temp variable which says whether the element is present
# or not in matrix at the end).
tempo = 0
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
    # Inside the For loop, Iterate till the given number of rows using another
    # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
        # Check if the gvnmatrix[n][m] value
        # (where n is the iterator value of the parent For loop and
        # m is the iterator value of the inner For loop)
        # is equal to gvnele using the if conditional statement.
        if(mtrx[n][m] == gvnele):
            # If it is true then print the iterator value of parent for loop+1
            # (Here it acts as row number)
            # and also print the inner loop iterator value+1
            # (Here it acts as column number).
            print('The given element {', gvnele, '} is present at row {' +
                  str(n+1)+'} and column {'+str(m+1)+'}')
            # Set the value of tempo to 1.
            tempo = 1
# After the end of loops check if the value of tempo is 0
# or not using the if conditional statement.
if(tempo == 0):
        # If it is true then print the given element doesn't exist in the given matrix.
    print('the given element doesnot exist in the given matrix.')

Output:

Enter some random number of rows of the matrix = 2
Enter some random number of columns of the matrix = 3
Enter {3} elements of row {1} separated by spaces = 2 5 6
Enter {3} elements of row {2} separated by spaces = 1 2 3
Enter some random element = 5
The given element { 5 } is present at row {1} and column {2}

Output2:(For Reference, if the element doesn’t exist in the matrix)

Enter some random number of rows of the matrix = 2
Enter some random number of columns of the matrix = 2
Enter {2} elements of row {1} separated by spaces = 1 2
Enter {2} elements of row {2} separated by spaces = 3 4
Enter some random element = 5
the given element doesnot exist in the given matrix

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 Position of an Element in a Matrix Read More »

Program to Find the Maximum Element in the Matrix

Python Program to Find the Maximum Element in the Matrix

In the previous article, we have discussed Python Program to find the Sum of Series 1^2+2^2+3^2…+N^2
Given a matrix, the task is to find the maximum element in the given Matrix in Python

What is a matrix:

A matrix is a rectangular sequence of numbers divided into columns and rows. A matrix element or entry is a number that appears in a matrix.

Example:

Above is the matrix which contains 5 rows and 4 columns and having elements from 1 to 20.

In this order, the dimensions of a matrix indicate the number of rows and columns.

Here as there are 5 rows and 4 columns it is called a 5*4 matrix.

Examples:

Example1:

Input:

Given Matrix
2   9   1
11 4   5 
9   2   3
1   2   3

Output:

The maximum element of the given matrix [[2, 9, 1], [11, 4, 5], [9, 2, 3], [1, 2, 3]] is :
11

Example2:

Input:

Given Matrix 
1   7   5
25 4   6

Output:

The maximum element of the given matrix [[1, 7, 5], [25, 4, 6]] is :
25

Program to Find the Maximum Element in the Matrix in Python

Below are the ways to find the maximum element in the given Matrix in Python

Method #1: Using For Loop (Static Input)

Approach:

  • Give the matrix as static input and store it in a variable.
  • Calculate the number of rows of the given matrix by calculating the length of the nested list using the len() function and store it in a variable mtrxrows.
  • Calculate the number of columns of the given matrix by calculating the length of the first list in the nested list using the len() function and store it in a variable mtrxcolums.
  • Take a variable mtrxmax which stores the maximum element of the given matrix and initialize its value to the first element of the given matrix.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of rows using another Nested For loop(Inner For loop).
  • Check if the gvnmatrix[n][m] value (where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop) is greater than mtrxmax using the if conditional statement.
  • If it is true then modify the mtrxmax value with gvnmatrix[n][m] value.
  • Print the mtrxmax value which is the maximum element of the given Matrix
  • The Exit of the Program.

Below is the implementation:

# Give the matrix as static input and store it in a variable.
mtrx = [[2, 9, 1], [11, 4, 5], [9, 2, 3], [1, 2, 3]]
# Calculate the number of rows of the given matrix by
# calculating the length of the nested list using the len() function
# and store it in a variable mtrxrows.
mtrxrows = len(mtrx)
# Calculate the number of columns of the given matrix by
# calculating the length of the first list in the nested list
# using the len() function and store it in a variable mtrxcols.
mtrxcols = len(mtrx[0])
# Take a variable mtrxmax which stores the maximum element of the given matrix
# and initialize its value to the first element of the given matrix.
mtrxmax = mtrx[0][0]
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
    # Inside the For loop, Iterate till the given number of rows using another
    # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
        # Check if the gvnmatrix[n][m] value (where n is the iterator value of the
        # parent For loop and m is the iterator value of the inner For loop)
        # is greater than mtrxmax using the if conditional statement.
        if(mtrx[n][m] > mtrxmax):
            # If it is true then modify the mtrxmax value with gvnmatrix[n][m] value.
            mtrxmax = mtrx[n][m]
# Print the mtrxmax value which is the maximum element of the given Matrix
print('The maximum element of the given matrix', mtrx, 'is :')
print(mtrxmax)

Output:

The maximum element of the given matrix [[2, 9, 1], [11, 4, 5], [9, 2, 3], [1, 2, 3]] is :
11

Method #2: Using For loop (User Input)

Approach:

  • Give the number of rows of the matrix as user input using the int(input()) function and store it in a variable.
  • Give the number of columns of the matrix as user input using the int(input()) function and store it in another variable.
  • Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
  • Loop till the given number of rows using the For loop
  • Inside the For loop, Give all the row elements of the given Matrix as a list using the list(),map(),int(),split() functions and store it in a variable.
  • Add the above row elements list to gvnmatrix using the append() function.
  • Take a variable mtrxmax which stores the maximum element of the given matrix and initialize its value to the first element of the given matrix.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of rows using another Nested For loop(Inner For loop).
  • Check if the gvnmatrix[n][m] value (where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop) is greater than mtrxmax using the if conditional statement.
  • If it is true then modify the mtrxmax value with gvnmatrix[n][m] value.
  • Print the mtrxmax value which is the maximum element of the given Matrix
  • The Exit of the Program.

Below is the implementation:

# Give the number of rows of the matrix as user input using the int(input()) function
# and store it in a variable.
mtrxrows = int(input('Enter some random number of rows of the matrix = '))
# Give the number of columns of the matrix as user input using the int(input()) function
# and store it in another variable.
mtrxcols = int(input('Enter some random number of columns of the matrix = '))
# Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
mtrx = []
# Loop till the given number of rows using the For loop
for n in range(mtrxrows):
    # Inside the For loop, Give all the row elements of the given Matrix as a list using
    # the list(),map(),int(),split() functions and store it in a variable.
    l = list(map(int, input(
        'Enter {'+str(mtrxcols)+'} elements of row {'+str(n+1)+'} separated by spaces = ').split()))
    # Add the above row elements list to gvnmatrix using the append() function.

    mtrx.append(l)
# Take a variable mtrxmax which stores the maximum element of the given matrix
# and initialize its value to the first element of the given matrix.
mtrxmax = mtrx[0][0]
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
    # Inside the For loop, Iterate till the given number of rows using another
    # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
        # Check if the gvnmatrix[n][m] value (where n is the iterator value of the
        # parent For loop and m is the iterator value of the inner For loop)
        # is greater than mtrxmax using the if conditional statement.
        if(mtrx[n][m] > mtrxmax):
            # If it is true then modify the mtrxmax value with gvnmatrix[n][m] value.
            mtrxmax = mtrx[n][m]
# Print the mtrxmax value which is the maximum element of the given Matrix
print('The maximum element of the given matrix', mtrx, 'is :')
print(mtrxmax)

Output:

Enter some random number of rows of the matrix = 2
Enter some random number of columns of the matrix = 3
Enter {3} elements of row {1} separated by spaces = 1 7 5
Enter {3} elements of row {2} separated by spaces = 25 4 6
The maximum element of the given matrix [[1, 7, 5], [25, 4, 6]] is :
25

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 Maximum Element in the Matrix Read More »

Program to Convert Binary to Octal using While Loop

Python Program to Convert Binary to Octal using While Loop

In the previous article, we have discussed Python Program to Convert Octal to Decimal using While Loop
Given a binary number and the task is to get the respective octal number using the while loop.

Examples:

Example1:

Input:

Given Binary Number = 1010

Output:

The Octal value of the given binary number { 1010 } is: 
12

Example2:

Input:

Given Binary Number = 1101

Output:

The Octal value of the given binary number { 1101 } is: 
15

Program to Convert Binary to Octal using While Loop in Python

Below are the ways to convert the given binary number into octal :

Method #1: Using While Loop (Static Input)

Approach:

  • Give the binary number as static input and store it in a variable.
  • Take a variable say octl_num and initialize its value with 0.
  • Take another variable say deciml_num and initialize its value with 0.
  • Again take another variable say ‘a’ and initialize its value with 0.
  • Loop till the given binary number is not equal to zero using the while loop.
  • Inside the loop, calculate the given binary number modulus 10 (to get the last digit).
  • Store it in a variable ‘b‘.
  • Calculate the value of 2 raised to the power a using the pow() function and multiply it with the above-obtained value ‘b‘.
  • Store it in a variable ‘c‘.
  • Add ‘c‘ to the above-initialized deciml_num and store it in the same variable deciml_num.
  • Increment the value a by 1 and store it in the same variable ‘a’.
  • Divide the given binary number by 10 and store it in the same variable binry_numb.
  • Come out of the while loop and initialize the value of ‘a’ with 1.
  • Loop till the decimal number is not equal to zero using the while loop.
  • Multiply  ‘a‘ with the deciml_num modulus 8 and store it in a variable ‘d’.
  • Add the value of ‘d’ with the above-initialized octl_num and store it in the same variable octl_num.
  • Divide the deciml_num by 8 and store it in the same variable deciml_num.
  • Multiply ‘a’ with 10 and store it in the same variable ‘a’.
  • Print the octl_num to get the octal value of the given binary number.
  • The Exit of the Program.

Below is the implementation:

# Give the binary number as static input and store it in a variable.
binry_numb = 1010
# Take a variable say octl_num and initialize its value with 0.
octl_num = 0
# Take another variable say deciml_num and initialize its value with 0.
deciml_num = 0
# Again take another variable say 'a' and initialize its value with 0.
a = 0
# Loop till the given binary number is not equal to zero using the while loop.
print("The Octal value of the given binary number {", binry_numb, "} is: ")
while (binry_numb != 0):
 # Inside the loop, calculate the given binary number modulus 10 (to get the last digit).
 # store it in a variable 'b'.
    b = (binry_numb % 10)
    # Calculate the value of 2 raised to the power a using the pow() function and multiply
# it with the above-obtained value 'b'.
 # Store it in a variable 'c'.
    c = pow(2, a)*b
 # Add 'c' to the above-initialized deciml_num and store it in the same variable deciml_num.
    deciml_num = deciml_num + c
    # Increment the value a by 1 and store it in the same variable 'a'.
    a += 1
 # Divide the given binary number by 10 and store it in the same variable binry_numb.
    binry_numb = binry_numb // 10
 # Come out of the while loop and initialize the value of 'a' with 1.
a = 1
# Loop till the decimal number is not equal to zero using the while loop.
while (deciml_num != 0):
    # Multiply 'a' with the deciml_num modulus 8 and store it in a variable 'd'.
    d = (deciml_num % 8) * a
 # Add the value of 'd' with the above-initialized octl_num and store it in the same
    # variable octl_num.
    octl_num = octl_num + d
    # Divide the deciml_num by 8 and store it in the same variable deciml_num.
    deciml_num = deciml_num // 8
    # Multiply 'a' with 10 and store it in the same variable 'a'.
    a = a * 10
# Print the octl_num to get the octal value of the given binary number.
print(octl_num)

Output:

The Octal value of the given binary number { 1010 } is: 
12

Method #2: Using While loop (User Input)

Approach:

  • Give the binary number as user input using the int(input()) function and store it in a variable.
  • Take a variable say octl_num and initialize its value with 0.
  • Take another variable say deciml_num and initialize its value with 0.
  • Again take another variable say ‘a’ and initialize its value with 0.
  • Loop till the given binary number is not equal to zero using the while loop.
  • Inside the loop, calculate the given binary number modulus 10 (to get the last digit).
  • Store it in a variable ‘b‘.
  • Calculate the value of 2 raised to the power a using the pow() function and multiply it with the above-obtained value ‘b‘.
  • Store it in a variable ‘c‘.
  • Add ‘c‘ to the above-initialized deciml_num and store it in the same variable deciml_num.
  • Increment the value a by 1 and store it in the same variable ‘a’.
  • Divide the given binary number by 10 and store it in the same variable binry_numb.
  • Come out of the while loop and initialize the value of ‘a’ with 1.
  • Loop till the decimal number is not equal to zero using the while loop.
  • Multiply  ‘a‘ with the deciml_num modulus 8 and store it in a variable ‘d’.
  • Add the value of ‘d’ with the above-initialized octl_num and store it in the same variable octl_num.
  • Divide the deciml_num by 8 and store it in the same variable deciml_num.
  • Multiply ‘a’ with 10 and store it in the same variable ‘a’.
  • Print the octl_num to get the octal value of the given binary number.
  • The Exit of the Program.

Below is the implementation:

# Give the binary number as user input using the int(input()) function and store it
# in a variable.
binry_numb = int(input("Enter some random Number = "))
# Take a variable say octl_num and initialize its value with 0.
octl_num = 0
# Take another variable say deciml_num and initialize its value with 0.
deciml_num = 0
# Again take another variable say 'a' and initialize its value with 0.
a = 0
# Loop till the given binary number is not equal to zero using the while loop.
print("The Octal value of the given binary number {", binry_numb, "} is: ")
while (binry_numb != 0):
 # Inside the loop, calculate the given binary number modulus 10 (to get the last digit).
 # store it in a variable 'b'.
    b = (binry_numb % 10)
    # Calculate the value of 2 raised to the power a using the pow() function and multiply
# it with the above-obtained value 'b'.
 # Store it in a variable 'c'.
    c = pow(2, a)*b
 # Add 'c' to the above-initialized deciml_num and store it in the same variable deciml_num.
    deciml_num = deciml_num + c
    # Increment the value a by 1 and store it in the same variable 'a'.
    a += 1
 # Divide the given binary number by 10 and store it in the same variable binry_numb.
    binry_numb = binry_numb // 10
 # Come out of the while loop and initialize the value of 'a' with 1.
a = 1
# Loop till the decimal number is not equal to zero using the while loop.
while (deciml_num != 0):
    # Multiply 'a' with the deciml_num modulus 8 and store it in a variable 'd'.
    d = (deciml_num % 8) * a
 # Add the value of 'd' with the above-initialized octl_num and store it in the same
    # variable octl_num.
    octl_num = octl_num + d
    # Divide the deciml_num by 8 and store it in the same variable deciml_num.
    deciml_num = deciml_num // 8
    # Multiply 'a' with 10 and store it in the same variable 'a'.
    a = a * 10
# Print the octl_num to get the octal value of the given binary number.
print(octl_num)

Output:

Enter some random Number = 1101
The Octal value of the given binary number { 1101 } is: 
15

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 Convert Binary to Octal using While Loop Read More »

Program to Convert Octal to Decimal using While Loop

Python Program to Convert Octal to Decimal using While Loop

In the previous article, we have discussed Python Program to Convert Binary to Decimal using While Loop
Given an octal number and the task is to get the respective decimal number using the while loop in Python.

Examples:

Example1:

Input:

Given Octal Number = 15

Output:

The Decimal value of the given Octal number { 15 } is: 
13

Example2:

Input:

Given Octal Number = 32

Output:

The Decimal value of the given Octal number { 32 } is: 
26

Program to Convert Octal to Decimal in Python

Below are the ways to convert the given octal number into decimal :

Method #1: Using While Loop (Static Input)

Approach:

  • Give the octal number as static input and store it in a variable.
  • Take a variable say ‘a ‘and initialize its value with 0.
  • Take another variable say deciml_numb and initialize its value with 0.
  • Loop till the given octal number is not equal to zero using the while loop.
  • Inside the loop, calculate the value of the given octal number modulus 10 (to get the last digit) and store it in a variable say ‘b’.
  • Calculate the value of 8 raised to the power ‘a’ using the pow() function and multiply it with the above-obtained ‘b’.
  • Store it in another variable ‘c’.
  • Add the above variable ‘c’ with the deciml_numb and store it in the same variable deciml_numb.
  • Increment the value a by 1 and store it in the same variable ‘a’.
  • Divide the given octal number by 10 (to remove the last digit) and store it in the same variable gvn_octl_numb.
  • Print the deciml_numb to get the decimal value of the given octal number.
  • The Exit of the Program.

Below is the implementation:

# Give the octal number as static input and store it in a variable.
gvn_octl_numb = 15
# Take a variable say 'a 'and initialize its value with 0.
a = 0
# Take another variable say deciml_numb and initialize its value with 0.
deciml_numb = 0
# Loop till the given octal number is not equal to zero using the while loop.
print("The Decimal value of the given Octal number {", gvn_octl_numb, "} is: ")
while(gvn_octl_numb != 0):
  # Inside the loop, calculate the value of the given octal number modulus 10
  # (to get the last digit) and store it in a variable say 'b'.
    b = (gvn_octl_numb % 10)
# Calculate the value of 8 raised to the power 'a' using the pow() function and multiply
# it with the above-obtained 'b'.
# Store it in another variable 'c'.
    c = b*pow(8, a)
  # Add the above variable 'c' with the deciml_numb and store it in the same variable
  # deciml_numb.
    deciml_numb = deciml_numb+c
  # Increment the value a by 1 and store it in the same variable 'a'.
    a += 1
# Divide the given octal number by 10 (to remove the last digit) and store it in the
# same variable gvn_octl_numb.
    gvn_octl_numb = gvn_octl_numb // 10
# Print the deciml_num to get the decimal value of the given Octal number.
print(deciml_numb)

Output:

The Decimal value of the given Octal number { 15 } is: 
13

Method #2: Using While loop (User Input)

Approach:

  • Give the octal number as user input using the int(input()) function and store it in a variable.
  • Take a variable say ‘a ‘and initialize its value with 0.
  • Take another variable say deciml_numb and initialize its value with 0.
  • Loop till the given octal number is not equal to zero using the while loop.
  • Inside the loop, calculate the value of the given octal number modulus 10 (to get the last digit) and store it in a variable say ‘b’.
  • Calculate the value of 8 raised to the power ‘a’ using the pow() function and multiply it with the above-obtained ‘b’.
  • Store it in another variable ‘c’.
  • Add the above variable ‘c’ with the deciml_numb and store it in the same variable deciml_numb.
  • Increment the value a by 1 and store it in the same variable ‘a’.
  • Divide the given octal number by 10 (to remove the last digit) and store it in the same variable gvn_octl_numb.
  • Print the deciml_numb to get the decimal value of the given octal number.
  • The Exit of the Program.

Below is the implementation:

# Give the octal number as user input using the int(input()) function and
# store it in a variable.
gvn_octl_numb = int(input("Enter some Random Number = "))
# Take a variable say 'a 'and initialize its value with 0.
a = 0
# Take another variable say deciml_numb and initialize its value with 0.
deciml_numb = 0
# Loop till the given octal number is not equal to zero using the while loop.
print("The Decimal value of the given Octal number {", gvn_octl_numb, "} is: ")
while(gvn_octl_numb != 0):
  # Inside the loop, calculate the value of the given octal number modulus 10
  # (to get the last digit) and store it in a variable say 'b'.
    b = (gvn_octl_numb % 10)
# Calculate the value of 8 raised to the power 'a' using the pow() function and multiply
# it with the above-obtained 'b'.
# Store it in another variable 'c'.
    c = b*pow(8, a)
  # Add the above variable 'c' with the deciml_numb and store it in the same variable
  # deciml_numb.
    deciml_numb = deciml_numb+c
  # Increment the value a by 1 and store it in the same variable 'a'.
    a += 1
# Divide the given octal number by 10 (to remove the last digit) and store it in the
# same variable gvn_octl_numb.
    gvn_octl_numb = gvn_octl_numb // 10
# Print the deciml_num to get the decimal value of the given Octal number.
print(deciml_numb)

Output:

Enter some Random Number = 32
The Decimal value of the given Octal number { 32 } is: 
26

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 Convert Octal to Decimal using While Loop Read More »

Program to Convert Binary to Decimal using While Loop

Python Program to Convert Binary to Decimal using While Loop

In the previous article, we have discussed Python Program to Convert a Decimal Number to Binary
Given a binary number and the task is to get the respective decimal number using the while loop.

Examples:

Example1:

Input:

Given Binary Number = 1000

Output:

The Decimal value of the given binary number { 1000 } is: 
8

Example2:

Input:

Given Binary Number = 1100

Output:

The Decimal value of the given binary number { 1100 } is: 
12

Program to Convert Binary to Decimal using While Loop in Python

Below are the ways to convert the given binary number into decimal :

Method #1: Using While Loop (Static Input)

Approach:

  • Give the binary number as static input and store it in a variable.
  • Take a variable say ‘a ‘and initialize its value with 0.
  • Take another variable say deciml_num and initialize its value with 0.
  • Loop till the given number is not equal to zero using the while loop.
  • Inside the loop, calculate the value of the given binary number modulus 10 (to get the last digit) and store it in a variable say rem.
  • Calculate the value of the given binary number divided by 10.
  • Store it in the same variable gvn_binry_num.
  • Multiply rem with the 2 power a using the pow() function and store it in another variable say  ‘b’.
  • Add b with the above deciml_num and store it in the same variable deciml_num.
  • Increment the value a by 1 and store it in the same variable ‘a’.
  • Print the deciml_num to get the decimal value of the given binary number.
  • The Exit of the Program.

Below is the implementation:

# Give the binary number as static input and store it in a variable.
gvn_binry_num = 1000
# Take a variable say 'a 'and initialize its value with 0.
a = 0
# Take another variable say deciml_num and initialize its value with 0.
deciml_num = 0
print(
    "The Decimal value of the given binary number {", gvn_binry_num, "} is: ")
# Loop till the given number is not equal to zero using the while loop.
while (gvn_binry_num != 0):
    # Inside the loop, calculate the value of the given binary number modulus 10
    # (to get the last digit) and store it in a variable say rem.
    rem = gvn_binry_num % 10
    # Calculate the value of the given binary number divided by 10.
# Store it in the same variable gvn_binry_num.
    gvn_binry_num = gvn_binry_num // 10
    # Multiply rem with the 2 power a using the pow() function and store it in
# another variable say  'b'.
    b = rem*pow(2, a)
    # Add b with the above deciml_num and store it in the same variable deciml_num.
    deciml_num = deciml_num + b
   # Increment the value a by 1 and store it in the same variable 'a'.
    a = a+1
# Print the deciml_num to get the decimal value of the given binary number.
print(deciml_num)

Output:

The Decimal value of the given binary number { 1000 } is: 
8

Method #2: Using While loop (User Input)

Approach:

  • Give the binary number as user input using the int(input()) function and store it in a variable.
  • Take a variable say ‘a ‘and initialize its value with 0.
  • Take another variable say deciml_num and initialize its value with 0.
  • Loop till the given number is not equal to zero using the while loop.
  • Inside the loop, calculate the value of the given binary number modulus 10 (to get the last digit) and store it in a variable say rem.
  • Calculate the value of the given binary number divided by 10.
  • Store it in the same variable gvn_binry_num.
  • Multiply rem with the 2 power a using the pow() function and store it in another variable say  ‘b’.
  • Add b with the above deciml_num and store it in the same variable deciml_num.
  • Increment the value a by 1 and store it in the same variable ‘a’.
  • Print the deciml_num to get the decimal value of the given binary number.
  • The Exit of the Program.

Below is the implementation of the above given approach:

# Give the binary number as user input using the int(input()) function and
# store it in a variable.
gvn_binry_num = int(input("Enter some Random Number = "))
# Take a variable say 'a 'and initialize its value with 0.
a = 0
# Take another variable say deciml_num and initialize its value with 0.
deciml_num = 0
print(
    "The Decimal value of the given binary number {", gvn_binry_num, "} is: ")
# Loop till the given number is not equal to zero using the while loop.
while (gvn_binry_num != 0):
    # Inside the loop, calculate the value of the given binary number modulus 10
    # (to get the last digit) and store it in a variable say rem.
    rem = gvn_binry_num % 10
    # Calculate the value of the given binary number divided by 10.
# Store it in the same variable gvn_binry_num.
    gvn_binry_num = gvn_binry_num // 10
    # Multiply rem with the 2 power a using the pow() function and store it in
# another variable say  'b'.
    b = rem*pow(2, a)
    # Add b with the above deciml_num and store it in the same variable deciml_num.
    deciml_num = deciml_num + b
   # Increment the value a by 1 and store it in the same variable 'a'.
    a = a+1
# Print the deciml_num to get the decimal value of the given binary number.
print(deciml_num)

Output:

Enter some Random Number = 011
The Decimal value of the given binary number { 11 } is: 
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 Convert Binary to Decimal using While Loop Read More »

Program to Convert a Decimal Number to Binary

Python Program to Convert a Decimal Number to Binary

In the previous article, we have discussed Python Program to Convert Decimal to Octal using While loop
Given a decimal number and the task is to get the respective binary number for a given number.

Examples:

Example1:

Input:

Given Number = 7

Output:

The Binary value of the given decimal number { 7 } is: 
111

Example2:

Input:

Given Number = 9

Output:

The Binary value of the given decimal number { 9 } is: 
1001

Program to Convert a Decimal Number to Binary in Python

Below are the ways to convert the given decimal number into Binary :

Method #1: Using While Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Take a variable say ‘a ‘and initialize its value with 1.
  • Take another variable say binry_num and initialize its value with 0.
  • Loop till the given number is not equal to zero using the while loop.
  • Inside the loop, calculate the value of the given number modulus 2 and store it in a variable remdr.
  • Divide the given number by 2 and store it in the same variable gvn_numb.
  • Multiply a with the remdr and store it in another variable b
  • Add b to the binry_num and convert to int using the int() function.
  • Store it in the same variable binry_num.
  • Multiply a with 10 and Store it in the same variable ‘a’.
  • Print the binry_num to get the binary value of the given decimal number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb = 7
# Take a variable say 'a 'and initialize its value with 1.
a = 1
# Take another variable say binry_num and initialize its value with 0.
binry_num = 0
print("The Binary value of the given decimal number {", gvn_numb, "} is: ")
# Loop till the given number is not equal to zero using the while loop.
while (gvn_numb != 0):
  # Inside the loop, calculate the value of the given number modulus 2 and
    # store it in a variable remdr.
    remdr = gvn_numb % 2
  # Divide the given number by 2 and store it in the same variable gvn_numb.
    gvn_numb = gvn_numb // 2
    # Multiply a with the remdr and store it in another variable b
    b = (remdr * a)
    # Add b to the binry_num and convert to int using the int() function.
    # Store it in the same variable binry_num.
    binry_num = int(binry_num + b)
    # Multiply a with 10 and Store it in the same variable 'a'.
    a = int(a * 10)
 # Print the binry_num to get the binary value of the given decimal number.
print(binry_num)

Output:

The Binary value of the given decimal number { 7 } is: 
111

Method #2: Using While 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 ‘a ‘and initialize its value with 1.
  • Take another variable say binry_num and initialize its value with 0.
  • Loop till the given number is not equal to zero using the while loop.
  • Inside the loop, calculate the value of the given number modulus 2 and store it in a variable remdr.
  • Divide the given number by 2 and store it in the same variable gvn_numb.
  • Multiply a with the remdr and store it in another variable b
  • Add b to the binry_num and convert to int using the int() function.
  • Store it in the same variable binry_num.
  • Multiply a with 10 and Store it in the same variable ‘a’.
  • Print the binry_num to get the binary value of the given decimal 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 'a 'and initialize its value with 1.
a = 1
# Take another variable say binry_num and initialize its value with 0.
binry_num = 0
print("The Binary value of the given decimal number {", gvn_numb, "} is: ")
# Loop till the given number is not equal to zero using the while loop.
while (gvn_numb != 0):
  # Inside the loop, calculate the value of the given number modulus 2 and
    # store it in a variable remdr.
    remdr = gvn_numb % 2
  # Divide the given number by 2 and store it in the same variable gvn_numb.
    gvn_numb = gvn_numb // 2
    # Multiply a with the remdr and store it in another variable b
    b = (remdr * a)
    # Add b to the binry_num and convert to int using the int() function.
    # Store it in the same variable binry_num.
    binry_num = int(binry_num + b)
    # Multiply a with 10 and Store it in the same variable 'a'.
    a = int(a * 10)
 # Print the binry_num to get the binary value of the given decimal number.
print(binry_num)

Output:

Enter some random Number = 9
The Binary value of the given decimal number { 9 } is: 
1001

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 Convert a Decimal Number to Binary Read More »

Program to Convert Decimal to Octal using While loop

Python Program to Convert Decimal to Octal using While loop

In the previous article, we have discussed Python Program to Find out How many 1 and 0 in a Given Number.
Given a decimal number and the task is to get the respective octal number using the while loop in Python.

Examples:

Example1:

Input:

Given Number = 15

Output:

The Octal value of the given decimal number { 15 } is: 
17

Example2:

Input:

Given Number = 25

Output:

The Octal value of the given decimal number { 25 } is: 
31

Program to Convert Decimal to Octal using While loop in Python

Below are the ways to convert the given decimal number into octal :

Method #1: Using While Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Take a variable say ‘a ‘and initialize its value with 1.
  • Take another variable say octl_num and initialize its value with 0.
  • Loop till the given number is not equal to zero using the while loop.
  • Multiply ‘a’ with the given number modulus 8 and store it in a variable say ‘b‘.
  • Add the above-got b to the octl_num and store it in the same variable octl_num.
  • Calculate the value of the given number divided by 8.
  • Store it in the same variable gvn_numb.
  • Multiply a with 10 and Store it in the same variable ‘a’.
  • Print the octl_num to get the octal value of the given decimal number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb = 15
# Take a variable say 'a 'and initialize its value with 1.
a = 1
print(
    "The Octal value of the given decimal number {", gvn_numb, "} is: ")
# Take another variable say octl_num and initialize its value with 0.
octl_num = 0
# Loop till the given number not equals to zero using the while loop.
while(gvn_numb != 0):
  # Multiply 'a' with the given number modulus 8 and store it in a variable say 'b'.
    b = (gvn_numb % 8)*a
  # Add the above-got b to the octl_num and store it in the same variable octl_num.
    octl_num = octl_num+b
 # Calculate the value of the given number divided by 8.
 # Store it in the same variable gvn_numb.
    gvn_numb = gvn_numb//8
   # Multiply a with 10 and Store it in the same variable 'a'.
    a = int(a*10)
 # Print the octl_num to get the octal value of the given decimal number.
print(octl_num)

Output:

The Octal value of the given decimal number { 15 } is: 
17

Method #2: Using While 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 ‘a ‘and initialize its value with 1.
  • Take another variable say octl_num and initialize its value with 0.
  • Loop till the given number is not equal to zero using the while loop.
  • Multiply ‘a’ with the given number modulus 8 and store it in a variable say ‘b‘.
  • Add the above-got b to the octl_num and store it in the same variable octl_num.
  • Calculate the value of the given number divided by 8.
  • Store it in the same variable gvn_numb.
  • Multiply a with 10 and Store it in the same variable ‘a’.
  • Print the octl_num to get the octal value of the given decimal 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 'a 'and initialize its value with 1.
a = 1
print(
    "The Octal value of the given decimal number {", gvn_numb, "} is: ")
# Take another variable say octl_num and initialize its value with 0.
octl_num = 0
# Loop till the given number not equals to zero using the while loop.
while(gvn_numb != 0):
  # Multiply 'a' with the given number modulus 8 and store it in a variable say 'b'.
    b = (gvn_numb % 8)*a
  # Add the above-got b to the octl_num and store it in the same variable octl_num.
    octl_num = octl_num+b
 # Calculate the value of the given number divided by 8.
 # Store it in the same variable gvn_numb.
    gvn_numb = gvn_numb//8
   # Multiply a with 10 and Store it in the same variable 'a'.
    a = int(a*10)
 # Print the octl_num to get the octal value of the given decimal number.
print(octl_num)

Output:

Enter some random number = 25
The Octal value of the given decimal number { 25 } is: 
31

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 Convert Decimal to Octal using While loop Read More »

Program to Find out How many 1 and 0 in a Given Number

Python Program to Find out How many 1 and 0 in a Given Number

In the previous article, we have discussed Python Program to Enter Basic Salary and Calculate Gross Salary of an Employee
Given a Number and the task is to calculate the count of 1’s and 0’s in a given Number in Python.

Examples:

Example1:

Input:

Given Number = 111000101

Output:

The Count of 0's in a given number =  4
The Count of 1's in a given number =  5

Example2:

Input:

Given Number = 1010101110000

Output:

The Count of 0's in a given number =  7
The Count of 1's in a given number =  6

Program to Find out How many 1 and 0 in a Given Number In Python

Below are the ways to calculate the count of 1’s and 0’s in a given Number:

Method #1: Using While Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Take a variable say ones_cnt and initialize its value with 0.
  • Take another variable say zeros_cnt and initialize its value with 0.
  • Loop till the given number becomes zero using the while loop.
  • Calculate the value of the given number modulus 10 (which gives the last digit of the given Number).
  • Store it in another variable.
  • Calculate the value of the given number divided by 10 (which removes the last digit of the given number).
  • Store it in the same variable gvn_number.
  • Check if the above-obtained value of the given number modulus 10 is equal to 1 using the if conditional statement.
  • If the statement is true, then increment the value of ones_cnt by 1 and store it in the same variable.
  • Check if the above-obtained value of the given number modulus 10 is equal to 0 using the if conditional statement.
  • If the statement is true, then increment the value of zeros_cnt by 1 and store it in the same variable.
  • Print the values of zeros_cnt, ones_cnt to get the count of 1’s and 0’s 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.
gvn_num = 111000101
# Take a variable say ones_cnt and initialize its value with 0.
ones_cnt = 0
# Take another variable say zeros_cnt and initialize its value with 0.
zeros_cnt = 0
# Loop till the given number becomes zero using the while loop.
while gvn_num:
    # Calculate the value of the given number modulus 10 (which gives the last digit of the given Number).
    # Store it in another variable.
    remindr = gvn_num % 10
# Calculate the value of the given number divided by 10 (which removes the last digit of the given number).
# Store it in the same variable gvn_number.
    gvn_num = int(gvn_num/10)
# Check if the above-obtained value of the given number modulus 10 is equal to 1
# using the if conditional statement.
    if remindr == 1:
         # If the statement is true, then increment the value of ones_cnt by 1 and
        # store it in the same variable.
        ones_cnt = ones_cnt+1
# Check if the above-obtained value of the given number modulus 10 is equal to 0
# using the if conditional statement.
    if remindr == 0:
     # If the statement is true, then increment the value of zeros_cnt by 1 and store it in
        # the same variable.
        zeros_cnt = zeros_cnt+1
 # Print the values of zeros_cnt ,ones_cnt to get the count of 1's and 0's in
# a given Number.
print("The Count of 0's in a given number = ", zeros_cnt)
print("The Count of 1's in a given number = ", ones_cnt)

Output:

The Count of 0's in a given number =  4
The Count of 1's in a given number =  5

Method #2: Using While 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 ones_cnt and initialize its value with 0.
  • Take another variable say zeros_cnt and initialize its value with 0.
  • Loop till the given number becomes zero using the while loop.
  • Calculate the value of the given number modulus 10 (which gives the last digit of the given Number).
  • Store it in another variable.
  • Calculate the value of the given number divided by 10 (which removes the last digit of the given number).
  • Store it in the same variable gvn_number.
  • Check if the above-obtained value of the given number modulus 10 is equal to 1 using the if conditional statement.
  • If the statement is true, then increment the value of ones_cnt by 1 and store it in the same variable.
  • Check if the above-obtained value of the given number modulus 10 is equal to 0 using the if conditional statement.
  • If the statement is true, then increment the value of zeros_cnt by 1 and store it in the same variable.
  • Print the values of zeros_cnt, ones_cnt to get the count of 1’s and 0’s 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.
gvn_num = int(input("Enter some random Number = "))
# Take a variable say ones_cnt and initialize its value with 0.
ones_cnt = 0
# Take another variable say zeros_cnt and initialize its value with 0.
zeros_cnt = 0
# Loop till the given number becomes zero using the while loop.
while gvn_num:
    # Calculate the value of the given number modulus 10 (which gives the last digit of the given Number).
    # Store it in another variable.
    remindr = gvn_num % 10
# Calculate the value of the given number divided by 10 (which removes the last digit of the given number).
# Store it in the same variable gvn_number.
    gvn_num = int(gvn_num/10)
# Check if the above-obtained value of the given number modulus 10 is equal to 1
# using the if conditional statement.
    if remindr == 1:
         # If the statement is true, then increment the value of ones_cnt by 1 and
        # store it in the same variable.
        ones_cnt = ones_cnt+1
# Check if the above-obtained value of the given number modulus 10 is equal to 0
# using the if conditional statement.
    if remindr == 0:
     # If the statement is true, then increment the value of zeros_cnt by 1 and store it in
        # the same variable.
        zeros_cnt = zeros_cnt+1
 # Print the values of zeros_cnt ,ones_cnt to get the count of 1's and 0's in
# a given Number.
print("The Count of 0's in a given number = ", zeros_cnt)
print("The Count of 1's in a given number = ", ones_cnt)

Output:

Enter some random Number = 1001101
The Count of 0's in a given number = 3
The Count of 1's in a given number = 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 Find out How many 1 and 0 in a Given Number Read More »

Program to Check Duck Number

Python Program to Check Duck Number

In the previous article, we have discussed Python Program to Convert Decimal Number to Binary String using Recursion
Duck Number:

A Duck number is one that has a zero in between or at the end of a given number.

For Example:

Let Number = 2300

It is a Duck number because it has zeros to the end.

Number= 00054

It is not a Duck number because it has zeros at the beginning. The actual value of a number is 54 if those zeros are removed.

Given a number and the task is to check if the given number is a Duck Number or not.

lstrip() Method in Python:

The lstrip() method returns a string copy with the leading characters removed (based on the string argument passed).

Based on the argument, lstrip() removes characters from the left (a string specifying the set of characters to be removed).

Examples:

Example1:

Input:

Given Number = 320045

Output:

The above given number { 320045 } is a Duck number

Example2:

Input:

Given Number = 1400

Output:

The above given number { 1400 } is a Duck number

Program to Check Duck Number in Python

Below are the ways to check if the given number is a Duck Number or not:

Method #1: Using lstrip() Method (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.
  • Apply the lstrip() method with the argument passed as 0 on the above string number and store it in another variable.
  • Check if 0 is present in the above lstrip number using the if conditional statement.
  • If the statement is true, then print “The given number is a Duck Number”.
  • If the statement is false, print “The given number is Not a Duck Number”.
  • The Exit of the program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb = 320045
# Convert the given number to a string using the str() function and
# store it in another variable.
str_numb = str(gvn_numb)
# Apply the lstrip() method with the argument passed as 0 on the above string number
# and store it in another variable.
lstrip_num = str_numb.lstrip("0")
# Check if 0 is present in the above lstrip number using the if conditional statement.
if("0" in lstrip_num):
  # If the statement is true, then print "The given number is a Duck Number".
    print("The above given number {", gvn_numb, "} is a Duck number")
else:
  # If the statement is false, print "The given number is Not a Duck Number".
    print("The above given number {", gvn_numb, "} is Not a Duck number")

Output:

The above given number { 320045 } is a Duck number

Method #2: Using lstrip() Method (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.
  • Apply the lstrip() method with the argument passed as 0 on the above string number and store it in another variable.
  • Check if 0 is present in the above lstrip number using the if conditional statement.
  • If the statement is true, then print “The given number is a Duck Number”.
  • If the statement is false, print “The given number is Not a Duck 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 = "))
# Convert the given number to a string using the str() function and
# store it in another variable.
str_numb = str(gvn_numb)
# Apply the lstrip() method with the argument passed as 0 on the above string number
# and store it in another variable.
lstrip_num = str_numb.lstrip("0")
# Check if 0 is present in the above lstrip number using the if conditional statement.
if("0" in lstrip_num):
  # If the statement is true, then print "The given number is a Duck Number".
    print("The above given number {", gvn_numb, "} is a Duck number")
else:
  # If the statement is false, print "The given number is Not a Duck Number".
    print("The above given number {", gvn_numb, "} is Not a Duck number")

Output:

Enter some random Number = 000897
The above given number { 897 } is Not a Duck 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 Duck Number Read More »

Program to Convert Decimal Number to Binary String using Recursion

Python Program to Convert Decimal Number to Binary String using Recursion

In the previous article, we have discussed Python Program to Convert Binary to Decimal using Recursion
Recursion:

Recursion is the process by which a function calls itself directly or indirectly, and the associated function is known as a recursive function. Certain issues can be addressed fairly easily using a recursive approach. Towers of Hanoi (TOH), Inorder /Preorder/Postorder Tree Traversals, DFS of Graph, and other analogous issues are examples.

Binary Code:

As previously stated, Binary Code is a Base-2 representation of a number. In Binary, all numbers are represented by simply two symbols: 0 and 1. Binary (also known as base-2) is a numerical system with only two digits: 0 and 1.

Given a binary string, the task is to convert the given decimal number to a binary string using recursion in Python.

Examples:

Example1:

Input:

Given binary number = 153

Output:

The decimal Equivalent of the given binary number { 153 } is : 10011001

Example2:

Input:

Given binary number = 408

Output:

The decimal Equivalent of the given binary number { 408 } is : 110011000

Program to Convert Decimal Number to Binary String using Recursion in Python

Below are the ways to convert the given decimal number to a binary string using recursion in Python:

Method #1: Using Recursion (Static Input)

Approach:

  • Give the decimal number as static input and store it in a variable.
  • Create a recursive function to say deciToBinary() which accepts the decimal number as an argument and returns the binary equivalent of the given decimal number.
  • Inside the deciToBinary() function, Check if the decimal number is equal to 0 using the if conditional statement.
  • If it is true then return 0.
  • Else return (n% 2 + 10* deciToBinary(n // 2)) {Recursive logic}
  • Inside the main function pass the given decimal number as an argument to deciToBinary() which returns the
  • binary equivalent of the given decimal number.
  • Print the binary equivalent of the given decimal number.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say deciToBinary() which accepts
# the decimal number as an argument and returns the binary equivalent
# of the given decimal number.


def deciToBinary(decinumb):
    # Inside the deciToBinary() function,
    # Check if the decimal number is equal to 0 using the if conditional statement.
    if(decinumb == 0):
        # If it is true then return 0.
        return 0
    # Else return (n% 2 + 10* deciToBinary(n // 2)) {Recursive logic}
    return (decinumb % 2 + 10 * deciToBinary(decinumb // 2))


# Give the decimal number as static input and store it in a variable.
gvndecimalnumb = 153
# Inside the main function pass the given decimal number as an argument
# to deciToBinary() which returns the
# binary equivalent of the given decimal number.
resbinarynumbr = deciToBinary(gvndecimalnumb)
# Print the decimal equivalent of the given binary number.
print(
    'The decimal Equivalent of the given binary number {', gvndecimalnumb, '} is :', resbinarynumbr)

Output:

The decimal Equivalent of the given binary number { 153 } is : 10011001

Method #2: Using Recursion (User Input)

Approach:

  • Give the binary number as user input using the int(input()) function and store it in a variable.
  • Create a recursive function to say deciToBinary() which accepts the decimal number as an argument and returns the binary equivalent of the given decimal number.
  • Inside the deciToBinary() function, Check if the decimal number is equal to 0 using the if conditional statement.
  • If it is true then return 0.
  • Else return (n% 2 + 10* deciToBinary(n // 2)) {Recursive logic}
  • Inside the main function pass the given decimal number as an argument to deciToBinary() which returns the binary equivalent of the given decimal number.
  • Print the binary equivalent of the given decimal number.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say deciToBinary() which accepts
# the decimal number as an argument and returns the binary equivalent
# of the given decimal number.


def deciToBinary(decinumb):
    # Inside the deciToBinary() function,
    # Check if the decimal number is equal to 0 using the if conditional statement.
    if(decinumb == 0):
        # If it is true then return 0.
        return 0
    # Else return (n% 2 + 10* deciToBinary(n // 2)) {Recursive logic}
    return (decinumb % 2 + 10 * deciToBinary(decinumb // 2))


# Give the binary number as user input using the int(input()) function and store it in a variable.
gvndecimalnumb = int(input('Enter some random decimal number = '))
# Inside the main function pass the given decimal number as an argument
# to deciToBinary() which returns the
# binary equivalent of the given decimal number.
resbinarynumbr = deciToBinary(gvndecimalnumb)
# Print the decimal equivalent of the given binary number.
print(
    'The decimal Equivalent of the given binary number {', gvndecimalnumb, '} is :', resbinarynumbr)

Output:

Enter some random decimal number = 408
The decimal Equivalent of the given binary number { 408 } is : 110011000

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 Convert Decimal Number to Binary String using Recursion Read More »