Python Program to Toggle the Last m Bits

Program to Toggle the Last m Bits

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

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

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

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

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

Program to Check if a Number has Bits in Alternate Pattern

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

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

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

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

Python Program Print Bitwise AND set of a Number N

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

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

 

 

Python Program to Toggle Bits of a Number Except First and Last bits

program-to-toggle-bits-of-a-number-except-first-and-last-bits

The task is to toggle all the bits of a given number except the first and last bits in python.

Toggling: 

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

Examples:

Example1:

Input:

Given Number = 8

Output:

The Number after toggling all the bits of a given number{ 8 } except the first and last bits =  14

Example2:

Input:

Given Number = 15

Output:

The Number after toggling all the bits of a given number{ 15 } except the first and last bits =  9

Program to Toggle Bits of a Number Except First and Last bits in Python

Below are the ways to toggle all the bits of a given number except the first and last bits in python:

Method #1: Using Right Shift (>>)Operator (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Pass the given number as an argument to the setallmidlebits function.
  • Create a  function to say setallmidlebits which takes the given number as an argument.
  • Apply the or(|) operator to the given number and given_numb >> 1(Right Shift) and store it in the same variable.
  • Apply the or(|) operator to the given number and given_numb >> 2(Right Shift) and store it in the same variable.
  • Apply the or(|) operator to the given number and given_numb >> 4(Right Shift) and store it in the same variable.
  • Apply the or(|) operator to the given number and given_numb >> 8(Right Shift) and store it in the same variable.
  • Apply the or(|) operator to the given number and given_numb >> 16(Right Shift) and store it in the same variable.
  • Right shift the given number by 1 and store it in another variable.
  • Return the Xor value of the above result and 1.
  • Pass the given number as an argument to the toglemidlebits function.
  • Create a  function to say toglemidlebits which takes the given number as an argument and returns the number after toggling all the bits of a given number except the first and last bits.
  • Check if the given number is equal to 1 using the if conditional statement.
  • If the statement is true, then return 1.
  • Return the Xor result of the given number and setallmidlebits(gven_numb).
  • Print the number after toggling all the bits of a given number except the first and last bits.
  • The Exit of the Program.

Below is the implementation:

# Create a  function to say setallmidlebits which takes the given number as an
# argument.


def setallmidlebits(gven_numb):
    # Apply the or(|) operator to the given number and given_numb >> 1(Right Shift) and
    # store it in the same variable.
    gven_numb = gven_numb | gven_numb >> 1
    # Apply the or(|) operator to the given number and given_numb >> 2(Right Shift) and
    # store it in the same variable.
    gven_numb = gven_numb | gven_numb >> 2
    # Apply the or(|) operator to the given number and given_numb >> 4(Right Shift) and
    # store it in the same variable.
    gven_numb = gven_numb | gven_numb >> 4
    # Apply the or(|) operator to the given number and given_numb >> 8(Right Shift) and
    # store it in the same variable.
    gven_numb = gven_numb | gven_numb >> 8
    # Apply the or(|) operator to the given number and given_numb >> 16(Right Shift) and
    # store it in the same variable.
    gven_numb = gven_numb | gven_numb >> 16
    # Right shift the given number by 1 and store it in another variable.
    p = (gven_numb >> 1)
    # Return the Xor value of the above result and 1.
    return (p ^ 1)

# Create a  function to say toglemidlebits which takes the given number as an
# argument and returns the number after toggling all the bits of a given number except the
# first and last bits.


def toglemidlebits(gven_numb):
  # Check if the given number is equal to 1 using the if conditional statement.
    if (gven_numb == 1):
      # If the statement is true, then return 1.
        return 1
    # Return the Xor result of the given number and setallmidlebits(gven_numb).
    return gven_numb ^ setallmidlebits(gven_numb)


# Give the number as static input and store it in a variable.
gven_numb = 8
# Pass the given number as an argument to the setallmidlebits function.
# Pass the given number as an argument to the toglemidlebits function.
# Print the number after toggling all the bits of a given number except the
# first and last bits.
print("The Number after toggling all the bits of a given number{", gven_numb,
      "} except the first and last bits = ", toglemidlebits(gven_numb))

Output:

The Number after toggling all the bits of a given number{ 8 } except the first and last bits =  14

Method #2: Using Right Shift (>>)Operator (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Pass the given number as an argument to the setallmidlebits function.
  • Create a  function to say setallmidlebits which takes the given number as an argument.
  • Apply the or(|) operator to the given number and given_numb >> 1(Right Shift) and store it in the same variable.
  • Apply the or(|) operator to the given number and given_numb >> 2(Right Shift) and store it in the same variable.
  • Apply the or(|) operator to the given number and given_numb >> 4(Right Shift) and store it in the same variable.
  • Apply the or(|) operator to the given number and given_numb >> 8(Right Shift) and store it in the same variable.
  • Apply the or(|) operator to the given number and given_numb >> 16(Right Shift) and store it in the same variable.
  • Right shift the given number by 1 and store it in another variable.
  • Return the Xor value of the above result and 1.
  • Pass the given number as an argument to the toglemidlebits function.
  • Create a  function to say toglemidlebits which takes the given number as an argument and returns the number after toggling all the bits of a given number except the first and last bits.
  • Check if the given number is equal to 1 using the if conditional statement.
  • If the statement is true, then return 1.
  • Return the Xor result of the given number and setallmidlebits(gven_numb).
  • Print the number after toggling all the bits of a given number except the first and last bits.
  • The Exit of the Program.

Below is the implementation:

# Create a  function to say setallmidlebits which takes the given number as an
# argument.


def setallmidlebits(gven_numb):
    # Apply the or(|) operator to the given number and given_numb >> 1(Right Shift) and
    # store it in the same variable.
    gven_numb = gven_numb | gven_numb >> 1
    # Apply the or(|) operator to the given number and given_numb >> 2(Right Shift) and
    # store it in the same variable.
    gven_numb = gven_numb | gven_numb >> 2
    # Apply the or(|) operator to the given number and given_numb >> 4(Right Shift) and
    # store it in the same variable.
    gven_numb = gven_numb | gven_numb >> 4
    # Apply the or(|) operator to the given number and given_numb >> 8(Right Shift) and
    # store it in the same variable.
    gven_numb = gven_numb | gven_numb >> 8
    # Apply the or(|) operator to the given number and given_numb >> 16(Right Shift) and
    # store it in the same variable.
    gven_numb = gven_numb | gven_numb >> 16
    # Right shift the given number by 1 and store it in another variable.
    p = (gven_numb >> 1)
    # Return the Xor value of the above result and 1.
    return (p ^ 1)

# Create a  function to say toglemidlebits which takes the given number as an
# argument and returns the number after toggling all the bits of a given number except the
# first and last bits.


def toglemidlebits(gven_numb):
  # Check if the given number is equal to 1 using the if conditional statement.
    if (gven_numb == 1):
      # If the statement is true, then return 1.
        return 1
    # Return the Xor result of the given number and setallmidlebits(gven_numb).
    return gven_numb ^ setallmidlebits(gven_numb)


# Give the number as user input using the int(input()) function and store it in a variable.
gven_numb = int(input("Enter some random number = "))
# Pass the given number as an argument to the setallmidlebits function.
# Pass the given number as an argument to the toglemidlebits function.
# Print the number after toggling all the bits of a given number except the
# first and last bits.
print("The Number after toggling all the bits of a given number{", gven_numb,
      "} except the first and last bits = ", toglemidlebits(gven_numb))

Output:

Enter some random number = 15
The Number after toggling all the bits of a given number{ 15 } except the first and last bits = 9

Python Program to Toggle First and Last Bits of a Number

program-to-toggle-first-and-last-bits-of-a-number

The task is to toggle the first bit and last bit of a given number in python.

Toggling: 

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

Examples:

Example1:

Input:

Given Number =12

Output:

The Number after toggling the first bit and last bit of a given number{ 12 } =  5

Example2:

Input:

Given Number =4

Output:

The Number after toggling the first bit and last bit of a given number{ 4 } =  1

Program to Toggle First and Last Bits of a Number in Python

Below are the ways to toggle the first bit and last bit of a given number in python:

Method #1: Using Right Shift (>>)Operator (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Pass the given number as an argument to the takeLastandFirstsetbits function.
  • Create a  function to say takeLastandFirstsetbits which takes the given number as an argument.
  • Apply the or(|) operator to the given number and given_numb >> 1(Right Shift) and store it in the same variable.
  • Apply the or(|) operator to the given number and given_numb >> 2(Right Shift) and store it in the same variable.
  • Apply the or(|) operator to the given number and given_numb >> 4(Right Shift) and store it in the same variable.
  • Apply the or(|) operator to the given number and given_numb >> 8(Right Shift) and store it in the same variable.
  • Apply the or(|) operator to the given number and given_numb >> 16(Right Shift) and store it in the same variable.
  • Add 1 to the given number and right shift the result by 1 and store it in another variable.
  • Return the above result +1.
  • Pass the given number as an argument to the toggleFirstandLastbits function.
  • Create a  function to say toggleFirstandLastbits which takes the given number as an argument and returns the number after toggling the first and last bits of a given number.
  • Check if the given number is equal to 1 using the if conditional statement.
  • If the statement is true, then return 0.
  • Return the Xor result of the given number and takeLastandFirstsetbits(gven_numb).
  • Print the number after toggling the first bit and last bit of a given number.
  • The Exit of the Program.

Below is the implementation:

# Create a  function to say takeLastandFirstsetbits which takes the given number as an
# argument.


def takeLastandFirstsetbits(gven_numb):
    # Apply the or(|) operator to the given number and given_numb >> 1(Right Shift) and
    # store it in the same variable.
    gven_numb = gven_numb | gven_numb >> 1
    # Apply the or(|) operator to the given number and given_numb >> 2(Right Shift) and
    # store it in the same variable.
    gven_numb = gven_numb | gven_numb >> 2
    # Apply the or(|) operator to the given number and given_numb >> 4(Right Shift) and
    # store it in the same variable.
    gven_numb = gven_numb | gven_numb >> 4
    # Apply the or(|) operator to the given number and given_numb >> 8(Right Shift) and
    # store it in the same variable.
    gven_numb = gven_numb | gven_numb >> 8
    # Apply the or(|) operator to the given number and given_numb >> 16(Right Shift) and
    # store it in the same variable.
    gven_numb = gven_numb | gven_numb >> 16
    # Add 1 to the given number and right shift the result by 1 and store it in another
    # variable.
    p = (gven_numb + 1) >> 1
    # Return the above result +1.
    return (p + 1)

# Create a  function to say toggleFirstandLastbits which takes the given number as an
# argument and returns the number after toggling the first and last bits of a given number.


def toggleFirstandLastbits(gven_numb):
  # Check if the given number is equal to 1 using the if conditional statement.
    if (gven_numb == 1):
      # If the statement is true, then return 0.
        return 0
    # Return the Xor result of the given number and takeLastandFirstsetbits(gven_numb).
    return gven_numb ^ takeLastandFirstsetbits(gven_numb)


# Give the number as static input and store it in a variable.
# Pass the given number as an argument to the takeLastandFirstsetbits function.
# Pass the given number as an argument to the toggleFirstandLastbits function.
gven_numb = 12
# Print the number after toggling the first bit and last bit of a given number.
print("The Number after toggling the first bit and last bit of a given number{", gven_numb, "} = ", toggleFirstandLastbits(
    gven_numb))

Output:

The Number after toggling the first bit and last bit of a given number{ 12 } =  5

Method #2: Using Right Shift (>>)Operator (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Pass the given number as an argument to the takeLastandFirstsetbits function.
  • Create a  function to say takeLastandFirstsetbits which takes the given number as an argument.
  • Apply the or(|) operator to the given number and given_numb >> 1(Right Shift) and store it in the same variable.
  • Apply the or(|) operator to the given number and given_numb >> 2(Right Shift) and store it in the same variable.
  • Apply the or(|) operator to the given number and given_numb >> 4(Right Shift) and store it in the same variable.
  • Apply the or(|) operator to the given number and given_numb >> 8(Right Shift) and store it in the same variable.
  • Apply the or(|) operator to the given number and given_numb >> 16(Right Shift) and store it in the same variable.
  • Add 1 to the given number and right shift the result by 1 and store it in another variable.
  • Return the above result +1.
  • Pass the given number as an argument to the toggleFirstandLastbits function.
  • Create a  function to say toggleFirstandLastbits which takes the given number as an argument and returns the number after toggling the first and last bits of a given number.
  • Check if the given number is equal to 1 using the if conditional statement.
  • If the statement is true, then return 0.
  • Return the Xor result of the given number and takeLastandFirstsetbits(gven_numb).
  • Print the number after toggling the first bit and last bit of a given number.
  • The Exit of the Program.

Below is the implementation:

# Create a  function to say takeLastandFirstsetbits which takes the given number as an
# argument.


def takeLastandFirstsetbits(gven_numb):
    # Apply the or(|) operator to the given number and given_numb >> 1(Right Shift) and
    # store it in the same variable.
    gven_numb = gven_numb | gven_numb >> 1
    # Apply the or(|) operator to the given number and given_numb >> 2(Right Shift) and
    # store it in the same variable.
    gven_numb = gven_numb | gven_numb >> 2
    # Apply the or(|) operator to the given number and given_numb >> 4(Right Shift) and
    # store it in the same variable.
    gven_numb = gven_numb | gven_numb >> 4
    # Apply the or(|) operator to the given number and given_numb >> 8(Right Shift) and
    # store it in the same variable.
    gven_numb = gven_numb | gven_numb >> 8
    # Apply the or(|) operator to the given number and given_numb >> 16(Right Shift) and
    # store it in the same variable.
    gven_numb = gven_numb | gven_numb >> 16
    # Add 1 to the given number and right shift the result by 1 and store it in another
    # variable.
    p = (gven_numb + 1) >> 1
    # Return the above result +1.
    return (p + 1)

# Create a  function to say toggleFirstandLastbits which takes the given number as an
# argument and returns the number after toggling the first and last bits of a given number.


def toggleFirstandLastbits(gven_numb):
  # Check if the given number is equal to 1 using the if conditional statement.
    if (gven_numb == 1):
      # If the statement is true, then return 0.
        return 0
    # Return the Xor result of the given number and takeLastandFirstsetbits(gven_numb).
    return gven_numb ^ takeLastandFirstsetbits(gven_numb)


# Give the number as user input using the int(input()) function and store it in a variable.
gven_numb = int(input("Enter some random number = "))
# Pass the given number as an argument to the takeLastandFirstsetbits function.
# Pass the given number as an argument to the toggleFirstandLastbits function.
# Print the number after toggling the first bit and last bit of a given number.
print("The Number after toggling the first bit and last bit of a given number{", gven_numb, "} = ", toggleFirstandLastbits(
    gven_numb))

Output:

Enter some random number = 4
The Number after toggling the first bit and last bit of a given number{ 4 } = 1

 

Python Program for Swapping Three Variables Without Using any Temporary Variable.

program-for-swapping-three-variables-without-using-any-temporary-variable

Given three numbers and the task is to swap the given three numbers without using any temporary variable in python

Examples:

Example1:

Input:

Given first number= 30
Given second number= 45
Given third number= 21

Output:

The above given three numbers before swapping :
first number =  30 second number =  45 third number =  21
The above given three numbers after swapping without using temporary variable:
first number =  21 second number =  30 third number =  45

Example2:

Input:

Given first number= 60
Given second number= 80
Given third number= 70

Output:

The above given three numbers before swapping :
first number =  60 second number =  80 third number =  70
The above given three numbers after swapping without using temporary variable:
first number =  70 second number =  60 third number =  80

Program for Swapping Three Variables Without Using any Temporary Variable in Python

Below are the ways to swap given three numbers without using any temporary variable in python:

Method #1: Using Arithmetic Operators (Static Input)

Approach:

  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Give the third number as static input and store it in another variable.
  • Add first, second, and third numbers and assign the result to the first number.
  • Add second, and third numbers and subtract the result from the given first number.
  • Assign the result to the second number.
  • Add second, and third numbers and subtract the result from the given first number.
  • Assign the result to the given third number.
  • Add second, and third numbers and subtract the result from the given first number.
  • Assign the result to the given first number.
  • Print the given three numbers after swapping without using a temporary variable.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as static input and store it in a variable.
fst_numb = 30
# Give the second number as static input and store it in another variable.
scnd_numb = 45
# Give the third number as static input and store it in another variable.
thrd_numb = 21
print("The above given three numbers before swapping :")
print("first number = ", fst_numb, "second number = ",
      scnd_numb, "third number = ", thrd_numb)
# Add first, second, and third numbers and assign the result to the first number.
fst_numb = fst_numb + scnd_numb + thrd_numb
# Add second, and third numbers and subtract the result from the given first number.
# Assign the result to the second number.
scnd_numb = fst_numb - (scnd_numb+thrd_numb)
# Add second, and third numbers and subtract the result from the given first number.
# Assign the result to the given third number.
thrd_numb = fst_numb - (scnd_numb+thrd_numb)
# Add second, and third numbers and subtract the result from the given first number.
# Assign the result to the given first number.
fst_numb = fst_numb - (scnd_numb+thrd_numb)
# Print the given three numbers after swapping without using a temporary variable.
print("The above given three numbers after swapping without using temporary variable:")
print("first number = ", fst_numb, "second number = ",
      scnd_numb, "third number = ", thrd_numb)

Output:

The above given three numbers before swapping :
first number =  30 second number =  45 third number =  21
The above given three numbers after swapping without using temporary variable:
first number =  21 second number =  30 third number =  45

Method #2: Using Arithmetic Operators (User Input)

Approach:

  • Give the first number as user input using the int(input()) function and store it in a variable.
  • Give the second number as user input using the int(input()) function and store it in another variable.
  • Give the third number as user input using the int(input()) function and store it in another variable.
  • Add first, second, and third numbers and assign the result to the first number.
  • Add second, and third numbers and subtract the result from the given first number.
  • Assign the result to the second number.
  • Add second, and third numbers and subtract the result from the given first number.
  • Assign the result to the given third number.
  • Add second, and third numbers and subtract the result from the given first number.
  • Assign the result to the given first number.
  • Print the given three numbers after swapping without using a temporary variable.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as user input using the int(input()) function and
# store it in a variable.
fst_numb = int(input('Enter some random number = '))
# Give the second number as user input using the int(input()) function and
# store it in another variable.
scnd_numb = int(input('Enter some random number = '))
# Give the third number as user input using the int(input()) function and 
# store it in another variable.
thrd_numb = int(input('Enter some random number = '))
print("The above given three numbers before swapping :")
print("first number = ", fst_numb, "second number = ",
      scnd_numb, "third number = ", thrd_numb)
# Add first, second, and third numbers and assign the result to the first number.
fst_numb = fst_numb + scnd_numb + thrd_numb
# Add second, and third numbers and subtract the result from the given first number.
# Assign the result to the second number.
scnd_numb = fst_numb - (scnd_numb+thrd_numb)
# Add second, and third numbers and subtract the result from the given first number.
# Assign the result to the given third number.
thrd_numb = fst_numb - (scnd_numb+thrd_numb)
# Add second, and third numbers and subtract the result from the given first number.
# Assign the result to the given first number.
fst_numb = fst_numb - (scnd_numb+thrd_numb)
# Print the given three numbers after swapping without using a temporary variable.
print("The above given three numbers after swapping without using temporary variable:")
print("first number = ", fst_numb, "second number = ",
      scnd_numb, "third number = ", thrd_numb)

Output:

Enter some random number = 60
Enter some random number = 80
Enter some random number = 70
The above given three numbers before swapping :
first number = 60 second number = 80 third number = 70
The above given three numbers after swapping without using temporary variable:
first number = 70 second number = 60 third number = 80

Note: It’s worth noting that the above method causes the stack to overflow when the variables have huge values. When dealing with enormous numbers, the solution is to adopt a different strategy.

Python Program to Find XOR of Two Numbers Without Using XOR operator

Program to Find XOR of Two Numbers Without Using XOR operator

Give two numbers the task is to find the XOR result of the given two numbers in Python.

Bitwise & Operator:

If both bits are 1, sets each bit to 1.

Bitwise or (|) operator:

If one of two bits is 1, sets each bit to 1.

Examples:

Example1:

Input:

Given First Number = 4
Given Second Number = 2

Output:

The XOR result of the given first and second numbers{ 4 , 2 } = 6

Example2:

Input:

Given First Number = 7
Given Second Number = 9

Output:

The XOR result of the given first and second numbers{ 7 , 9 } = 14

Program to Find XOR of Two Numbers Without Using XOR operator in Python

Below are the ways to find the XOR result of the given two numbers in Python:

Method #1: Using Bitwise And(&), Or(|) Operators (Static Input)

Approach:

  • Create a function XOR_result() which accepts the given two numbers as the arguments and returns the XOR result of the given first and second numbers.
  • Inside the XOR_result() function.
  • Calculate and the value of (gvnfst_numb | gvnscnd_numb) & (~gvnfst_numb | ~gvnscnd_numb) which gives the XOR result of the given first and second numbers and store it in a variable say xor_rslt.
  • Return the value of xor_rslt (Which is the XOR result of the given first and second numbers).
  • Inside the main code.
  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Pass the given first and second numbers as the arguments to XOR_result() function and store the result in a variable (xorreslt_val).
  • Print the xorreslt_val value.
  • The Exit of the Program.

Below is the implementation:

# Create a function XOR_result() which accepts the given two numbers as the argument and
# returns the XOR result of the given first and second numbers.


def XOR_result(gvnfst_numb, gvnscnd_numb):
    # Inside the XOR_result() function.
    # Calculate and the value of (gvnfst_numb | gvnscnd_numb) & (~gvnfst_numb | ~gvnscnd_numb)
    # which gives the XOR result of the given first and second numbers and store it in a
    # variable say xor_rslt.

    xor_rslt = (gvnfst_numb | gvnscnd_numb) & (~gvnfst_numb | ~gvnscnd_numb)
    # Return the value of xor_rslt (Which is the XOR result of the given first and
    # second numbers).
    return(xor_rslt)


# Inside the main code.
# Give the first number as static input and store it in a variable.
gvnfst_numb = 4
# Give the second number as static input and store it in another variable.
gvnscnd_numb = 2
# Pass the given first and second numbers as the arguments to XOR_result() function and
# store the result in a variable (xorreslt_val).
xorreslt_val = XOR_result(gvnfst_numb, gvnscnd_numb)
# Print the xorreslt_val value.
print("The XOR result of the given first and second numbers{",
      gvnfst_numb, ",", gvnscnd_numb, "} =", xorreslt_val)

Output:

The XOR result of the given first and second numbers{ 4 , 2 } = 6

Method #2: Using Bitwise And(&), Or(|) Operators (User Input)

Approach:

  • Create a function XOR_result() which accepts the given two numbers as the argument and returns the XOR result of the given first and second numbers.
  • Inside the XOR_result() function.
  • Calculate and the value of (gvnfst_numb | gvnscnd_numb) & (~gvnfst_numb | ~gvnscnd_numb) which gives the XOR result of the given first and second numbers and store it in a variable say xor_rslt.
  • Return the value of xor_rslt (Which is the XOR result of the given first and second numbers).
  • Inside the main code.
  • Give the first number as user input using the int(input()) function and store it in a variable.
  • Give the second number using the int(input()) function and store it in another variable.
  • Pass the given first and second numbers as the arguments to XOR_result() function and store the result in a variable (xorreslt_val).
  • Print the xorreslt_val value.
  • The Exit of the Program.

Below is the implementation:

# Create a function XOR_result() which accepts the given two numbers as the argument and
# returns the XOR result of the given first and second numbers.


def XOR_result(gvnfst_numb, gvnscnd_numb):
    # Inside the XOR_result() function.
    # Calculate and the value of (gvnfst_numb | gvnscnd_numb) & (~gvnfst_numb | ~gvnscnd_numb)
    # which gives the XOR result of the given first and second numbers and store it in a
    # variable say xor_rslt.

    xor_rslt = (gvnfst_numb | gvnscnd_numb) & (~gvnfst_numb | ~gvnscnd_numb)
    # Return the value of xor_rslt (Which is the XOR result of the given first and
    # second numbers).
    return(xor_rslt)


# Inside the main code.
# Give the first number as user input using the int(input()) function and store it in a variable.
gvnfst_numb = int(input('Enter some random number = '))
# Give the second number using the int(input()) function and store it in another variable.
gvnscnd_numb = int(input('Enter some random number = '))
# Pass the given first and second numbers as the arguments to XOR_result() function and
# store the result in a variable (xorreslt_val).
xorreslt_val = XOR_result(gvnfst_numb, gvnscnd_numb)
# Print the xorreslt_val value.
print("The XOR result of the given first and second numbers{",
      gvnfst_numb, ",", gvnscnd_numb, "} =", xorreslt_val)

Output:

Enter some random number = 7
Enter some random number = 9
The XOR result of the given first and second numbers{ 7 , 9 } = 14

 

Python Program to Find Position of Rightmost Set Bit

Program to Find Position of Rightmost Set Bit

Give a number the task is to find the position of the rightmost set bit of the given number in Python.

Examples:

Example1:

Input:

Given Number = 22

Output:

The first set bit position of the given number { 22 } with binary string value { 10110 } = 2

Example2:

Input:

Given Number = 40

Output:

The first set bit position of the given number { 40 } with binary string value { 101000 } = 4

Program to Find Position of Rightmost Set Bit in Python

Below are the ways to find the position of the Rightmost set bit of the given number in Python:

Algorithm:

  • Let us take the given number 12.
  • The binary equivalent of the given number is 1100
  • Take the two’s complement of the provided number, excluding the first ‘1’ from right to left (0100).
  • Do a bit-wise & with the original no; this will return no with only the required one (0100).
  • If you take log2 of the number, you will obtain (position – 1).
  • Add 1.

Explanation:

  • (n&~(n-1)) Always return 1 for the binary number containing the rightmost set bit.
  • If N equals 12 (1100), it will return 4 (100).
  • In this case, log2 will return the number of times that number may be expressed in powers of two.
  • For all binary numbers with only the rightmost set bit as 1, such as 2, 4, 8, 16, 32…
  • We’ll discover that the position of the rightmost set bit is always equal to log2(Number)+1.

Method #1: Using log() Function (Static Input)

Approach:

  • Import the math function using the import keyword.
  • Create a function getFirstSetBitPosition() which accepts the given number as the argument and returns the position of the first set bit of the given number.
  • Inside the getFirstSetBitPosition() function.
  • Calculate and the value of log2(n&-n)+1 which gives the first set bit position of the given number and store it in a variable say result_pos.
  • Return the value of result_pos(Which is the position of the first set bit).
  • Inside the main code.
  • Give the number as static input and store it in a variable.
  • Pass the given number as the argument to getFirstSetBitPosition() function and store the result in a variable (firstSetBitposi).
  • Print the firstSetBitposi value.
  • The Exit of the Program.

Below is the implementation:

# Import the math function using the import keyword.
import math
# Create a function getFirstSetBitPosition()
# which accepts the given number as the argument and
# returns the position of the first set bit of the given number.


def getFirstSetBitPosition(numb):
    # Inside the getFirstSetBitPosition() function.
    # Calculate and the value of log2(n&-n)+1 which gives the first set bit position
    # of the given number and store it in a variable say result_pos.
    result_pos = math.log2(numb & -numb)+1
    # Return the value of result_pos(Which is the position of the first set bit).
    return int(result_pos)


# Inside the main code.
# Give the number as static input and store it in a variable.
gvnnumb = 22
# Pass the given number as the argument to getFirstSetBitPosition() 
# function and store the result in a variable(firstSetBitposi).
firstSetBitposi = getFirstSetBitPosition(gvnnumb)
# Print the firstSetBitposi value.
print('The first set bit position of the given number {', gvnnumb, '} with binary string value {', bin(
    gvnnumb)[2:], '} =', firstSetBitposi)

Output:

The first set bit position of the given number { 22 } with binary string value { 10110 } = 2

Method #2: Using log() Function (User Input)

Approach:

  • Import the math function using the import keyword.
  • Create a function getFirstSetBitPosition() which accepts the given number as the argument and returns the position of the first set bit of the given number.
  • Inside the getFirstSetBitPosition() function.
  • Calculate and the value of log2(n&-n)+1 which gives the first set bit position of the given number and store it in a variable say result_pos.
  • Return the value of result_pos(Which is the position of the first set bit).
  • Inside the main code.
  • Give the number as user input using the int(input())) function and store it in a variable.
  • Pass the given number as the argument to getFirstSetBitPosition() function and store the result in a variable (firstSetBitposi).
  • Print the firstSetBitposi value.
  • The Exit of the Program.

Below is the implementation:

# Import the math function using the import keyword.
import math
# Create a function getFirstSetBitPosition()
# which accepts the given number as the argument and
# returns the position of the first set bit of the given number.


def getFirstSetBitPosition(numb):
    # Inside the getFirstSetBitPosition() function.
    # Calculate and the value of log2(n&-n)+1 which gives the first set bit position
    # of the given number and store it in a variable say result_pos.
    result_pos = math.log2(numb & -numb)+1
    # Return the value of result_pos(Which is the position of the first set bit).
    return int(result_pos)


# Inside the main code.
# Give the number as user input using the int(input())) function and store it in a variable.
gvnnumb = int(input('Enter some random number = '))
# Pass the given number as the argument to getFirstSetBitPosition() 
# function and store the result in a variable(firstSetBitposi).
firstSetBitposi = getFirstSetBitPosition(gvnnumb)
# Print the firstSetBitposi value.
print('The first set bit position of the given number {', gvnnumb, '} with binary string value {', bin(
    gvnnumb)[2:], '} =', firstSetBitposi)

Output:

Enter some random number = 40
The first set bit position of the given number { 40 } with binary string value { 101000 } = 4