Author name: Vikram Chiluka

Program to Clear the Rightmost Set Bit of a Number in C++ and Python

Program to Clear the Rightmost Set Bit of a Number in C++ and Python

In the previous article, we have discussed about C++ Program to Check if it is Sparse Matrix or Not. Let us learn Program to Clear the Rightmost Set Bit of a Number in C++ Program and Python.

Binary Representation of a Number:

Binary is a base-2 number system in which a number is represented by two states: 0 and 1. We can also refer to it as a true and false state. A binary number is constructed in the same way that a decimal number is constructed.

Examples:

Examples1:

Input:

given number=19

Output:

The given number before removing right most set bit : 
19
The given number after removing right most set bit : 
18

Examples2:

Input:

given number =18

Output:

The given number before removing right most set bit : 
18
The given number after removing right most set bit : 
16

Examples3:

Input:

given number=512

Output:

The given number before removing right most set bit : 
512
The given number after removing right most set bit : 
0

Program to Clear the Rightmost Set Bit of a Number in C++ and Python

There are several ways to clear the rightmost set Bit of a Number in C++ and Python some of them are:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

Method #1: Using Bitwise Operators in C++

Approach:

  • There is a function called clear rightmost set bit that is defined.
  • It accepts n as an argument and returns n with its rightmost set bit cleared.
  • This is accomplished by computing n & (n – 1) and returning the result.
  • (n – 1) equals n when all the rightmost successive 0s are flipped and the initial rightmost 1 is flipped.
  • As a result, n & (n – 1) equals n with the rightmost 1 cleared.

Below is the implementation of above approach:

#include <bits/stdc++.h>
using namespace std;
// function which removes the right most set bit in the
// given number
int clearRight(int numb)
{
    // clearing the right most set bit from
    // the given number and store it in the result
    int reslt = (numb) & (numb - 1);
    // returing the calculated result
    return reslt;
}

// main function
int main()
{
    // given number
    int numb = 19;

    cout << "The given number before removing right most "
            "set bit : "
         << numb << endl;
    // passing the given number to clearRight function
    // to remove the clear the rightmost setbit
    cout << "The given number after removing right most "
            "set bit : "
         << clearRight(numb) << endl;
    return 0;
}

Output:

The given number before removing right most set bit : 19
The given number after removing right most set bit : 18

Method #2: Using Bitwise Operators in Python

Approach:

  • There is a function called clear rightmost set bit that is defined.
  • It accepts n as an argument and returns n with its rightmost set bit cleared.
  • This is accomplished by computing n & (n – 1) and returning the result.
  • (n – 1) equals n when all the rightmost successive 0s are flipped and the initial rightmost 1 is flipped.
  • As a result, n & (n – 1) equals n with the rightmost 1 cleared.
  • We will implement the same function in python

Below is the implementation:

# function which removes the right most set bit in the
# given number


def clearRight(numb):
    # clearing the right most set bit from
    # the given number and store it in the result
    reslt = (numb) & (numb - 1)
    # returing the calculated result
    return reslt
# Driver Code


# given number
numb = 19

print("The given number before removing right most "
      "set bit : ")
print(numb)
# passing the given number to clearRight function
# to remove the clear the rightmost setbit
print("The given number after removing right most set bit : ")
print(clearRight(numb))

Output:

The given number before removing right most set bit : 
19
The given number after removing right most set bit : 
18

Related Programs:

Program to Clear the Rightmost Set Bit of a Number in C++ and Python Read More »

Program for Transpose a Matrix

Program for Transpose a Matrix in Python & C++ Programming

In the previous article, we have discussed about Program for addition of two matrices in Python & C++ Programming. Let us learn Program for Transpose a Matrix in C++ Program and 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 as 5*4 matrix.

What is Matrix Transpose:

The interchanging of rows and columns is known as a matrix transpose. It’s abbreviated as A’. The element in A’s ith row and jth column will be moved to A’s jth row and ith column.

Examples for matrix Transpose:

Input:

Matrix 1 = 2 3 1 
                 1 2 3

Output:

Printing the transpose of matrices : 
2 1
3 2
1 3

Program for Matrix Transpose

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.

Method #1:Using nested Loops in Python

A matrix can be implemented as a nested list in Python (list inside a list). Each variable can be thought of as a row in the matrix.

Approach:

  • Create two two-dimensional arrays A, and set their values. (In this case, we used a  initialized statically)
  • Calculate the number of rows and columns in the array A and store it in the variables rows and columns.
  • Declare a new array transpose, this time with dimensions in columns an rows(in reverse order).
  • Calculate the transpose matrix by initializing transpose[i][j]=A[j][i].
  • Print the transpose matrix.

Below is the implementation:

# given matrix A
A = [[2, 3, 1],
     [1, 2, 3]]
rows = len(A)
columns = len(A[0])
# Initialize the transpose of matrices elements to 0
# with rows as columns and columns as rows as dimensions
matrixTrans = [[0, 0],
               [0, 0],
               [0, 0]]
# iterate through rows
for i in range(rows):
    # iterate through columns
    for j in range(columns):
        matrixTrans[j][i] = A[i][j]
# printing the transpose of matrices
print("Printing the transpose of matrices : ")
for rows in matrixTrans:
    print(*rows)

Output:

Printing the transpose of matrices : 
2 1
3 2
1 3

Method #2:Using List Comprehension in Python

The program’s output is the same as previously. For iterating through each element in the array, we used the nested list comprehension.

Understanding the list helps us to write concise codes and we need to always try to use them in Python. They’re really beneficial.

Below is the implementation:

# given matrix A
A = [[2, 3, 1],
     [1, 2, 3]]
rows = len(A)
columns = len(A[0])
# Initialize the transpose of matrices elements to 0
# with rows as columns and columns as rows as dimensions
matrixTrans = [[0, 0],
               [0, 0],
               [0, 0]]
# using list comprehension to transpose a matrix
matrixTrans = [[A[j][i] for j in range(rows)] for i in range(columns)]
# printing the transpose of matrices
print("Printing the transpose of matrices : ")
for rows in matrixTrans:
    print(*rows)

Output:

Printing the transpose of matrices : 
2 1
3 2
1 3

Method #3:Using nested loops in C++

We used nesting loops in this program to iterate through and row and column.

Calculate the transpose matrix by initializing transpose[i][j]=A[j][i].In the  the appropriate elements and store them in the result at each level.

Let us take dynamic input in this case.

Below is the implementation:

#include <iostream>
using namespace std;
int main()
{
    int rows, columns, A[100][100], matrixTrans[100][100], i, j;
    cout << "Enter the number of rows of the matrix "<<endl;
    cin >> rows;
    cout << "Enter the number of columns of the matrix"<<endl;
    cin >> columns;
    cout << "Enter the elements of the matrix " << endl;
    // Initializing matrix A with the user defined values
    for(i = 0; i < rows; ++i)
       for(j = 0; j < columns; ++j)
       {
           cout << "Enter element A" << i + 1 << j + 1 << " = ";
           cin >> A[i][j];
       }
 
    // Calculating transpose of the matrix
    for(i = 0; i < rows; ++i)
        for(j = 0; j < columns; ++j)
            matrixTrans[j][i] = A[i][j];
    //printing matrix A
    cout << endl << " printing the matrix A" << endl;
    for (i = 0; i < rows; ++i) {
    for (j = 0; j < columns; ++j) {
        cout << A[i][j] << "  ";
    }
    cout << endl;
}
    
    //printing the transpose of matrices
    cout << endl << " printing the transpose of matrices A " << endl;
    
    for (i = 0; i < columns; ++i) {
    for (j = 0; j < rows; ++j) {
        cout << matrixTrans[i][j] << "  ";
    }
    cout << endl;
}
    return 0;
}

Output:

Enter the number of rows of the matrix 
5
Enter the number of columns of the matrix
4
Enter the elements of the matrix 
Enter element A11 = 1
Enter element A12 = 2
Enter element A13 = 3
Enter element A14 = 4
Enter element A21 = 5
Enter element A22 = 8
Enter element A23 = 9
Enter element A24 = 7
Enter element A31 = 2
Enter element A32 = 1
Enter element A33 = 6
Enter element A34 = 4
Enter element A41 = 5
Enter element A42 = 2
Enter element A43 = 8
Enter element A44 = 0
Enter element A51 = -5
Enter element A52 = 3
Enter element A53 = 4
Enter element A54 = 8

printing the matrix A
1 2 3 4 
5 8 9 7 
2 1 6 4 
5 2 8 0 
-5 3 4 8

printing the transpose of matrices A 
1 5 2 5 -5 
2 8 1 2 3 
3 9 6 8 4 
4 7 4 0 8

Related Programs:

Program for Transpose a Matrix in Python & C++ Programming Read More »

Write a Program for Matrix Addition

Program for addition of two matrices in Python & C++ Programming

In the previous article, we have discussed about C++11 Multithreading – Part 8: std::future , std::promise and Returning values from Thread. Let us learn Program for addition of two matrices in C++ Program and 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 as 5*4 matrix.

What is matrix addition:

Given two matrices of same order(dimensions) then we can easily add the two matrices by doing the sum of corresponding elements in both the matrices.

Example:

Here Matrix C is matrix addition of the matrices A and B.

Examples for matrix addition:

Input:

Matrix 1  =  [  11  -2    0  ]
                    [   4    8    6  ]
Matrix 2 =   [   5    1   -5  ]
                    [   2    3    0 ]

Output:

Printing the sum of matrices : 
16 -1 -5
6 11 6

Program for matrix Addition

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

Method #1:Using nested Loops in Python

A matrix can be implemented as a nested list in Python (list inside a list). Each variable can be thought of as a row in the matrix.

We used nesting loops in this program to iterate through and row and column. In the two matrices we will add the appropriate elements and store them in the result at each level.

Here we give the matrix input as static.

Below is the  implementation:

# given matrix A
A = [[11, -2, 0],
     [4, 8, 6]]
# given matrix B
B = [[5, 1, -5],
     [2, 3, 0]]
# Initialize the sum of matrices elements to 0
matrixSum = [[0, 0, 0],
             [0, 0, 0]]

# Traverse the rows
for rows in range(len(A)):
    # Traverse the  columns
    for columns in range(len(A[0])):
        matrixSum[rows][columns] = A[rows][columns] + B[rows][columns]
# printing the sum of matrices
print("Printing the sum of matrices : ")
for rows in matrixSum:
    print(*rows)

Output:

Printing the sum of matrices : 
16 -1 -5
6 11 6

Method #2:Using List Comprehension in Python

The program’s output is the same as previously. For iterating through each element in the array, we used the nested list comprehension.

Understanding the list helps us to write concise codes and we need to always try to use them in Python. They’re really beneficial.

Below is the implementation:

# given matrix A
A = [[11, -2, 0],
     [4, 8, 6]]
# given matrix B
B = [[5, 1, -5],
     [2, 3, 0]]
# using list comprehension
matrixSum = [[A[i][j] + B[i][j]
              for j in range(len(A[0]))] for i in range(len(A))]
# printing the sum of matrices
print("Printing the sum of matrices : ")
for rows in matrixSum:
    print(*rows)

Output:

Printing the sum of matrices : 
16 -1 -5
6 11 6

Method #3:Using nested loops in C++

We used nesting loops in this program to iterate through and row and column. In the two matrices we will add the appropriate elements and store them in the result at each level.

Let us take dynamic input in this case.

Below is the implementation:

#include <iostream>
using namespace std;

int main()
{
    int rows, columns, A[100][100], B[100][100], sumMatrix[100][100], i, j;

    cout << "Enter the number of rows of the matrix "<<endl;
    cin >> rows;

    cout << "Enter the number of columns of the matrix"<<endl;
    cin >> columns;

    cout << "Enter the elements of first matrix " << endl;

    // Initializing matrix A with the user defined values
    for(i = 0; i < rows; ++i)
       for(j = 0; j < columns; ++j)
       {
           cout << "Enter element A" << i + 1 << j + 1 << " = ";
           cin >> A[i][j];
       }

   // Initializing matrix B with the user defined values
    cout << endl << "Enter elements of 2nd matrix: " << endl;
    for(i = 0; i < rows; ++i)
       for(j = 0; j < columns; ++j)
       {
           cout << "Enter element B" << i + 1 << j + 1 << " = ";
           cin >> B[i][j];
       }

    // Performing matrix addition by doing sum of given two matrices A and B
    for(i = 0; i < rows; ++i)
        for(j = 0; j < columns; ++j)
            sumMatrix[i][j] = A[i][j] + B[i][j];
    //printing matrix A
    cout << endl << " printing the matrix A" << endl;
    for (i = 0; i < rows; ++i) {
    for (j = 0; j < columns; ++j) {
        cout << A[i][j] << "  ";
    }
    cout << endl;
}
    //printing matrix B
    cout << endl << " printing the matrix B" << endl;
    for (i = 0; i < rows; ++i) {
    for (j = 0; j < columns; ++j) {
        cout << B[i][j] << "  ";
    }
    cout << endl;
}

    //printing the sum of matrices
    cout << endl << " printing the sum of matrices A and B" << endl;
    
    for (i = 0; i < rows; ++i) {
    for (j = 0; j < columns; ++j) {
        cout << sumMatrix[i][j] << "  ";
    }
    cout << endl;
}

    return 0;
}

Output:

Enter the number of rows of the matrix 
3
Enter the number of columns of the matrix
3
Enter the elements of first matrix 
Enter element A11 = 1
Enter element A12 = 2
Enter element A13 = 3
Enter element A21 = 4
Enter element A22 = 5
Enter element A23 = 6
Enter element A31 = 7
Enter element A32 = 8
Enter element A33 = 9

Enter elements of 2nd matrix: 
Enter element B11 = -3
Enter element B12 = 2
Enter element B13 = 5
Enter element B21 = 7
Enter element B22 = 1
Enter element B23 = 0
Enter element B31 = 3
Enter element B32 = 4
Enter element B33 = 6

printing the matrix A
1 2 3 
4 5 6 
7 8 9

printing the matrix B
-3 2 5 
7 1 0 
3 4 6

printing the sum of matrices A and B
-2 4 8 
11 6 6 
10 12 15

Related Programs:

Program for addition of two matrices in Python & C++ Programming Read More »

Program to Determine all Pythagorean Triplets in the Range in C++ and Python

Program to Determine all Pythagorean Triplets in the Range in C++ and Python

In the previous article, we have discussed about Program to Print Collatz Conjecture for a Given Number in C++ and Python. Let us learn Program to Determine all Pythagorean Triplets in C++ Program.

A Pythagorean triplet is a collection of three positive numbers, a, b, and c, such that a^2 + b^2 = c^2.

Given a limit, find all Pythagorean Triples with values less than that limit.

Examples:

Example1:

Input:

given upper limit =63

Output:

printing the Pythagorean triplets till the upper limit 63 :
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61

Example2:

Input:

given upper limit =175

Output:

printing the Pythagorean triplets till the upper limit 175 :
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61
48 14 50
45 28 53
40 42 58
33 56 65
24 70 74
13 84 85
63 16 65
60 32 68
55 48 73
48 64 80
39 80 89
28 96 100
15 112 113
80 18 82
77 36 85
72 54 90
65 72 97
56 90 106
45 108 117
32 126 130
17 144 145
99 20 101
96 40 104
91 60 109
84 80 116
75 100 125
64 120 136
51 140 149
36 160 164

Find all Pythagorean triplets in the given range in C++ and Python

A simple solution is to use three nested loops to generate these triplets that are less than the provided limit. Check if the Pythagorean condition is true for each triplet; if so, print the triplet. This solution has a time complexity of O(limit3), where ‘limit’ is the stated limit.

An Efficient Solution will print all triplets in O(k) time, where k is the number of triplets to be printed. The solution is to apply the Pythagorean triplet’s square sum connection, i.e., addition of squares a and b equals square of c, and then represent these numbers in terms of m and n.

For every choice of positive integer m and n, the formula of Euclid creates Pythagorean Triplets:

a=m^2 -n^2

b= 2 * m * n

c= m ^2 +n^2

Below is the implementation of efficient solution in C++ and Python:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

1)Finding all Pythagorean till the given limit in Python

Approach:

  • Scan the upper limit or give static input and save the variable.
  • Calculate the Pythagorean triplets using the formula with a while loop and for loop.
  • If the c value exceeds the upper limit, or if a number equals 0, break from the loop.
  • Print down all Pythagorean triplets’ three numbers.
  • Exit of program.

Below is the implementation:

# enter the upper limit till you find pythagorean triplets
upper_limit = 63
n3 = 0
a = 2
print("printing the pythagorean triplets till the upper limit", upper_limit, ":")
while(n3 < upper_limit):
    for b in range(1, a+1):
        n1 = a*a-b*b
        n2 = 2*a*b
        n3 = a*a+b*b
        if(n3 > upper_limit):
            break
        if(n1 == 0 or n2 == 0 or n3 == 0):
            break
        print(n1, n2, n3)
    a = a+1

Output:

printing the Pythagorean triplets till the upper limit 63 :
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61

Explanation:

The upper limit / input should be entered by a user as static, and stored in a variable.
The value of Pythagorean triplets using the formula is used during and for loops.
The loop breaks out if the value of a side is greater than the upper boundary, or if one side is 0.
The triplets will then be printed.

2)Finding all Pythagorean till the given limit in C++

Approach:

  • Scan the upper limit using cin or give static input and save the variable.
  • Calculate the Pythagorean triplets using the formula with a while loop and for loop.
  • If the c value exceeds the upper limit, or if a number equals 0, break from the loop.
  • Print down all Pythagorean triplets’ three numbers.
  • Exit of program.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
int main()
{

    // enter the upper limit till you find pythagorean
    // triplets
    int upper_limit = 175;
    int n3 = 0;
    int a = 2;
    cout << "printing the pythagorean triplets till the "
            "upper limit"
         << upper_limit << ":" << endl;
    while (n3 < upper_limit) {
        for (int b = 1; b <= a; b++) {
            int n1 = a * a - b * b;
            int n2 = 2 * a * b;
            n3 = a * a + b * b;
            if (n3 > upper_limit)
                break;
            if (n1 == 0 or n2 == 0 or n3 == 0)
                break;
            cout << n1 << " " << n2 << " " << n3 << endl;
        }
        a = a + 1;
    }
    return 0;
}

Output:

printing the Pythagorean triplets till the upper limit175:
3 4 5
8 6 10
5 12 13
15 8 17
12 16 20
7 24 25
24 10 26
21 20 29
16 30 34
9 40 41
35 12 37
32 24 40
27 36 45
20 48 52
11 60 61
48 14 50
45 28 53
40 42 58
33 56 65
24 70 74
13 84 85
63 16 65
60 32 68
55 48 73
48 64 80
39 80 89
28 96 100
15 112 113
80 18 82
77 36 85
72 54 90
65 72 97
56 90 106
45 108 117
32 126 130
17 144 145
99 20 101
96 40 104
91 60 109
84 80 116
75 100 125
64 120 136
51 140 149
36 160 164

Related Programs:

Program to Determine all Pythagorean Triplets in the Range in C++ and Python Read More »

Program to Subtract two Complex Numbers

Python Program to Subtract two Complex Numbers

In the previous article, we have discussed Python Program to Count the Number of Null elements in a List.

Complex numbers in python:

A complex number is formed by combining two real numbers. Python complex numbers can be generated using two methods: the complex() function and a direct assignment statement. Complex numbers are most commonly used when two real numbers are used to define something.

Given two complex numbers, and the task is to subtract given two complex numbers and get the result.

Example:

given complex no = complex(2, 3)   # result  = 2+3j

Examples:

Example1:

Input:

Given first complex number = 2+3j
Given second complex number = 1+5j

Output:

The Subtraction of  (2+3j) - (1+5j) = (1-2j)

Example2:

Input:

Given first complex number = 6+1j
Given second complex number = 5+2j

Output:

The Subtraction of  (6+1j) - (5+2j) = (1-1j)

Program to Subtract two Complex Numbers

Below are the ways to Subtract given two Complex Numbers.

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

Approach:

  • Give the first complex number as static input and store it in a variable.
  • Give the second complex number as static input and store it in another variable.
  • Subtract the given two complex numbers and store it in another variable.
  • Print the Subtraction of the given two complex numbers
  • The Exit of the program.

Below is the implementation:

# Give the first complex number as static input and store it in a variable.
fst_complx_no = 2 + 3j
# Give the second complex number as static input and store it in another variable.
scnd_complx_no = 1 + 5j
# Subtract the given two complex numbers and store it in another variable.
subtrctn_res = fst_complx_no - scnd_complx_no
# Print the Subtraction of the given two complex numbers
print(" The Subtraction of ", fst_complx_no,
      "-", scnd_complx_no, "=", subtrctn_res)

Output:

The Subtraction of  (2+3j) - (1+5j) = (1-2j)

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

Approach:

  • Give the real part and imaginary part of the first complex number as user input using map(), int(), split().
  • Store it in two variables.
  • Using a complex() function convert those two variables into a complex number and store it in a variable.
  • Give the real part and imaginary part of the second complex number as user input using map(), int(), split().
  • Store it in two variables.
  • Using a complex() function convert those two variables into a complex number and store it in another variable.
  • Subtract the given two complex numbers and store it in another variable.
  • Print the Subtraction of the given two complex numbers
  • The Exit of the program.

Below is the implementation:

#Give the real part and imaginary part of the first complex number as user input using map(), int(), split().
#Store it in two variables.
realpart_1, imaginarypart_1 = map(int, input(
    'Enter real part and complex part of the complex number = ').split())
#Using a complex() function convert those two variables into a complex number and store it in a variable.   
fst_complexnumbr = complex(realpart_1, imaginarypart_1)
#Give the real part and imaginary part of the second complex number as user input using map(), int(), split().
#Store it in two variables.
realpart_2, imaginarypart_2 = map(int, input(
    'Enter real part and complex part of the complex number = ').split())
#Using a complex() function convert those two variables into a complex number and store it in another variable.
scnd_complexnumbr = complex(realpart_2, imaginarypart_2)
# Subtract the given two complex numbers and store it in another variable.
subtrctn_res = fst_complexnumbr - scnd_complexnumbr
# Print the Subtraction of the given two complex numbers
print(" The Subtraction of ", fst_complexnumbr,
      "-", scnd_complexnumbr, "=", subtrctn_res)

Output:

Enter real part and complex part of the complex number = 3 7
Enter real part and complex part of the complex number = 1 14
The Subtraction of (3+7j) - (1+14j) = (2-7j)

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 Subtract two Complex Numbers Read More »

Program to Count the Number of Alphabets in a String

Python Program to Count the Number of Alphabets in a String

In the previous article, we have discussed Python Program to Count the Number of Null elements in a List.

Given a string, the task is to count the Number of Alphabets in a given String.

isalpha() Method:

The isalpha() method is a built-in method for string-type objects. If all of the characters are alphabets from a to z, the isalpha() method returns true otherwise, it returns False.

Examples:

Example1:

Input:

Given String = hello btechgeeks

Output:

The Number of Characters in a given string { hello btechgeeks } =  15

Example 2:

Input:

Given String = good morning btechgeeks

Output:

The Number of Characters in a given string { good morning btechgeeks } =  21

Program to Count the Number of Alphabets in a String

Below are the ways to Count the Number of Alphabets in a String.

Method #1: Using isalpha() Method (Static input)

Approach:

  • Give the String as static input and store it in a variable.
  • Take a variable to say ‘count’ and initialize its value with ‘0’
  • Loop from 0 to the length of the above-given String using For Loop.
  • Inside the loop, check whether if the value of the iterator is an alphabet or using the built-in isalpha() method inside the if conditional statement.
  • If the given condition is true, then increment the above-initialized count value by ‘1’.
  • Print the number of Alphabets in a given string by printing the above count value.
  • The Exit of the program.

Below is the implementation:

# Give the String as static input and store it in a variable.
gvn_str = "hello btechgeeks"
# Take a variable say 'count' and initialize it's value with '0'
count_no = 0
# Loop from 0 to the length of the above given String using For Loop.
for itrtor in gvn_str:
    # Inside the loop, check whether  if the value of iterator is alphabet or
    # using built-in isalpha() method inside the if conditional statement.
    if(itrtor.isalpha()):
     # If the given condition is true ,then increment the above initialized count value by '1'.
    	count_no = count_no+1
# Print the number of Alphabets in a given string by printing the above count value.
print(
    "The Number of Characters in a given string {", gvn_str, "} = ", count_no)

Output:

The Number of Characters in a given string { hello btechgeeks } =  15

Method #2: Using isalpha() Method (User input)

Approach:

  • Give the String as user input using the input() function and store it in the variable.
  • Take a variable to say ‘count’ and initialize its value with ‘0’
  • Loop from 0 to the length of the above-given String using For Loop.
  • Inside the loop, check whether if the value of the iterator is an alphabet or using the built-in isalpha() method inside the if conditional statement.
  • If the given condition is true, then increment the above-initialized count value by ‘1’.
  • Print the number of Alphabets in a given string by printing the above count value.
  • The Exit of the program.

Below is the implementation:

# Give the String as user input using the input()function and store it in the variable.
gvn_str = input("Enter some random String = ")
# Take a variable say 'count' and initialize it's value with '0'
count_no = 0
# Loop from 0 to the length of the above given String using For Loop.
for itrtor in gvn_str:
    # Inside the loop, check whether  if the value of iterator is alphabet or
    # using built-in isalpha() method inside the if conditional statement.
    if(itrtor.isalpha()):
     # If the given condition is true ,then increment the above initialized count value by '1'.
    	count_no = count_no+1
# Print the number of Alphabets in a given string by printing the above count value.
print(
    "The Number of Characters in a given string {", gvn_str, "} = ", count_no)

Output:

Enter some random String = good morning btechgeeks
The Number of Characters in a given string { good morning btechgeeks } = 21

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 Alphabets in a String Read More »

Program to Count the Number of Null elements in a List

Python Program to Count the Number of Null elements in a List

In the previous article, we have discussed Python Program to Convert Binary to Octal using While Loop
Python lists are similar to arrays in C or Java. A list is a collection of elements.
The primary distinction between a list and an array is that a list can store multiple types of elements, whereas an array can only store one type.

A list can contain “null elements” in addition to numbers, characters, strings, and so on.

Examples:

Example1:

Input:

Given List =["btechgeeks","hello", "", 123, "" ]

Output:

The Number of Null Elements in the above given list =  2

Example 2:

Input:

Given List =["", "btechgeeks", "good ", "",  "hello",  "",  "",1,2,9 ]

Output:

The Number of Null Elements in the above given list =  4

Program to Count the Number of Null elements in a List

Below are the ways to Count the Number of Null elements in a given list.

Method #1: Using For Loop (Static input)

Approach:

  • Give the list as static input and store it in a variable.
  • Take a variable to say ‘count’ and initialize its value with ‘0’
  • Loop from 0 to the length of the above-given list using For Loop.
  • Inside the loop, check whether the value of the iterator is Null or not using the if conditional statement.
  • If the given condition is true, then increment the above-initialized count value by ‘1’.
  • Print the number of Null elements in a given List by printing the above count value.
  • The Exit of the program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_lst = ["btechgeeks", "hello", "", 123, ""]
# Take a variable say count and initialize it's value with '0'
cou_nt = 0
# Loop from 0 to the length of the above given list using For Loop.
for itetor in range(len(gvn_lst)):
 # Inside the loop, check the if the value of iterator is Null or not using if condition.
    if(gvn_lst[itetor] == ""):
      # If the given condition is true ,then increment the above initialized count value.
        cou_nt += 1
 # Print the number of Null elements in a given List by printing the above count value.
print("The Number of Null Elements in the above given list = ", cou_nt)

Output:

The Number of Null Elements in the above given list =  2

Method #2: Using For Loop (User input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions and store it in a variable.
  • Take a variable to say ‘count’ and initialize its value with ‘0’
  • Loop from 0 to the length of the above-given list using For Loop.
  • Inside the loop, check if the value of the iterator is Null or not using the if conditional statement.
  • If the given condition is true, then increment the above-initialized count value.
  • Print the number of Null elements in a given List by printing the above count value.
  • The Exit of the program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions
# and store it in a variable.
gvn_lst = list( input(
    'Enter some random List Elements separated by spaces = ').split(' '))
# Take a variable say count and initialize it's value with '0'
cou_nt = 0
# Loop from 0 to the length of the above given list using For Loop.
for itetor in range(len(gvn_lst)):
 # Inside the loop, check the if the value of iterator is Null or not using if condition.
    if(gvn_lst[itetor] == ""):
      # If the given condition is true ,then increment the above initialized count value.
        cou_nt += 1
 # Print the number of Null elements in a given List by printing the above count value.
print("The Number of Null Elements in the above given list = ", cou_nt)

Output:

Enter some random List Elements separated by spaces = hello this is btechgeeks 
The Number of Null Elements in the above given list = 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 Count the Number of Null elements in a List Read More »

Program to get the Last Word from a String

Python Program to get the Last Word from a String

In the previous article, we have discussed Python Program to Subtract two Complex Numbers

Given a string that contains the words the task is to print the last word in the given string in Python.

Examples:

Example1:

Input:

Given string =hello this is BTechgeeks

Output:

The last word in the given string { hello this is BTechgeeks } is: BTechgeeks

Example2:

Input:

Given string =good morning this is btechgeeks

Output:

The last word in the given string { good morning this is btechgeeks } is: btechgeeks

Program to get the Last Word from a String in Python

Below are the ways to get the last word from the given string in Python.

Method #1: Using split() Method (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Split the words of the given string to a list of words using the built-in split() function.
  • Get the last word from the above list of words using negative indexing and store it in a variable.
  • Print the last word of the given string by printing the above variable.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvnstrng = 'hello this is BTechgeeks'
# Split the words of the given string to a list of words
# using the built-in split() function.
lsttofwrds = gvnstrng.split()
# Get the last word from the above list of words using negative indexing
# and store it in a variable.
lstwrd = lsttofwrds[-1]
# Print the last word of the given string by printing the above variable.
print('The last word in the given string {', gvnstrng, '} is:', lstwrd)

Output:

The last word in the given string { hello this is BTechgeeks } is: BTechgeeks

Method #2: Using split() Method (User Input)

Approach:

  • Give the string as user input using the input() function and store it in the variable.
  • Split the words of the given string to a list of words using the built-in split() function.
  • Get the last word from the above list of words using negative indexing and store it in a variable.
  • Print the last word of the given string by printing the above variable.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in the variable.
gvnstrng = input('Enter some random string = ')
# Split the words of the given string to a list of words
# using the built-in split() function.
lsttofwrds = gvnstrng.split()
# Get the last word from the above list of words using negative indexing
# and store it in a variable.
lstwrd = lsttofwrds[-1]
# Print the last word of the given string by printing the above variable.
print('The last word in the given string {', gvnstrng, '} is:', lstwrd)

Output:

Enter some random string = good morning this is btechgeeks
The last word in the given string { good morning this is btechgeeks } is: btechgeeks

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

 

Python Program to get the Last Word from a String Read More »

Program to Calculate GST

Python Program to Calculate GST

In the previous article, we have discussed Python Program to Find Median of List
Goods and Services Tax (GST):

GST is an abbreviation for Goods and Services Tax. It is a value-added tax levied on goods and services sold for domestic use or consumption. Customers pay GST to the government when they buy goods and services.

To calculate the GST percentage, first, compute the net GST amount by subtracting the original price from the net price that includes the GST. We will use the GST percent formula after calculating the net GST amount.

Formula:

GST% formula = ((GST Amount * 100)/Original price)

Net price        = Original price + GST amount

GST amount   = Net price – Original price

GST%             = ((GST amount * 100)/Original price)

round() function: round function rounds off to the nearest integer value.

Given the Net price, the original price, and the task is to calculate the GST percentage.

Examples:

Example1:

Input:

Given original price = 520
Given Net price       = 650

Output:

The GST percent for the above given input net and original prices =  25.0%

Example 2:

Input:

Given original price = 354.80
Given Net price       = 582.5

Output:

The GST percent for the above given input net and original prices =  64.17700112739571%

Program to Calculate GST

Below are the ways to Calculate GST.

Method #1: Using Mathematical Formula (Static input)

Approach:

  • Give the original price as static input and store it in a variable.
  • Give the net price as static input and store it in another variable.
  • Calculate the GST amount by using the above-given formula and store it in another variable.
  • Calculate the given GST percentage by using the above-given formula and store it in another variable.
  • Print the given GST value for the above given original and net prices.
  • The Exit of the program.

Below is the implementation:

# Give the original price as static input and store it in a variable.
gvn_Orignl_amt = 520
# Give the net price as static input and store it in another variable.
gvn_Net_amt = 650
# Calculate the GST amount by using the above given formula and store it in
# another variable.
GST_amnt = gvn_Net_amt - gvn_Orignl_amt
# Calculate the given GST percentage by using the above given formula and
# store it in another variable.
gvn_GST_percnt = ((GST_amnt * 100) / gvn_Orignl_amt)
# Print the given GST value for the above given original and net prices.
print("The GST percent for the above given input net and original prices = ",
      gvn_GST_percnt, end='')
print("%")

Output:

The GST percent for the above given input net and original prices =  25.0%

Method #2: Using Mathematical Formula (User input)

Approach:

  • Give the original price as user input using float(input()) and store it in a variable.
  • Give the net price as user input using float(input()) and store it in another variable.
  • Calculate the GST amount by using the above-given formula and store it in another variable.
  • Calculate the given GST percentage by using the above-given formula and store it in another variable.
  • Print the given GST value for the above given original and net prices.
  • The Exit of the program.

Below is the implementation:

# Give the original price as user input using float(input()) and store it in a variable.
gvn_Orignl_amt = float(input("Enter some random number = "))
# Give the net price as user input using float(input()) and store it in another variable.
gvn_Net_amt = float(input("Enter some random number = "))
# Calculate the GST amount by using the above given formula and store it in
# another variable.
GST_amnt = gvn_Net_amt - gvn_Orignl_amt
# Calculate the given GST percentage by using the above given formula and
# store it in another variable.
gvn_GST_percnt = ((GST_amnt * 100) / gvn_Orignl_amt)
# Print the given GST value for the above given original and net prices.
print("The GST percent for the above given input net and original prices = ",
      gvn_GST_percnt, end='')
print("%")

Output:

Enter some random number = 354.80
Enter some random number = 582.5
The GST percent for the above given input net and original prices = 64.17700112739571%

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 GST Read More »

Program to Add Trailing Zeros to String

Python Program to Add Trailing Zeros to String

In the previous article, we have discussed Python Program to Calculate GST
Given a String, and the task is to add the given number of trialing Zeros to the given String.

ljust() method :

We can add trailing zeros to the string using the ljust() method. It has two parameters, x, and y, where x is the length of the string. What will this method accomplish? It will simply go through a string and then to the length of the string that we require, and if both are not the same, it will pad those zeros that they have passed through a string and then store them in another.

Examples:

Example1:

Input:

Given String = hello btechgeeks
no of zeros to be added = 5

Output:

The above given string = hello btechgeeks
The above Given string with added given number of trailing zeros =  hello btechgeeks00000

Example1:

Input:

Given String = good morning btechgeeks
no of zeros to be added = 10

Output:

Enter some Random String = good morning btechgeeks
The above given string = good morning btechgeeks
Enter some Random Number = 10
The above Given string with added given number of trailing zeros = good morning btechgeeks0000000000

Program to Add Trailing Zeros to String

Below are the ways to add trailing Zeros to the given String

Method #1: Using ljust() Method (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Print the above-given string.
  • Give the number of trailing zeros to be added as static input and store it in another variable.
  • Calculate the length of the above-given string using the built-in len() function.
  • Add it with the given number of zeros and store it in another variable.
  • Add the given number of trailing zeros to the above-given String Using the built-in ljust() method and store it in another variable.
  • Print the above-Given string with added given the number of trailing Zeros.
  • The Exit of the program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_strng = 'hello btechgeeks'
# Print the above given string .
print("The above given string = " + str(gvn_strng))
# Give the number of trailing zeros to be added as static input and store it in another
# variable.
No_trzers = 5
# Calculate the length of the above given string using built- in len() function .
# Add it with the given number of zeros and store it in another variable.
tot_lenth = No_trzers + len(gvn_strng)
# Add the given number of trailing zeros to the above given String Using built-in ljust()
# method and store it in another variable.
finl_reslt = gvn_strng.ljust(tot_lenth, '0')
# Print the above Given string with added given number of trailing Zeros.
print("The above Given string with added given number of trailing zeros = ", finl_reslt)

Output:

The above given string = hello btechgeeks
The above Given string with added given number of trailing zeros =  hello btechgeeks00000

Method #2 : Using ljust() Method (User Input)

Approach:

  • Give the string as User input using the input() function and store it in a variable.
  • Print the above given string .
  • Give the number of trailing zeros to be added as User input using the int(input()) function and store it in another variable.
  • Calculate the length of the above given string using built- in len() function .
  • Add it with the given number of zeros and store it in another variable.
  • Add the given number of trailing zeros to the above given String Using built-in ljust() method and store it in another variable.
  • Print the above Given string with added given number of trailing Zeros.
  • The Exit of the program.

Below is the implementation:

# Give the string as User input  using the input() function and store it in a variable.
gvn_strng = input("Enter some Random String = ")
# Print the above given string .
print("The above given string = " + str(gvn_strng))
# Give the number of trailing zeros to be added as User input using the int(input()) function and store it in another
# variable.
No_trzers = int(input("Enter some Random Number = "))
# Calculate the length of the above given string using built- in len() function .
# Add it with the given number of zeros and store it in another variable.
tot_lenth = No_trzers + len(gvn_strng)
# Add the given number of trailing zeros to the above given String Using built-in ljust()
# method and store it in another variable.
finl_reslt = gvn_strng.ljust(tot_lenth, '0')
# Print the above Given string with added given number of trailing Zeros.
print("The above Given string with added given number of trailing zeros = ", finl_reslt)

Output:

Enter some Random String = good morning btechgeeks
The above given string = good morning btechgeeks
Enter some Random Number = 10
The above Given string with added given number of trailing zeros = good morning btechgeeks0000000000

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 Add Trailing Zeros to String Read More »