Author name: Vikram Chiluka

Program to find Maximum Product Quadruple in an Array or List

Python Program to find Maximum Product Quadruple in an Array or List

Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

Given a list, the task is to write a python program to find the Maximum Product Quadruple in the given array or list in Python.

Examples:

Example1:

Input:

Given list =[-9, -24, 15, 3, 19, 23, 18, 11, 10, 7, 6]

Output:

The maximum product quadruple in the given list [-9, -24, 15, 3, 19, 23, 18, 11, 10, 7, 6] is :
[ 117990 ]

Example2:

Input:

Given list =[8, 11, 4, 6, 9, -7, 22, 9, 15]

Output:

The maximum product quadruple in the given list [8, 11, 4, 6, 9, -7, 22, 9, 15] is :
[ 32670 ]

Program to find Maximum Product Quadruple in an Array or List in Python

Below are the ways to find the Maximum Product Quadruple in the given array or list in Python.

Method #1: Using Sorting (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Sort the given list in ascending order using the built-in sort() function.
  • Find the product of the last four elements in the above-sorted list and store it in a variable maxproduct1.
  • Find the product of the first four elements in the above-sorted list and store it in a variable maxproduct2.
  • Find the product of the first two elements and last two elements in the above-sorted list and store it in a variable maxproduct3.
  • Find the maximum value of the above three variables maxproduct1,maxproduct2,maxproduct3 using the max() function.
  • Print the maximum product.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvnlist = [-9, -24, 15, 3, 19, 23, 18, 11, 10, 7, 6]
print('The maximum product quadruple in the given list', gvnlist, 'is :')
# Sort the given list in ascending order using the built-in sort() function.
gvnlist.sort()
# Find the product of the last four elements in the above-sorted list
# and store it in a variable maxproduct1.
maxproduct1 = gvnlist[-1]*gvnlist[-2]*gvnlist[-3]*gvnlist[-4]
# Find the product of the first four elements in the above-sorted list
# and store it in a variable
maxproduct2 = gvnlist[0]*gvnlist[1]*gvnlist[2]*gvnlist[3]
# Find the product of the first two elements and last two elements
# in the above-sorted list and store it in a variable maxproduct3.
maxproduct3 = gvnlist[0]*gvnlist[1]*gvnlist[-1]*gvnlist[-2]
# Find the maximum value of the above three variables
# maxproduct1,maxproduct2,maxproduct3 using the max() function.
maxproductval = max(maxproduct1, maxproduct2, maxproduct3)
# Print the maximum product.
print('[', maxproductval, ']')

Output:

The maximum product quadruple in the given list [-9, -24, 15, 3, 19, 23, 18, 11, 10, 7, 6] is :
[ 117990 ]

Time complexity: O(n*logn) where n is the length of the given list.

Method #2: Using Sorting (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Sort the given list in ascending order using the built-in sort() function.
  • Find the product of the last four elements in the above-sorted list and store it in a variable maxproduct1.
  • Find the product of the first four elements in the above-sorted list and store it in a variable maxproduct2.
  • Find the product of the first two elements and last two elements in the above-sorted list and store it in a variable maxproduct3.
  • Find the maximum value of the above three variables maxproduct1,maxproduct2,maxproduct3 using the max() function.
  • Print the maximum product.
  • The Exit of the Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
# Store it in a variable.
gvnlist = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))
print('The maximum product quadruple in the given list', gvnlist, 'is :')
# Sort the given list in ascending order using the built-in sort() function.
gvnlist.sort()
# Find the product of the last four elements in the above-sorted list
# and store it in a variable maxproduct1.
maxproduct1 = gvnlist[-1]*gvnlist[-2]*gvnlist[-3]*gvnlist[-4]
# Find the product of the first four elements in the above-sorted list
# and store it in a variable
maxproduct2 = gvnlist[0]*gvnlist[1]*gvnlist[2]*gvnlist[3]
# Find the product of the first two elements and last two elements
# in the above-sorted list and store it in a variable maxproduct3.
maxproduct3 = gvnlist[0]*gvnlist[1]*gvnlist[-1]*gvnlist[-2]
# Find the maximum value of the above three variables
# maxproduct1,maxproduct2,maxproduct3 using the max() function.
maxproductval = max(maxproduct1, maxproduct2, maxproduct3)
# Print the maximum product.
print('[', maxproductval, ']')

Output:

Enter some random List Elements separated by spaces = 8 11 4 6 9 -7 22 9 15
The maximum product quadruple in the given list [8, 11, 4, 6, 9, -7, 22, 9, 15] is :
[ 32670 ]

Time complexity: O(n*logn) where n is the length of the given list.
Related Programs:

Python Program to find Maximum Product Quadruple in an Array or List Read More »

Program to Find a Pair with a Minimum Absolute Sum in an List

Python Program to Find a Pair with a Minimum Absolute Sum in an List

Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Lists in Python:

Lists are one of Python’s most commonly used built-in data structures. You can make a list by putting all of the elements inside square brackets[ ] and separating them with commas. Lists can include any type of object, making them extremely useful and adaptable.

Examples:

Example1:

Input:

given list =[1, 12, 7, 10, 11, 13, 5, 4, 8, 4, 9, 3, 6, 5, 21, 8, 9]

Output:

The pair with minimum absolute sum in the given list [1, 12, 7, 10, 11, 13, 5, 4, 8, 4, 9, 3, 6, 5, 21, 8, 9]
1 3

Example2:

Input:

given list = [11, 23, 78, 5, 19, 23, 9, 78, 123]

Output:

The pair with minimum absolute sum in the given list [11, 23, 78, 5, 19, 23, 9, 78, 123]
5 9

Given a list, the task is to search a pair with the minimum absolute sum in the given list in Python.

Program to Find a pair with a minimum absolute sum in a List in Python

Below is the full approach for finding a pair with the minimum absolute sum in the given list in Python.

1)Using While loop(Static Input)

Idea:

The aim is to keep search space by keeping two indexes (low and high) that originally point to two array endpoints. Then, if low is smaller than high, loop and decrease the search space list[low…high] at each loop iteration by comparing the sum of elements existing at low and high indexes with 0. If the total is less than zero, we increment the index low otherwise, we decrement index high if the sum is greater than zero. We also save the smallest absolute difference between all pairings present at low and high indexes.

Input:

Give the list as static input and store it in a variable.

Pass the given list to the findMinAbsSum function as an argument.

Print then pair which is having Minimum Absolute Sum in a given List.

The Exit of the Program.

Below is the implementation:

import sys
# Function which accepts the given list as argument
# which returns the pair in a list with an absolute minimum sum


def findMinAbsSum(given_list):

    if len(given_list) < 2:
        return
    print("The pair with minimum absolute sum in the given list", given_list)
    # sort the given list if it is unsorted using sort() function
    given_list.sort()
    # keep two indexes pointing to the list's ends
    (lowptr, highptr) = (0, len(given_list) - 1)

    # minsum keeps track of the smallest absolute difference.
    minsum = sys.maxsize
    i = j = 0

    # At each loop iteration, lower the search space given list[lowptr...highptr].

    # If lowptr is less than highptr, loop using while loop
    while lowptr < highptr:
        # If the current absolute sum is less than the minimum, it will be updated.
        if abs(given_list[highptr] + given_list[lowptr]) < minsum:
            minsum = abs(given_list[highptr] + given_list[lowptr])
            (i, j) = (lowptr, highptr)

        # Optimization: A pair with a zero-sum value is identified.
        if minsum == 0:
            break

        # f the sum is less than 0, increase the lowptr index.
        # If the total exceeds 0, reduce the highptr index.
        if given_list[highptr] + given_list[lowptr] < 0:
            lowptr = lowptr + 1
        else:
            highptr = highptr - 1

    # printing the pair
    print(given_list[i], given_list[j])


# Driver Code
# Give the list as static input and store it in a variable.
given_list = [1, 12, 7, 10, 11, 13, 5, 4, 8, 4, 9, 3, 6, 5, 21, 8, 9]
# pass the given list as an argument to the findMinAbsSum function.
findMinAbsSum(given_list)

Output:

The pair with minimum absolute sum in the given list [1, 12, 7, 10, 11, 13, 5, 4, 8, 4, 9, 3, 6, 5, 21, 8, 9]
1 3

2)Using While loop(User Input)

Idea:

The aim is to keep search space by keeping two indexes (low and high) that originally point to two array endpoints. Then, if low is smaller than high, loop and decrease the search space list[low…high] at each loop iteration by comparing the sum of elements existing at low and high indexes with 0. If the total is less than zero, we increment the index low otherwise, we decrement index high if the sum is greater than zero. We also save the smallest absolute difference between all pairings present at low and high indexes.

Input:

Give the list as user input using map(), split(), and list functions and store it in a variable.

Pass the given list to the findMinAbsSum function as an argument.

Print then pair which is having Minimum Absolute Sum in a given List.

The Exit of the Program.

Below is the implementation:

import sys
# Function which accepts the given list as argument
# which returns the pair in a list with an absolute minimum sum


def findMinAbsSum(given_list):

    if len(given_list) < 2:
        return
    print("The pair with minimum absolute sum in the given list", given_list)
    # sort the given list if it is unsorted using sort() function
    given_list.sort()
    # keep two indexes pointing to the list's ends
    (lowptr, highptr) = (0, len(given_list) - 1)

    # minsum keeps track of the smallest absolute difference.
    minsum = sys.maxsize
    i = j = 0

    # At each loop iteration, lower the search space given list[lowptr...highptr].

    # If lowptr is less than highptr, loop using while loop
    while lowptr < highptr:
        # If the current absolute sum is less than the minimum, it will be updated.
        if abs(given_list[highptr] + given_list[lowptr]) < minsum:
            minsum = abs(given_list[highptr] + given_list[lowptr])
            (i, j) = (lowptr, highptr)

        # Optimization: A pair with a zero-sum value is identified.
        if minsum == 0:
            break

        # f the sum is less than 0, increase the lowptr index.
        # If the total exceeds 0, reduce the highptr index.
        if given_list[highptr] + given_list[lowptr] < 0:
            lowptr = lowptr + 1
        else:
            highptr = highptr - 1

    # printing the pair
    print(given_list[i], given_list[j])


# Driver Code
# Give the list as user input using map(), split(), and list
# functions and store it in a variable.
given_list = list(map(int, input(
    'Enter some random elements to the list separated by spaces = ').split()))
# pass the given list as an argument to the findMinAbsSum function.
findMinAbsSum(given_list)

Output:

Enter some random elements to the list separated by spaces = 11 23 78 5 19 23 9 78 123
The pair with minimum absolute sum in the given list [11, 23, 78, 5, 19, 23, 9, 78, 123]
5 9

Related Programs:

Python Program to Find a Pair with a Minimum Absolute Sum in an List Read More »

Python Program to Left Rotate a List by R Times

Practice Java programming from home without using any fancy software just by tapping on this Simple Java Programs for Beginners tutorial.

Left Rotation of a List:

An array’s elements are shifted to the left when it is rotated to the left, as demonstrated in the image below. Left rotation involves rotating the array’s elements clockwise to the provided number of places.

Examples:

Example1:

Input:

given list =[11, 28, 9, 7, 6, 1, 3, 4, 19]
number of positions = 3

Output:

The list before rotating 3 times = [11, 28, 9, 7, 6, 1, 3, 4, 19] 
The list after rotating 3 times : [7, 6, 1, 3, 4, 19, 11, 28, 9]

Example2:

Input:

given list = ['hello', 'this', 'is', 'the', 'btechgeeks']
number of positions = 2

Output:

The list before rotating 2 times = ['hello', 'this', 'is', 'the', 'btechgeeks']
The list after rotating 2 times : ['is', 'the', 'btechgeeks', 'hello', 'this']

Program to Left Rotate a List by r Times in Python

There are several ways to left rotate the given list by r times in Python some of them are:

Method #1:Using Indexing(Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Give the number of rotations r as static input and store it in another variable.
  • Pass the given list and number of rotations as arguments to the leftRotateList function which rotates the given list to the left by r positions.
  • Use for loop to loop r times.
  • Pass the given list to the LeftRotateOne function inside the for loop which rotates the list to the left one time.
  • In this way, we rotate the given list to the left r times.
  • The Exit of the Program.

Below is the implementation:

# function which accepts the giveen list as argument
# and rotates the given list to the lefy by one time


def leftRotateByOne(given_list):
    # intializing first variablee to the first element of the given list
    firstval = given_list[0]
    # traversing length of given list -1 times using for loop
    for i in range(len(given_list) - 1):
      # initializing every element with the next element
        given_list[i] = given_list[i + 1]
    # intializing last value to the first valuee of the given list
    given_list[-1] = firstval


# function which accepts the given list and number
# of positions as arguments and rotate the given list r times here r=positions
def leftRotateList(given_list, positions):
    # Pass the given list to the LeftRotateOne function inside the
    # for loop which rotates the list to the left one time.
    for numb in range(positions):
        leftRotateByOne(given_list)


# Driver Code
# Give the list as static input and store it in a variable.
given_list = [9, 1, 3, 10, 47, 19, 43]
print('The list before rotating r times = ', given_list)
# Give the number of rotations r as static input and store it in another variable.
positions = 4
# Pass the given list and number of rotations as arguments to the leftRotateList function
# which rotates the given list to the left by r positions.
leftRotateList(given_list, positions)
# print the list after rotating to the left r times
print('The list after rotating r times : ', given_list)
print(given_list)

Output:

The list before rotating r times =  [9, 1, 3, 10, 47, 19, 43]
The list after rotating r times :  [47, 19, 43, 9, 1, 3, 10]

The above solution has a time complexity of, where n is the size of the input and r is the number of rotations.

Method #2:Using Indexing(User Input)

i)Integer List

Approach:

  • Give the integer list as user input using map(),split(),list() and int functions.
  • Store it in a variable.
  • Give the number of rotations r as user input using int(input()) and store it in another variable.
  • Pass the given list and number of rotations as arguments to the leftRotateList function which rotates the given list to the left by r positions.
  • Use for loop to loop r times.
  • Pass the given list to the LeftRotateOne function inside the for loop which rotates the list to the left one time.
  • In this way, we rotate the given list to the left r times.
  • The Exit of the Program.

Below is the implementation:

# function which accepts the giveen list as argument
# and rotates the given list to the lefy by one time


def leftRotateByOne(given_list):
    # intializing first variablee to the first element of the given list
    firstval = given_list[0]
    # traversing length of given list -1 times using for loop
    for i in range(len(given_list) - 1):
      # initializing every element with the next element
        given_list[i] = given_list[i + 1]
    # intializing last value to the first valuee of the given list
    given_list[-1] = firstval


# function which accepts the given list and number
# of positions as arguments and rotate the given list r times here r=positions
def leftRotateList(given_list, positions):
    # Pass the given list to the LeftRotateOne function inside the
    # for loop which rotates the list to the left one time.
    for numb in range(positions):
        leftRotateByOne(given_list)


# Driver Code
# Give the list as user input using map(),split(),list() and int functions.
# Store it in a variable. 
given_list = list(
    map(int, input('Enter some random list separated by spaces = ').split()))
print('The list before rotating r times = ', given_list)
# Give the number of rotations r as user input using int(input())
# and store it in another variable.
positions = int(input('Enter some random number of positions = '))
# Pass the given list and number of rotations as arguments to the leftRotateList function
# which rotates the given list to the left by r positions.
leftRotateList(given_list, positions)
# print the list after rotating to the left r times
print('The list after rotating r times : ', given_list)

Output:

Enter some random list separated by spaces = 11 28 9 7 6 1 3 4 19
The list before rotating r times = [11, 28, 9, 7, 6, 1, 3, 4, 19]
Enter some random number of positions = 3
The list after rotating r times : [7, 6, 1, 3, 4, 19, 11, 28, 9]

The above solution has a time complexity of, where n is the size of the input and r is the number of rotations.

ii)String List

Approach:

  • Give the string list as user input using split(),list() functions.
  • Store it in a variable.
  • Give the number of rotations r as user input using int(input()) and store it in another variable.
  • Pass the given list and number of rotations as arguments to the leftRotateList function which rotates the given list to the left by r positions.
  • Use for loop to loop r times.
  • Pass the given list to the LeftRotateOne function inside the for loop which rotates the list to the left one time.
  • In this way, we rotate the given list to the left r times.
  • The Exit of the Program.

Below is the implementation:

# function which accepts the giveen list as argument
# and rotates the given list to the lefy by one time


def leftRotateByOne(given_list):
    # intializing first variablee to the first element of the given list
    firstval = given_list[0]
    # traversing length of given list -1 times using for loop
    for i in range(len(given_list) - 1):
      # initializing every element with the next element
        given_list[i] = given_list[i + 1]
    # intializing last value to the first valuee of the given list
    given_list[-1] = firstval


# function which accepts the given list and number
# of positions as arguments and rotate the given list r times here r=positions
def leftRotateList(given_list, positions):
    # Pass the given list to the LeftRotateOne function inside the
    # for loop which rotates the list to the left one time.
    for numb in range(positions):
        leftRotateByOne(given_list)


# Driver Code
# Give the list as user input using map(),split(),list() and int functions.
# Store it in a variable. 
given_list = list(input('Enter some random list separated by spaces = ').split())
print('The list before rotating r times = ', given_list)
# Give the number of rotations r as user input using int(input())
# and store it in another variable.
positions = int(input('Enter some random number of positions = '))
# Pass the given list and number of rotations as arguments to the leftRotateList function
# which rotates the given list to the left by r positions.
leftRotateList(given_list, positions)
# print the list after rotating to the left r times
print('The list after rotating r times : ', given_list)
print(given_list)

Output:

Enter some random list separated by spaces = hello this is the btechgeeks
The list before rotating r times = ['hello', 'this', 'is', 'the', 'btechgeeks']
Enter some random number of positions = 2
The list after rotating r times : ['is', 'the', 'btechgeeks', 'hello', 'this']

Related Programs:

Python Program to Left Rotate a List by R Times Read More »

Program to Find the Minimum Difference Between the Index of Two Given Elements Present in an Array

Python Program to Find the Minimum Difference Between the Index of Two Given Elements Present in an Array

If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

Lists in Python:

Lists are one of Python’s most commonly used built-in data structures. You can make a list by putting all of the elements inside square brackets[ ] and separating them with commas. Lists can include any type of object, making them extremely useful and adaptable.

Given a list/array, the task is to find the minimum difference between the index of given two elements present in a list in Python.

Examples:

Example1:

Input:

given list =[1, 3, 7, 10, 11, 13, 5, 4, 8, 2, 4, 3, 6, 5, 21, 8, 9]
given first element =2
given second element =5

Output:

The minimum difference between the elements 2 and 5 = 3

Example2:

Input:

given list =[7, 9, 6, 8, 7, 5, 9, 4, 3, 2, 11, 19, 23, 4, 5, 8, 6, 3 ,2, 9, 7,]
given first element =7
given second element =8

Output:

The minimum difference between the elements 7 and 8 = 1

Program to Find the Minimum Difference Between the Index of Two Given Elements Present in an Array in Python

Below is the full approach for finding the minimum difference between the index of given two elements present in a list in Python.

Method #1:Using min() function,For loop and If statements(Static Input)

Idea:

The intention is to traverse the array and maintain track of the most recent occurrences of x and y.
If the current element is x, calculate the absolute difference between the current index of x and the index of the last occurrence of y and, if necessary, update the result.
If the current element is y, calculate the absolute difference between the current index of y and the index of the last occurrence of x and, if necessary, update the result.

Input:

Give the list as static input and store it in a variable.

Give the two elements as static input and store them in separate variables.

Pass the given list and two elements as arguments to the findMinDiff function.

Print the minimum difference between the given two elements.

The Exit of the Program.

Below is the implementation:

import sys


# function which accepts the given list and the given two elements as arguments
# and return the minimum difference between the given two elements
def findMinDiff(given_list, firstele, secondele):

    firstindex = secondindex = len(given_list)
    min_differ = sys.maxsize

    # traverse the given list
    for i in range(len(given_list)):

        # if the current element is `firstele`
        if given_list[i] == firstele:
            # set `firstindex` to the current index
            firstindex = i

            # if `secondele` is seen before, update the result if required
            if secondindex != len(given_list):
                min_differ = min(min_differ, abs(firstindex - secondindex))

        # if the current element is `secondele`
        if given_list[i] == secondele:
            # set `secondindex` to the current index
            secondindex = i

            # if `firstindex` is seen before, update the result if required
            if firstindex != len(given_list):
                min_differ = min(min_differ, abs(firstindex - secondindex))

    return min_differ


# Driver Code
# Give the list as static input and store it in a variable.

given_list = [1, 3, 7, 10, 11, 13, 5, 4, 8, 2, 4, 3, 6, 5, 21, 8, 9]
# Give the two elements as static input and store them in separate variables.
firstele = 2
secondele = 5
# Pass the given list and two elements as arguments to the findMinDiff function.
miniDifference = findMinDiff(given_list, firstele, secondele)

if miniDifference != sys.maxsize:
    print("The minimum difference between the elements",
          firstele, 'and', secondele, '=', miniDifference)
# if the two elements are not found then the minidifference will
# be sys.maxsize in that case print it as invalid input
else:
    print("Invalid input")

Output:

The minimum difference between the elements 2 and 5 = 3

Method #2:Using min() function,For loop and If statements(User Input)

Idea:

The intention is to traverse the array and maintain track of the most recent occurrences of x and y.
If the current element is x, calculate the absolute difference between the current index of x and the index of the last occurrence of y and, if necessary, update the result.
If the current element is y, calculate the absolute difference between the current index of y and the index of the last occurrence of x and, if necessary, update the result.

Input:

Give the list as user input using map(), split(), and list functions and store it in a variable.

Give the two elements as user input using map(), split() functions, and store them in separate variables.

Pass the given list and two elements as arguments to the findMinDiff function.

Print the minimum difference between the given two elements.

The Exit of the Program.

Below is the implementation:

import sys


# function which accepts the given list and the given two elements as arguments
# and return the minimum difference between the given two elements
def findMinDiff(given_list, firstele, secondele):

    firstindex = secondindex = len(given_list)
    min_differ = sys.maxsize

    # traverse the given list
    for i in range(len(given_list)):

        # if the current element is `firstele`
        if given_list[i] == firstele:
            # set `firstindex` to the current index
            firstindex = i

            # if `secondele` is seen before, update the result if required
            if secondindex != len(given_list):
                min_differ = min(min_differ, abs(firstindex - secondindex))

        # if the current element is `secondele`
        if given_list[i] == secondele:
            # set `secondindex` to the current index
            secondindex = i

            # if `firstindex` is seen before, update the result if required
            if firstindex != len(given_list):
                min_differ = min(min_differ, abs(firstindex - secondindex))

    return min_differ


# Driver Code
# Give the list as user input using map(), split(), and list functions
# and store it in a variable.
given_list = list(map(int, input(
    'Enter some random list elements separated by spaces = ').split()))

# Give the two elements as user input using map(), split() functions,
# and store them in separate variables.
firstele, secondele = map(int, input(
    'Enter some random two elements which are present in the list separated by spaces = ').split())
# Pass the given list and two elements as arguments to the findMinDiff function.
miniDifference = findMinDiff(given_list, firstele, secondele)

if miniDifference != sys.maxsize:
    print("The minimum difference between the elements",
          firstele, 'and', secondele, '=', miniDifference)
# if the two elements are not found then the minidifference will
# be sys.maxsize in that case print it as invalid input
else:
    print("Invalid input")

Output:

Enter some random list elements separated by spaces = 7 9 6 8 7 5 9 4 3 2 11 19 23 4 5 8 6 3 2 9 7
Enter some random two elements which are present in the list separated by spaces = 7 8
The minimum difference between the elements 7 and 8 = 1

Related Programs:

Python Program to Find the Minimum Difference Between the Index of Two Given Elements Present in an Array Read More »

Program to Find the Odd Occurring Element in an Arraylist

Python Program to Find the Odd Occurring Element in an Array/list

Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples

Given a list which contains all duplicate elements (each element occurs even times) except one element we have to find the odd occurring element.

Given a array/list the task is to print the odd occurring element in the given list.

Examples:

Example1:

Input:

given list = [  3 , 5, 4 ,1 ,4 ,8 ,5 , 1 ,3]

Output:

The odd occurring number in the given list 8

Example2:

Input:

given list = [ 1 , 4 ,2 ,4 ,1]

Output:

The odd occurring number in the given list 2

Program to Find the Odd Occurring Element in an Array/list in Python

There are several ways to find the odd occurring element in an array .

The first thought is to run two loops and use the count to determine the frequency of the items.

If the count is one, the element is the odd one out in the specified array/list.

But this approach takes two loops. This approach therefore requires O(n^2) time complexity.

This program is therefore not an efficient way.

We will look at the efficient approaches below.

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 Hashing

We can use hashing to solve this problem in O(n) time for an input containing elements. We start by traversing the array and keeping track of the frequency of each entry in a hash table. Then, after processing each array element, return the element with the odd frequency. The drawback with this strategy is that it also need O(n) more space. It also necessitates one array traverse and one hash table traversal.

Approach:

  • We use the Counter function to count the frequency of all entries in the given list, and it returns a dictionary with the elements as keys and the frequency as values.
  • Traverse the frequency dictionary and check the values of every key in it.
  • If the value is 1 then print the element because it is odd occurring element in the given list
  • Break the loop.

Below is the implementation:

# importing counter from collections
from collections import Counter
# function which returns the odd occuring element in the given list


def findOddNumb(given_list):
    # Calculating the frequency of all elements using Counter() function
    frequency = Counter(given_list)
    # Traversing the frequency dictionary
    for key in frequency:
        # checking the value if it is 1
        if(frequency[key] == 1):
            # return the element
            return key


# Driver code
# given list
given_list = [3, 5, 4, 1, 4, 8, 5, 1, 3]
# passing the given list to findOddNumb  to print the odd occuring number

print("The odd occuring number in the given list", findOddNumb(given_list))

Output:

The odd occurring number in the given list 8

Complexity analysis of the above approach :

Time Complexity : O( n)

Since hashing requires max of O(n) Time Complexity

Space Complexity : O(n)

Since it requires extra space

Method #2:Using XOR(Bitwise Operator)

We can solve this problem during a single traversal of the array and constant space. The idea is to use the XOR operator. We know that if we XOR of a number with itself an odd number of times, the result’s the amount itself; otherwise, if we XOR of a number a even number of times with itself, the result’s 0. Also, the XOR of a number with 0 is usually the amount itself.

So, if we take XOR of all array elements, even appearing elements will cancel each other, and we are left with the only odd appearing element.

Below is the implementation:

# importing counter from collections
from collections import Counter
# function which returns the odd occuring element in the given list


def findOddNumb(given_list):
    # Taking a variable xorEle and initialize it with 0
    xorEle = 0
    # Traversing the given list
    for ele in given_list:
        xorEle = xorEle ^ ele

    # return the odd occuring element
    return xorEle


# Driver code
# given list
given_list = [3, 5, 4, 1, 4, 8, 5, 1, 3]
# passing the given list to findOddNumb  to print the odd occuring number

print("The odd occuring number in the given list", findOddNumb(given_list))

Output:

The odd occurring number in the given list 8

Complexity analysis of the above approach :

Time Complexity : O( n)

Since it requires only one Traversal

Space Complexity : O(1)

Since it doesn’t requires any extra space

Related Programs:

Python Program to Find the Odd Occurring Element in an Array/list Read More »

Program to Find the Minimum Index of a Repeating Element in an ArrayList

Python Program to Find the Minimum Index of a Repeating Element in an Array/List

Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.

Lists in Python:

Lists are one of Python’s most commonly used built-in data structures. You can make a list by putting all of the elements inside square brackets[ ] and separating them with commas. Lists can include any type of object, making them extremely useful and adaptable.

Given a list/array, the task is to find the minimum index of the repeating element in the given list in Python.

Examples:

Example1:

Input:

given list = [8, 12, 38, 7, 1, 9, 19, 11, 45, 62, 57, 18, 12, 32, 45, 7, 1]

Output:

The minimum index of the repeating element of the given list [8, 12, 38, 7, 1, 9, 19, 11, 45, 62, 57, 18, 12, 32, 45, 7, 1] :
 1

Example2:

Input:

given list =[7, 86, 23, 96, 11, 23, 45, 78, 96, 23, 79, 123, 456, 789]

Output:

The minimum index of the repeating element of the given list [7, 86, 23, 96, 11, 23, 45, 78, 96, 23, 79, 123, 456, 789] :
2

Program to Find the Minimum Index of a Repeating Element in an Array/List in Python

Below is the full approach for finding the minimum index of the repeating element in the given list in Python

1)Using Hashing with Counter() function(Static Input)

Counter() function:

The Counter class is a subset of the object data-set offered by Python3’s collections module. The Collections module provides the user with specialized container datatypes, acting as an alternative to Python’s general-purpose built-ins such as dictionaries, lists, and tuples.

The counter is a subclass that counts hashable objects. When called, it constructs an iterable hash table implicitly.

Approach:

  • Import the Counter function from the collections module.
  • Give the list as static input and store it in a variable.
  • Calculate the frequency of all the elements of the given list using the Counter() function and store it in a variable.
  • Traverse the given list using For loop.
  • Check if the element has a frequency greater than 1 using the if statement.
  • If it has a frequency greater than 1, then print the iterator value of the loop(which is the minimum index of the repeating element)
  • Break the loop using a break statement
  • The Exit of the Program.

Below is the implementation:

# Import the Counter function from the collections module.
from collections import Counter
# Give the list as static input and store it in a variable.
given_list = [8, 12, 38, 7, 1, 9, 19, 11, 45, 62, 57, 18, 12, 32, 45, 7, 1]
# Calculate the frequency of all the elements of the given list
# using the Counter() function and store it in a variable.
elemeFreq = Counter(given_list)
# Traverse the given list using For loop.
for indeval in range(len(given_list)):
    # Check if the element has a frequency greater than 1 using the if statement.
    if(elemeFreq[given_list[indeval]] > 1):
        # If it has a frequency greater than 1, then print the iterator value of the loop
        # (which is the minimum index of the repeating element)
        print('The minimum index of the repeating element of the given list',
              given_list, ':\n', indeval)
        # Break the loop using the break statement
        break

Output:

The minimum index of the repeating element of the given list [8, 12, 38, 7, 1, 9, 19, 11, 45, 62, 57, 18, 12, 32, 45, 7, 1] :
 1

Since we iterate only once the Time Complexity of the above approach is O(n).

2)Using Hashing with Counter() function(User Input)

Approach:

  • Import the Counter function from the collections module.
  • Give the list as user input using split(),int,map() and list() functions.
  • Store it in a variable.
  • Calculate the frequency of all the elements of the given list using the Counter() function and store it in a variable.
  • Traverse the given list using For loop.
  • Check if the element has a frequency greater than 1 using the if statement.
  • If it has a frequency greater than 1, then print the iterator value of the loop(which is the minimum index of the repeating element)
  • Break the loop using a break statement
  • The Exit of the Program.

Below is the implementation:

# Import the Counter function from the collections module.
from collections import Counter
# Give the list as user input using split(),int,map() and list() functions.
# Store it in a variable.
given_list = list(
    map(int, input('Enter some random list elements separated by spaces = ').split()))
# Calculate the frequency of all the elements of the given list
# using the Counter() function and store it in a variable.
elemeFreq = Counter(given_list)
# Traverse the given list using For loop.
for indeval in range(len(given_list)):
    # Check if the element has a frequency greater than 1 using the if statement.
    if(elemeFreq[given_list[indeval]] > 1):
        # If it has a frequency greater than 1, then print the iterator value of the loop
        # (which is the minimum index of the repeating element)
        print('The minimum index of the repeating element of the given list',
              given_list, ':\n', indeval)
        # Break the loop using break statement
        break

Output:

Enter some random list elements separated by spaces = 7 86 23 96 11 23 45 78 96 23 79 123 456 789
The minimum index of the repeating element of the given list [7, 86, 23, 96, 11, 23, 45, 78, 96, 23, 79, 123, 456, 789] :
2

Since we iterate only once the Time Complexity of the above approach is O(n).
Related Programs:

Python Program to Find the Minimum Index of a Repeating Element in an Array/List Read More »

Program to Right Rotate a List by R Times

Python Program to Right Rotate a List by R Times

Interested in programming and want to excel in it by choosing the short ways. Then, practicing with the available Java Program list is mandatory.

Right Rotation of a List:

An array’s elements are shifted to the right when it is rotated to the right, as demonstrated in the image below. right rotation involves rotating the array’s elements clockwise to the provided number of places.

Examples:

Example1:

Input:

given list =[3, 9, 1, 2, 4, 5, 11, 23]
number of positions = 6

Output:

The list before rotating r times =  [3, 9, 1, 2, 4, 5, 11, 23]
The list after  rotating r times :  [1, 2, 4, 5, 11, 23, 3, 9]

Example2:

Input:

given list =  ['good', 'morning', 'this', 'is', 'btechgeeks']
number of positions = 3

Output:

The list before rotating r times = ['good', 'morning', 'this', 'is', 'btechgeeks']
The list after rotating r times : ['this', 'is', 'btechgeeks', 'good', 'morning']

Program to Right Rotate a List by r Times in Python

There are several ways to right rotate the given list by r times to the right in Python some of them are:

Method #1:Using Indexing(Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Give the number of rotations r as static input and store it in another variable.
  • Pass the given list and number of rotations as arguments to the rightRotateList function which rotates the given list to the right by r positions.
  • Use for loop to loop r times.
  • Pass the given list to the rightRotateOne function inside the for loop which rotates the list to the right one time.
  • Inside the rightRotateOne function follow the below steps.
  • Initialize the last variable to the last element of the given list.
  • Traverse length in reverse order of given list -1 times using for loop and reversed range functions.
  • Initialize the next index element to the current index element inside the For loop.
  • After the loop Initialize the first value of the given list to the last value.
  • In this way, we rotate the given list to the right r times.
  • The Exit of the Program.

Below is the implementation:

# function which accepts the giveen list as argument
# and rotates the given list to the right by one time


def rightRotateByOne(given_list):
    # intializing last variable to the last element of the given list
    lastval = given_list[-1]
    # traversing length in reverse order of given list -1 times using for loop and reversed,range functions
    for i in reversed(range(len(given_list) - 1)):
      # initializing the next index element to the current index element
        given_list[i+1] = given_list[i]
    # Initialize the first value of the given list to the last value.
    given_list[0] = lastval


# function which accepts the given list and number
# of positions as arguments and rotate the given list r times here r=positions
def rightRotateList(given_list, positions):
    # Pass the given list to the rightRotateOne function inside the
    # for loop which rotates the list to the right one time.
    for numb in range(positions):
        rightRotateByOne(given_list)


# Driver Code
# Give the list as static input and store it in a variable.
given_list = [3, 9, 1, 2, 4, 5, 11, 23]
print('The list before rotating r times = ', given_list)
# Give the number of rotations r as static input and store it in another variable.
positions = 6
# Pass the given list and number of rotations as arguments to the rightRotateList function
# which rotates the given list to the right by r positions.
rightRotateList(given_list, positions)
# print the list after rotating to the right r times
print('The list after  rotating r times : ', given_list)

Output:

The list before rotating r times =  [3, 9, 1, 2, 4, 5, 11, 23]
The list after  rotating r times :  [1, 2, 4, 5, 11, 23, 3, 9]

The above solution has a time complexity of, where n is the size of the input and r is the number of rotations.

Method #2:Using Indexing(User Input)

i)Integer List

Approach:

  • Give the integer list as user input using map(),split(),list() and int functions.
  • Store it in a variable.
  • Give the number of rotations r as user input using int(input()) and store it in another variable.
  • Pass the given list and number of rotations as arguments to the rightRotateList function which rotates the given list to the right by r positions.
  • Use for loop to loop r times.
  • Pass the given list to the rightRotateOne function inside the for loop which rotates the list to the right one time.
  • Inside the rightRotateOne function follow the below steps.
  • Initialize the last variable to the last element of the given list.
  • Traverse length in reverse order of given list -1 times using for loop and reversed range functions.
  • Initialize the next index element to the current index element inside the For loop.
  • After the loop Initialize the first value of the given list to the last value.
  • In this way, we rotate the given list to the right r times.
  • The Exit of the Program.

Below is the implementation:

# function which accepts the giveen list as argument
# and rotates the given list to the right by one time


def rightRotateByOne(given_list):
    # intializing last variable to the last element of the given list
    lastval = given_list[-1]
    # traversing length in reverse order of given list -1 times using for loop and reversed,range functions
    for i in reversed(range(len(given_list) - 1)):
      # initializing the next index element to the current index element
        given_list[i+1] = given_list[i]
    # Initialize the first value of the given list to the last value.
    given_list[0] = lastval


# function which accepts the given list and number
# of positions as arguments and rotate the given list r times here r=positions
def rightRotateList(given_list, positions):
    # Pass the given list to the rightRotateOne function inside the
    # for loop which rotates the list to the right one time.
    for numb in range(positions):
        rightRotateByOne(given_list)


# Driver Code
# Give the list as user input using map(),split(),list() and int functions.
# Store it in a variable. 
given_list = list(
    map(int, input('Enter some random list separated by spaces = ').split()))
print('The list before rotating r times = ', given_list)
# Give the number of rotations r as user input using int(input())
# and store it in another variable.
positions = int(input('Enter some random number of positions = '))
# Pass the given list and number of rotations as arguments to the rightRotateList function
# which rotates the given list to the right by r positions.
rightRotateList(given_list, positions)
# print the list after rotating to the right r times
print('The list after rotating r times : ', given_list)

Output:

Enter some random list separated by spaces = 8 77 9 12 1 6 4 3 7 9
The list before rotating r times = [8, 77, 9, 12, 1, 6, 4, 3, 7, 9]
Enter some random number of positions = 4
The list after rotating r times : [4, 3, 7, 9, 8, 77, 9, 12, 1, 6]

The above solution has a time complexity of, where n is the size of the input and r is the number of rotations.

ii)String List

Approach:

  • Give the string list as user input using split(),list() functions.
  • Store it in a variable.
  • Give the number of rotations r as user input using int(input()) and store it in another variable.
  • Pass the given list and number of rotations as arguments to the rightRotateList function which rotates the given list to the right by r positions.
  • Use for loop to loop r times.
  • Pass the given list to the rightRotateOne function inside the for loop which rotates the list to the right one time.
  • Inside the rightRotateOne function follow the below steps.
  • Initialize the last variable to the last element of the given list.
  • Traverse length in reverse order of given list -1 times using for loop and reversed range functions.
  • Initialize the next index element to the current index element inside the For loop.
  • After the loop Initialize the first value of the given list to the last value.
  • In this way, we rotate the given list to the right r times.
  • The Exit of the Program.

Below is the implementation:

# function which accepts the giveen list as argument
# and rotates the given list to the right by one time


def rightRotateByOne(given_list):
    # intializing last variable to the last element of the given list
    lastval = given_list[-1]
    # traversing length of given list -1 times using for loop
    for i in reversed(range(len(given_list) - 1)):
      # initializing the next index element to the current index element
        given_list[i+1] = given_list[i]
    # intializing first value to the last value of the given list
    given_list[0] = lastval


# function which accepts the given list and number
# of positions as arguments and rotate the given list r times here r=positions
def rightRotateList(given_list, positions):
    # Pass the given list to the rightRotateOne function inside the
    # for loop which rotates the list to the right one time.
    for numb in range(positions):
        rightRotateByOne(given_list)


# Driver Code
#Give the string list as user input using split(),list() functions.
given_list = list( input('Enter some random list separated by spaces = ').split())
print('The list before rotating r times = ', given_list)
# Give the number of rotations r as user input using int(input())
# and store it in another variable.
positions = int(input('Enter some random number of positions = '))
# Pass the given list and number of rotations as arguments to the rightRotateList function
# which rotates the given list to the right by r positions.
rightRotateList(given_list, positions)
# print the list after rotating to the right r times
print('The list after rotating r times : ', given_list)

Output:

Enter some random list separated by spaces = good morning this is btechgeeks
The list before rotating r times = ['good', 'morning', 'this', 'is', 'btechgeeks']
Enter some random number of positions = 3
The list after rotating r times : ['this', 'is', 'btechgeeks', 'good', 'morning']

Related Programs:

Python Program to Right Rotate a List by R Times Read More »

Python Program to Put Even and Odd elements in a List into Two Different Lists

Python Program to Put Even and Odd elements in a List into Two Different Lists

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Lists in Python:

The majority of applications do not merely deal with variables. Lists of variables are also used. For example, a program may use the list of students from a keyboard or a file to handle information about students in a class. No modification of program source code shall be required to adjust the number of students in the classes.
In Python, the data structure named list can be used for the saving of this data (the term “array” is used in other programming languages). A list is like characters in string a succession of elements numbers 0. The list can be manually set by enumerating the list’s elements in square brackets [ ].

In this article, we will look at how to separate odd and even integers in a list into two separate lists.

When you divide a number by two, the result is an even number if the balance is zero.

An odd number is one that when divided by two has a remaining balance of one.

Examples:

Example1:

Input:

given_list = [7, 24, 72, 39, 65, 87, 93,27, 64, 96, 82, 36, 47, 75, 12, 58, 97]

Output:

The even elements present in given list are :
[24, 72, 64, 96, 82, 36, 12, 58]
The odd elements present in given list are :
[7, 39, 65, 87, 93, 27, 47, 75, 97]

Example2:

Input:

given_list = [55, 22, 28, 11, 98, 29, 33, 26, 73, 48, 63]

Output:

The even elements present in given list are :
[22, 28, 98, 26, 48]
The odd elements present in given list are :
[55, 11, 29, 33, 73, 63]

Program to Put Even and Odd elements in a List into Two Different Lists in Python

There are several ways to keep even and odd elements in a given list into two separate lists 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 the append() function and traversing the list to check the elements

Approach:

  • Scan the given list or give list input as static.
  • Create two empty lists. one for storing even numbers and the other for storing odd numbers referred to as evenList and oddList.
  • Using a for loop, traverse the given list.
  • Using the modulus operator, determine whether the element is even or odd.
  • If the given list element is even then append this element to evenList
  • If the given list element is odd then append this element to oddList
  • As a result, the even and odd items are divided into two independent lists.
  • Both the evenList and the oddList should be printed.

Below is the implementation:

# given list
given_list = [7, 24, 72, 39, 65, 87, 93,
              27, 64, 96, 82, 36, 47, 75, 12, 58, 97]
# Create two empty lists. one for storing even numbers and the other
# for storing odd numbers, referred to as evenList and oddList.
evenList = []
oddList = []
# Using a for loop, traverse the given list.
for element in given_list:
    # If the given list element is even then append this element to evenList
    if(element % 2 == 0):
        evenList.append(element)
    # If the given list element is odd then append this element to oddList
    else:
        oddList.append(element)
# printing both evenList and oddList
print("The even elements present in given list are :")
print(evenList)
print("The odd elements present in given list are :")
print(oddList)

Output:

The even elements present in given list are :
[24, 72, 64, 96, 82, 36, 12, 58]
The odd elements present in given list are :
[7, 39, 65, 87, 93, 27, 47, 75, 97]

Method #2:Using List Comprehension

List Comprehension:

Set-builder notation, commonly known as set comprehension, is a notion in mathematics. Python provides list comprehensions, which are inspired by this notion. In fact, Python list comprehension is one of the language’s distinguishing characteristics. It enables us to write simple, understandable code that outperforms uglier alternatives like as for loops or map functions ().

We may simply complete the same task using list comprehension.

Approach:

  • Scan the given list or give list input as static.
  • Take a list say evenList and use list comprehension to store all even elements of the given list.
  • Take a list say oddList and use list comprehension to store all odd elements of the given list.
  • As a result, the even and odd items are divided into two independent lists.
  • Both the evenList and the oddList should be printed.
  • The Exit of the Program.

Below is the implementation:

# given list
given_list = [7, 24, 72, 39, 65, 87, 93,
              27, 64, 96, 82, 36, 47, 75, 12, 58, 97]

# Take a list say evenList and use list comprehension
# to store all even elements of the given list.
evenList = [element for element in given_list if element % 2 == 0]
# Take a list say oddList and use
# list comprehension to store all odd elements of the given list.
oddList = [element for element in given_list if element % 2 != 0]
# printing both evenList and oddList
print("The even elements present in given list are :")
print(evenList)
print("The odd elements present in given list are :")
print(oddList)

Output:

The even elements present in given list are :
[24, 72, 64, 96, 82, 36, 12, 58]
The odd elements present in given list are :
[7, 39, 65, 87, 93, 27, 47, 75, 97]

Related Programs:

Python Program to Put Even and Odd elements in a List into Two Different Lists Read More »

Program to Find the Second Largest Number in a List

Python Program to Find the Second Largest Number in a List

The best and excellent way to learn a java programming language is by practicing Simple Java Program Examples as it includes basic to advanced levels of concepts.

Lists in Python:

We’ve learnt a lot of things so far, from printing something to making a decision to iterating with loops. This and the following chapters will be about storing data. So, let’s begin with a list, which is used to hold a collection of facts.

In our program, we frequently require a list. Assume you’re creating a software to save the grades of all 50 students in a class. Considering 50 distinct factors is not a smart idea. Instead, we can store all 50 values (marks) in a single variable as a list. Isn’t it cool?

The Python list is a straightforward ordered list of items. Python lists are extremely powerful since the objects in them do not have to be homogeneous or even of the same type. Strings, numbers, and characters, as well as other lists, can all be found in a Python list. Python lists are also mutable: once stated, they can be easily altered via a variety of list methods. Let’s look at how to use these techniques to handle Python lists.

Given a list , the task is to print the second largest Number in the given array/list

Examples:

Example1:

Input:

given list = [8, 12, 4, 6, 7, 3, 2, 6, 1, 9]

Output:

printing the second largest element in the given list :  9

Example2:

Input:

given list = [5, 6, 7, 7, 8, 1, 9, 9]

Output:

printing the second largest element in the given list :  8

Program to Find the Second Largest Number in a List in Python

There are several ways to print the second largest element in the  given list some of them are:

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: By sorting the given list

We can get the second largest number of the given list by sorting it in =and printing the second largest number in the given list

1)By sorting the given list in ascending order

Approach:

  • Scan the given list or give list as static input.
  • Sort the given list using sort() function in ascending order.
  • Print the second number from the end of the list.
  • End of program.

Below is the implementation:

# given list
given_list = [8, 12, 4, 6, 7, 3, 2, 6, 1, 9]
# sorting the given list in ascending order
given_list.sort()
# Calculating the second largest element after sorting
seclarg = given_list[-2]
# printing the second largest element in the given list
print("printing the second largest element in the given list : ", seclarg)

Output:

printing the second largest element in the given list :  9

2)By sorting the given list in descending order

Approach:

  • Scan the given list or give list as static input.
  • Sort the given list using sort() function and (reverse=True) in descending order.
  • Print the second number from the start number of the list.
  • End of program.

Below is the implementation:

# given list
given_list = [8, 12, 4, 6, 7, 3, 2, 6, 1, 9]
# sorting the given list in ascending order
given_list.sort(reverse=True)
# Calculating the second largest element after sorting
seclarg = given_list[1]
# printing the second largest element in the given list
print("printing the second largest element in the given list : ", seclarg)

Note : If there are duplicate values, this technique does not print the right output (specially two largest numbers)

Example:

given list = [5, 6, 7, 7, 8, 1, 9, 9]

When we sort the given list in descending order, it appears like this:

given list =[ 9 , 9, 8 , 7 , 7, ,6 , 5 ,1 ]

When we print the second element, it prints 9, although the correct output is 8.

To solve this, we use sets to eliminate duplicates.

Method #2:Using sets

Approach:

  • First we convert the given list to set using set() function.
  • Then we convert the given set to list using list() function because we cannot apply sort function in set.
  • Sort this list using sort() function and (reverse=True) in descending order.
  • Print the second number from the start number of the list.
  • End of program.

Below is the implementation:

# given list
given_list = [5, 6, 7, 7, 8, 1, 9, 9]
# converting the given list into set using set() function
given_list = set(given_list)
# converting the given_list set to list using list() function
given_list = list(given_list)
# sorting the given list in ascending order
given_list.sort(reverse=True)
# Calculating the second largest element after sorting
seclarg = given_list[1]
# printing the second largest element in the given list
print("printing the second largest element in the given list : ", seclarg)

Output:

printing the second largest element in the given list :  8

Related Programs:

Python Program to Find the Second Largest Number in a List Read More »

Program to Remove the ith Occurrence of the Given Word in a List where Words can Repeat

Python Program to Remove the ith Occurrence of the Given Word in a List where Words can Repeat

Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.

Lists in Python:

We’ve learnt a lot of things so far, from printing something to making a decision to iterating with loops. This and the following chapters will be about storing data. So, let’s begin with a list, which is used to hold a collection of facts.

In our program, we frequently require a list. Assume you’re creating a software to save the grades of all 50 students in a class. Considering 50 distinct factors is not a smart idea. Instead, we can store all 50 values (marks) in a single variable as a list. Isn’t it cool?

The Python list is a straightforward ordered list of items. Python lists are extremely powerful since the objects in them do not have to be homogeneous or even of the same type. Strings, numbers, and characters, as well as other lists, can all be found in a Python list. Python lists are also mutable: once stated, they can be easily altered via a variety of list methods. Let’s look at how to use these techniques to handle Python lists.

Given the list of words the task is to remove the ith Occurrence of the word in the given list of words in Python.

Examples:

Example1:

Input:

given list of words =['hello', 'this', 'is', 'btechgeeks', 'this', 'online', 'this', 'platform'] , occurrence=2 , word =this

Output:

Enter the word which you want to remove the ith occurrence = this
Enter which occurrence you wish to delete of the provided term = 2
printing the list before removing the ith occurrence of word :
['hello', 'this', 'is', 'btechgeeks', 'this', 'online', 'this', 'platform']
printing the list after removing the ith occurrence of word :
['hello', 'this', 'is', 'btechgeeks', 'online', 'this', 'platform']

Example2:

Input:

given list of words =['this', 'is', 'is', 'is', 'this'] , occurrence=2 , word =is

Output:

Enter the word which yoou want to remove the ith occurrence = is
Enter which occurrence you wish to delete of the provided term = 2
printing the list before removing the ith occurrence of word :
['this', 'is', 'is', 'is', 'this']
printing the list after removing the ith occurrence of word :
['this', 'is', 'is', 'this']

Python Program to Remove the ith Occurrence of the Given Word in a List where Words can Repeat

There are numerous methods for reading a list of words and removing the ith occurrence of the given word in a list where words can repeat themselves.

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: Reading a list of words separated by new line and using count (User Input)

Approach:

  • Scan the number of elements/strings and store it in a variable
  • Take a new list say anslist
  • Take a count and initialize it to 0
  • Using a for loop, accept the values into the list and put them into the list.
  • Then use an if statement to check that the term that will be removed coincides with the element and the occurrence number.
  • If it matches then increment the count
  • If the count doesn’t matches with the occurrence value then append it to anslist.
  • Print the anslist.

Below is the implementation:

# Taking a empty list
listWords = []
# Taking an empty list which gives the result say anslist
anslist = []
# taking a word count and initalize it to 0
wordCount = 0
# scanning the number of strings
numb = int(input("enter the total number of strings :"))
# Using for loop
for i in range(numb):
    elem = input("enter some random string or word :\n")
    listWords.append(elem)
# given word
given_word = input("Enter the word which you want to remove the ith occurrence")
# given occurrence number
occur = int(
    input("Enter which occurrence you wish to delete of the provided term"))

# printing the list before removing the ith occurrence of word
print("printing the list before removing the ith occurrence of word :")
print(listWords)
# Traversing the given listWords
for word in listWords:
    # checking if the given word mathches with the word
    if(word == given_word):
        # increasing the count
        wordCount = wordCount+1
        # If the count doesn't matches with the occurrence value then append it to anslist.
        if(wordCount != occur):
            anslist.append(word)
    else:
        anslist.append(word)
# printing the list before after the ith occurrence of word
print("printing the list after removing the ith occurrence of word :")
print(anslist)

Output:

enter the total number of strings :8
enter some random string or word :
hello
enter some random string or word :
this
enter some random string or word :
is
enter some random string or word :
btechgeeks
enter some random string or word :
this
enter some random string or word :
online
enter some random string or word :
this
enter some random string or word :
platform
Enter the word which you want to remove the ith occurrence = this
Enter which occurrence you wish to delete of the provided term = 2
printing the list before removing the ith occurrence of word :
['hello', 'this', 'is', 'btechgeeks', 'this', 'online', 'this', 'platform']
printing the list after removing the ith occurrence of word :
['hello', 'this', 'is', 'btechgeeks', 'online', 'this', 'platform']

Method #2: Reading a list of words separated by space and using count (User Input)

Approach:

  • Scan the list of words separated by space .
  • Store the above string in list using split() function.
  • Take a new list say anslist
  • Take a count and initialize it to 0
  • Using a for loop, accept the values into the list and put them into the list.
  • Then use an if statement to check that the term that will be removed coincides with the element and the occurrence number.
  • If it matches then increment the count
  • If the count doesn’t matches with the occurrence value then append it to anslist.
  • Print the anslist.

Below is the implementation:

# Taking an empty list which gives the result say anslist
anslist = []
# taking a word count and initalize it to 0
wordCount = 0
# Taking a list of words in list using split
listWords = list(
    input("Enter the list of words / enter the sentence\n").split())

# given word
given_word = input(
    "Enter the word which yoou want to remove the ith occurrence")
# given occurrence number
occur = int(
    input("Enter which occurrence you wish to delete of the provided term"))

# printing the list before removing the ith occurrence of word
print("printing the list before removing the ith occurrence of word :")
print(listWords)
# Traversing the given listWords
for word in listWords:
    # checking if the given word mathches with the word
    if(word == given_word):
        # increasing the count
        wordCount = wordCount+1
        # If the count doesn't matches with the occurrence value then append it to anslist.
        if(wordCount != occur):
            anslist.append(word)
    else:
        anslist.append(word)
# printing the list before after the ith occurrence of word
print("printing the list after removing the ith occurrence of word :")
print(anslist)

Output:

Enter the list of words / enter the sentence
hello this is btechgeeks online this platform this
Enter the word which yoou want to remove the ith occurrence = this
Enter which occurrence you wish to delete of the provided term =2
printing the list before removing the ith occurrence of word :
['hello', 'this', 'is', 'btechgeejsks', 'this', 'is', 'online', 'this', 'platform', 'this']
printing the list after removing the ith occurrence of word :
['hello', 'this', 'is', 'btechgeejsks', 'is', 'online', 'this', 'platform', 'this']

Related Programs:

Python Program to Remove the ith Occurrence of the Given Word in a List where Words can Repeat Read More »