Python

Program to Remove Characters that Appear More than k Times

Python Program to Remove Characters that Appear More than k Times

In the previous article, we have discussed Python Program to Remove Odd Occurring Characters from the String

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

Examples:

Example1:

Input:

Given String = "goodmorningall"
Given k value = 2

Output:

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

Example2:

Input:

Given String = "hellobtechgeeks"
Given k value= 3

Output:

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

Program to Remove Characters that Appear More than k Times in Python

Below are the ways to remove all the characters from the given string that appears 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 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 less than 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 = "hellobtechgeeks"
# 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 = 3
# 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 less than 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 { hellobtechgeeks } after removal of all characters that appears more than k{ 3 } times : hllobtchgks

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 less than 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 less than 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 = goodmorningall
Enter some random number =2
The given string { goodmorningall } after removal of all characters that appears more than k{ 2 } times : dmria

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 less than 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 = "hellobtechgeeks"
# 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 = 3
# 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 less than 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 { hellobtechgeeks } after removal of all characters that appears more than k{ 3 } times : hllobtchgks

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 less than 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 less than 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 = goodmorningall
Enter some random number =2
The given string { goodmorningall } after removal of all characters that appears more than k{ 2 } times : dmria

Dive into numerous Python Programming Language Examples for practice and get the best out of the tutorial and learn python one step at a time.

Python Program to Remove Characters that Appear More than k Times Read More »

Program to Delete All Odd Frequency Elements from an ArrayList

Python Program to Delete All Odd Frequency Elements from an Array/List

In the previous article, we have discussed Python Program to Remove Even Frequency Characters from the String

Given a list and the task is to delete all the elements from a given list that has an odd frequency.

Examples:

Example1:

Input:

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

Output:

The list after deletion of all the elements from a given list that has an odd frequency : [10, 4, 2, 10, 2, 4, 6, 6]

Example2:

Input:

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

Output:

The list after deletion of all the elements from a given list that has an odd frequency : [1, 6, 8, 1, 6, 8]

Program to Delete All Odd Frequency Elements from an Array/List in Python

Below are the ways to delete all the elements from a given list that has an odd frequency:

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 given list using the For loop.
  • Check if the key in the freqncyDictionary having value even 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 has an odd frequency.
  • 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 = [10, 4, 2, 10, 1, 2, 3, 4, 5, 6, 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
# 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 even using the if conditional
  # statement.
    if(freqncyDictionary[lstelmt] % 2 == 0):
      # 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 has an odd
# frequency.
print("The list after deletion of all the elements from a given list that has an odd frequency :", modifdlst)

Output:

The list after deletion of all the elements from a given list that has an odd frequency : [10, 4, 2, 10, 2, 4, 6, 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.
  • 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 value even 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 has an odd frequency.
  • 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 given list using the For loop.
for lstelmt in gvnlst:
  # Check if the key in the freqncyDictionary having value even using the if conditional
  # statement.
    if(freqncyDictionary[lstelmt] % 2 == 0):
      # 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 has an odd
# frequency.
print("The list after deletion of all the elements from a given list that has an odd frequency :", modifdlst)


Output:

Enter some random list element separated by spaces = 1 6 8 2 1 7 6 8
The list after deletion of all the elements from a given list that has an odd frequency : [1, 6, 8, 1, 6, 8]

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 given list using the For loop.
  • Check if the key in the freqncyDictionary having value even 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 has an odd frequency.
  • 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 = [10, 4, 2, 10, 1, 2, 3, 4, 5, 6, 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)
# 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 even using the if conditional
  # statement.
    if(freqncyDictionary[lstelmt] % 2 == 0):
      # 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 has an odd
# frequency.
print("The list after deletion of all the elements from a given list that has an odd frequency :", modifdlst)

Output:

The list after deletion of all the elements from a given list that has an odd frequency : [10, 4, 2, 10, 2, 4, 6, 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)
  • 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 value even 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 has an odd frequency.
  • 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 given list using the For loop.
for lstelmt in gvnlst:
  # Check if the key in the freqncyDictionary having value even using the if conditional
  # statement.
    if(freqncyDictionary[lstelmt] % 2 == 0):
      # 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 has an odd
# frequency.
print("The list after deletion of all the elements from a given list that has an odd frequency :", modifdlst)

Output:

Enter some random list element separated by spaces = 3 6 2 1 8 3 6 8 
The list after deletion of all the elements from a given list that has an odd frequency : [3, 6, 8, 3, 6, 8]

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 Delete All Odd Frequency Elements from an Array/List Read More »

Program to Remove Even Frequency Characters from the String

Python Program to Remove Even Frequency Characters from the String

In the previous article, we have discussed Python Program to Find the Sum of all Even Occurring Elements in an Array/List

Given a string and the task is to remove all the even occurring characters from the given string.

Examples:

Example1:

Input:

Given String = "zzzkkooopppzytuh"

Output:

The given string { zzzkkooopppzytuh } after removing even frequency elements is : ooopppytuh

Example2:

Input:

Given String = "hellobtechgeeks"

Output:

The given string { hellobtechgeeks } after removing even frequency elements is : obtcgks

Program to Remove Even Frequency Characters from the String in Python

Below are the ways to remove all the even occurring characters from the given string 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 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.
  • 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 an odd frequency 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 = "zzzkkooopppzytuh"
# 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
# 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 odd frequency by checking value of that character in frequency dictionary
        # we check using the if conditional statement
    if(freqncyDictionary[charac] % 2 != 0):
        # 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 removing even frequency elements is :', modifd_string)

Output:

The given string { zzzkkooopppzytuh } after removing even frequency elements is : ooopppytuh

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.
  • 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 an odd frequency 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
# 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 odd frequency by checking value of that character in frequency dictionary
        # we check using the if conditional statement
    if(freqncyDictionary[charac] % 2 != 0):
        # 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 removing even frequency elements is :', modifd_string)

Output:

Enter some random string = hellobtechgeeks
The given string { hellobtechgeeks } after removing even frequency elements is : obtcgks

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)
  • 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 an odd frequency 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 = "zzzkkooopppzytuh"
# 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)
# 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 odd frequency by checking value of that character in frequency dictionary
        # we check using the if conditional statement
    if(freqncyDictionary[charac] % 2 != 0):
        # 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 removing even frequency elements is :', modifd_string)

Output:

The given string { zzzkkooopppzytuh } after removing even frequency elements is : ooopppytuh

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)
  • 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 an odd frequency 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 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)
# 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 odd frequency by checking value of that character in frequency dictionary
        # we check using the if conditional statement
    if(freqncyDictionary[charac] % 2 != 0):
        # 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 removing even frequency elements is :', modifd_string)

Output:

Enter some random string = hellobtechgeeks
The given string { hellobtechgeeks } after removing even frequency elements is : obtcgks

Explore more Example Python Programs with output and explanation and practice them for your interviews, assignments and stand out from the rest of the crowd.

Python Program to Remove Even Frequency Characters from the String Read More »

Program to Find the Sum of all Even Occurring Elements in an ArrayList

Python Program to Find the Sum of all Even Occurring Elements in an Array/List

In the previous article, we have discussed Python Program to Find the sum of all Highest Occurring Elements in an Array/List

Given a list, the task is to find the sum of the elements which are having an even frequency in the given array/List.

Examples:

Example1:

Input:

Given List = [6, 1, 4, 1, 1, 6, 4, 4, 2, 2]

Output:

The sum of all even frequency elements in the given list [6, 1, 4, 1, 1, 6, 4, 4, 2, 2] is:
8

Explanation:

Here 6,2 are the elements in the given list which are having even frequency
sum=6+2=8

Example2:

Input:

Given List = [7, 6, 8, 8, 1, 4, 1, 5, 4, 7]

Output:

The sum of all even frequency elements in the given list [7, 6, 8, 8, 1, 4, 1, 5, 4, 7] is:
20

Program to Find the Sum of all Even Occurring Elements in an Array/List in Python

Below are the ways to find the sum of the elements which are having an even frequency in the given array/List:

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 variable say evenfreqncycnt and initialize its value to 0.
  • Loop in the freqncyDictionary using the For loop.
  • Check if the key in the freqncyDictionary having value even using the if conditional statement.
  • If it is true then increment the evenfreqncycnt by the key and store it in the same variable.
  • After the end of For loop then print the evenfreqncycnt value.
  • 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 = [6, 1, 4, 1, 1, 6, 4, 4, 2, 2]
# 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 variable say evenfreqncycnt and initialize its value to 0.
evenfreqncycnt = 0
# Loop in the freqncyDictionary using the For loop.
for elemnt in freqncyDictionary:
    # Check if the key in the freqncyDictionary having value even
    # using the if conditional statement.
    if(freqncyDictionary[elemnt] % 2 == 0):
                # If it is true then increment the evenfreqncycnt by the key
        # and store it in the same variable.
        evenfreqncycnt += elemnt
# After the end of For loop then print the evenfreqncycnt value.
print('The sum of all even frequency elements in the given list', gvnlst, 'is:')
print(evenfreqncycnt)

Output:

The sum of all even frequency elements in the given list [6, 1, 4, 1, 1, 6, 4, 4, 2, 2] is:
8

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 variable say evenfreqncycnt and initialize its value to 0.
  • Loop in the freqncyDictionary using the For loop.
  • Check if the key in the freqncyDictionary having value even using the if conditional statement.
  • If it is true then increment the evenfreqncycnt by the key and store it in the same variable.
  • After the end of For loop then print the evenfreqncycnt value.
  • 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 variable say evenfreqncycnt and initialize its value to 0.
evenfreqncycnt = 0
# Loop in the freqncyDictionary using the For loop.
for elemnt in freqncyDictionary:
    # Check if the key in the freqncyDictionary having value even
    # using the if conditional statement.
    if(freqncyDictionary[elemnt] % 2 == 0):
                # If it is true then increment the evenfreqncycnt by the key
        # and store it in the same variable.
        evenfreqncycnt += elemnt
# After the end of For loop then print the evenfreqncycnt value.
print('The sum of all even frequency elements in the given list', gvnlst, 'is:')
print(evenfreqncycnt)

Output:

Enter some random list element separated by spaces = 1 2 3 4 5 1 3 4
The sum of all even frequency elements in the given list [1, 2, 3, 4, 5, 1, 3, 4] is:
8

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 variable say evenfreqncycnt and initialize its value to 0.
  • Loop in the freqncyDictionary using the For loop.
  • Check if the key in the freqncyDictionary having value even using the if conditional statement.
  • If it is true then increment the evenfreqncycnt by the key and store it in the same variable.
  • After the end of For loop then print the evenfreqncycnt value.
  • 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 = [10, 4, 2, 10, 1, 2, 3, 4, 5, 6, 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)

# Take a variable say evenfreqncycnt and initialize its value to 0.
evenfreqncycnt = 0
# Loop in the freqncyDictionary using the For loop.
for elemnt in freqncyDictionary:
    # Check if the key in the freqncyDictionary having value even
    # using the if conditional statement.
    if(freqncyDictionary[elemnt] % 2 == 0):
                # If it is true then increment the evenfreqncycnt by the key
        # and store it in the same variable.
        evenfreqncycnt += elemnt
# After the end of For loop then print the evenfreqncycnt value.
print('The sum of all even frequency elements in the given list', gvnlst, 'is:')
print(evenfreqncycnt)

Output:

The sum of all even frequency elements in the given list [10, 4, 2, 10, 1, 2, 3, 4, 5, 6, 6] is:
22

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 variable say evenfreqncycnt and initialize its value to 0.
  • Loop in the freqncyDictionary using the For loop.
  • Check if the key in the freqncyDictionary having value even using the if conditional statement.
  • If it is true then increment the evenfreqncycnt by the key and store it in the same variable.
  • After the end of For loop then print the evenfreqncycnt value.
  • 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 variable say evenfreqncycnt and initialize its value to 0.
evenfreqncycnt = 0
# Loop in the freqncyDictionary using the For loop.
for elemnt in freqncyDictionary:
    # Check if the key in the freqncyDictionary having value even
    # using the if conditional statement.
    if(freqncyDictionary[elemnt] % 2 == 0):
                # If it is true then increment the evenfreqncycnt by the key
        # and store it in the same variable.
        evenfreqncycnt += elemnt
# After the end of For loop then print the evenfreqncycnt value.
print('The sum of all even frequency elements in the given list', gvnlst, 'is:')
print(evenfreqncycnt)

Output:

Enter some random list element separated by spaces = 3 4 1 2 4 1 3 
The sum of all even frequency elements in the given list [3, 4, 1, 2, 4, 1, 3] is:
8

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 to Find the Sum of all Even Occurring Elements in an Array/List Read More »

Program to Find the sum of all Highest Occurring Elements in an ArrayList

Python Program to Find the sum of all Highest Occurring Elements in an Array/List

In the previous article, we have discussed Python Program to Find the Sum of all Odd Frequency Elements in an Array/List

Given a list, the task is to find the sum of the maximum frequency elements of a given list.

Examples:

Example1:

Input:

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

Output:

The sum of elements in the given list [4, 5, 5, 2, 4, 2, 2, 3, 3, 4, 9, 8, 5, 1, 1] which are having maximum frequency are :
11

Example2:

Input:

Given List = [10, 20, 30, 40, 20, 25]

Output:

The sum of elements in the given list [10, 20, 30, 40, 20, 25] which are having maximum frequency are :
20

Program to Find the sum of all Highest Occurring Elements in an Array/List in Python

Below are the ways to find the sum of the maximum frequency elements of a given list 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 variable that stores the sum of all the most occurring elements in the given list and initialize its value to 0.
  • Find the maximum frequency in the freqncyDictionary
  • We can find it by converting freqncyDictionary values to list(using list and values() functions) and using max() function.
  • Loop in the freqncyDictionary using the For loop.
  • Check if any element value having a frequency equal to max frequency using the if conditional statement.
  • If it is true then increment the count by the key(list element).
  • 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, 5, 2, 4, 2, 2, 3, 3, 4, 9, 8, 5, 1, 1]
# 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 variable which stores sum of all the most occuring elements in the given list
# and initialize its value to 0
summaxfreqelemnts = 0
# find the maximum frequency in the freqncyDictionary
# We can find it by converting freqncyDictionary values to list(using list and values() functions)
# and using max() function
maxfrqncy = max(freqncyDictionary.values())
print('The sum of elements in the given list', gvnlst,
      'which are having maximum frequency are :')
# loop in the freqncyDictionary using the For loop
for key in freqncyDictionary:
    # check if any element value having frequency equal to max frequency using the if conditional statement.
    if(freqncyDictionary[key] == maxfrqncy):
        # if it is true then increment the count by the key(list element)
        summaxfreqelemnts = summaxfreqelemnts+key
print(summaxfreqelemnts)

Output:

The sum of elements in the given list [4, 5, 5, 2, 4, 2, 2, 3, 3, 4, 9, 8, 5, 1, 1] which are having maximum frequency are :
11

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 variable that stores the sum of all the most occurring elements in the given list and initialize its value to 0.
  • Find the maximum frequency in the freqncyDictionary
  • We can find it by converting freqncyDictionary values to list(using list and values() functions) and using max() function.
  • Loop in the freqncyDictionary using the For loop.
  • Check if any element value having a frequency equal to max frequency using the if conditional statement.
  • If it is true then increment the count by the key(list element).
  • 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 variable which stores sum of all the most occuring elements in the given list
# and initialize its value to 0
summaxfreqelemnts = 0
# find the maximum frequency in the freqncyDictionary
# We can find it by converting freqncyDictionary values to list(using list and values() functions)
# and using max() function
maxfrqncy = max(freqncyDictionary.values())
print('The sum of elements in the given list', gvnlst,
      'which are having maximum frequency are :')
# loop in the freqncyDictionary using the For loop
for key in freqncyDictionary:
    # check if any element value having frequency equal to max frequency using the if conditional statement.
    if(freqncyDictionary[key] == maxfrqncy):
        # if it is true then increment the count by the key(list element)
        summaxfreqelemnts = summaxfreqelemnts+key
print(summaxfreqelemnts)

Output:

Enter some random list element separated by spaces = 1 2 3 4 1 2 6 84 6
The sum of elements in the given list [1, 2, 3, 4, 1, 2, 6, 84, 6] which are having maximum frequency are :
9

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 variable that stores the sum of all the most occurring elements in the given list and initialize its value to 0.
  • Find the maximum frequency in the freqncyDictionary
  • We can find it by converting freqncyDictionary values to list(using list and values() functions) and using max() function.
  • Loop in the freqncyDictionary using the For loop.
  • Check if any element value having a frequency equal to max frequency using the if conditional statement.
  • If it is true then increment the count by the key(list element).
  • 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 = [4, 5, 5, 2, 4, 2, 2, 3, 3, 4, 9, 8, 5, 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)
# Take a variable which stores sum of all the most occuring elements in the given list
# and initialize its value to 0
summaxfreqelemnts = 0
# find the maximum frequency in the freqncyDictionary
# We can find it by converting freqncyDictionary values to list(using list and values() functions)
# and using max() function
maxfrqncy = max(freqncyDictionary.values())
print('The sum of elements in the given list', gvnlst,
      'which are having maximum frequency are :')
# loop in the freqncyDictionary using the For loop
for key in freqncyDictionary:
    # check if any element value having frequency equal to max frequency using the if conditional statement.
    if(freqncyDictionary[key] == maxfrqncy):
        # if it is true then increment the count by the key(list element)
        summaxfreqelemnts = summaxfreqelemnts+key
print(summaxfreqelemnts)

Output:

The sum of elements in the given list [4, 5, 5, 2, 4, 2, 2, 3, 3, 4, 9, 8, 5, 1, 1] which are having maximum frequency are :
11

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 variable that stores the sum of all the most occurring elements in the given list and initialize its value to 0.
  • Find the maximum frequency in the freqncyDictionary
  • We can find it by converting freqncyDictionary values to list(using list and values() functions) and using max() function.
  • Loop in the freqncyDictionary using the For loop.
  • Check if any element value having a frequency equal to max frequency using the if conditional statement.
  • If it is true then increment the count by the key(list element).
  • 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 variable which stores sum of all the most occuring elements in the given list
# and initialize its value to 0
summaxfreqelemnts = 0
# find the maximum frequency in the freqncyDictionary
# We can find it by converting freqncyDictionary values to list(using list and values() functions)
# and using max() function
maxfrqncy = max(freqncyDictionary.values())
print('The sum of elements in the given list', gvnlst,
      'which are having maximum frequency are :')
# loop in the freqncyDictionary using the For loop
for key in freqncyDictionary:
    # check if any element value having frequency equal to max frequency using the if conditional statement.
    if(freqncyDictionary[key] == maxfrqncy):
        # if it is true then increment the count by the key(list element)
        summaxfreqelemnts = summaxfreqelemnts+key
print(summaxfreqelemnts)

Output:

Enter some random list element separated by spaces = 10 20 30 40 20 25
The sum of elements in the given list [10, 20, 30, 40, 20, 25] which are having maximum frequency are :
20

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 the sum of all Highest Occurring Elements in an Array/List Read More »

Program to Toggle the Last m Bits

Python Program to Toggle the Last m Bits

In the previous article, we have discussed Python Program to Count Minimum Bits to Flip such that XOR of A and B Equal to C

Given a number n, the task is to toggle the last m bits of the given number in its binary representation.

Toggling: 

A toggling operation changes the value of a bit from 0 to 1 and from 1 to 0.

let Given number =30 m=3

The binary representation of 30=11110

Binary representation after toggling the last 3 bits is =11001

Decimal equivalent after toggling =25

Examples:

Example1:

Input:

Given Number = 30
Given m value =  3

Output:

The given number{ 30 } after toggling the given last m { 3 } bits =  25

Example2:

Input:

Given Number = 45
Given m value =  2

Output:

The given number{ 45 } after toggling the given last m { 2 } bits =  46

Program to Toggle the Last m Bits in Python

Below are the ways to toggle the given last m bits of a given number in python:

Method #1: Using Xor(^) Operator (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Give the value of m as static input and store it in another variable.
  • Pass the given number, m value as the arguments to the toglng_lstmbits function.
  • Create a  function to say toglng_lstmbits which takes the given number, m value as the arguments and returns the number after toggling the given last m bits.
  • Apply the left shift operator to 1 and the above-given m value and subtract 1 from it.
  • Store it in another variable.
  • Return the XOR value of the given number and the above result.
  • Print the number after toggling the given last m bits.
  • The Exit of the Program.

Below is the implementation:

# Create a  function to say toglng_lstmbits which takes the given number, m value as the
# arguments and returns the number after toggling the given last m bits.


def toglng_lstmbits(gvn_numb, m):
    # Apply the left shift operator to 1 and the above-given m value and subtract 1 from it.
    # Store it in another variable.
    fnl_numbr = (1 << m) - 1
    # Return the XOR value of the given number and the above result.
    return (gvn_numb ^ fnl_numbr)


# Give the number as static input and store it in a variable.
gvn_numb = 30
# Give the value of m as static input and store it in another variable.
m = 3
# Pass the given number, m value as the arguments to the toglng_lstmbits function.
# Print the number after toggling the given last m bits.
print("The given number{", gvn_numb, "} after toggling the given last m {",
      m, "} bits = ", toglng_lstmbits(gvn_numb, m))

Output:

The given number{ 30 } after toggling the given last m { 3 } bits =  25

Method #2: Using Xor(^) Operator (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Give the value of m as user input using the int(input()) function and store it in another variable.
  • Pass the given number, m value as the arguments to the toglng_lstmbits function.
  • Create a  function to say toglng_lstmbits which takes the given number, m value as the arguments and returns the number after toggling the given last m bits.
  • Apply the left shift operator to 1 and the above-given m value and subtract 1 from it.
  • Store it in another variable.
  • Return the XOR value of the given number and the above result.
  • Print the number after toggling the given last m bits.
  • The Exit of the Program.

Below is the implementation:

# Create a  function to say toglng_lstmbits which takes the given number, m value as the
# arguments and returns the number after toggling the given last m bits.


def toglng_lstmbits(gvn_numb, m):
    # Apply the left shift operator to 1 and the above-given m value and subtract 1 from it.
    # Store it in another variable.
    fnl_numbr = (1 << m) - 1
    # Return the XOR value of the given number and the above result.
    return (gvn_numb ^ fnl_numbr)


# 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 value of m as user input using the int(input()) function and 
# store it in another variable.
m = int(input("Enter some random number = "))
# Pass the given number, m value as the arguments to the toglng_lstmbits function.
# Print the number after toggling the given last m bits.
print("The given number{", gvn_numb, "} after toggling the given last m {",
      m, "} bits = ", toglng_lstmbits(gvn_numb, m))

Output:

Enter some random number = 45
Enter some random number = 2
The given number{ 45 } after toggling the given last m { 2 } bits = 46

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 Toggle the Last m Bits Read More »

Program to Count Minimum Bits to Flip such that XOR of A and B Equal to C

Python Program to Count Minimum Bits to Flip such that XOR of A and B Equal to C

In the previous article, we have discussed Python Program to Check if a Number has Bits in Alternate Pattern

Given an N-bit binary sequence consisting of three binary sequences A, B, and C. Count the minimal number of bits required to flip A and B in such a way that the XOR of A and B equals C.

X       Y      X XOR Y

0       0        0

0       1        1

1       0        1

1       1        0

Cases:

  • If A[i]==B[i] and C[i]==0 then no flip,
  • If A[i]==B[i] and C[i]==1 then flip either A[i] or B[i] and increase flip count by 1
  • If A[i]!=B[i] and C[i]==0 then flip either A[i] or B[i] and increase flip count by 1
  • If A[i]!=B[i] and C[i]==1 then no flip required.

Examples:

Example1:

Input:

Given number = 5
Given first string=  "11011"
Given second string= "11001"
Given third string = "11100"

Output:

The count of minimum bits to Flip in such a way that the XOR of A and B equals C =  4

Example2:

Input:

Given number = 3
Given first string= "110"
Given second string= "111"
Given third string = "101"

Output:

The count of minimum bits to Flip in such a way that the XOR of A and B equals C =  1

Program to Count Minimum Bits to Flip such that XOR of A and B Equal to C in Python

Below are the ways to Count the minimal number of bits required to flip A and B in such a way that the XOR of A and B equals C:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number (which is the count of bits) as static input and store it in a variable.
  • Give the first binary sequence string as static input and store it in another variable.
  • Give the second binary sequence string as static input and store it in another variable.
  • Give the third binary sequence string as static input and store it in another variable.
  • Pass the given three sequence strings and the given number as the arguments to the Flips_Count function.
  • Create a function to say Flips_Count which takes the given three sequence strings and the given number as the arguments and returns the count of minimum bits to Flip in such a way that the XOR of A and B equals C.
  • Take a variable say totl_cnt and initialize its value to 0.
  • Loop till the given number using the for loop.
  • Check if the fst_seqnce[itr] == scnd_seqnce[itr] and third_seqnce[itr] == ‘1’ using the if conditional statement.
  • If the statement is true, then increment the value of above totl_cnt by 1.
  • Store it in the same variable.
  • Check if the fst_seqnce[itr] != scnd_seqnce[itr] and third_seqnce[itr] == ‘0’ using the elif conditional statement.
  • If the statement is true, then increment the value of above totl_cnt by 1.
  • Store it in the same variable.
  • Return the value of totl_cnt.
  • Print the count of minimum bits to Flip in such a way that the XOR of A and B equals C.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say Flips_Count which takes the given three sequence
# strings and the given number as the arguments and returns the count of minimum bits
# to Flip in such a way that the XOR of A and B equals C.


def Flips_Count(fst_seqnce, scnd_seqnce, third_seqnce, numb):
    # Take a variable say totl_cnt and initialize its value to 0.
    totl_cnt = 0
    # Loop till the given number using the for loop.
    for itr in range(numb):
        # Check if the fst_seqnce[itr] == scnd_seqnce[itr] and third_seqnce[itr] == '1'
        # using the if conditional statement.
        if fst_seqnce[itr] == scnd_seqnce[itr] and third_seqnce[itr] == '1':
          # If the statement is true, then increment the value of above totl_cnt by 1.
          # Store it in the same variable.
            totl_cnt = totl_cnt+1

        # Check if the fst_seqnce[itr] != scnd_seqnce[itr] and third_seqnce[itr] == '0' using
        # the elif conditional statement.
        elif fst_seqnce[itr] != scnd_seqnce[itr] and third_seqnce[itr] == '0':
          # If the statement is true, then increment the value of above totl_cnt by 1.
          # Store it in the same variable.
            totl_cnt = totl_cnt+1
    # Return the value of totl_cnt.
    return totl_cnt


# Give the number (which is the count of bits) as static input and store it in a variable.
numb = 5
# Give the first binary sequence string as static input and store it in another variable.
fst_seqnce = "11011"
# Give the second binary sequence string as static input and store it in another variable.
scnd_seqnce = "11001"
# Give the third binary sequence string as static input and store it in another variable.
third_seqnce = "11100"
# Pass the given three sequence strings and the given number as the arguments to the
# Flips_Count function.
# Print the count of minimum bits to Flip in such a way that the XOR of A and B equals C.
print("The count of minimum bits to Flip in such a way that the XOR of A and B equals C = ",
      Flips_Count(fst_seqnce, scnd_seqnce, third_seqnce, numb))

Output:

The count of minimum bits to Flip in such a way that the XOR of A and B equals C =  4

Method #2: Using For loop (User Input)

Approach:

  • Give the number (which is the count of bits) as user input using the int(input()) function and store it in a variable.
  • Give the first binary sequence string as user input using the input() function and store it in another variable.
  • Give the second binary sequence string as user input using the input() function and store it in another variable.
  • Give the third binary sequence string as user input using the input() function and store it in another variable.
  • Pass the given three sequence strings and the given number as the arguments to the Flips_Count function.
  • Create a function to say Flips_Count which takes the given three sequence strings and the given number as the arguments and returns the count of minimum bits to Flip in such a way that the XOR of A and B equals C.
  • Take a variable say totl_cnt and initialize its value to 0.
  • Loop till the given number using the for loop.
  • Check if the fst_seqnce[itr] == scnd_seqnce[itr] and third_seqnce[itr] == ‘1’ using the if conditional statement.
  • If the statement is true, then increment the value of above totl_cnt by 1.
  • Store it in the same variable.
  • Check if the fst_seqnce[itr] != scnd_seqnce[itr] and third_seqnce[itr] == ‘0’ using the elif conditional statement.
  • If the statement is true, then increment the value of above totl_cnt by 1.
  • Store it in the same variable.
  • Return the value of totl_cnt.
  • Print the count of minimum bits to Flip in such a way that the XOR of A and B equals C.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say Flips_Count which takes the given three sequence
# strings and the given number as the arguments and returns the count of minimum bits
# to Flip in such a way that the XOR of A and B equals C.


def Flips_Count(fst_seqnce, scnd_seqnce, third_seqnce, numb):
    # Take a variable say totl_cnt and initialize its value to 0.
    totl_cnt = 0
    # Loop till the given number using the for loop.
    for itr in range(numb):
        # Check if the fst_seqnce[itr] == scnd_seqnce[itr] and third_seqnce[itr] == '1'
        # using the if conditional statement.
        if fst_seqnce[itr] == scnd_seqnce[itr] and third_seqnce[itr] == '1':
          # If the statement is true, then increment the value of above totl_cnt by 1.
          # Store it in the same variable.
            totl_cnt = totl_cnt+1

        # Check if the fst_seqnce[itr] != scnd_seqnce[itr] and third_seqnce[itr] == '0' using
        # the elif conditional statement.
        elif fst_seqnce[itr] != scnd_seqnce[itr] and third_seqnce[itr] == '0':
          # If the statement is true, then increment the value of above totl_cnt by 1.
          # Store it in the same variable.
            totl_cnt = totl_cnt+1
    # Return the value of totl_cnt.
    return totl_cnt


# Give the number (which is the count of bits) as user input using the int(input()) function 
# and store it in a variable.
numb = int(input('Enter some random number = '))
# Give the first binary sequence string as user input using the input() function and 
# store it in another variable.
fst_seqnce = input('Enter some random binary number string  = ')
# Give the second binary sequence string as user input using the input() function and 
# store it in another variable.
scnd_seqnce = input('Enter some random binary number string  = ')
# Give the third binary sequence string as user input using the input() function and 
# store it in another variable.
third_seqnce = input('Enter some random binary number string  = ')
# Pass the given three sequence strings and the given number as the arguments to the
# Flips_Count function.
# Print the count of minimum bits to Flip in such a way that the XOR of A and B equals C.
print("The count of minimum bits to Flip in such a way that the XOR of A and B equals C = ",
      Flips_Count(fst_seqnce, scnd_seqnce, third_seqnce, numb))

Output:

Enter some random number = 3
Enter some random binary number string = 110
Enter some random binary number string = 111
Enter some random binary number string = 101
The count of minimum bits to Flip in such a way that the XOR of A and B equals C = 1

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 Count Minimum Bits to Flip such that XOR of A and B Equal to C Read More »

Program to Check if a Number has Bits in Alternate Pattern

Python Program to Check if a Number has Bits in Alternate Pattern

In the previous article, we have discussed Python Program to Find XOR of Two Numbers Without Using XOR operator

Given a number, the task is to check if the given Number has the bits in an alternate pattern

For example, the number 42 has an alternate pattern, which is 101010 (after 1 we are getting 0 and next 1 so on).
If it has an alternate bit pattern, print “Yes,” else “No.”

Examples:

Example1:

Input:

Given Number= 42

Output:

Yes, the given number{ 42 } has an alternate bit pattern

Example2:

Input:

Given Number= 14

Output:

No, the given number{ 14 } doesn't have an alternate bit pattern

Program to Check if a Number has Bits in Alternate Pattern in Python

Below are the ways to check if a given number has bits in an alternate pattern in python:

Method #1: Using While Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Create a function to say chek_alterntebit which takes the given number as an argument and returns true if it has an alternate bit pattern else returns False.
  • Apply given number modulus 2 to get the last bit and store it in a variable.
  • Divide the given number by 2 and store it in the same variable gvn_numbr.
  • Loop until the given number is greater than 0 using a while loop.
  • Inside the loop, calculate the current bit by applying the given number modulus 2 and store it in another variable.
  • Check if the current bit is equal to the last bit using the if conditional statement.
  • If the statement is true, then return false.
  • Assign the current bit to the last bit.
  • Divide the given number by 2 and store it in the same variable gvn_numbr.
  • Return True. (out of while loop)
  • Pass the gvn_numbr as an argument to the chek_alterntebit() function and check whether it returns true or false using the if conditional statement.
  • If the statement is true, print “Yes, the given number has an alternate bit pattern”.
  • Else print “No, the given number doesn’t have an alternate bit pattern”.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say chek_alterntebit which takes the given number as an
# argument and returns true if it has an alternate bit pattern else returns False.


def chek_alterntebit(gvn_numbr):
    # Apply given number modulus 2 to get the last bit and store it in a variable.
    lst_bit = gvn_numbr % 2
    # Divide the given number by 2 and store it in the same variable gvn_numbr.
    gvn_numbr = gvn_numbr // 2
    # Loop until the given number is greater than 0 using a while loop.
    while (gvn_numbr > 0):
      # Inside the loop, calculate the current bit by applying the given number modulus 2
      # and store it in another variable.

        prsent_bit = gvn_numbr % 2
      # Check if the current bit is equal to the last bit using the if conditional
      # statement.
        if (prsent_bit == lst_bit):
          # If the statement is true, then return false.
            return False
        # Assign the current bit to the last bit.
        lst_bit = prsent_bit
        # Divide the given number by 2 and store it in the same variable gvn_numbr.
        gvn_numbr = gvn_numbr // 2
    # Return True. (out of while loop)
    return True


# Give the number as static input and store it in a variable.
gvn_numbr = 42
# Pass the given number as an argument to the chek_alterntebit function.
# Check if the chek_alterntebit(gvn_numbr) using the if conditional statement.
if(chek_alterntebit(gvn_numbr)):
  # If the statement is true, print "Yes, the given number has an alternate bit pattern".
    print("Yes, the given number{", gvn_numbr,
          "} has an alternate bit pattern")
else:
  # Else print "No, the given number doesn't have an alternate bit pattern".
    print("No, the given number{", gvn_numbr,
          "} doesn't have an alternate bit pattern")

Output:

Yes, the given number{ 42 } has an alternate bit pattern

Method #2: Using While loop (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Create a function to say chek_alterntebit which takes the given number as an argument and returns true if it has an alternate bit pattern else returns False.
  • Apply given number modulus 2 to get the last bit and store it in a variable.
  • Divide the given number by 2 and store it in the same variable gvn_numbr.
  • Loop until the given number is greater than 0 using a while loop.
  • Inside the loop, calculate the current bit by applying the given number modulus 2 and store it in another variable.
  • Check if the current bit is equal to the last bit using the if conditional statement.
  • If the statement is true, then return false.
  • Assign the current bit to the last bit.
  • Divide the given number by 2 and store it in the same variable gvn_numbr.
  • Return True. (out of while loop)
  • Pass the gvn_numbr as an argument to the chek_alterntebit() function and check whether it returns true or false using the if conditional statement.
  • If the statement is true, print “Yes, the given number has an alternate bit pattern”.
  • Else print “No, the given number doesn’t have an alternate bit pattern”.
  • The Exit of the Program.

Below is the implementation:

# Create a function to say chek_alterntebit which takes the given number as an
# argument and returns true if it has an alternate bit pattern else returns False.


def chek_alterntebit(gvn_numbr):
    # Apply given number modulus 2 to get the last bit and store it in a variable.
    lst_bit = gvn_numbr % 2
    # Divide the given number by 2 and store it in the same variable gvn_numbr.
    gvn_numbr = gvn_numbr // 2
    # Loop until the given number is greater than 0 using a while loop.
    while (gvn_numbr > 0):
      # Inside the loop, calculate the current bit by applying the given number modulus 2
      # and store it in another variable.

        prsent_bit = gvn_numbr % 2
      # Check if the current bit is equal to the last bit using the if conditional
      # statement.
        if (prsent_bit == lst_bit):
          # If the statement is true, then return false.
            return False
        # Assign the current bit to the last bit.
        lst_bit = prsent_bit
        # Divide the given number by 2 and store it in the same variable gvn_numbr.
        gvn_numbr = gvn_numbr // 2
    # Return True. (out of while loop)
    return True


# Give the number as user input using the int(input()) function and store it in a variable.
gvn_numbr = int(input('Enter some random number = '))
# Pass the given number as an argument to the chek_alterntebit function.
# Check if the chek_alterntebit(gvn_numbr) using the if conditional statement.
if(chek_alterntebit(gvn_numbr)):
  # If the statement is true, print "Yes, the given number has an alternate bit pattern".
    print("Yes, the given number{", gvn_numbr,
          "} has an alternate bit pattern")
else:
  # Else print "No, the given number doesn't have an alternate bit pattern".
    print("No, the given number{", gvn_numbr,
          "} doesn't have an alternate bit pattern")

Output:

Enter some random number = 14
No, the given number{ 14 } doesn't have an alternate bit pattern

Dive into numerous Python Programming Language Examples for practice and get the best out of the tutorial and learn python one step at a time.

Python Program to Check if a Number has Bits in Alternate Pattern Read More »

program-to-find-the-sum-of-all-odd-frequency-elements-in-an-arraylist

Python Program to Find the Sum of all Odd Frequency Elements in an Array/List

In the previous article, we have discussed Python Program Print Bitwise AND set of a Number N

Given a list, the task is to find the sum of the elements which are having an odd frequency in the given array/List.

Examples:

Example1:

Input:

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

Output:

The sum of all odd frequency elements in the given list [10, 4, 2, 10, 1, 2, 3, 4, 5, 6, 6] is:
9

Explanation:

Here 1,3,5 are the elements in the given list which are having odd frequency
sum=1+3+5

Example2:

Input:

Given List = [2, 2, 3]

Output:

The sum of all odd frequency elements in the given list [2, 2, 3] is:
3

Program to Find the Sum of all Odd Frequency Elements in an Array/List

Below are the ways to find the sum of the elements which are having an odd frequency in the given array/List:

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 variable say oddfreqncycnt and initialize its value to 0.
  • Loop in the freqncyDictionary using the For loop.
  • Check if the key in the freqncyDictionary having value odd using the if conditional statement.
  • If it is true then increment the oddfreqncycnt by the key and store it in the same variable.
  • After the end of For loop then print the oddfreqncycnt value.
  • 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 = [10, 4, 2, 10, 1, 2, 3, 4, 5, 6, 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

# Take a variable say oddfreqncycnt and initialize its value to 0.
oddfreqncycnt = 0
# Loop in the freqncyDictionary using the For loop.
for elemnt in freqncyDictionary:
    # Check if the key in the freqncyDictionary having value odd
    # using the if conditional statement.
    if(freqncyDictionary[elemnt] % 2 != 0):
                # If it is true then increment the oddfreqncycnt by the key
        # and store it in the same variable.
        oddfreqncycnt += elemnt
# After the end of For loop then print the oddfreqncycnt value.
print('The sum of all odd frequency elements in the given list', gvnlst, 'is:')
print(oddfreqncycnt)

Output:

The sum of all odd frequency elements in the given list [10, 4, 2, 10, 1, 2, 3, 4, 5, 6, 6] is:
9

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 variable say oddfreqncycnt and initialize its value to 0.
  • Loop in the freqncyDictionary using the For loop.
  • Check if the key in the freqncyDictionary having value odd using the if conditional statement.
  • If it is true then increment the oddfreqncycnt by the key and store it in the same variable.
  • After the end of For loop then print the oddfreqncycnt value.
  • 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 variable say oddfreqncycnt and initialize its value to 0.
oddfreqncycnt = 0
# Loop in the freqncyDictionary using the For loop.
for elemnt in freqncyDictionary:
    # Check if the key in the freqncyDictionary having value odd
    # using the if conditional statement.
    if(freqncyDictionary[elemnt] % 2 != 0):
                # If it is true then increment the oddfreqncycnt by the key
        # and store it in the same variable.
        oddfreqncycnt += elemnt
# After the end of For loop then print the oddfreqncycnt value.
print('The sum of all odd frequency elements in the given list', gvnlst, 'is:')
print(oddfreqncycnt)

Output:

Enter some random list element separated by spaces = 2 11 37 11 37 8 1 2 3
The sum of all odd frequency elements in the given list [2, 11, 37, 11, 37, 8, 1, 2, 3] is:
12

Method #3: Using Counter() function (Hashing, Static 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 variable say oddfreqncycnt and initialize its value to 0.
  • Loop in the freqncyDictionary using the For loop.
  • Check if the key in the freqncyDictionary having value odd using the if conditional statement.
  • If it is true then increment the oddfreqncycnt by the key and store it in the same variable.
  • After the end of For loop then print the oddfreqncycnt value.
  • 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 = [10, 4, 2, 10, 1, 2, 3, 4, 5, 6, 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)
# Take a variable say oddfreqncycnt and initialize its value to 0.
oddfreqncycnt = 0
# Loop in the freqncyDictionary using the For loop.
for elemnt in freqncyDictionary:
    # Check if the key in the freqncyDictionary having value odd
    # using the if conditional statement.
    if(freqncyDictionary[elemnt] % 2 != 0):
                # If it is true then increment the oddfreqncycnt by the key
        # and store it in the same variable.
        oddfreqncycnt += elemnt
# After the end of For loop then print the oddfreqncycnt value.
print('The sum of all odd frequency elements in the given list', gvnlst, 'is:')
print(oddfreqncycnt)

Output:

The sum of all odd frequency elements in the given list [10, 4, 2, 10, 1, 2, 3, 4, 5, 6, 6] is:
9

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 variable say oddfreqncycnt and initialize its value to 0.
  • Loop in the freqncyDictionary using the For loop.
  • Check if the key in the freqncyDictionary having value odd using the if conditional statement.
  • If it is true then increment the oddfreqncycnt by the key and store it in the same variable.
  • After the end of For loop then print the oddfreqncycnt value.
  • 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 variable say oddfreqncycnt and initialize its value to 0.
oddfreqncycnt = 0
# Loop in the freqncyDictionary using the For loop.
for elemnt in freqncyDictionary:
    # Check if the key in the freqncyDictionary having value odd
    # using the if conditional statement.
    if(freqncyDictionary[elemnt] % 2 != 0):
                # If it is true then increment the oddfreqncycnt by the key
        # and store it in the same variable.
        oddfreqncycnt += elemnt
# After the end of For loop then print the oddfreqncycnt value.
print('The sum of all odd frequency elements in the given list', gvnlst, 'is:')
print(oddfreqncycnt)

Output:

Enter some random list element separated by spaces = 2 2 3
The sum of all odd frequency elements in the given list [2, 2, 3] is:
3

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

Python Program to Find the Sum of all Odd Frequency Elements in an Array/List Read More »

program-print-bitwise-and-set-of-a-number-n

Python Program Print Bitwise AND set of a Number N

In the previous article, we have discussed Python Program to Toggle Bits of a Number Except First and Last bits

Given a number and the task is to print all the bitwise AND set of a given number.

For some number I the bitwise AND set of a number N is all feasible numbers x smaller than or equal to N such that N & I equals x.

Examples:

Example1:

Input:

Given Number = 6

Output:

The all bitwise AND set of a given number{ 6 } : 
0  2  4  6

Explanation:

Iterating from 0 to 6 so
0 & 6 = 0
1 & 6 = 0                            
2 & 6 = 2
3 & 6 = 2
4 & 6 = 4
5 & 6 = 4
6 & 6 = 6
Hence the all bitwise AND set of a given number = 0 2 4 6 (removing duplicates)

Example2:

Input:

Given Number = 3

Output:

The all bitwise AND set of a given number{ 3 } : 
0  1  2  3

Program Print Bitwise AND set of a Number N in Python

Below are the ways to print all the bitwise AND set of a given number in Python:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Loop till the given number using the for loop.
  • Inside the Loop, apply AND operation for the given number and the iterator value and store it in another variable.
  • Check if the above result is equal to the iterator value using the if conditional statement.
  • If the statement is true, then print the iterator value separated by spaces.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb = 6
# Loop till the given number using the for loop.
print("The all bitwise AND set of a given number{", gvn_numb, "} : ")
for itr in range(gvn_numb + 1):
   # Apply AND operation for the given number and the iterator value and store it in
   # another variable.
    p = gvn_numb & itr
    # Check if the above result is equal to the iterator value using the if conditional
    # statement.
    if (p == itr):
      # If the statement is true, then print the iterator value separated by spaces.
        print(itr, " ", end="")

Output:

The all bitwise AND set of a given number{ 6 } : 
0  2  4  6

Method #2: Using For loop (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Loop till the given number using the for loop.
  • Inside the Loop, apply AND operation for the given number and the iterator value and store it in another variable.
  • Check if the above result is equal to the iterator value using the if conditional statement.
  • If the statement is true, then print the iterator value separated by spaces.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function and
# store it in a variable.
gvn_numb = int(input("Enter some random number = "))
# Loop till the given number using the for loop.
print("The all bitwise AND set of a given number{", gvn_numb, "} : ")
for itr in range(gvn_numb + 1):
   # Apply AND operation for the given number and the iterator value and store it in
   # another variable.
    p = gvn_numb & itr
    # Check if the above result is equal to the iterator value using the if conditional
    # statement.
    if (p == itr):
      # If the statement is true, then print the iterator value separated by spaces.
        print(itr, " ", end="")

Output:

Enter some random number = 3
The all bitwise AND set of a given number{ 3 } : 
0 1 2 3

Method #3: Using While Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Assign the given number to the variable say tempry.
  • Loop till the above variable tempry is not equal to 0 using the while loop.
  • Inside the Loop, Print the value of tempry separated by spaces.
  • Apply AND operation for the tempry -1 and given number and store it in the same variable tempry.
  • Exit the loop.
  • Print 0.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb = 10
# Assign the given number to the variable say tempry.
tempry = gvn_numb
print("The all bitwise AND set of a given number{", gvn_numb, "} : ")
# Loop till the above variable tempry is not equal to 0 using the while loop.
while(tempry != 0):
    # Inside the Loop, Print the value of tempry separated by spaces.
    print(tempry, end=" ")
    # Apply AND operation for the tempry -1 and given number and store it in the same variable
    # tempry.
    tempry = (tempry - 1) & gvn_numb
    # Exit the loop.
# Print 0.
print("0")

Output:

The all bitwise AND set of a given number{ 10 } : 
10 8 2 0

Method #4: Using While loop (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Assign the given number to the variable say tempry.
  • Loop till the above variable tempry is not equal to 0 using the while loop.
  • Inside the Loop, Print the value of tempry separated by spaces.
  • Apply AND operation for the tempry -1 and given number and store it in the same variable tempry.
  • Exit the loop.
  • Print 0.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function and store it in a variable.
gvn_numb = int(input("Enter some random number = "))
# Assign the given number to the variable say tempry.
tempry = gvn_numb
print("The all bitwise AND set of a given number{", gvn_numb, "} : ")
# Loop till the above variable tempry is not equal to 0 using the while loop.
while(tempry != 0):
    # Inside the Loop, Print the value of tempry separated by spaces.
    print(tempry, end=" ")
    # Apply AND operation for the tempry -1 and given number and store it in the same variable
    # tempry.
    tempry = (tempry - 1) & gvn_numb
    # Exit the loop.
# Print 0.
print("0")

Output:

Enter some random number = 7
The all bitwise AND set of a given number{ 7 } : 
7 6 5 4 3 2 1 0

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 Print Bitwise AND set of a Number N Read More »