Python

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

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

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

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

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

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

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

Python Program to Toggle First and Last Bits of a Number

In the previous article, we have discussed Python Program for Swapping Three Variables Without Using any Temporary Variable.

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

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

Python Program to Toggle First and Last Bits of a Number Read More »

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

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

In the previous article, we have discussed Python Program to Toggle the Last m Bits

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.

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

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

Program to Find XOR of Two Numbers Without Using XOR operator

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

In the previous article, we have discussed Python Program to Find Position of Rightmost Set Bit

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

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 Find XOR of Two Numbers Without Using XOR operator Read More »

Program to Find Position of Rightmost Set Bit

Python Program to Find Position of Rightmost Set Bit

In the previous article, we have discussed Python Program for Efficient Way to Multiply With 7

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

Remediate your knowledge gap by attempting the Python Code Examples regularly and understand the areas of need and work on them.

Python Program to Find Position of Rightmost Set Bit Read More »

Program for Efficient Way to Multiply With 7

Python Program for Efficient Way to Multiply With 7

In the previous article, we have discussed Python Program to Check if Two Numbers are Equal Without using Arithmetic and Comparison Operators

The bitwise operator can be used to multiply a value by seven. Subtract the original number from the shifted number and return the difference (8n – n) by left shifting the number by 3 bits (you’ll receive 8n).

Give a number the task is to get the multiplication of the given number by 7 in an efficient way.

Examples:

Example1:

Input:

Given Number = 5

Output:

After multiplying the given number{ 5 } by 7 =  35

Example2:

Input:

Given Number = 3

Output:

After multiplying the given number{ 3 } by 7 =  21

Program for Efficient Way to Multiply With 7 in Python

Below are the ways to get the multiplication of the given number by 7 in an efficient way in Python:

Method #1: Using Left Shift (<<) Operator (Static Input)

Approach:

  • Create a recursive function to say effcnt_mult_bysevn() which takes the given number as an argument and returns the result of the given number multiplied by 7 in an efficient way.
  • Inside the effcnt_mult_bysevn () function.
  • Calculate and the value of (gvn_numb << 3) – gvn_numb which gives the multiplication of the given number by 7 and store it in a variable say rslt_mult.
  • Return the value of rslt_mult(Which is the multiplication of the given number by 7).
  • Inside the main code.
  • Give the number as static input and store it in a variable.
  • Pass the given number as the argument to effcnt_mult_bysevn() function and store the result in a variable (fnl_rslt).
  • Print the fnl_rslt value.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say effcnt_mult_bysevn() which takes the given number
# as an argument and returns the result of the given number multiplied by 7 in an
# efficient way.


def effcnt_mult_bysevn(gvn_numb):
  # Inside the effcnt_mult_bysevn () function.
  # Calculate and the value of (gvn_numb << 3) - gvn_numb which gives the multiplication
  # of the given number by 7 and store it in a variable say rslt_mult.

    rslt_mult = (gvn_numb << 3) - gvn_numb
  # Return the value of rslt_mult(Which is the multiplication of the given number by 7).
    return (rslt_mult)


# Inside the main code.
# Give the number as static input and store it in a variable.
gvn_numb = 5
# Pass the given number as the argument to effcnt_mult_bysevn() function and
# store the result in a variable (fnl_rslt).
fnl_rslt = effcnt_mult_bysevn(gvn_numb)
# Print the fnl_rslt value.
print("After multiplying the given number{", gvn_numb, "} by 7 = ", fnl_rslt)

Output:

After multiplying the given number{ 5 } by 7 =  35

Method #2: Using Left Shift (<<) Operator (User Input)

Approach:

  • Create a recursive function to say effcnt_mult_bysevn() which takes the given number as an argument and returns the result of the given number multiplied by 7 in an efficient way.
  • Inside the effcnt_mult_bysevn () function.
  • Calculate and the value of (gvn_numb << 3) – gvn_numb which gives the multiplication of the given number by 7 and store it in a variable say rslt_mult.
  • Return the value of rslt_mult(Which is the multiplication of the given number by 7).
  • 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 effcnt_mult_bysevn() function and store the result in a variable (fnl_rslt).
  • Print the fnl_rslt value.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say effcnt_mult_bysevn() which takes the given number
# as an argument and returns the result of the given number multiplied by 7 in an
# efficient way.


def effcnt_mult_bysevn(gvn_numb):
  # Inside the effcnt_mult_bysevn () function.
  # Calculate and the value of (gvn_numb << 3) - gvn_numb which gives the multiplication
  # of the given number by 7 and store it in a variable say rslt_mult.

    rslt_mult = (gvn_numb << 3) - gvn_numb
  # Return the value of rslt_mult(Which is the multiplication of the given number by 7).
    return (rslt_mult)


# Inside the main code.
# 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 = '))
# Pass the given number as the argument to effcnt_mult_bysevn() function and
# store the result in a variable (fnl_rslt).
fnl_rslt = effcnt_mult_bysevn(gvn_numb)
# Print the fnl_rslt value.
print("After multiplying the given number{", gvn_numb, "} by 7 = ", fnl_rslt)

Output:

Enter some random number = 3
After multiplying the given number{ 3 } by 7 = 21

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 for Efficient Way to Multiply With 7 Read More »

Program to Check if Two Numbers are Equal Without using Arithmetic and Comparison Operators

Python Program to Check if Two Numbers are Equal Without using Arithmetic and Comparison Operators

In the previous article, we have discussed Python Program to Check Given Two Integers have Opposite signs

Given two numbers the task is to check whether the given two numbers are equal in Python.

Examples:

Example1:

Input:

Given First Number = 10
Given Second Number = 10

Output:

The given two numbers { 10 , 10 } are Equal

Example2:

Input:

Given First Number = 8
Given Second Number = 15

Output:

The given two numbers { 8 , 15 } are Not equal

Program to Check if Two Numbers are Equal Without using Arithmetic and Comparison Operators in Python

Below are the ways to check whether the given two numbers are equal in Python:

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

Approach:

  • Create a function isEqualNumbers() which takes the given two numbers as arguments and returns true if they are equal else returns false if they are not equal.
  • Inside the isEqualNumbers() function.
  • Apply xor to the first number and second number and store it in a variable say xor_result.
  • Check if the value of xor_result is not equal to 0 using the if conditional statement.
  • If it is true then return False
  • Else return True.
  • 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 two numbers as the arguments to isEqualNumbers() function and store the result in a variable Reslt.
  • Check if the Value of Reslt using the If conditional statement.
  • If it is true then print the given two numbers are equal.
  • Else print the given two numbers are not equal.
  • The Exit of the Program.

Below is the implementation:

# Create a function isEqualNumbers()
# which takes the given two numbers as arguments and
# returns true if they are equal
# else returns false if they are not equal.


def isEqualNumbers(first_numb, second_numb):
        # Inside the isEqualNumbers() function.
        # Apply xor to the first number and second number and
    # store it in a variable say xor_result.
    xor_result = first_numb ^ second_numb
    # Check if the value of xor_result is not equal to 0
    # using the if conditional statement.
    if(xor_result != 0):
        # If it is true then return False
        return False
    # Else return True.
    return True


# Inside the main code.
# Give the first number as static input and store it in a variable.
firstnumb = 10
# Give the second number as static input and store it in another variable.
secondnumb = 10
# Pass the given two numbers as the arguments to isEqualNumbers() function
# and store the result in a variable Reslt.
Reslt = isEqualNumbers(firstnumb, secondnumb)
# Check if the Value of Reslt using the If conditional statement.
if(Reslt):
        # If it is true then print the given two numbers are Equal.
    print('The given two numbers {', firstnumb,
          ',', secondnumb, '} are Equal')
# Else print the given two numbers are Not Equal.
else:
    print('The given two numbers {', firstnumb,
          ',', secondnumb, '} are Not equal')

Output:

The given two numbers { 10 , 10 } are Equal

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

Approach:

  • Create a function isEqualNumbers() which takes the given two numbers as arguments and returns true if they are equal else returns false if they are not equal.
  • Inside the isEqualNumbers() function.
  • Apply xor to the first number and second number and store it in a variable say xor_result.
  • Check if the value of xor_result is not equal to 0 using the if conditional statement.
  • If it is true then return False
  • Else return True.
  • 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 as user input using the int(input()) function and store it in another variable.
  • Pass the given two numbers as the arguments to isEqualNumbers() function and store the result in a variable Reslt.
  • Check if the Value of Reslt using the If conditional statement.
  • If it is true then print the given two numbers are equal.
  • Else print the given two numbers are not equal.
  • The Exit of the Program.

Below is the implementation:

# Create a function isEqualNumbers()
# which takes the given two numbers as arguments and
# returns true if they are equal
# else returns false if they are not equal.


def isEqualNumbers(first_numb, second_numb):
        # Inside the isEqualNumbers() function.
        # Apply xor to the first number and second number and
    # store it in a variable say xor_result.
    xor_result = first_numb ^ second_numb
    # Check if the value of xor_result is not equal to 0
    # using the if conditional statement.
    if(xor_result != 0):
        # If it is true then return False
        return False
    # Else return True.
    return True


# Inside the main code.
# Give the first number as user input using the int(input()) function and store it in a variable.
firstnumb = int(input('Enter some random number ='))
# Give the second number as user input using the int(input()) function and 
# store it in another variable.
secondnumb = int(input('Enter some random number ='))
# Pass the given two numbers as the arguments to isEqualNumbers() function
# and store the result in a variable Reslt.
Reslt = isEqualNumbers(firstnumb, secondnumb)
# Check if the Value of Reslt using the If conditional statement.
if(Reslt):
        # If it is true then print the given two numbers are Equal.
    print('The given two numbers {', firstnumb,
          ',', secondnumb, '} are Equal')
# Else print the given two numbers are Not Equal.
else:
    print('The given two numbers {', firstnumb,
          ',', secondnumb, '} are Not equal')

Output:

Enter some random number =8
Enter some random number =15
The given two numbers { 8 , 15 } are Not equal

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 Check if Two Numbers are Equal Without using Arithmetic and Comparison Operators Read More »

Program to Check Given Two Integers have Opposite signs

Python Program to Check Given Two Integers have Opposite signs

In the previous article, we have discussed Python Program to Clear nth Bit of a Number

Given two numbers the task is to check whether the given two numbers have opposite signs in Python.

Examples:

Example1:

Input:

Given First Number =3
Given Second Number = -17

Output:

The given two numbers { 3 , -17 } have opposite signs

Example2:

Input:

Given First Number =4
Given Second Number = 9

Output:

The given two numbers { 4 , 9 } have same signs

Program to Detect Given Two Integers have Opposite signs in Python

Below are the ways to check whether the given two numbers have opposite signs in Python:

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

Approach:

  • Create a function isOppositeSign() which takes the given two numbers as arguments and returns true if they have opposite sign else returns false if they have the same sign.
  • Inside the isOppositeSign() function.
  • Apply xor to the first number and second number and store it in a variable say xor_result.
  • Check if the value of xor_result is less than 0 using the if conditional statement.
  • If it is true then return True
  • Else return False.
  • 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 two numbers as the arguments to isOppositeSign() function and store the result in a variable signResult.
  • Check if the Value of SignResult using the If conditional statement.
  • If it is true then print the given two numbers have opposite signs.
  • Else print the given two numbers have the same sign.
  • The Exit of the Program.

Below is the implementation:

# Create a function isOppositeSign()
# which takes the given two numbers as arguments and
# returns true if they have opposite sign
# else returns false if they have the same sign.


def isOppositeSign(first_numb, second_numb):
        # Inside the isOppositeSign() function.
        # Apply xor to the first number and second number and
    # store it in a variable say xor_result.
    xor_result = first_numb ^ second_numb
    # Check if the value of xor_result is less than 0
    # using the if conditional statement.
    if(xor_result < 0):
        # If it is true then return True
        return True
    # Else return False.
    return False


# Inside the main code.
# Give the first number as static input and store it in a variable.
firstnumb = 3
# Give the second number as static input and store it in another variable.
secondnumb = -17
# Pass the given two numbers as the arguments to isOppositeSign() function
# and store the result in a variable signResult.
signResult = isOppositeSign(firstnumb, secondnumb)
# Check if the Value of SignResult using the If conditional statement.
if(signResult):
        # If it is true then print the given two numbers have opposite signs.
    print('The given two numbers {', firstnumb,
          ',', secondnumb, '} have opposite signs')
# Else print the given two numbers have the same sign.
else:
    print('The given two numbers {', firstnumb,
          ',', secondnumb, '} have same signs')

Output:

The given two numbers { 3 , -17 } have opposite signs

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

Approach:

  • Create a function isOppositeSign() which takes the given two numbers as arguments and returns true if they have opposite sign else returns false if they have the same sign.
  • Inside the isOppositeSign() function.
  • Apply xor to the first number and second number and store it in a variable say xor_result.
  • Check if the value of xor_result is less than 0 using the if conditional statement.
  • If it is true then return True
  • Else return False.
  • 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 two numbers as the arguments to isOppositeSign() function and store the result in a variable signResult.
  • Check if the Value of SignResult using the If conditional statement.
  • If it is true then print the given two numbers have opposite signs.
  • Else print the given two numbers have the same sign.
  • The Exit of the Program.

Below is the implementation:

# Create a function isOppositeSign()
# which takes the given two numbers as arguments and
# returns true if they have opposite sign
# else returns false if they have the same sign.


def isOppositeSign(first_numb, second_numb):
        # Inside the isOppositeSign() function.
        # Apply xor to the first number and second number and
    # store it in a variable say xor_result.
    xor_result = first_numb ^ second_numb
    # Check if the value of xor_result is less than 0
    # using the if conditional statement.
    if(xor_result < 0):
        # If it is true then return True
        return True
    # Else return False.
    return False


# Inside the main code.
# Give the first number as user input using the int(input()) function
# and store it in a variable.
firstnumb = int(input('Enter some random number ='))
# Give the second number using the int(input()) function and store it in another variable.
secondnumb = int(input('Enter some random number ='))
# Pass the given two numbers as the arguments to isOppositeSign() function
# and store the result in a variable signResult.
signResult = isOppositeSign(firstnumb, secondnumb)
# Check if the Value of SignResult using the If conditional statement.
if(signResult):
        # If it is true then print the given two numbers have opposite signs.
    print('The given two numbers {', firstnumb,
          ',', secondnumb, '} have opposite signs')
# Else print the given two numbers have the same sign.
else:
    print('The given two numbers {', firstnumb,
          ',', secondnumb, '} have same signs')

Output:

Enter some random number =4
Enter some random number =9
The given two numbers { 4 , 9 } have same signs

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 Check Given Two Integers have Opposite signs Read More »

Program to Clear nth Bit of a Number

Python Program to Clear nth Bit of a Number

In the previous article, we have discussed Python Program to Count Number of Uppercase Letters in a String using Recursion

Given a number, bit position and the task is to get the number after clearing the bit at the given bit position for a given number.

In simple words, it converts all 1’s to 0

let number=7  (111)

Bit position that you want to clear =1

It converts the 1 at index 1 to 0

Number after clearing = 5 (101)

Bitwise & Operator:

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

Complement operator(~):

The ones’ complement operator flips the bits of an integer, transforming one into zero and zero into one.

Examples:

Example1:

Input:

Given Number = 60 
Bit position(in range 0-31)= 3

Output:

The Number after clearing the bit at the given position{ 3 } for a given number{ 60 } = 52

Example2:

Input:

Given Number = 7 
Bit position(in range 0-31)= 1

Output:

The Number after clearing the bit at the given position{ 1 } for a given number{ 7 } = 5

Program to Clear nth Bit of a Number in Python

Below are the ways to get the number after clearing the bit at the given bit position for a given number:

Method #1: Using Bitwise &(and) Operator (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Give the bit position as static input and store it in another variable.
  • Apply the left shift operator to 1 and the above-given bit position and store it in another variable.
  • Apply the complement operator (which converts 0 to 1 and vice-versa) to the above result and store it in another variable.
  • Apply bitwise & operation for the given number and the above result and store it in another variable say rslt_numb.
  • Print the number after clearing the bit at the given position for a given number.
  • The Exit of the Program.

Note: ‘0’ indexing .Give the bit position in range(0-31).

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numb = 60
# Give the bit position as static input and store it in another variable.
bitpositin = 3
# Apply the left shift operator to 1 and the above-given bit position and
# store it in another variable.
numbr_bit = (1 << bitpositin)
# Apply the complement operator (which converts 0 to 1 and vice-versa) to the above result
# and store it in another variable.
complemt = (~numbr_bit)
# Apply bitwise & operation for the given number and the above result and store it in
# another variable say rslt_numb.
rslt_numb = gvn_numb & complemt
# Print the number after clearing the bit at the given position for a given number.
print("The Number after clearing the bit at the given position{",
      bitpositin, "} for a given number{", gvn_numb, "} =", rslt_numb)

Output:

The Number after clearing the bit at the given position{ 3 } for a given number{ 60 } = 52

Method #2: Using Bitwise &(and) Operator (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Give the bit position as user input using the int(input()) function and store it in another variable.
  • Apply the left shift operator to 1 and the above-given bit position and store it in another variable.
  • Apply the complement operator (which converts 0 to 1 and vice-versa) to the above result and store it in another variable.
  • Apply bitwise & operation for the given number and the above result and store it in another variable say rslt_numb.
  • Print the number after clearing the bit at the given position for a given number.
  • 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 = "))
# Give the bit position as user input using the int(input()) function 
# and store it in another variable.
bitpositin = int(input("Enter some random number = "))
# Apply the left shift operator to 1 and the above-given bit position and
# store it in another variable.
numbr_bit = (1 << bitpositin)
# Apply the complement operator (which converts 0 to 1 and vice-versa) to the above result
# and store it in another variable.
complemt = (~numbr_bit)
# Apply bitwise & operation for the given number and the above result and store it in
# another variable say rslt_numb.
rslt_numb = gvn_numb & complemt
# Print the number after clearing the bit at the given position for a given number.
print("The Number after clearing the bit at the given position{",
      bitpositin, "} for a given number{", gvn_numb, "} =", rslt_numb)

Output:

Enter some random number = 7
Enter some random number = 1
The Number after clearing the bit at the given position{ 1 } for a given number{ 7 } = 5

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

Python Program to Clear nth Bit of a Number Read More »

Program to Count Number of Uppercase Letters in a String using Recursion

Python Program to Count Number of Uppercase Letters in a String using Recursion

In the previous article, we have discussed Python Program to Count Number of Digits in a Number using Recursion

Given a string and the task is to count the number of uppercase letters present in a given string using recursion.

Recursion:

Recursion is the process by which a function calls itself directly or indirectly, and the associated function is known as a recursive function. Certain issues can be addressed fairly easily using a recursive approach. Towers of Hanoi (TOH), Inorder /Preorder/Postorder Tree Traversals, DFS of Graph, and other analogous issues are examples.

Examples:

Example1:

Input:

Given String = "Hello This is Btechgeeks"

Output:

The Number Of UpperCase characters Present in the above given String { Hello This is Btechgeeks } = 3

Example2:

Input:

Given String = "GOOD morning btechgeeks"

Output:

The Number Of UpperCase characters Present in the above given String { GOOD morning btechgeeks } = 4

Program to Count Number of Uppercase Letters in a String using Recursion in Python

Below are the ways to count the number of uppercase letters present in a given string using recursion in python:

Method #1: Using Recursion (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Take a variable say cnt and initialize its value to 0.
  • Pass the given string and length of the given string-1 as the arguments to the cntUpprCase_chactrs function and store it in a variable rslt_cnt.
  • Create a recursive function to say cntUpprCase_chactrs which takes the given string and a variable p (initially it is the length of the given string ) and returns the count of uppercase characters in a given string.
  • Make the cnt a global declaration.
  • Check if the character present at the index p of the given string is greater than or equal to ‘A’ and less than or equal to ‘Z’ using the if conditional statement.
  • If the statement is true, then increment the value of cnt by 1 and store it in the same variable.
  • Check if the value of p is greater than 0 using the if conditional statement.
  • If the statement is true, pass the given string and p-1 as the arguments to the cntUpprCase_chactrs function.{Recursive logic}
  • Return the value of cnt.
  • Check if the value of rslt_cnt is equal to 0 using the if conditional statement.
  • If the statement is true, then print “There are no UpperCase characters in a given string”.
  • Else print the number of uppercase characters present in the above-given string.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say cntUpprCase_chactrs which takes the given string and
# a variable p (initially it is the length of the given string ) as the arguments to
# the cntUpprCase_chactrs function which returns the count of uppercase characters in
# a given string.


def cntUpprCase_chactrs(gvn_strng, p):
  # Make the cnt a global declaration.
    global cnt
    # Check if the character present at the index p of the given string is greater than or
    # equal to 'A' and less than or equal to 'Z' using the if conditional statement.
    if (gvn_strng[p] >= 'A' and gvn_strng[p] <= 'Z'):
        # If the statement is true, then increment the value of cnt by 1 and store it in the
        # same variable.
        cnt += 1
    # Check if the value of p is greater than 0 using the if conditional statement.
    if (p > 0):
        # If the statement is true, pass the given string and p-1 as the arguments to the
        # cntUpprCase_chactrs function.{Recursive logic}
        cntUpprCase_chactrs(gvn_strng, p - 1)
    # Return the value of cnt.
    return cnt


# Give the string as static input and store it in a variable.
gvn_strng = "Hello This is Btechgeeks"
# Take a variable say cnt and initialize its value to 0.
cnt = 0
# Pass the given string and length of the given string-1 as the arguments to the
# cntUpprCase_chactrs function and store it in a variable rslt_cnt.
rslt_cnt = cntUpprCase_chactrs(gvn_strng, len(gvn_strng)-1)
# Check if the value of rslt_cnt is equal to 0 using the if conditional statement.
if(rslt_cnt == 0):
  # If the statement is true, then print "There are no UpperCase characters in a given
  # string".
    print("There are no UpperCase characters in a given string")
else:
  # Else print the number of uppercase characters present in the above-given string.
    print(
        "The Number Of UpperCase characters Present in the above given String {", gvn_strng, "} =", rslt_cnt)

Output:

The Number Of UpperCase characters Present in the above given String { Hello This is Btechgeeks } = 3

Method #2: Using Recursion (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Take a variable say cnt and initialize its value to 0.
  • Pass the given string and length of the given string-1 as the arguments to the cntUpprCase_chactrs function and store it in a variable rslt_cnt.
  • Create a recursive function to say cntUpprCase_chactrs which takes the given string and a variable p (initially it is the length of the given string ) as the arguments to the cntUpprCase_chactrs function which returns the count of uppercase characters in a given string.
  • Make the cnt a global declaration.
  • Check if the character present at the index p of the given string is greater than or equal to ‘A’ and less than or equal to ‘Z’ using the if conditional statement.
  • If the statement is true, then increment the value of cnt by 1 and store it in the same variable.
  • Check if the value of p is greater than 0 using the if conditional statement.
  • If the statement is true, pass the given string and p-1 as the arguments to the cntUpprCase_chactrs function.{Recursive logic}
  • Return the value of cnt.
  • Check if the value of rslt_cnt is equal to 0 using the if conditional statement.
  • If the statement is true, then print “There are no UpperCase characters in a given string”.
  • Else print the number of uppercase characters present in the above-given string.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say cntUpprCase_chactrs which takes the given string and
# a variable p (initially it is the length of the given string ) as the arguments to
# the cntUpprCase_chactrs function which returns the count of uppercase characters in
# a given string.


def cntUpprCase_chactrs(gvn_strng, p):
  # Make the cnt a global declaration.
    global cnt
    # Check if the character present at the index p of the given string is greater than or
    # equal to 'A' and less than or equal to 'Z' using the if conditional statement.
    if (gvn_strng[p] >= 'A' and gvn_strng[p] <= 'Z'):
        # If the statement is true, then increment the value of cnt by 1 and store it in the
        # same variable.
        cnt += 1
    # Check if the value of p is greater than 0 using the if conditional statement.
    if (p > 0):
        # If the statement is true, pass the given string and p-1 as the arguments to the
        # cntUpprCase_chactrs function {Recursive logic}
        cntUpprCase_chactrs(gvn_strng, p - 1)
    # Return the value of cnt.
    return cnt


# Give the string as user input using the input() function and 
# store it in a variable.
gvn_strng = input("Enter some Random String = ")
# Take a variable say cnt and initialize its value to 0.
cnt = 0
# Pass the given string and length of the given string-1 as the arguments to the
# cntUpprCase_chactrs function and store it in a variable rslt_cnt.
rslt_cnt = cntUpprCase_chactrs(gvn_strng, len(gvn_strng)-1)
# Check if the value of rslt_cnt is equal to 0 using the if conditional statement.
if(rslt_cnt == 0):
  # If the statement is true, then print "There are no UpperCase characters in a given
  # string".
    print("There are no UpperCase characters in a given string")
else:
  # Else print the number of uppercase characters present in the above-given string.
    print(
        "The Number Of UpperCase characters Present in the above given String {", gvn_strng, "} =", rslt_cnt)

Output:

Enter some Random String = GOOD morning btechgeeks
The Number Of UpperCase characters Present in the above given String { GOOD morning btechgeeks } = 4

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 to Count Number of Uppercase Letters in a String using Recursion Read More »