Python

Program to Swap Major and Minor Diagonals of a Square Matrix

Python Program to Swap Major and Minor Diagonals of a Square Matrix

In the previous article, we have discussed Python Program for Exponential Squaring (Fast Modulo Multiplication)

Given a square matrix, the task is to swap the major diagonal elements and minor diagonal elements of a given matrix.

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.

Diagonal Matrix:

The entries outside the main diagonal of a diagonal matrix are all 0; the word usually refers to square matrices.

Major Diagonal Matrix :

The Major Diagonal Elements of a Matrix are those that occur from the top left corner of the matrix down to the bottom right corner. The Major Diagonal is also referred to as the Main Diagonal or the Primary Diagonal.

Minor Diagonal Matrix :

Minor Diagonal Elements are those that appear from the top right corner of the matrix down to the bottom left corner. Secondary Diagonal is another name for it.

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 : 
6 2 0
1 4 2
3 7 5

Output:

The given matix after swapping the major and the minor diagonal elements: 
0 2 6 
1 4 2 
5 7 3

Example2:

Input:

Given Matrix : 
1 2 3
4 5 6
7 8 9

Output:

The given matix after swapping the major and the minor diagonal elements: 
3 2 1 
4 5 6 
9 8 7

Program to Swap Major and Minor Diagonals of a Square Matrix in Python:

Below are the ways to swap the major diagonal elements and minor diagonal elements of a given matrix.

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.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, swap mtrx[n][n], mtrx[n][mtrxrows-n-1] using the comma(,) operator ( where n is the iterator value and mtrxrows is the no of rows of matrix).
  • To print all the elements 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).
  • Print the element of the matrix by printing 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.
  • The Exit of the Program.

Below is the implementation:

# Give the matrix as static input and store it in a variable.
mtrx = [[6, 2, 0], [1, 4, 2], [3, 7, 5]]
# 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])
print("The given matix after swapping the major and the minor diagonal elements: ")
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
    # Inside the For loop, swap mtrx[n][n], mtrx[n][mtrxrows-n-1] using the comma(,) operator
    # ( where n is the iterator value and mtrxrows is the no of rows of matrix).

    mtrx[n][n], mtrx[n][mtrxrows-n-1] = mtrx[n][mtrxrows-n-1], mtrx[n][n]

# 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):
        # Print the element of the matrix by printing 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.
        print(mtrx[n][m], end=' ')
    print()

Output:

The given matix after swapping the major and the minor diagonal elements: 
0 2 6 
1 4 2 
5 7 3

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.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, swap mtrx[n][n], mtrx[n][mtrxrows-n-1] using the comma(,) operator ( where n is the iterator value and mtrxrows is the no of rows of matrix).
  • To print all the elements 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).
  • Print the element of the matrix by printing 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.
  • 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)

# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
    # Inside the For loop, swap mtrx[n][n], mtrx[n][mtrxrows-n-1] using the comma(,) operator
    # ( where n is the iterator value and mtrxrows is the no of rows of matrix).

    mtrx[n][n], mtrx[n][mtrxrows-n-1] = mtrx[n][mtrxrows-n-1], mtrx[n][n]

# 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):
        # Print the element of the matrix by printing 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.
        print(mtrx[n][m], end=' ')
    print()

Output:

Enter some random number of rows of the matrix = 3
Enter some random number of columns of the matrix = 3
Enter {3} elements of row {1} separated by spaces = 1 2 3
Enter {3} elements of row {2} separated by spaces = 4 5 6
Enter {3} elements of row {3} separated by spaces = 7 8 9
3 2 1 
4 5 6 
9 8 7

If you are new to the Python Programming Language then practice using our Python Programming Examples for Beginners as our expert team has designed them from scratch.

Python Program to Swap Major and Minor Diagonals of a Square Matrix Read More »

Program for Modular Multiplicative Inverse from 1 to n

Python Program for Modular Multiplicative Inverse from 1 to n

In the previous article, we have discussed Python Program to Find Value of y Mod (2 raised to power x)

Given two numbers n and a prime number, the task is to find the modular multiplicative inverse from 1 to the given number n

The modular multiplicative inverse of an is an integer ‘x’ in such a way that

a x ≡ 1 (mod prime)

Examples:

Example1:

Input:

Given number = 5
Given prime number = 7

Output:

The modular multiplicative inverse from 1 to the given number{ 5 } :
1 4 5 2 3

Explanation:

For 1, modular inverse is 1 as (1 * 1)%7 is 1
For 2, modular inverse is 4 as (2 * 4)%7 is 1
For 3, modular inverse is 6 as (3 * 5)%7 is 1
..
..

Example2:

Input:

Given number = 9
Given prime number = 11

Output:

The modular multiplicative inverse from 1 to the given number{ 9 } :
1 6 4 3 9 2 8 7 5

Program for Modular Multiplicative Inverse from 1 to n in Python

Below are the ways to find the modular multiplicative inverse from 1 to the given number n in python:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Give the prime number as static input and store it in another variable.
  • Create a function to say modularmultInverse() which takes the iterator value and the given number as the arguments and returns the modular multiplicative inverse from 1 to the given number n.
  • Inside the function, calculate the iterator value modulus given prime number and store it in the same variable iterator value.
  • Loop from 1 to the given prime number using the for loop.
  • Check if the iterator value multiplied by k (where k is the iterator value of for loop) modulus given prime number is equal to 1 using the if conditional statement.
  • If it is true, return the value of k.
  • Return -1.
  • Loop from 1 to the given number using the for loop.
  • Pass the iterator value and the given prime number to the modularmultInverse() function and print it.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say modularmultInverse() which takes the iterator value and the
# given number as the arguments and returns the modular multiplicative inverse from 1
# to the given number n.


def modularmultInverse(itrvl, gvn_primenum):
  # Inside the function, calculate the iterator value modulus given prime number and
  # store it in the same variable iterator value.
    itrvl = itrvl % gvn_primenum
    # Loop from 1 to the given prime number using the for loop.
    for k in range(1, gvn_primenum):
     # Check if the iterator value multiplied by k (where k is the iterator value of for loop)
     # modulus given prime number is equal to 1 using the if conditional statement.
        if ((itrvl*k) % gvn_primenum == 1):
          # If it is true, return the value of k.
            return k
    #Return -1.
    return -1


# Give the number as static input and store it in a variable.
gvn_numb = 5
# Give the prime number as static input and store it in another variable.
gvn_primenum = 7
# Loop from 1 to the given number using the for loop.
print(
    "The modular multiplicative inverse from 1 to the given number{", gvn_numb, "} :")
for itr in range(1, gvn_numb+1):
  # Pass the iterator value and the given prime number to the modularmultInverse() function
  # and print it.
    print(modularmultInverse(itr, gvn_primenum), end=" ")

Output:

The modular multiplicative inverse from 1 to the given number{ 5 } :
1 4 5 2 3

Method #2: Using For loop (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Give the prime number as user input using the int(input()) function and store it in another variable.
  • Create a function to say modularmultInverse() which takes the iterator value and the given number as the arguments and returns the modular multiplicative inverse from 1 to the given number n.
  • Inside the function, calculate the iterator value modulus given prime number and store it in the same variable iterator value.
  • Loop from 1 to the given prime number using the for loop.
  • Check if the iterator value multiplied by k (where k is the iterator value of for loop) modulus given prime number is equal to 1 using the if conditional statement.
  • If it is true, return the value of k.
  • Return -1.
  • Loop from 1 to the given number using the for loop.
  • Pass the iterator value and the given prime number to the modularmultInverse() function and print it.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say modularmultInverse() which takes the iterator value and the
# given number as the arguments and returns the modular multiplicative inverse from 1
# to the given number n.


def modularmultInverse(itrvl, gvn_primenum):
  # Inside the function, calculate the iterator value modulus given prime number and
  # store it in the same variable iterator value.
    itrvl = itrvl % gvn_primenum
    # Loop from 1 to the given prime number using the for loop.
    for k in range(1, gvn_primenum):
     # Check if the iterator value multiplied by k (where k is the iterator value of for loop)
     # modulus given prime number is equal to 1 using the if conditional statement.
        if ((itrvl*k) % gvn_primenum == 1):
          # If it is true, return the value of k.
            return k
    #Return -1.
    return -1
    
    
# Give the number as user input using the int(input()) function and store it in a variable.
gvn_numb = int(input("Enter some random number = "))
# Give the prime number as user input using the int(input()) function and 
# store it in another variable.
gvn_primenum = int(input("Enter some random number = "))
# Loop from 1 to the given number using the for loop.
print(
    "The modular multiplicative inverse from 1 to the given number{", gvn_numb, "} :")
for itr in range(1, gvn_numb+1):
  # Pass the iterator value and the given prime number to the modularmultInverse() function
  # and print it.
    print(modularmultInverse(itr, gvn_primenum), end=" ")

Output:

Enter some random number = 9
Enter some random number = 11
The modular multiplicative inverse from 1 to the given number{ 9 } :
1 6 4 3 9 2 8 7 5

If you are learning Python then the Python Programming Example is for you and gives you a thorough description of concepts for beginners, experienced programmers.

Python Program for Modular Multiplicative Inverse from 1 to n Read More »

Program to Find Value of y Mod (2 raised to power x)

Python Program to Find Value of y Mod (2 raised to power x)

In the previous article, we have discussed Python Program to Find Sum of Modulo K of First N Natural Numbers

Given two numbers x, y(integers) and the task is to find the value of given y modulus 2 raised to the power x.

Examples:

Example1:

Input:

Given x value = 5
Given y value = 9

Output:

The result of given y modulus 2 raised to the power x = 9

Example2:

Input:

Given x value = 3
Given y value = 12

Output:

The result of given y modulus 2 raised to the power x = 4

Program to Find Value of y Mod (2 raised to power x) in python

Below are the ways to find the value of given y modulus 2 raised to the power x in python:    

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number x as static input and store it in a variable.
  • Give the number y as static input and store it in another variable.
  • Pass the given two numbers y and x as the arguments to the y_mod2powx function.
  • Create a function to say y_mod2powx which takes the given two numbers y and x as the arguments and returns the value of given y modulus 2 raised to the power x.
  • Calculate the value of 2 raised to the power x using the pow() function and store it in a variable.
  • Calculate the value of the given y value modulus the above result and store it in another variable rslt.
  • Return the above result value rslt.
  • Print the value of given y modulus 2 raised to the power x.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say y_mod2powx which takes the given two numbers y and x as
# the arguments and returns the value of given y modulus 2 raised to the power x.


def y_mod2powx(gvn_yval, x):
   # Calculate the value of 2 raised to the power x using the pow() function and store it
   # in a variable.
    p = pow(2, gvn_xval)
    # Calculate the value of the given y value modulus the above result and store it in
    # another variable rslt.
    rslt = gvn_yval % p
    # Return the above result value rslt.
    return (rslt)


# Give the number x as static input and store it in a variable.
gvn_xval = 5
# Give the number y as static input and store it in another variable.
gvn_yval = 9
# Pass the given two numbers y and x as the arguments to the y_mod2powx function.
# Print the value of given y modulus 2 raised to the power x.
print("The result of given y modulus 2 raised to the power x =",
      y_mod2powx(gvn_yval, gvn_xval))

Output:

The result of given y modulus 2 raised to the power x = 9

Method #2: Using For loop (User Input)

Approach:

  • Give the number x as user input using the int(input()) function and store it in a variable.
  • Give the number y as user input using the int(input()) function and store it in another variable.
  • Pass the given two numbers y and x as the arguments to the y_mod2powx function.
  • Create a function to say y_mod2powx which takes the given two numbers y and x as the arguments and returns the value of given y modulus 2 raised to the power x.
  • Calculate the value of 2 raised to the power x using the pow() function and store it in a variable.
  • Calculate the value of the given y value modulus the above result and store it in another variable rslt.
  • Return the above result value rslt.
  • Print the value of given y modulus 2 raised to the power x.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say y_mod2powx which takes the given two numbers y and x as
# the arguments and returns the value of given y modulus 2 raised to the power x.


def y_mod2powx(gvn_yval, x):
   # Calculate the value of 2 raised to the power x using the pow() function and store it
   # in a variable.
    p = pow(2, gvn_xval)
    # Calculate the value of the given y value modulus the above result and store it in
    # another variable rslt.
    rslt = gvn_yval % p
    # Return the above result value rslt.
    return (rslt)


# Give the number x as user input using the int(input()) function and 
# store it in a variable.
gvn_xval = int(input("Enter some random number = "))
# Give the number y as user input using the int(input()) function and 
# store it in another variable.
gvn_yval = int(input("Enter some random number = "))
# Pass the given two numbers y and x as the arguments to the y_mod2powx function.
# Print the value of given y modulus 2 raised to the power x.
print("The result of given y modulus 2 raised to the power x =",
      y_mod2powx(gvn_yval, gvn_xval))

Output:

Enter some random number = 3
Enter some random number = 12
The result of given y modulus 2 raised to the power x = 4

Grab the opportunity and utilize the Python Program Code Examples over here to prepare basic and advanced topics too with ease and clear all your doubts.

Python Program to Find Value of y Mod (2 raised to power x) Read More »

Program to Find Sum of Modulo K of First N Natural Numbers

Python Program to Find Sum of Modulo K of First N Natural Numbers

In the previous article, we have discussed Python Program for Modular Multiplicative Inverse

Given two numbers N and K, the task is to find the sum of Modulo K of the first N natural numbers in Python.

Examples:

Example1:

Input:

Given Number = 5
Given k value = 6

Output:

The sum of modulo k of the given n natural numbers =  15

Explanation:

here 1%6+2%6+3%6+4%6+5%6 gives 15

Example2:

Input:

Given Number = 4
Given k value =  7

Output:

The sum of modulo k of the given n natural numbers =  10

Program to Find Sum of Modulo K of First N Natural Numbers in Python

Below are the ways to find the sum of Modulo K of the first N natural numbers in Python.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Give the k value as static input and store it in another variable.
  • Pass the given number and k value as the arguments to the Sum_mod_k function.
  • Create a function to say Sum_mod_k which takes the given number and k value as the arguments and returns the sum of modulo K of the given first N natural numbers.
  • Take a variable to say rslt and initialize its value to 0.
  • Loop from 1 to the given number using the for loop.
  • Calculate the value of the iterator modulus given k value and store it in a variable.
  • Add the above result to the rslt and store it in the same variable rslt.
  • Return the value of rslt.
  • Print the sum of modulo K of the given first N natural numbers.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say Sum_mod_k which takes the given number and k value as the
# arguments and returns the sum of modulo K of the given first N natural numbers.


def Sum_mod_k(gvn_numb, gvn_Kval):
    # Take a variable to say rslt and initialize its value to 0.
    rslt = 0
    # Loop from 1 to the given number using the for loop.
    for itr in range(1, gvn_numb + 1):
      # Calculate the value of the iterator modulus given k value and store it in a variable.
        mod_rslt = (itr % gvn_Kval)
      # Add the above result to the rslt and store it in the same variable rslt.
        rslt += mod_rslt
   # Return the value of rslt.
    return rslt


# Give the number as static input and store it in a variable.
gvn_numb = 5
# Give the k value as static input and store it in another variable.
gvn_Kval = 6
# Pass the given number and k value as the arguments to the Sum_mod_k function.
# Print the sum of modulo K of the given first N natural numbers.
print("The sum of modulo k of the given n natural numbers = ",
      Sum_mod_k(gvn_numb, gvn_Kval))

Output:

The sum of modulo k of the given n natural numbers =  15

Method #2: Using For loop (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Give the k value as user input using the int(input()) function and store it in another variable.
  • Pass the given number and k value as the arguments to the Sum_mod_k function.
  • Create a function to say Sum_mod_k which takes the given number and k value as the arguments and returns the sum of modulo K of the given first N natural numbers.
  • Take a variable to say rslt and initialize its value to 0.
  • Loop from 1 to the given number using the for loop.
  • Calculate the value of the iterator modulus given k value and store it in a variable.
  • Add the above result to the rslt and store it in the same variable rslt.
  • Return the value of rslt.
  • Print the sum of modulo K of the given first N natural numbers.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say Sum_mod_k which takes the given number and k value as the
# arguments and returns the sum of modulo K of the given first N natural numbers.


def Sum_mod_k(gvn_numb, gvn_Kval):
    # Take a variable to say rslt and initialize its value to 0.
    rslt = 0
    # Loop from 1 to the given number using the for loop.
    for itr in range(1, gvn_numb + 1):
      # Calculate the value of the iterator modulus given k value and store it in a variable.
        mod_rslt = (itr % gvn_Kval)
      # Add the above result to the rslt and store it in the same variable rslt.
        rslt += mod_rslt
   # Return the value of rslt.
    return rslt


# Give the number as user input using the int(input()) function and store it in a variable.
gvn_numb = int(input("Enter some random number = "))
# Give the k value as user input using the int(input()) function and store it in another variable.
gvn_Kval = int(input("Enter some random number = "))
# Pass the given number and k value as the arguments to the Sum_mod_k function.
# Print the sum of modulo K of the given first N natural numbers.
print("The sum of modulo k of the given n natural numbers = ",
      Sum_mod_k(gvn_numb, gvn_Kval))

Output:

Enter some random number = 4
Enter some random number = 7
The sum of modulo k of the given n natural numbers = 10

Practice Python Program Examples to master coding skills and learn the fundamental concepts in the dynamic programming language Python.

Python Program to Find Sum of Modulo K of First N Natural Numbers Read More »

Python Program for Modular Multiplicative Inverse

In the previous article, we have discussed Python Program to Find Square Root Under Modulo k (When k is in Form of 4*i + 3)

Given two integers and the task is to find the modular multiplicative inverse of ‘first number’ under modulo ‘second number’.

The modular multiplicative inverse is an integer ‘x’ such that

first number x ≡ 1 (mod second number)

The value of x should be in the range 0 to 1, 2,…second number-1, i.e. in the integer modulo second number ring.

If and only if the first number and second number are relatively prime (i.e., if gcd( first number, second number) = 1), the multiplicative inverse of “first number modulo second number” exists.

Examples:

Example1:

Input:

Given First Number = 10
Given Second Number = 17

Output:

The modular multiplicative inverse of given first number under modulo second number =  12

Example2:

Input:

Given First Number = 4
Given Second Number = 9

Output:

The modular multiplicative inverse of given first number under modulo second number =  7

Program for Modular Multiplicative Inverse in Python

Below are the ways to find the modular multiplicative inverse of ‘first number’ under modulo ‘second number’ in python.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Pass the given first and second numbers as the arguments to the modular_MultInverse function.
  • Create a function to say modular_MultInverse which takes the given first and second numbers as the arguments and returns the modular multiplicative inverse of ‘first number’ under modulo ‘second number’.
  • Calculate the value of the given first number modulus second number and store it in the same variable first number.
  • Loop from 1 to the given second number using the for loop.
  • Multiply the given first number with the iterator value and store it in another variable.
  • Check if the above result modulus second number is equal to 1 using the if conditional statement.
  • If it is true, then return the iterator value.
  • Return 1.
  • Print the modular multiplicative inverse of ‘first number’ under modulo ‘second number’.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say modular_MultInverse which takes the given first and second
# numbers as the arguments and returns the modular multiplicative inverse of
# ‘first number’ under modulo ‘second number’.


def modular_MultInverse(fst_numb, secnd_numb):
  # Calculate the value of the given first number modulus second number and store it in the
  # same variable first number.
    fst_numb = fst_numb % secnd_numb
    # Loop from 1 to the given second number using the for loop.
    for itror in range(1, secnd_numb):
        # Multiply the given first number with the iterator value and store it in
        # another variable.
        mul = (fst_numb * itror)
      # Check if the above result modulus second number is equal to 1 using the if conditional
      # statement.
        if (mul % secnd_numb == 1):
          # If it is true, then return the iterator value.
            return itror
    # Return 1.
    return 1


# Give the first number as static input and store it in a variable.
fst_numb = 10
# Give the second number as static input and store it in another variable.
secnd_numb = 17
# Pass the given first and second numbers as the arguments to the modular_MultInverse
# function.
# Print the modular multiplicative inverse of ‘first number’ under modulo ‘second number'.
print("The modular multiplicative inverse of given first number under modulo second number = ",
      modular_MultInverse(fst_numb, secnd_numb))

Output:

The modular multiplicative inverse of given first number under modulo second number =  12

Method #2: Using For loop (User Input)

Approach:

  • Give the first number as user input using the int(input()) function and store it in a variable.
  • Give the second number as user input using the int(input()) function and store it in another variable.
  • Pass the given first and second numbers as the arguments to the modular_MultInverse function.
  • Create a function to say modular_MultInverse which takes the given first and second numbers as the arguments and returns the modular multiplicative inverse of ‘first number’ under modulo ‘second number’.
  • Calculate the value of the given first number modulus second number and store it in the same variable first number.
  • Loop from 1 to the given second number using the for loop.
  • Multiply the given first number with the iterator value and store it in another variable.
  • Check if the above result modulus second number is equal to 1 using the if conditional statement.
  • If it is true, then return the iterator value.
  • Return 1.
  • Print the modular multiplicative inverse of ‘first number’ under modulo ‘second number’.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say modular_MultInverse which takes the given first and second
# numbers as the arguments and returns the modular multiplicative inverse of
# ‘first number’ under modulo ‘second number’.


def modular_MultInverse(fst_numb, secnd_numb):
  # Calculate the value of the given first number modulus second number and store it in the
  # same variable first number.
    fst_numb = fst_numb % secnd_numb
    # Loop from 1 to the given second number using the for loop.
    for itror in range(1, secnd_numb):
        # Multiply the given first number with the iterator value and store it in
        # another variable.
        mul = (fst_numb * itror)
      # Check if the above result modulus second number is equal to 1 using the if conditional
      # statement.
        if (mul % secnd_numb == 1):
          # If it is true, then return the iterator value.
            return itror
    # Return 1.
    return 1


# Give the first number as user input using the int(input()) function and store it in a variable.
fst_numb = int(input("Enter some random number = "))
# Give the second number as user input using the int(input()) function and store it in
# another variable.
secnd_numb = int(input("Enter some random number = "))
# Pass the given first and second numbers as the arguments to the modular_MultInverse
# function.
# Print the modular multiplicative inverse of ‘first number’ under modulo ‘second number'.
print("The modular multiplicative inverse of given first number under modulo second number = ",
      modular_MultInverse(fst_numb, secnd_numb))

Output:

Enter some random number = 4
Enter some random number = 9
The modular multiplicative inverse of given first number under modulo second number = 7

If you wanna write simple python programs as a part of your coding practice refer to numerous Simple Python Program Examples existing and learn the approach used.

Python Program for Modular Multiplicative Inverse Read More »

Program to Find Square Root Under Modulo k (When k is in Form of 4i + 3)

Python Program to Find Square Root Under Modulo k (When k is in Form of 4*i + 3)

In the previous article, we have discussed Python Program for Array/List Elements that Appear More than Once

Given the number N, prime number k and the task is to find the square root of the given number under modulo k(When k is in form of 4*i + 3). Here i is an integer.

Examples:

Example1:

Input:

Given prime number k=5
Given Number = 4

Output:

The Square root of the given number{ 4 } under modulo k= 2

Example2:

Input:

Given prime number k=3
Given Number = 5

Output:

No, we cannot find the square root for a given number

Program to Find Square Root Under Modulo k (When k is in Form of 4*i + 3) in Python

Below are the ways to find the square root of the given number under modulo k (When k is in form of 4*i + 3) in python:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the prime number k as static input and store it in a variable.
  • Give the number as static input and store it in another variable.
  • Pass the given number and k as the arguments to the sqrt_undermodk function.
  • Create a function to say sqrt_undermodk which takes the given number and k as the arguments and returns the square root of the given number under modulo k (When k is in form of 4*i + 3).
  • Calculate the value of the given number modulus k and store it in the same variable given number.
  • Loop from 2 to the given k value using the for loop.
  • Multiply the iterator value with itself and store it in another variable.
  • Check if the above result modulus k is equal to the given number using the if conditional statement.
  • If it is true then print the iterator value.
  • Return and exit the for loop.
  • Print “No, we cannot find the square root for a given number”.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say sqrt_undermodk which takes the given number and k as
# the arguments and returns the square root of the given number under modulo k
# (When k is in form of 4*i + 3).


def sqrt_undermodk(gvn_numb, k):
    # Calculate the value of the given number modulus k and store it in the same variable
    # given number.
    gvn_numb = gvn_numb % k
    # Loop from 2 to the given k value using the for loop.
    for itror in range(2, k):
      # Multiply the iterator value with itself and store it in another variable.
        mul = (itror * itror)
        # Check if the above result modulus k is equal to the given number using the if
        # conditional statement.
        if (mul % k == gvn_numb):
            # If it is true then print the iterator value.
            print(
                "The Square root of the given number{", gvn_numb, "} under modulo k=", itror)
            # Return and exit the for loop.
            return
    # Print "No, we cannot find the square root for a given number".
    print("No, we cannot find the square root for a given number")


# Give the prime number k as static input and store it in a variable.
k = 5
# Give the number as static input and store it in another variable.
gvn_numb = 4
# Pass the given number and k as the arguments to the sqrt_undermodk function.
sqrt_undermodk(gvn_numb, k)

Output:

The Square root of the given number{ 4 } under modulo k= 2

Method #2: Using For loop (User Input)

Approach:

  • Give the prime number k as user input using the int(input()) function and store it in a variable.
  • Give the number as user input using the int(input()) function and store it in another variable.
  • Pass the given number and k as the arguments to the sqrt_undermodk function.
  • Create a function to say sqrt_undermodk which takes the given number and k as the arguments and returns the square root of the given number under modulo k (When k is in form of 4*i + 3).
  • Calculate the value of the given number modulus k and store it in the same variable given number.
  • Loop from 2 to the given k value using the for loop.
  • Multiply the iterator value with itself and store it in another variable.
  • Check if the above result modulus k is equal to the given number using the if conditional statement.
  • If it is true then print the iterator value.
  • Return and exit the for loop.
  • Print “No, we cannot find the square root for a given number”.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say sqrt_undermodk which takes the given number and k as
# the arguments and returns the square root of the given number under modulo k
# (When k is in form of 4*i + 3).


def sqrt_undermodk(gvn_numb, k):
    # Calculate the value of the given number modulus k and store it in the same variable
    # given number.
    gvn_numb = gvn_numb % k
    # Loop from 2 to the given k value using the for loop.
    for itror in range(2, k):
      # Multiply the iterator value with itself and store it in another variable.
        mul = (itror * itror)
        # Check if the above result modulus k is equal to the given number using the if
        # conditional statement.
        if (mul % k == gvn_numb):
            # If it is true then print the iterator value.
            print(
                "The Square root of the given number{", gvn_numb, "} under modulo k=", itror)
            # Return and exit the for loop.
            return
    # Print "No, we cannot find the square root for a given number".
    print("No, we cannot find the square root for a given number")


# Give the prime number k as user input using the int(input()) function and 
# store it in a variable.
k = int(input("Enter some random number = "))
# Give the number as user input using the int(input()) function and 
# store it in another variable.
gvn_numb = int(input("Enter some random number = "))
# Pass the given number and k as the arguments to the sqrt_undermodk function.
sqrt_undermodk(gvn_numb, k)

Output:

Enter some random number = 7
Enter some random number = 2
The Square root of the given number{ 2 } under modulo k= 3

Find a comprehensive collection of Examples of Python Programs ranging from simple ones to complex ones to guide you throughout your coding journey.

Python Program to Find Square Root Under Modulo k (When k is in Form of 4*i + 3) Read More »

Program to Remove Elements from the ArrayList Which Appear Strictly Less than k Times

Python Program to Remove Elements from the Array/List Which Appear Strictly Less than k Times

In the previous article, we have discussed Python Program to Remove String Elements that Appear Strictly Less than k Times

Given a list, k value and the task is to delete all the elements from a given list that appears Strictly less than k times in python.

Examples:

Example1:

Input:

Given List = [2, 4, 6, 2, 3, 5, 6]
Given k value = 1

Output:

The list [2, 4, 6, 2, 3, 5, 6] after deletion all the elements from a given list that appears strictly less than k times:
[2, 6, 2, 6]

Example2:

Input:

Given List = [10, 20, 30, 40, 20, 10, 20, 10, 30]
Given k value = 2

Output:

The list [10, 20, 30, 40, 20, 10, 20, 10, 30] after deletion all the elements from a given list that appears strictly less than k times:
[10, 20, 20, 10, 20, 10]

Program to Remove Elements from the Array/List Which Appear Strictly Less than k Times in Python

Below are the ways to delete all the elements from a given list that appears Strictly less than k times in python:

Method #1: Using Dictionary (Hashing, Static Input)

Approach:

  • Take a dictionary and initialize it to empty using the {} or dict() say freqncyDictionary.
  • Give the list as static input and store it in a variable.
  • Loop in the given list using the For loop.
  • Inside the For loop, Check if the list element is present in the dictionary or not using the if conditional statement and ‘in‘ keyword.
  • If it is true then increment the count of the list element in the dictionary by 1.
  • Else initialize the dictionary with the list element as key and value as 1.
  • Give the k value as static input and store it in a variable.
  • Take a new empty list say modifdlst and store it in a variable.
  • Loop in the given list using the For loop.
  • Check if the key in the freqncyDictionary having a value greater than k using the if conditional statement.
  • If it is true then append the key value to the above declared empty list modifdlst.
  • Print the list after deletion of all the elements from a given list that appears strictly less than k times.
  • The Exit of the Program.

Below is the implementation:

# Take a dictionary and initialize it to empty
# using the {} or dict() say freqncyDictionary.
freqncyDictionary = {}
# Give the list as static input and store it in a variable.
gvnlst = [2, 4, 6, 2, 3, 5, 6]
# Loop in the given list using the For loop.
for i in gvnlst:
        # Inside the For loop,
    # Check if the list element is present in the dictionary
    # or not using the if conditional statement and 'in' keyword.
    if i in freqncyDictionary.keys():
                # If it is true then increment the count of the list element
        # in the dictionary by 1.
        freqncyDictionary[i] = freqncyDictionary[i]+1
    # Else initialize the dictionary with the list element as key and value as 1.
    else:
        freqncyDictionary[i] = 1
# Give the k value as static input and store it in a variable.
k = 1
# Take a new empty list say modifdlst and store it in a variable.
modifdlst = []
# Loop in the given list using the For loop.
for lstelmt in gvnlst:
  # Check if the key in the freqncyDictionary having value greater than k
  # using the if conditional statement.

    if(freqncyDictionary[lstelmt] > k):
      # If it is true then append the key value to the above declared empty list modifdlst.
        modifdlst.append(lstelmt)
# Print the list after deletion of all the elements from a given list that appears
# Strictly less than k times.
print("The list", gvnlst,
      "after deletion all the elements from a given list that appears strictly less than k times:")
print(modifdlst)

Output:

The list [2, 4, 6, 2, 3, 5, 6] after deletion all the elements from a given list that appears strictly less than k times:
[2, 6, 2, 6]

Method #2: Using Dictionary (Hashing, User Input)

Approach:

  • Take a dictionary and initialize it to empty using the {} or dict() say freqncyDictionary.
  • Give the list as user input using the list(),map(),split(),int functions and store it in a variable.
  • Loop in the given list using the For loop.
  • Inside the For loop, Check if the list element is present in the dictionary or not using the if conditional statement and ‘in‘ keyword.
  • If it is true then increment the count of the list element in the dictionary by 1.
  • Else initialize the dictionary with the list element as key and value as 1.
  • Give the k value as user input using the int(input()) function and store it in a variable.
  • Take a new empty list say modifdlst and store it in a variable.
  • Loop in the given list using the For loop.
  • Check if the key in the freqncyDictionary having a value greater than k using the if conditional statement.
  • If it is true then append the key value to the above declared empty list modifdlst.
  • Print the list after deletion of all the elements from a given list that appears strictly less than k times.
  • The Exit of the Program.

Below is the implementation:

# Take a dictionary and initialize it to empty
# using the {} or dict() say freqncyDictionary.
freqncyDictionary = {}
# Give the list as user input using the list(),map(),split(),int functions
# and store it in a variable.
gvnlst = list(
    map(int, input('Enter some random list element separated by spaces = ').split()))
# Loop in the given list using the For loop.
for i in gvnlst:
        # Inside the For loop,
    # Check if the list element is present in the dictionary
    # or not using the if conditional statement and 'in' keyword.
    if i in freqncyDictionary.keys():
                # If it is true then increment the count of the list element
        # in the dictionary by 1.
        freqncyDictionary[i] = freqncyDictionary[i]+1
    # Else initialize the dictionary with the list element as key and value as 1.
    else:
        freqncyDictionary[i] = 1
# Give the k value as user input using the int(input()) function and store it in a variable.
k = int(input("Enter some random number ="))
# Take a new empty list say modifdlst and store it in a variable.
modifdlst = []
# Loop in the given list using the For loop.
for lstelmt in gvnlst:
  # Check if the key in the freqncyDictionary having value greater than k
  # using the if conditional statement.

    if(freqncyDictionary[lstelmt] > k):
      # If it is true then append the key value to the above declared empty list modifdlst.
        modifdlst.append(lstelmt)
# Print the list after deletion of all the elements from a given list that appears
# Strictly less than k times.
print("The list", gvnlst,
      "after deletion all the elements from a given list that appears strictly less than k times:")
print(modifdlst)

Output:

Enter some random list element separated by spaces = 10 20 30 40 20 10 20 10 30
Enter some random number =2
The list [10, 20, 30, 40, 20, 10, 20, 10, 30] after deletion all the elements from a given list that appears strictly less than k times:
[10, 20, 20, 10, 20, 10]

Method #3: Using Counter() function (Hashing, Static Input)

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the list as static input and store it in a variable.
  • Calculate the frequency of all the given list elements using the Counter() function which returns the element and its frequency as key-value pair and store this dictionary in a variable(say freqncyDictionary)
  • Give the k value as static input and store it in a variable.
  • Take a new empty list say modifdlst and store it in a variable.
  • Loop in the given list using the For loop.
  • Check if the key in the freqncyDictionary having a value greater than k using the if conditional statement.
  • If it is true then append the key value to the above declared empty list modifdlst.
  • Print the list after deletion of all the elements from a given list that appears strictly less than k times.
  • The Exit of the Program.

Below is the implementation:

# Import the Counter() function from collections using the import keyword.
from collections import Counter
# Give the list as static input and store it in a variable.
gvnlst = [2, 4, 6, 2, 3, 5, 6]
# Calculate the frequency of all the given list elements using the Counter()
# function which returns the element and its frequency as key-value pair
# and store this dictionary in a variable(say freqncyDictionary)
freqncyDictionary = Counter(gvnlst)
# Give the k value as static input and store it in a variable.
k = 1
# Take a new empty list say modifdlst and store it in a variable.
modifdlst = []
# Loop in the given list using the For loop.
for lstelmt in gvnlst:
  # Check if the key in the freqncyDictionary having value greater than k
  # using the if conditional statement.

    if(freqncyDictionary[lstelmt] > k):
      # If it is true then append the key value to the above declared empty list modifdlst.
        modifdlst.append(lstelmt)
# Print the list after deletion of all the elements from a given list that appears
# Strictly less than k times.
print("The list", gvnlst,
      "after deletion all the elements from a given list that appears strictly less than k times:")
print(modifdlst)

Output:

The list [2, 4, 6, 2, 3, 5, 6] after deletion all the elements from a given list that appears strictly less than k times:
[2, 6, 2, 6]

Method #4: Using Counter() function (Hashing, User Input)

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the list as user input using the list(),map(),split(),int functions and store it in a variable.
  • Calculate the frequency of all the given list elements using the Counter() function which returns the element and its frequency as key-value pair and store this dictionary in a variable(say freqncyDictionary)
  • Give the k value as user input using the int(input()) function and store it in a variable.
  • Take a new empty list say modifdlst and store it in a variable.
  • Loop in the given list using the For loop.
  • Check if the key in the freqncyDictionary having a value greater than k using the if conditional statement.
  • If it is true then append the key value to the above declared empty list modifdlst.
  • Print the list after deletion of all the elements from a given list that appears strictly less than k times.
  • The Exit of the Program.

Below is the implementation:

# Import the Counter() function from collections using the import keyword.
from collections import Counter
# Give the list as user input using the list(),map(),split(),int functions
# and store it in a variable.
gvnlst = list(
    map(int, input('Enter some random list element separated by spaces = ').split()))
# Calculate the frequency of all the given list elements using the Counter()
# function which returns the element and its frequency as key-value pair
# and store this dictionary in a variable(say freqncyDictionary)
freqncyDictionary = Counter(gvnlst)
# Give the k value as user input using the int(input()) function and store it in a variable.
k = int(input("Enter some random number ="))
# Take a new empty list say modifdlst and store it in a variable.
modifdlst = []
# Loop in the given list using the For loop.
for lstelmt in gvnlst:
  # Check if the key in the freqncyDictionary having value greater than k
  # using the if conditional statement.

    if(freqncyDictionary[lstelmt] > k):
      # If it is true then append the key value to the above declared empty list modifdlst.
        modifdlst.append(lstelmt)
# Print the list after deletion of all the elements from a given list that appears
# Strictly less than k times.
print("The list", gvnlst,
      "after deletion all the elements from a given list that appears strictly less than k times:")
print(modifdlst)

Output:

Enter some random list element separated by spaces = 10 20 30 40 20 10 20 10 30
Enter some random number =2
The list [10, 20, 30, 40, 20, 10, 20, 10, 30] after deletion all the elements from a given list that appears strictly less than k times:
[10, 20, 20, 10, 20, 10]

Find the best practical and ready-to-use Python Programming Examples that you can simply run on a variety of platforms and never stop learning.

Python Program to Remove Elements from the Array/List Which Appear Strictly Less than k Times Read More »

Program for ArrayList Elements that Appear More than Once

Python Program for Array/List Elements that Appear More than Once

In the previous article, we have discussed Python Program to Remove Elements from the Array/List Which Occurs More than k Times

Given a list, and the task is to print all the elements from a given list that appears more than once in python.

Examples:

Example1:

Input:

Given List = [20, 30, 40, 50, 20, 50]

Output:

The Elements from a given list [20, 30, 40, 50, 20, 50] that appears more than once : 
20 50

Example2:

Input:

Given List = [15, 25, 35, 25, 15, 40]

Output:

The Elements from a given list [15, 25, 35, 25, 15, 40] that appears more than once : 
15 25

Program for Array/List Elements that Appear More than Once in Python

Below are the ways to print all the elements from a given list that appears more than once in python:

Method #1: Using Dictionary (Hashing, Static Input)

Approach:

  • Take a dictionary and initialize it to empty using the {} or dict() say freqncyDictionary.
  • Give the list as static input and store it in a variable.
  • Loop in the given list using the For loop.
  • Inside the For loop, Check if the list element is present in the dictionary or not using the if conditional statement and ‘in‘ keyword.
  • If it is true then increment the count of the list element in the dictionary by 1.
  • Else initialize the dictionary with the list element as key and value as 1.
  • Take a new empty list say modifdlst and store it in a variable.
  • Loop in the above-calculated frequency dictionary using the For loop
  • Check if the key in the freqncyDictionary having a value greater than 1 using the if conditional statement.
  • If it is true then append the key value to the above declared empty list modifdlst.
  • Print all the elements from a given list that appears more than once.
  • The Exit of the Program.

Below is the implementation:

# Take a dictionary and initialize it to empty
# using the {} or dict() say freqncyDictionary.
freqncyDictionary = {}
# Give the list as static input and store it in a variable.
gvnlst = [20, 30, 40, 50, 20, 50]
# Loop in the given list using the For loop.
for i in gvnlst:
        # Inside the For loop,
    # Check if the list element is present in the dictionary
    # or not using the if conditional statement and 'in' keyword.
    if i in freqncyDictionary.keys():
                # If it is true then increment the count of the list element
        # in the dictionary by 1.
        freqncyDictionary[i] = freqncyDictionary[i]+1
    # Else initialize the dictionary with the list element as key and value as 1.
    else:
        freqncyDictionary[i] = 1
# Take a new empty list say modifdlst and store it in a variable.
modifdlst = []
# Loop in the above calculated frequency dictionary using the For loop
for key in freqncyDictionary:
  # Check if the key in the freqncyDictionary having value greater than 1
  # using the if conditional statement.

    if(freqncyDictionary[key] > 1):
      # If it is true then append the key value to the above declared empty list modifdlst.
        modifdlst.append(key)
# Print all the elements from a given list that appears more than once.
print("The Elements from a given list", gvnlst,
      "that appears more than once : ")
print(*modifdlst)

Output:

The Elements from a given list [20, 30, 40, 50, 20, 50] that appears more than once : 
20 50

Method #2: Using Dictionary (Hashing, User Input)

Approach:

  • Take a dictionary and initialize it to empty using the {} or dict() say freqncyDictionary.
  • Give the list as user input using the list(),map(),split(),int functions and store it in a variable.
  • Loop in the given list using the For loop.
  • Inside the For loop, Check if the list element is present in the dictionary or not using the if conditional statement and ‘in‘ keyword.
  • If it is true then increment the count of the list element in the dictionary by 1.
  • Else initialize the dictionary with the list element as key and value as 1.
  • Take a new empty list say modifdlst and store it in a variable.
  • Loop in the above-calculated frequency dictionary using the For loop
  • Check if the key in the freqncyDictionary having a value greater than 1 using the if conditional statement.
  • If it is true then append the key value to the above declared empty list modifdlst.
  • Print all the elements from a given list that appears more than once.
  • The Exit of the Program.

Below is the implementation:

# Take a dictionary and initialize it to empty
# using the {} or dict() say freqncyDictionary.
freqncyDictionary = {}
# Give the list as user input using the list(),map(),split(),int functions
# and store it in a variable.
gvnlst = list(
    map(int, input('Enter some random list element separated by spaces = ').split()))
# Loop in the given list using the For loop.
for i in gvnlst:
        # Inside the For loop,
    # Check if the list element is present in the dictionary
    # or not using the if conditional statement and 'in' keyword.
    if i in freqncyDictionary.keys():
                # If it is true then increment the count of the list element
        # in the dictionary by 1.
        freqncyDictionary[i] = freqncyDictionary[i]+1
    # Else initialize the dictionary with the list element as key and value as 1.
    else:
        freqncyDictionary[i] = 1
# Take a new empty list say modifdlst and store it in a variable.
modifdlst = []
# Loop in the above calculated frequency dictionary using the For loop
for key in freqncyDictionary:
  # Check if the key in the freqncyDictionary having value greater than 1
  # using the if conditional statement.

    if(freqncyDictionary[key] > 1):
      # If it is true then append the key value to the above declared empty list modifdlst.
        modifdlst.append(key)
# Print all the elements from a given list that appears more than once.
print("The Elements from a given list", gvnlst,
      "that appears more than once : ")
print(*modifdlst)


Output:

Enter some random list element separated by spaces = 15 25 35 25 15 40
The Elements from a given list [15, 25, 35, 25, 15, 40] that appears more than once : 
15 25

Method #3: Using Counter() function (Hashing, Static Input)

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the list as static input and store it in a variable.
  • Calculate the frequency of all the given list elements using the Counter() function which returns the element and its frequency as key-value pair and store this dictionary in a variable(say freqncyDictionary)
  • Take a new empty list say modifdlst and store it in a variable.
  • Loop in the above-calculated frequency dictionary using the For loop
  • Check if the key in the freqncyDictionary having a value greater than 1 using the if conditional statement.
  • If it is true then append the key value to the above declared empty list modifdlst.
  • Print all the elements from a given list that appears more than once.
  • The Exit of the Program.

Below is the implementation:

# Import the Counter() function from collections using the import keyword.
from collections import Counter
# Give the list as static input and store it in a variable.
gvnlst = [20, 30, 40, 50, 20, 50]
# Calculate the frequency of all the given list elements using the Counter()
# function which returns the element and its frequency as key-value pair
# and store this dictionary in a variable(say freqncyDictionary)
freqncyDictionary = Counter(gvnlst)
# Take a new empty list say modifdlst and store it in a variable.
modifdlst = []
# Loop in the above calculated frequency dictionary using the For loop
for key in freqncyDictionary:
  # Check if the key in the freqncyDictionary having value greater than 1
  # using the if conditional statement.

    if(freqncyDictionary[key] > 1):
      # If it is true then append the key value to the above declared empty list modifdlst.
        modifdlst.append(key)
# Print all the elements from a given list that appears more than once.
print("The Elements from a given list", gvnlst,
      "that appears more than once : ")
print(*modifdlst)

Output:

The Elements from a given list [20, 30, 40, 50, 20, 50] that appears more than once : 
20 50

Method #4: Using Counter() function (Hashing, User Input)

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the list as user input using the list(),map(),split(),int functions and store it in a variable.
  • Calculate the frequency of all the given list elements using the Counter() function which returns the element and its frequency as key-value pair and store this dictionary in a variable(say freqncyDictionary)
  • Take a new empty list say modifdlst and store it in a variable.
  • Loop in the above-calculated frequency dictionary using the For loop
  • Check if the key in the freqncyDictionary having a value greater than 1 using the if conditional statement.
  • If it is true then append the key value to the above declared empty list modifdlst.
  • Print all the elements from a given list that appears more than once.
  • The Exit of the Program.

Below is the implementation:

# Import the Counter() function from collections using the import keyword.
from collections import Counter
# Give the list as user input using the list(),map(),split(),int functions
# and store it in a variable.
gvnlst = list(
    map(int, input('Enter some random list element separated by spaces = ').split()))
# Calculate the frequency of all the given list elements using the Counter()
# function which returns the element and its frequency as key-value pair
# and store this dictionary in a variable(say freqncyDictionary)
freqncyDictionary = Counter(gvnlst)
# Take a new empty list say modifdlst and store it in a variable.
modifdlst = []
# Loop in the above calculated frequency dictionary using the For loop
for key in freqncyDictionary:
  # Check if the key in the freqncyDictionary having value greater than 1
  # using the if conditional statement.

    if(freqncyDictionary[key] > 1):
      # If it is true then append the key value to the above declared empty list modifdlst.
        modifdlst.append(key)
# Print all the elements from a given list that appears more than once.
print("The Elements from a given list", gvnlst,
      "that appears more than once : ")
print(*modifdlst)

Output:

Enter some random list element separated by spaces = 1 2 4 4 2 3 6 1
The Elements from a given list [1, 2, 4, 4, 2, 3, 6, 1] that appears more than once : 
1 2 4

Access the big list of Python Programming Code Examples with actual logical code asked in Programming and Coding Interviews for Python and stand out from the crowd.

Python Program for Array/List Elements that Appear More than Once Read More »

Program to Remove String Elements that Appear Strictly Less than k Times

Python Program to Remove String Elements that Appear Strictly Less than k Times

In the previous article, we have discussed Python Program to Remove Characters that Appear More than k Times

Given a string, K value and the task is to remove all the characters from the given string that appears strictly less than k times.

Examples:

Example1:

Input:

Given String = "hellobtechgeekssss "
Given k value = 2

Output:

The given string { hellobtechgeekssss } after removal of all characters that appears more than k{ 2 } times : helleheessss

Example2:

Input:

Given String = "gooodmorningallll "
Given k value= 3

Output:

The given string { gooodmorningallll } after removal of all characters that appears more than k{ 3 } times : oooollll

Program to Remove Elements that Appear Strictly Less than k Times in Python

Below are the ways to remove all the characters from the given string that appears strictly less than k times:

Method #1: Using Dictionary (Hashing, Static Input)

Approach:

  • Take a dictionary and initialize it to empty using the {} or dict() say freqncyDictionary.
  • Give the string as static input and store it in a variable.
  • Loop in the given string using the For loop.
  • Inside the For loop, Check if the string character is present in the dictionary or not using the if conditional statement and ‘in’ keyword.
  • If it is true then increment the count of the string character in the dictionary by 1.
  • Else initialize the dictionary with the string character as key and value as 1.
  • Give the k value as static input and store it in a variable.
  • Take a string that stores all the characters which are not occurring even a number of times and initialize it to null string using “or str()
  • loop in the given string using the for loop.
  • Check if the character has a frequency greater than or equal to k by checking the value of that character in the frequency dictionary.
  • we check using the if conditional statement
  • If it is true then concatenate this character to modifd_string using string concatenation.
  • Print the modifd_string string.
  • The Exit of the Program.

Below is the implementation:

# Take a dictionary and initialize it to empty
# using the {} or dict() say freqncyDictionary.
freqncyDictionary = {}
# Give the string as static input and store it in a variable
gvnstrng = "hellobtechgeekssss"
# Loop in the given string using the For loop.
for i in gvnstrng:
        # Inside the For loop,
    # Check if the string character is present in the dictionary
    # or not using the if conditional statement and 'in' keyword.
    if i in freqncyDictionary.keys():
                # If it is true then increment the count of the string character
        # in the dictionary by 1.
        freqncyDictionary[i] = freqncyDictionary[i]+1
    # Else initialize the dictionary with the string character as key and value as 1.
    else:
        freqncyDictionary[i] = 1
# Give the k value as static input and store it in a variable.
k = 2
# Take a string which stores all the characters which are not occuring even number
# of times and initialize it to null string using "" or str()
modifd_string = ""
# loop in the given string using the for loop
for charac in gvnstrng:

        # check if the character has frequency greater than or equal to k by checking value of that character in frequency dictionary
        # we check using the if conditional statement
    if(freqncyDictionary[charac] >= k):
        # if it is true then concatenate this character to modifd_string using string concatenation
        modifd_string = modifd_string+charac

# print the modifd_string string
print('The given string {', gvnstrng,
      '} after removal of all characters that appears more than k{', k, '} times :', modifd_string)

Output:

The given string { hellobtechgeekssss } after removal of all characters that appears more than k{ 2 } times : helleheessss

Method #2: Using Dictionary (Hashing, User Input)

Approach:

  • Take a dictionary and initialize it to empty using the {} or dict() say freqncyDictionary.
  • Give the string as the user input using the input() function and store it in a variable.
  • Loop in the given string using the For loop.
  • Inside the For loop, Check if the string character is present in the dictionary or not using the if conditional statement and ‘in’ keyword.
  • If it is true then increment the count of the string character in the dictionary by 1.
  • Else initialize the dictionary with the string character as key and value as 1.
  • Give the k value as user input using the int(input()) function and store it in a variable.
  • Take a string that stores all the characters which are not occurring even a number of times and initialize it to null string using “or str()
  • loop in the given string using the for loop.
  • Check if the character has a frequency greater than or equal to k by checking the value of that character in the frequency dictionary.
  • we check using the if conditional statement
  • If it is true then concatenate this character to modifd_string using string concatenation.
  • Print the modifd_string string.
  • The Exit of the Program.

Below is the implementation:

# Take a dictionary and initialize it to empty
# using the {} or dict() say freqncyDictionary.
freqncyDictionary = {}
# Give the string as the user input using the input() function and store it in a variable.
gvnstrng = input("Enter some random string = ")
# Loop in the given string using the For loop.
for i in gvnstrng:
        # Inside the For loop,
    # Check if the string character is present in the dictionary
    # or not using the if conditional statement and 'in' keyword.
    if i in freqncyDictionary.keys():
                # If it is true then increment the count of the string character
        # in the dictionary by 1.
        freqncyDictionary[i] = freqncyDictionary[i]+1
    # Else initialize the dictionary with the string character as key and value as 1.
    else:
        freqncyDictionary[i] = 1
# Give the k value as user input using the int(input()) function and store it in a variable.
k = int(input("Enter some random number ="))
# Take a string which stores all the characters which are not occuring even number
# of times and initialize it to null string using "" or str()
modifd_string = ""
# loop in the given string using the for loop
for charac in gvnstrng:

        # check if the character has frequency greater than or equal to k by checking value of that character in frequency dictionary
        # we check using the if conditional statement
    if(freqncyDictionary[charac] >= k):
        # if it is true then concatenate this character to modifd_string using string concatenation
        modifd_string = modifd_string+charac

# print the modifd_string string
print('The given string {', gvnstrng,
      '} after removal of all characters that appears more than k{', k, '} times :', modifd_string)

Output:

Enter some random string = gooodmorningallll
Enter some random number =3
The given string { gooodmorningallll } after removal of all characters that appears more than k{ 3 } times : oooollll

Method #3: Using Counter() function (Hashing, Static Input)

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the string as static input and store it in a variable
  • Calculate the frequency of all the given string characters using the Counter() function which returns the element and its frequency as key-value pair  and store this dictionary in a variable(say freqncyDictionary)
  • Give the k value as static input and store it in a variable.
  • Take a string that stores all the characters which are not occurring even a number of times and initialize it to null string using “or str()
  • loop in the given string using the for loop.
  • Check if the character has a frequency greater than or equal to k by checking the value of that character in the frequency dictionary.
  • we check using the if conditional statement
  • If it is true then concatenate this character to modifd_string using string concatenation.
  • Print the modifd_string string.
  • The Exit of the Program.

Below is the implementation:

# Import the Counter() function from collections using the import keyword.
from collections import Counter
# Give the string as static input and store it in a variable
gvnstrng = "hellobtechgeekssss "
# Calculate the frequency of all the given string characters using the Counter()
# function which returns the element and its frequency as key-value pair
# and store this dictionary in a variable(say freqncyDictionary)
freqncyDictionary = Counter(gvnstrng)
# Give the k value as static input and store it in a variable.
k = 2
# Take a string which stores all the characters which are not occuring even number
# of times and initialize it to null string using "" or str()
modifd_string = ""
# loop in the given string using the for loop
for charac in gvnstrng:

        # check if the character has frequency greater than or equal to k by checking value of that character in frequency dictionary
        # we check using the if conditional statement
    if(freqncyDictionary[charac] >= k):
        # if it is true then concatenate this character to modifd_string using string concatenation
        modifd_string = modifd_string+charac

# print the modifd_string string
print('The given string {', gvnstrng,
      '} after removal of all characters that appears more than k{', k, '} times :', modifd_string)

Output:

The given string { hellobtechgeekssss  } after removal of all characters that appears more than k{ 2 } times : helleheessss

Method #4: Using Counter() function (Hashing, User Input)

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the string as the user input using the input() function and store it in a variable.
  • Calculate the frequency of all the given string characters using the Counter() function which returns the element and its frequency as key-value pair  and store this dictionary in a variable(say freqncyDictionary)
  • Give the k value as user input using the int(input()) function and store it in a variable.
  • Take a string that stores all the characters which are not occurring even a number of times and initialize it to null string using “or str()
  • loop in the given string using the for loop.
  • Check if the character has a frequency greater than or equal to k by checking the value of that character in the frequency dictionary.
  • we check using the if conditional statement
  • If it is true then concatenate this character to modifd_string using string concatenation.
  • Print the modifd_string string.
  • The Exit of the Program.

Below is the implementation:

# Import the Counter() function from collections using the import keyword.
from collections import Counter
# Give the string as the user input using the input() function and store it in a variable.
gvnstrng = input("Enter some random string = ")
# Calculate the frequency of all the given string characters using the Counter()
# function which returns the element and its frequency as key-value pair
# and store this dictionary in a variable(say freqncyDictionary)
freqncyDictionary = Counter(gvnstrng)
# Give the k value as user input using the int(input()) function and store it in a variable.
k = int(input("Enter some random number ="))
# Take a string which stores all the characters which are not occuring even number
# of times and initialize it to null string using "" or str()
modifd_string = ""
# loop in the given string using the for loop
for charac in gvnstrng:

        # check if the character has frequency greater than or equal to k by checking value of that character in frequency dictionary
        # we check using the if conditional statement
    if(freqncyDictionary[charac] >= k):
        # if it is true then concatenate this character to modifd_string using string concatenation
        modifd_string = modifd_string+charac

# print the modifd_string string
print('The given string {', gvnstrng,
      '} after removal of all characters that appears more than k{', k, '} times :', modifd_string)

Output:

Enter some random string = gooodmorningallll
Enter some random number =3
The given string { gooodmorningallll } after removal of all characters that appears more than k{ 3 } times : oooollll

The best way to learn Python for Beginners is to practice as much as they can taking help of the Sample Python Programs For Beginners. Using them you can develop code on your own and master coding skills.

Python Program to Remove String Elements that Appear Strictly Less than k Times Read More »

Program to Remove Elements from the ArrayList Which Occurs More than k Times

Python Program to Remove Elements from the Array/List Which Occurs More than k Times

In the previous article, we have discussed Python Program to Delete All Odd Frequency Elements from an Array/List

Given a list, k value and the task is to delete all the elements from a given list that appears more than k times in python.

Examples:

Example1:

Input:

Given List = [4, 5, 8, 9, 4, 6, 3, 3, 3]
Given k value = 2

Output:

The list [4, 5, 8, 9, 4, 6, 3, 3, 3] after deletion all the elements from a given list that appears more than k times:
[4, 5, 8, 9, 4, 6]

Example2:

Input:

Given List = [5, 6, 8, 1, 5, 6, 1, 1, 1]
Given k value = 3

Output:

The list [5, 6, 8, 1, 5, 6, 1, 1, 1] after deletion all the elements from a given list that appears more than k times:
[5, 6, 8, 5, 6]

Program to Remove Elements from the Array/List Which Occurs More than k Times in Python

Below are the ways to delete all the elements from a given list that appear more than k times in python:

Method #1: Using Dictionary (Hashing, Static Input)

Approach:

  • Take a dictionary and initialize it to empty using the {} or dict() say freqncyDictionary.
  • Give the list as static input and store it in a variable.
  • Loop in the given list using the For loop.
  • Inside the For loop, Check if the list element is present in the dictionary or not using the if conditional statement and ‘in‘ keyword.
  • If it is true then increment the count of the list element in the dictionary by 1.
  • Else initialize the dictionary with the list element as key and value as 1.
  • Give the k value as static input and store it in a variable.
  • Take a new empty list say modifdlst and store it in a variable.
  • Loop in the given list using the For loop.
  • Check if the key in the freqncyDictionary having a value less than or equal to k using the if conditional statement.
  • If it is true then append the key value to the above declared empty list modifdlst.
  • Print the list after deletion of all the elements from a given list that appears more than k times
  • The Exit of the Program.

Below is the implementation:

# Take a dictionary and initialize it to empty
# using the {} or dict() say freqncyDictionary.
freqncyDictionary = {}
# Give the list as static input and store it in a variable.
gvnlst = [4, 5, 8, 9, 4, 6, 3, 3, 3]
# Loop in the given list using the For loop.
for i in gvnlst:
        # Inside the For loop,
    # Check if the list element is present in the dictionary
    # or not using the if conditional statement and 'in' keyword.
    if i in freqncyDictionary.keys():
                # If it is true then increment the count of the list element
        # in the dictionary by 1.
        freqncyDictionary[i] = freqncyDictionary[i]+1
    # Else initialize the dictionary with the list element as key and value as 1.
    else:
        freqncyDictionary[i] = 1
# Give the k value as static input and store it in a variable.
k = 2
# Take a new empty list say modifdlst and store it in a variable.
modifdlst = []
# Loop in the given list using the For loop.
for lstelmt in gvnlst:
  # Check if the key in the freqncyDictionary having value less than or equal to k
  # using the if conditional statement.

    if(freqncyDictionary[lstelmt] <= k):
      # If it is true then append the key value to the above declared empty list modifdlst.
        modifdlst.append(lstelmt)
# Print the list after deletion of all the elements from a given list that appears
# more than k times
print("The list", gvnlst,
      "after deletion all the elements from a given list that appears more than k times:")
print(modifdlst)

Output:

The list [4, 5, 8, 9, 4, 6, 3, 3, 3] after deletion all the elements from a given list that appears more than k times:
[4, 5, 8, 9, 4, 6]

Method #2: Using Dictionary (Hashing, User Input)

Approach:

  • Take a dictionary and initialize it to empty using the {} or dict() say freqncyDictionary.
  • Give the list as user input using the list(),map(),split(),int functions and store it in a variable.
  • Loop in the given list using the For loop.
  • Inside the For loop, Check if the list element is present in the dictionary or not using the if conditional statement and ‘in‘ keyword.
  • If it is true then increment the count of the list element in the dictionary by 1.
  • Else initialize the dictionary with the list element as key and value as 1.
  • Give the k value as user input using the int(input()) function and store it in a variable.
  • Take a new empty list say modifdlst and store it in a variable.
  • Loop in the given list using the For loop.
  • Check if the key in the freqncyDictionary having a value less than or equal to k using the if conditional statement.
  • If it is true then append the key value to the above declared empty list modifdlst.
  • Print the list after deletion of all the elements from a given list that appears more than k times
  • The Exit of the Program.

Below is the implementation:

# Take a dictionary and initialize it to empty
# using the {} or dict() say freqncyDictionary.
freqncyDictionary = {}
# Give the list as user input using the list(),map(),split(),int functions
# and store it in a variable.
gvnlst = list(
    map(int, input('Enter some random list element separated by spaces = ').split()))
# Loop in the given list using the For loop.
for i in gvnlst:
        # Inside the For loop,
    # Check if the list element is present in the dictionary
    # or not using the if conditional statement and 'in' keyword.
    if i in freqncyDictionary.keys():
                # If it is true then increment the count of the list element
        # in the dictionary by 1.
        freqncyDictionary[i] = freqncyDictionary[i]+1
    # Else initialize the dictionary with the list element as key and value as 1.
    else:
        freqncyDictionary[i] = 1
# Give the k value as user input using the int(input()) function and store it in a variable.
k = int(input("Enter some random number ="))
# Take a new empty list say modifdlst and store it in a variable.
modifdlst = []
# Loop in the given list using the For loop.
for lstelmt in gvnlst:
  # Check if the key in the freqncyDictionary having value less than or equal to k
  # using the if conditional statement.

    if(freqncyDictionary[lstelmt] <= k):
      # If it is true then append the key value to the above declared empty list modifdlst.
        modifdlst.append(lstelmt)
# Print the list after deletion of all the elements from a given list that appears
# more than k times
print("The list", gvnlst,
      "after deletion all the elements from a given list that appears more than k times:")
print(modifdlst)

Output:

Enter some random list element separated by spaces = 3 1 5 6 1 2 2
Enter some random number =1
The list [3, 1, 5, 6, 1, 2, 2] after deletion all the elements from a given list that appears more than k times:
[3, 5, 6]

Method #3: Using Counter() function (Hashing, Static Input)

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the list as static input and store it in a variable.
  • Calculate the frequency of all the given list elements using the Counter() function which returns the element and its frequency as key-value pair and store this dictionary in a variable(say freqncyDictionary)
  • Give the k value as static input and store it in a variable.
  • Take a new empty list say modifdlst and store it in a variable.
  • Loop in the given list using the For loop.
  • Check if the key in the freqncyDictionary having a value less than or equal to k using the if conditional statement.
  • If it is true then append the key value to the above declared empty list modifdlst.
  • Print the list after deletion of all the elements from a given list that appears more than k times
  • The Exit of the Program

Below is the implementation:

# Import the Counter() function from collections using the import keyword.
from collections import Counter
# Give the list as static input and store it in a variable.
gvnlst = [5, 6, 8, 1, 5, 6, 1, 1, 1]
# Calculate the frequency of all the given list elements using the Counter()
# function which returns the element and its frequency as key-value pair
# and store this dictionary in a variable(say freqncyDictionary)
freqncyDictionary = Counter(gvnlst)
# Give the k value as static input and store it in a variable.
k = 3
# Take a new empty list say modifdlst and store it in a variable.
modifdlst = []
# Loop in the given list using the For loop.
for lstelmt in gvnlst:
  # Check if the key in the freqncyDictionary having value less than or equal to k
  # using the if conditional statement.

    if(freqncyDictionary[lstelmt] <= k):
      # If it is true then append the key value to the above declared empty list modifdlst.
        modifdlst.append(lstelmt)
# Print the list after deletion of all the elements from a given list that appears
# more than k times
print("The list", gvnlst,
      "after deletion all the elements from a given list that appears more than k times:")
print(modifdlst)

Output:

The list [5, 6, 8, 1, 5, 6, 1, 1, 1] after deletion all the elements from a given list that appears more than k times:
[5, 6, 8, 5, 6]

Method #4: Using Counter() function (Hashing, User Input)

Approach:

  • Import the Counter() function from collections using the import keyword.
  • Give the list as user input using the list(),map(),split(),int functions and store it in a variable.
  • Calculate the frequency of all the given list elements using the Counter() function which returns the element and its frequency as key-value pair and store this dictionary in a variable(say freqncyDictionary)
  • Give the k value as user input using the int(input()) function and store it in a variable.
  • Take a new empty list say modifdlst and store it in a variable.
  • Loop in the given list using the For loop.
  • Check if the key in the freqncyDictionary having a value less than or equal to k using the if conditional statement.
  • If it is true then append the key value to the above declared empty list modifdlst.
  • Print the list after deletion of all the elements from a given list that appears more than k times
  • The Exit of the Program.

Below is the implementation:

# Import the Counter() function from collections using the import keyword.
from collections import Counter
# Give the list as user input using the list(),map(),split(),int functions
# and store it in a variable.
gvnlst = list(
    map(int, input('Enter some random list element separated by spaces = ').split()))
# Calculate the frequency of all the given list elements using the Counter()
# function which returns the element and its frequency as key-value pair
# and store this dictionary in a variable(say freqncyDictionary)
freqncyDictionary = Counter(gvnlst)
# Give the k value as user input using the int(input()) function and store it in a variable.
k = int(input("Enter some random number ="))
# Take a new empty list say modifdlst and store it in a variable.
modifdlst = []
# Loop in the given list using the For loop.
for lstelmt in gvnlst:
  # Check if the key in the freqncyDictionary having value less than or equal to k
  # using the if conditional statement.

    if(freqncyDictionary[lstelmt] <= k):
      # If it is true then append the key value to the above declared empty list modifdlst.
        modifdlst.append(lstelmt)
# Print the list after deletion of all the elements from a given list that appears
# more than k times
print("The list", gvnlst,
      "after deletion all the elements from a given list that appears more than k times:")
print(modifdlst)

Output:

Enter some random list element separated by spaces = 3 1 5 6 1 2 2
Enter some random number =1
The list [3, 1, 5, 6, 1, 2, 2] after deletion all the elements from a given list that appears more than k times:
[3, 5, 6]

Enhance your coding skills with our list of Python Basic Programs provided and become a pro in the general-purpose programming language Python in no time.

Python Program to Remove Elements from the Array/List Which Occurs More than k Times Read More »