Clear a bit in c – Program to Clear the Rightmost Set Bit of a Number in C++ and Python

Program to Clear the Rightmost Set Bit of a Number in C++ and Python


Clear a bit in c:
In the previous article, we have discussed about C++ Program to Check if it is Sparse Matrix or Not. Let us learn Program to Clear the Rightmost Set Bit of a Number in C++ Program and Python.

Binary Representation of a Number:

Binary is a base-2 number system in which a number is represented by two states: 0 and 1. We can also refer to it as a true and false state. A binary number is constructed in the same way that a decimal number is constructed.

Examples:

Examples1:

Input:

given number=19

Output:

The given number before removing right most set bit : 
19
The given number after removing right most set bit : 
18

Examples2:

Input:

given number =18

Output:

The given number before removing right most set bit : 
18
The given number after removing right most set bit : 
16

Examples3:

Input:

given number=512

Output:

The given number before removing right most set bit : 
512
The given number after removing right most set bit : 
0

Program to Clear the Rightmost Set Bit of a Number in C++ and Python

There are several ways to clear the rightmost set Bit of a Number in C++ and Python some of them are:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

Method #1: Using Bitwise Operators in C++

Approach:

  • There is a function called clear rightmost set bit that is defined.
  • It accepts n as an argument and returns n with its rightmost set bit cleared.
  • This is accomplished by computing n & (n – 1) and returning the result.
  • (n – 1) equals n when all the rightmost successive 0s are flipped and the initial rightmost 1 is flipped.
  • As a result, n & (n – 1) equals n with the rightmost 1 cleared.

Below is the implementation of above approach:

#include <bits/stdc++.h>
using namespace std;
// function which removes the right most set bit in the
// given number
int clearRight(int numb)
{
    // clearing the right most set bit from
    // the given number and store it in the result
    int reslt = (numb) & (numb - 1);
    // returing the calculated result
    return reslt;
}

// main function
int main()
{
    // given number
    int numb = 19;

    cout << "The given number before removing right most "
            "set bit : "
         << numb << endl;
    // passing the given number to clearRight function
    // to remove the clear the rightmost setbit
    cout << "The given number after removing right most "
            "set bit : "
         << clearRight(numb) << endl;
    return 0;
}

Output:

The given number before removing right most set bit : 19
The given number after removing right most set bit : 18

Method #2: Using Bitwise Operators in Python

Approach:

  • There is a function called clear rightmost set bit that is defined.
  • It accepts n as an argument and returns n with its rightmost set bit cleared.
  • This is accomplished by computing n & (n – 1) and returning the result.
  • (n – 1) equals n when all the rightmost successive 0s are flipped and the initial rightmost 1 is flipped.
  • As a result, n & (n – 1) equals n with the rightmost 1 cleared.
  • We will implement the same function in python

Below is the implementation:

# function which removes the right most set bit in the
# given number


def clearRight(numb):
    # clearing the right most set bit from
    # the given number and store it in the result
    reslt = (numb) & (numb - 1)
    # returing the calculated result
    return reslt
# Driver Code


# given number
numb = 19

print("The given number before removing right most "
      "set bit : ")
print(numb)
# passing the given number to clearRight function
# to remove the clear the rightmost setbit
print("The given number after removing right most set bit : ")
print(clearRight(numb))

Output:

The given number before removing right most set bit : 
19
The given number after removing right most set bit : 
18

Related Programs:

Angle between two vectors python – Python Program To Calculate the Angle Between Two Vectors

Program To Calculate the Angle Between Two Vectors

Angle between two vectors python: In the previous article, we have discussed Python Program to Find the Sine Series for the Given range
Mathematical Way :

Python angle between two vectors: The angle between two vectors can be calculated using the formula, which states that the angle cos of two vectors is equal to the dot product of two vectors divided by the dot product of the mod of two vectors.

cosθ = X.Y/|X|.|Y|  =>θ =  cos^-1 X.Y/|X|.|Y|

Example:

Let  X={5,6} and y={4,3} are two vectors.

The angle between given two vectors = X.Y=  5*4+6*3 = 38

|X| = √ 5^2 +6^2 = 7.8102

|Y| = √ 4^2 +3^2 = 5

cosθ = 38/7.8102*5 = 0.973

θ= 13.324°

In this, we use the ‘math’ module to perform some complex calculations for us, such as square root, cos inverse, and degree, by calling the functions sqrt(), acos(), and degrees ().

Given two vectors, and the task is to calculate the angle between the given two vectors.

Examples:

Example1:

Input: 

Given x1, y1, x2, y2 = 5, 6, 4, 3

Output:

The Cos angle between given two vectors = 0.9730802874900094
The angle in degree between given two vectors =  13.324531261890783

Example 2:

Input:

Given x1, y1, x2, y2  =  7, 3, 2, 1

Output:

The Cos angle between given two vectors = 0.9982743731749958
The angle in degree between given two vectors = 3.36646066342994

Program To Calculate the Angle Between Two Vectors

Python angle between two vectors: Below are the ways to Calculate the Angle Between Two Vectors.

Method #1: Using Mathematical Formula (Static input)

Approach:

  • Import math module using the import keyword.
  • Give four variables as static input and store them in four different variables.
  • Calculate the dot product of the given two vectors using the above mathematical formula and store them in another variable.
  • Calculate the Mod of given two vectors using the above mathematical formula and store them in another variable.
  • Find the cosine angle between the given two vectors using the above mathematical formula and store them in another variable.
  • Print the cosine angle between the given two vectors.
  • Calculate the angle in degrees using built-in math.degrees(), math.acos() functions and store it in a variable .
  • Print the angle ‘θ’ between the given two vectors.
  • The Exit of the program.

Below is the implementation:

# Import math module using the import keyword.
import math
# Give four variables as static input and store them in four different variables.
x1, y1, x2, y2 = 5, 6, 4, 3


def angle_between_Gvnvectors(x1, y1, x2, y2):
    # Calculate the dot product of given two vectors using above mathematical formula
    # and store them in another variable.

    dot_Prodct = x1*x2 + y1*y2
 # Calculate the Mod of given two vectors using above mathematical formula and
# store them in another variable
    mod_Of_Vectr1 = math.sqrt(x1*x1 + y1*y1)*math.sqrt(x2*x2 + y2*y2)
 # Find the cosine angle between given two vectors  using above mathematical formula
# and store them in another variable.
    cosine_angle = dot_Prodct/mod_Of_Vectr1
 # Print the cosine angle between given two vectors.
    print(" The Cos angle between given two vectors =", cosine_angle)
# Calculate the angle in degrees using built-in math.degrees(), math.acos() functions
# and store it in a variable .
    angl_in_Degres = math.degrees(math.acos(cosine_angle))
# Print the angle 'θ' between given two vectors.
    print("The angle in degree between given two vectors = ", angl_in_Degres)


angle_between_Gvnvectors(x1, y1, x2, y2)

Output:

The Cos angle between given two vectors = 0.9730802874900094
The angle in degree between given two vectors =  13.324531261890783

Method #2: Using Mathematical Formula (User input)

Approach:

  • Import math module using the import keyword.
  • Give four variables as user input using map(),split() , int(input()) functions and store them in four different variables.
  • Calculate the dot product of the given two vectors using the above mathematical formula and store them in another variable.
  • Calculate the Mod of given two vectors using the above mathematical formula and store them in another variable.
  • Find the cosine angle between the given two vectors using the above mathematical formula and store them in another variable.
  • Print the cosine angle between the given two vectors.
  • Calculate the angle in degrees using built-in math.degrees(), math.acos() functions and store it in a variable .
  • Print the angle ‘θ’ between the given two vectors.
  • The Exit of the program.

Below is the implementation of the above approach:

# Import math module using the import keyword.
import math
# Give four variables as user input using map(),split() ,int(input())functions and 
#store them in four different variables.
x1, y1, x2, y2 = map(int,input("Enter four random numbers = ").split())
def angle_between_Gvnvectors(x1, y1, x2, y2):
    # Calculate the dot product of given two vectors using above mathematical formula
    # and store them in another variable.

    dot_Prodct = x1*x2 + y1*y2
 # Calculate the Mod of given two vectors using above mathematical formula and
# store them in another variable
    mod_Of_Vectr1 = math.sqrt(x1*x1 + y1*y1)*math.sqrt(x2*x2 + y2*y2)
 # Find the cosine angle between given two vectors  using above mathematical formula
# and store them in another variable.
    cosine_angle = dot_Prodct/mod_Of_Vectr1
 # Print the cosine angle between given two vectors.
    print(" The Cos angle between given two vectors =", cosine_angle)
# Calculate the angle in degrees using built-in math.degrees(), math.acos() functions
# and store it in a variable .
    angl_in_Degres = math.degrees(math.acos(cosine_angle))
# Print the angle 'θ' between given two vectors.
    print("The angle in degree between given two vectors = ", angl_in_Degres)

angle_between_Gvnvectors(x1, y1, x2, y2)

Output:

Enter four random numbers = 7 3 2 1
The Cos angle between given two vectors = 0.9982743731749958
The angle in degree between given two vectors = 3.36646066342994

Here we calculated the angle between the given vectors.

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Palindrome recursion python – Python Program to Check Whether a String is a Palindrome or not Using Recursion

Program to Check Whether a String is a Palindrome or not Using Recursion

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

Recursion in Python:

Palindrome recursion python: When a function calls itself and loops until it reaches the intended end state, this is referred to as recursion. It is based on the mathematics idea of recursive definitions, which define elements in a set in terms of other members in the set.

Each recursive implementation contains a base case in which the desired state is reached, and a recursive case in which the desired state is not reached and the function enters another recursive phase.

On each step, the behavior in the recursive situation before the recursive function call, the internal self-call, is repeated. Recursive structures are beneficial when a larger problem (the base case) can be solved by solving repeated subproblems (the recursive case) that incrementally advance the program to the base case.
It behaves similarly to for and while loops, with the exception that recursion moves closer to the desired condition, whereas for loops run a defined number of times and while loops run until the condition is no longer met.

In other words, recursion is declarative because you specify the desired state, whereas for/while loops are iterative because you provide the number of repeats.

Strings in Python:

Recursive palindrome python: A string is typically a piece of text (sequence of characters). To represent a string in Python, we use ” (double quotes) or ‘ (single quotes).

Examples:

Example1:

Input:

given string = "btechgeeksskeeghcetb"

Output:

The given string [ btechgeeksskeeghcetb ] is a palindrome

Example2:

Input:

given string = "aplussulpa"

Output:

The given string [ aplussulpa ] is a palindrome

Program to Check Whether a String is a Palindrome or not Using Recursion

Below are the ways to Check Whether a String is a Palindrome or not using the recursive approach in Python:

1)Using Recursion (Static Input)

Approach:

  • Give some string as static input and store it in a variable.
  • Pass the string to a recursive function checkPalindromeRecursion function as an argument.
  • Calculate the length of the string using the len() function.
  • If the length of the string is less than 1, the function returns True.
  • If the end letter is the same as the initial letter, execute the function recursively with the parameter as the sliced list with the first and last characters deleted, otherwise return False.
  • Use an if statement to determine whether the given string is True or False and then print the result.
  • If the function returns true then the given string is a palindrome.
  • Else the given string is not a palindrome.
  • The exit of the program.

Below is the implementation:

# function which checks the given string is palindrome or not using recursion
# if th given string is palindrome then it is true else the string is false.


def checkPalindromeRecursion(givenstr):
  # Calculate the length of the string using the len() function.
    stringLen = len(givenstr)
    # If the length of the string is less than 1, the function returns True.
    if stringLen < 1:
        return True
    else:
      # If the end letter is the same as the initial letter, execute the function
      # recursively with the parameter as the sliced list
      # with the first and last characters deleted, otherwise return False.
      # Use an if statement to determine whether the given string is
      # True or False and then print the result.
        if givenstr[0] == givenstr[-1]:
            return checkPalindromeRecursion(givenstr[1:-1])
        else:
            return False


# Give some string as static input and store it in a variable.
given_str = 'btechgeeksskeeghcetb'
# Pass the string to a recursive function checkPalindromeRecursion function as an argument.
# If the function returns true then the given string is a palindrome.
if(checkPalindromeRecursion(given_str)):
    print("The given string [", given_str, '] is a palindrome')
# Else the given string is not a palindrome.
else:
    print("The given string", given_str, 'is not a palindrome')

Output:

The given string [ btechgeeksskeeghcetb ] is a palindrome

2)Using Recursion (User Input)

Approach:

  • Give some random string as user input using the input() function and store it in a variable.
  • Pass the string to a recursive function checkPalindromeRecursion function as an argument.
  • Calculate the length of the string using the len() function.
  • If the length of the string is less than 1, the function returns True.
  • If the end letter is the same as the initial letter, execute the function recursively with the parameter as the sliced list with the first and last characters deleted, otherwise return False.
  • Use an if statement to determine whether the given string is True or False and then print the result.
  • If the function returns true then the given string is a palindrome.
  • Else the given string is not a palindrome.
  • The exit of the program.

Below is the implementation:

# function which checks the given string is palindrome or not using recursion
# if th given string is palindrome then it is true else the string is false.


def checkPalindromeRecursion(givenstr):
  # Calculate the length of the string using the len() function.
    stringLen = len(givenstr)
    # If the length of the string is less than 1, the function returns True.
    if stringLen < 1:
        return True
    else:
      # If the end letter is the same as the initial letter, execute the function
      # recursively with the parameter as the sliced list
      # with the first and last characters deleted, otherwise return False.
      # Use an if statement to determine whether the given string is
      # True or False and then print the result.
        if givenstr[0] == givenstr[-1]:
            return checkPalindromeRecursion(givenstr[1:-1])
        else:
            return False


# Give some random string as user input using the input()
# function and store it in a variable.
given_str = input('Enter some random string = ')
# Pass the string to a recursive function checkPalindromeRecursion function as an argument.
# If the function returns true then the given string is a palindrome.
if(checkPalindromeRecursion(given_str)):
    print("The given string [", given_str, '] is a palindrome')
# Else the given string is not a palindrome.
else:
    print("The given string", given_str, 'is not a palindrome')

Output:

Enter some random string = aplussulpa
The given string [ aplussulpa ] is a palindrome

Explanation:

  • A string must be entered by the user.
  • A recursive function gets the string as an argument.
  • If the length of the string is less than one, the function returns True.
  • If the end letter is the same as the initial letter, the function is repeated recursively with the argument as the sliced list with the first and last characters removed, otherwise, false is returned.
  • The if statement is used to determine whether the returned value is True or False, and the result is printed.

Related Programs:

Numpy unique – Python: Find Unique Values in a Numpy Array With Frequency and Indices

Methods to find unique values in a numpy array with frequency and indices

Numpy get unique values: In this article, we will discuss how to find unique values, rows, and columns in a 1D & 2D Numpy array. Before going to the methods first we see numpy.unique() method because this method is going to be used.

numpy.unique() method

Numpy unique: numpy.unique() method help us to get the unique() values from given array.

syntax:numpy.unique(array, return_index=False, return_inverse=False, return_counts=False, axis=None)

Parameters

  1. array-Here we have to pass our array from which we want to get unique value.
  2. return_index- If this parameter is true then it will return the array of the index of the first occurrence of each unique value. By default it is false.
  3. return_counts-If this parameter is true then it will return the array of the count of the occurrence of each unique value. By default it is false.
  4. axis- It is used in the case of nd array, not in 1d array. axis=1 means we have to do operation column-wise and axis=0 means we have to do operation row-wise.

Now we will see different methods to find unique value with their indices and frequencies in a numpy array.

case 1-When our array is 1-D

  • Method 1-Find unique value from the array

Numpy unique values: As we only need unique values and not their frequencies and indices hence we simply pass our numpy array in the unique() method because the default value of other parameters is false so we don’t need to change them. Let see this with the help of an example.

import numpy as np
arr = np.array([1, 1, 2, 3, 4, 5, 6, 7, 2, 3, 1, 4, 7])
unique_values=np.unique(arr)
print("Original array is")
print(arr)
print("------------------")
print("Unique values are")
print(unique_values)

Output

Original array is
[1 1 2 3 4 5 6 7 2 3 1 4 7]
------------------
Unique values are
[1 2 3 4 5 6 7]
  • Method 2-Find unique value from the array along with their indices

Numpy frequency count: In this method, as we want to get unique values along with their indices hence we make the return_index parameter true and pass our array. Let see this with the help of an example.

import numpy as np
arr = np.array([1, 1, 2, 3, 4, 5, 6, 7, 2, 3, 1, 4, 7])
unique_values,index=np.unique(arr,return_index=True)
print("Original array is")
print(arr)
print("------------------")
print("Unique values are")
print(unique_values)
print("First index of unique values are:")
print(index)

Output

Original array is
[1 1 2 3 4 5 6 7 2 3 1 4 7]
------------------
Unique values are
[1 2 3 4 5 6 7]
First index of unique values are:
[0 2 3 4 5 6 7]
  • Method 3-Find unique value from the array along with their frequencies

Numpy count unique: In this method, as we want to get unique values along with their frequencies hence we make the return_counts parameter true and pass our array. Let see this with the help of an example.

import numpy as np
arr = np.array([1, 1, 2, 3, 4, 5, 6, 7, 2, 3, 1, 4, 7])
unique_values,count=np.unique(arr,return_counts=True)
print("Original array is")
print(arr)
print("------------------")
print("Unique values are")
print(unique_values)
print("Count of unique values are:")
for i in range(0,len(unique_values)):
  print("count of ",unique_values[i]," is ",count[i])

Output

Original array is
[1 1 2 3 4 5 6 7 2 3 1 4 7]
------------------
Unique values are
[1 2 3 4 5 6 7]
Count of unique values are:
count of  1  is  3
count of  2  is  2
count of  3  is  2
count of  4  is  2
count of  5  is  1
count of  6  is  1
count of  7  is  2

Case 2: When our array is 2-D

  • Method 1-Find unique value from the array

Numpy unique: Here we simply pass our array and all the parameter remain the same. Here we don’t make any changes because we want to work on both rows and columns. Let see this with the help of an example.

import numpy as np
arr = np.array([[1, 1, 2,1] ,[ 3, 1, 2,1] , [ 6, 1, 2, 1],  [1, 1, 2, 1]])
unique_values=np.unique(arr)
print("Original array is")
print(arr)
print("------------------")
print("Unique values are")
print(unique_values)

Output

Original array is
[[1 1 2 1]
 [3 1 2 1]
 [6 1 2 1]
 [1 1 2 1]]
------------------
Unique values are
[1 2 3 6]

Method 2-Get unique rows

Numpy unique: As here want to want to work only on rows so here we will make axis=0 and simply pass our array. Let see this with the help of an example.

import numpy as np
arr = np.array([[1, 1, 2,1] ,[ 3, 1, 2,1] , [ 6, 1, 2, 1],  [1, 1, 2, 1]])
unique_values=np.unique(arr,axis=0)
print("Original array is")
print(arr)
print("------------------")
print("Unique rows are")
print(unique_values)

Output

Original array is
[[1 1 2 1]
 [3 1 2 1]
 [6 1 2 1]
 [1 1 2 1]]
------------------
Unique rows are
[[1 1 2 1]
 [3 1 2 1]
 [6 1 2 1]]

Method 3-Get unique columns

As here want to want to work only on columns so here we will make axis=1 and simply pass our array. Let see this with the help of an example.

import numpy as np
arr = np.array([[1, 1, 2,1] ,[ 3, 1, 2,1] , [ 6, 1, 2, 1],  [1, 1, 2, 1]])
unique_values=np.unique(arr,axis=1)
print("Original array is")
print(arr)
print("------------------")
print("Unique columns are")
print(unique_values)

Output

Original array is
[[1 1 2 1]
 [3 1 2 1]
 [6 1 2 1]
 [1 1 2 1]]
------------------
Unique columns are
[[1 1 2]
 [1 3 2]
 [1 6 2]
 [1 1 2]]

so these are the methods to find unique values in a numpy array with frequency and indices.

 

Python Program to Read Height in Centimeters and then Convert the Height to Feet and Inches

Program to Read Height in Centimeters and then Convert the Height to Feet and Inches

179.5cm in feet: Given height in centimeters , the task is to convert the given height to feet and inches in Python.

Examples:

Example1:

Input:

Enter some random height in centimeters = 179.5

Output:

The given height 179.5 cm in inches = 70.72 inches
The given height 179.5 cm in feet = 5.89 feet

Example2:

Input:

Enter some random height in centimeters = 165

Output:

The given height 165.0 cm in inches = 65.01 inches
The given height 165.0 cm in feet = 5.41 feet

Program to Read Height in Centimeters and then Convert the Height to Feet and Inches in Python

179.5cm in feet: There are several ways to read height in centimeters and then convert it to feet and inches in  Python some of them are:

Method #1:Python Static Input

  • Give the height in centimeters as static input.
  • Convert the given height in centimeters to feet by multiplying it with 0.0328 and store it in a variable.
  • Convert the given height in centimeters to inches by multiplying it with 0.0.394 and store it in a variable.
  • Print the height in feet and inches.
  • Exit of Program.

Below is the implementation:

# Give the height in centimeters as static input.
heightcm = 165
# Convert the given height in centimeters to feet by multiplying it with 0.0328
# and store it in a variable.
heightfeet = 0.0328*heightcm
# Convert the given height in centimeters to inches by multiplying it with 0.0.394
# and store it in a variable.
heightinches = 0.394*heightcm
# Print the height in feet and inches.
print("The given height", heightcm, 'cm',
      'in inches = ', round(heightinches, 2), 'inches')
print("The given height", heightcm, 'cm',
      'in feet = ', round(heightfeet, 2), 'feet')

Output:

The given height 165 cm in inches =  65.01 inches
The given height 165 cm in feet =  5.41 feet

Explanation:

  • Given the height in centimeters as static input.
  • The height in centimeters is multiplied by 0.394 and saved in a new variable called height in inches.
  • The height in centimeters is multiplied by 0.0328 and saved in a new variable called height in feet.
  • It is printed the conversion height in inches and feet.

Method #2:Python User Input

Approach:

  • Enter the height in centimeters as user input using float(input()) function .
  • Convert the given height in centimeters to feet by multiplying it with 0.0328 and store it in a variable.
  • Convert the given height in centimeters to inches by multiplying it with 0.0.394 and store it in a variable.
  • Print the height in feet and inches.
  • Exit of Program.

Below is the implementation:

# Enter the height in centimeters as user input using int(input()) function.
heightcm = int(input('Enter some random height in centimeters = '))
# Convert the given height in centimeters to feet by multiplying it with 0.0328
# and store it in a variable.
heightfeet = 0.0328*heightcm
# Convert the given height in centimeters to inches by multiplying it with 0.0.394
# and store it in a variable.
heightinches = 0.394*heightcma
# Print the height in feet and inches.
print("The given height", heightcm, 'cm',
      'in inches = ', round(heightinches, 2), 'inches')
print("The given height", heightcm, 'cm',
      'in feet = ', round(heightfeet, 2), 'feet')

Output:

Enter some random height in centimeters = 169
The given height 169 cm in inches = 66.59 inches
The given height 169 cm in feet = 5.54 feet

Explanation:

  • As the height can be in decimals we take input using  float(input()) function.
  • The height in centimeters is multiplied by 0.394 and saved in a new variable called height in inches.
  • The height in centimeters is multiplied by 0.0328 and saved in a new variable called height in feet.
  • It is printed the conversion height in inches and feet.

Related Programs:

Divide all elements of list python – Python Program Divide all Elements of a List by a Number

Program Divide all Elements of a List by a Number

Divide all elements of list python: In the previous article, we have discussed Python Program to Get Sum of all the Factors of a Number

Given a list, and the task is to divide all the elements of a given List by the given Number in Python

As we know, elements such as int, float, string, and so on can be stored in a List. As we all know, dividing a string by a number is impossible. To divide elements of a list, all elements must be int or float.

Examples:

Example1:

Input:

Given List = [3, 2.5, 42, 24, 15, 32]
Given Number = 2

Output:

The above given list after division all elements of a List by the given Number= [1.5, 1.25, 21.0, 12.0, 7.5, 16.0]

Example 2:

Input:

Given List =  [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
Given Number = 5

Output:

The above given list after division all elements of a List by the given Number= [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]

Program Divide all Elements of a List by a Number

Python divide list by number: Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language

Below are the ways to divide all Elements of a List by a Number.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Give the number as static input and store it in another variable.
  • Take a new empty list and store it in a variable.
  • Iterate in the above-given list using For Loop.
  • Divide the iterator by the above-given number and append the result to the above declared new list.
  • print the above given new list after division all elements of a List by the given Number.
  • The Exit of the program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gven_Lst = [3, 2.5, 42, 24, 15, 32]
# Give the number as static input and store it in another variable.
gvn_numb = 2
# Take a new empty list and store it in a variable.
Lst_aftr_div = []
# Iterate in the above given list using For Loop.
for itr in gven_Lst:
  # Divide the iterator  by  the above given number and append the result to the
  # above declared new list.
    Lst_aftr_div.append(itr/gvn_numb)
# print the above given list after division all elements of a List by the given Number.
print("The above given list after division all elements of a List by the given Number=", Lst_aftr_div)

Output:

The above given list after division all elements of a List by the given Number= [1.5, 1.25, 21.0, 12.0, 7.5, 16.0]

Method #2: Using For Loop (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions and store it in a variable.
  • Give the number as user input using the int(input()) function and store it in another variable.
  • Take a new empty list and store it in a variable.
  • Iterate in the above-given list using the For Loop.
  • Divide the iterator by the above-given number and append the result to the above declared new list.
  • Print the above given new list after division all elements of a List by the given Number.
  • The Exit of the program.

Below is the implementation:

#Give the list as user input using list(),map(),input(),and split() functions.
gven_Lst = list(map(float, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Give the number as user input using int(input()) and store it in another variable.
gvn_numb = int(input("Enter some random number = " ))
#Take a new empty list and store it in a variable.
Lst_aftr_div = []
# Iterate in the above given list using For Loop.
for itr in gven_Lst:
  # Divide the iterator by the above given number and append the result to the
  # above declared new list.
    Lst_aftr_div.append(itr/gvn_numb)
# print the above given list after division all elements of a List by the given Number.
print("The above given list after division all elements of a List by the given Number=", Lst_aftr_div)

Output:

Enter some random List Elements separated by spaces = 4 5 8 9.6 15 63 32 84
Enter some random number = 4
The above given list after division all elements of a List by the given Number= [1.0, 1.25, 2.0, 2.4, 3.75, 15.75, 8.0, 21.0]

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python invert dictionary – Python Program to invert a Dictionary

Program to invert a Dictionary

Python invert dictionary: In the previous article, we have discussed Python Program to Check if two Lines are Parallel or Not
Dictionary in python:

Python includes a class dictionary, which is typically defined as a set of key-value pairs. In Python, inverting a dictionary means swapping the key and value in the dictionary.

One thing is certain: complexity can be found in all of the different ways of storing key-value pairs. That is why dictionaries are used.

Python dictionaries are mutable collections of things that contain key-value pairs. The dictionary contains two main components: keys and values. These keys must be single elements, and the values can be of any data type, such as list, string, integer, tuple, and so on. The keys are linked to their corresponding values. In other words, the values can be retrieved using their corresponding keys.

A dictionary is created in Python by enclosing numerous key-value pairs in curly braces.

For example :

dictionary ={‘monday’:1, ‘tuesday’:2, ‘wednesday’:3}

The output after inverting the dictionary is { 1: [‘monday’] , 2: [‘tuesday’] , 3: [‘wednesday’] }

Given a dictionary, and the task is to invert the given dictionary.

Examples:

Example1:

Input:

Given dictionary = {10: 'jan', 20: 'feb', 30: 'march', 40: 'April', 50: 'may'}

Output:

The inverse of the given dictionary =  {'jan': [10], 'feb': [20], 'march': [30], 'April': [40], 'may': [50]}

Example 2:

Input:

Given dictionary = {'monday': 1, 'tuesday': 2, 'wednesday': 3}

Output:

The inverse of the given dictionary = {1: ['monday'], 2: ['tuesday'], 3: ['wednesday']}

Program to invert a Dictionary in Python

Below are the ways to invert a given dictionary

Method #1: Using For Loop (Static Input)

Approach:

  • Give the dictionary as static input and store it in a variable.
  • Create a new empty dictionary say ” inverse_dict” and store it in another variable.
  • Iterate in the above dictionary using the dictionary. items() and for loop.
  • Check if the value is present in the above declared  ” inverse_dict” using the if conditional statement and the ‘in’ keyword.
  • If the statement is true, then append the value to the “inverse_dict” dictionary using the append() function.
  • Else assign the value to the key.
  • Print the above declared ” inverse_dict” variable to get the inverse of the given dictionary.
  • The Exit of the program.

Below is the implementation:

# Give the dictionary as static input and store it in a variable.
gvn_dict = {'monday': 1, 'tuesday': 2, 'wednesday': 3}
# Create a new empty dictionary say " inverse_dict" and store it in another variable.
inverse_dict = {}
# Iterate in the above dictionary using the dictionary. items() and for loop.
for key, value in gvn_dict.items():
  # Check if the value is present in the above declared  " inverse_dict" using
  # the if conditional statement and the 'in' keyword.
    if value in inverse_dict:
     # If the statement is true, then append the value to the "inverse_dict" dictionary
     # using the append() function.
        inverse_dict[value].append(key)
    else:
     # Else assign the value to the key.
        inverse_dict[value] = [key]
  # Print the above declared " inverse_dict" variable to get the inverse of the
  # given dictionary.
print("The inverse of the given dictionary = ", inverse_dict)

Output:

The inverse of the given dictionary =  {1: ['monday'], 2: ['tuesday'], 3: ['wednesday']}

Method #2: Using For Loop (User Input)

Approach:

  • Take a dictionary and initialize it with an empty dictionary using dict() or {}.
  • Give the number of keys as user input using int(input()) and store it in a variable.
  • Loop till the given number of keys using for loop.
  • Inside the for loop scan the key and value as user input using input(), split() functions, and store them in two separate variables.
  • Initialize the key with the value of the dictionary.
  • Create a new empty dictionary say ” inverse_dict” and store it in another variable.
  • Iterate in the above dictionary using the dictionary. items() and for loop.
  • Check if the value is present in the above declared  ” inverse_dict” using the if conditional statement and the ‘in’ keyword.
  • If the statement is true, then append the value to the “inverse_dict” dictionary using the append() function.
  • Else assign the value to the key.
  • Print the above declared ” inverse_dict” variable to get the inverse of the given dictionary.
  • The Exit of the program.

Below is the implementation:

# Take a dictionary and initialize it with an empty dictionary using dict() or {}.
gvn_dict = {}
# Give the number of keys as user input using int(input()) and store it in a variable.
numb_of_kys = int(
    input('Enter some random number of keys of the dictionary = '))
# Loop till the given number of keys using for loop.
for p in range(numb_of_kys):
        # Inside the for loop scan the key and value as
    # user input using input(),split() functions
    # and store them in two separate variables.
    keyy, valuee = input(
        'Enter key and value separated by spaces = ').split()
    # Initialize the key with the value of the dictionary.
    gvn_dict[keyy] = valuee

# Create a new empty dictionary say " inverse_dict" and store it in another variable.
inverse_dict = {}
# Iterate in the above dictionary using the dictionary. items() and for loop.
for key, value in gvn_dict.items():
  # Check if the value is present in the above declared  " inverse_dict" using
  # the if conditional statement and the 'in' keyword.
    if value in inverse_dict:
     # If the statement is true, then append the value to the "inverse_dict" dictionary
     # using the append() function.
        inverse_dict[value].append(key)
    else:
     # Else assign the value to the key.
        inverse_dict[value] = [key]
  # Print the above declared " inverse_dict" variable to get the inverse of the
  # given dictionary.
print("The inverse of the given dictionary = ", inverse_dict)

Output:

Enter some random number of keys of the dictionary = 5
Enter key and value separated by spaces = hello 785
Enter key and value separated by spaces = this 100
Enter key and value separated by spaces = is 900
Enter key and value separated by spaces = btechgeeks 500
Enter key and value separated by spaces = python 400
The inverse of the given dictionary = {'785': ['hello'], '100': ['this'], '900': ['is'], '500': ['btechgeeks'], '400': ['python']}

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python random choice no repeat – Random Choice of Random Module in Python with no Repeat

Random Choice of Random Module in Python with no Repeat

Python random choice no repeat: Given the upper limit and lower limit, the task is to generate n natural numbers which are not repeating in Python.

Examples:

Example1:

Input:

Given N=13
Given lower limit range =19
Given upper limit range =45

Output:

The random numbers present in the range from 19 to 45 are :
28 40 24 25 20 44 38 29 21 31 43

Example2:

Input:

Given N=19
Given lower limit range =23
Given upper limit range =41

Output:

The random numbers present in the range from 23 to 41 are : 26 27 40 38 37 41 30 35 36 23 25

Random choice of Random module in Python with no Repeat

Below are the ways to generate n natural numbers which are not repeating in Python.

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

Method #1: Using For Loop and randint function (Static Input)

Approach:

  • Import the random module using the import keyword.
  • Give the number n as static input and store it in a variable.
  • Give the lower limit range and upper limit range as static input and store them in two separate variables.
  • Take an empty list (say rndmnumbs) and initialize it with an empty list using [] or list().
  • Loop till n times using For loop.
  • Generate a random number using randint(lowerlimitrange,upperlimitrange) and store it in a variable.
  • Check whether the above random number is present in the list or not using not in operator.
  • If it is not in the list then append the element to the rndmnumbs list using the append() function.
  • Print the rndmnumbs.
  • The Exit of the Program.

Below is the implementation:

# Import the random module using the import keyword.
import random
# Give the number n as static input and store it in a variable.
numbe = 13
# Give the lower limit range and upper limit range as static input
# and store them in two separate variables.
lowerlimitrange = 19
upperlimitrange = 45
# Take an empty list (say rndmnumbs) and initialize it with an empty list
# using [] or list().
rndmnumbs = []
# Loop till n times using For loop.
for m in range(numbe):
        # Generate a random number using randint(lowerlimitrange,upperlimitrange)
    # and store it in a variable.
    randomnumbe = random.randint(lowerlimitrange, upperlimitrange)
    # Check whether the above random number is present in the list or not
    # using not in operator.
    if randomnumbe not in rndmnumbs:
        # If it is not in the list then append the element
        # to the rndmnumbs list using the append() function.
        rndmnumbs.append(randomnumbe)

# Print the rndmnumbs
print('The random numbers present in the range from',
      lowerlimitrange, 'to', upperlimitrange, 'are :')
for q in rndmnumbs:
    print(q, end=' ')

Output:

The random numbers present in the range from 19 to 45 are :
28 40 24 25 20 44 38 29 21 31 43

Method #2: Using For Loop and randint function (User Input)

Approach:

  • Import the random module using the import keyword.
  • Give the number n as user input using int(input()) and store it in a variable.
  • Give the lower limit range and upper limit range as user input using map(),int(),split(),input() functions.
  • Store them in two separate variables.
  • Take an empty list (say rndmnumbs) and initialize it with an empty list using [] or list().
  • Loop till n times using For loop.
  • Generate a random number using randint(lowerlimitrange,upperlimitrange) and store it in a variable.
  • Check whether the above random number is present in the list or not using not in operator.
  • If it is not in the list then append the element to the rndmnumbs list using the append() function.
  • Print the rndmnumbs.
  • The Exit of the Program.

Below is the implementation:

# Import the random module using the import keyword.
import random
# Give the number n as user input using int(input()) and store it in a variable.
numbe = int(input('Enter some random number = '))
# Give the lower limit range and upper limit range as user input
# using map(),int(),split(),input() functions.
# Store them in two separate variables.
lowerlimitrange = int(input('Enter random lower limit range = '))
upperlimitrange = int(input('Enter random upper limit range = '))
# Take an empty list (say rndmnumbs) and initialize it with an empty list
# using [] or list().
rndmnumbs = []
# Loop till n times using For loop.
for m in range(numbe):
        # Generate a random number using randint(lowerlimitrange,upperlimitrange)
    # and store it in a variable.
    randomnumbe = random.randint(lowerlimitrange, upperlimitrange)
    # Check whether the above random number is present in the list or not
    # using not in operator.
    if randomnumbe not in rndmnumbs:
        # If it is not in the list then append the element
        # to the rndmnumbs list using the append() function.
        rndmnumbs.append(randomnumbe)

# Print the rndmnumbs
print('The random numbers present in the range from',
      lowerlimitrange, 'to', upperlimitrange, 'are :')
for q in rndmnumbs:
    print(q, end=' ')

Output:

Enter some random number = 19
Enter random lower limit range = 23
Enter random upper limit range = 41
The random numbers present in the range from 23 to 41 are :
26 27 40 38 37 41 30 35 36 23 25

Related Programs:

Collatz conjecture c++ – Program to Print Collatz Conjecture for a Given Number in C++ and Python

Program to Print Collatz Conjecture for a Given Number in C++ and Python

Collatz conjecture c++: In the previous article, we have discussed about Program to Read a Number n and Compute n+nn+nnn in C++ and Python. Let us learn Program to Print Collatz Conjecture for a Given Number in C++ Program.

Given a number , the task is to print Collatz Conjecture of the given number in C++ and Python.

Collatz Conjecture:

  • The Collatz Conjecture states that a specific sequence will always reach the value 1.
  • It is given as follows, beginning with some integer n:
  • If n is an even number, the following number in the sequence is n/2.
  • Otherwise, the following number is 3n+1 (if n is odd).

Examples:

Example1:

Input:

given number =5425

Output:

The Collatz Conjecture of the number :
5425 16276 8138 4069 12208 6104 3052 1526 763 2290 1145 3436 1718 859 2578 1289 3868 1934 967 2902 1451 4354 2177 6532 3266 1633 4900 2450 1225 3676 1838 919 2758 1379 4138 2069 6208 3104 1552 776 388 194 97 292 146 73 220 110 55 166 83 250 125 376 188 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2  1

Example2:

Input:

given number=847

Output:

The Collatz Conjecture of the number :
847 2542 1271 3814 1907 5722 2861 8584 4292 2146 1073 3220 1610 805 2416 1208 604 302 151 454 227 682 341 1024 512 256 128 64 32 16 8 4 2  1

Program to Print Collatz Conjecture for a Given Number in C++ and Python

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

1)Printing Collatz Conjecture sequence of the given number in Python

Approach:

  • Scan the given number or give number as static input.
  • Iterate till the given number is not equal to 1 using while loop.
  • Print the number numb.
  • If the number is even then set n to n/2.
  • If the number is odd then set  n to 3*n+1.
  • Print 1 after end of while loop.
  • The Exit of the Program.

Below is the implementation:

# function which prints collatz sequence of the given number
def printCollatz(numb):
  # Iterate till the given number is not equal to 1 using while loop.
    while numb > 1:
      # Print the number numb
        print(numb, end=' ')
        # If the number is even then set n to n/2.
        if (numb % 2 == 0):
            numb = numb//2
        # If the number is odd then set  n to 3*n+1.
        else:
            numb = 3*numb + 1
   # Print 1 after end of while loop.
    print(1, end='')


# given number
numb = 179
print('The Collatz Conjecture of the number :')
# passing the given numb to printCollatz function to
# print collatzConjecture sequence of the given number
printCollatz(numb)

Output:

The Collatz Conjecture of the number :
179 538 269 808 404 202 101 304 152 76 38 19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1

2)Printing Collatz Conjecture sequence of the given number in C++

Approach:

  • Scan the given number using cin or give number as static input
  • Iterate till the given number is not equal to 1 using while loop.
  • Print the number numb.
  • If the number is even then set n to n/2.
  • If the number is odd then set  n to 3*n+1.
  • Print 1 after end of while loop.

Below is the implementation:

#include <bits/stdc++.h>
using namespace std;
// function which prints collatz sequence of the given
// number
void printCollatz(int numb)
{

    // Iterate till the given number is not equal to 1 using
    // while loop.
    while (numb > 1) {
        // Print the number numb
        cout << numb << " ";
        // the number is even then set n to n / 2.
        if (numb % 2 == 0) {
            numb = numb / 2;
        }
        // the number is odd then set  n to 3 * n + 1.
        else {
            numb = 3 * numb + 1;
        }
    }
    // Print 1 after end of while loop.
    cout << " 1";
}
int main()
{

    // given number
    int numb = 179;
    cout << "The Collatz Conjecture of the number :"
         << endl;
    // passing the given numb to printCollatz function to
    // print collatzConjecture sequence of the given number
    printCollatz(numb);
    return 0;
}

Output:

The Collatz Conjecture of the number :
179 538 269 808 404 202 101 304 152 76 38 19 58 29 88 44 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2  1

Related Programs:

Python Program to Check if a Date is Valid and Print the Incremented Date

Program to Check if a Date is Valid and Print the Incremented Date

Given a date , the task is to Check if a Date is Valid and increment the given date and print it in python

Examples:

Example1:

Input:

given date ="11/02/2001"

Output:

The incremented given date is:  12 / 2 / 2001

Example2:

Input:

 given date = "29/02/2001"

Output:

The given date 29/02/2001 is not valid

Program to Check and Print the Incremented Date in Python

Below are the ways to check and implement the increment the given date in Python:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

1)By using if..elif..else Conditional Statements  and split() function(Static Input)

Approach:

  • Give the date in the format dd/mm/yyyy as static input
  • Separate the date by storing the day, month, and year in different variables.
  • Check the validity of the day, month, and year using various if-statements.
  • If the date is valid, increment it .
  • Print the increment date.
  • Exit of Program.

Below is the implementation:

# given given_data
given_date = "11/02/2001"
# splitting the given_data by / character to separate given_data,month and year
day, month, year = given_date.split('/')
day = int(day)
month = int(month)
year = int(year)
if(month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12):
    maxdays = 31
elif(month == 4 or month == 6 or month == 9 or month == 11):
    maxdays = 30
elif(year % 4 == 0 and year % 100 != 0 or year % 400 == 0):
    maxdays = 29
else:
    maxdays = 28
if(month < 1 or month > 12):
    print("The given date", given_date, "is not valid")
elif(day < 1 or day > maxdays):
    print("The given date", given_date, "is not valid")
elif(day == maxdays and month != 12):
    day = 1
    month = month+1
    print("The incremented given date is: ", day, month, year)
elif(day == 31 and month == 12):
    day = 1
    month = 1
    year = year+1
    print("The incremented given date is: ", day, '/', month, '/', year)
else:
    day = day + 1
    print("The incremented given date is: ",  day, '/', month, '/', year)

Output:

The incremented given date is:  12 / 2 / 2001

Explanation:

  • Give the date in the format dd/mm/yyyy as static input.
  • The date is then divided, with the day, month, and year recorded in separate variables.
  • The date is invalid if it is not between 1 and 30 in the months of April, June, September, and November.
  • The date is invalid if it is not between 1 and 31 for the months of January, March, April, May, July, August, October, and December.
  • If the month is February, the day should be between 1 and 28 for non-leap years and between 1 and 29 for leap years.
  • If the date is correct, it should be increased.
  • The final incremented date is printed

2)By using if..elif..else Conditional Statements  and split() function(User Input)

Approach:

  • Scan the date, month and year as int(input()).
  • Separate the date by storing the day, month, and year in different variables.
  • Check the validity of the day, month, and year using various if-statements.
  • If the date is valid, increment it .
  • Print the increment date.
  • Exit of Program.

Below is the implementation:

# Scan the date, month and year as int(input()).
day = int(input("Enter some random day = "))
month = int(input("Enter some random month = "))
year = int(input("Enter some random year = "))
if(month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12):
    maxdays = 31
elif(month == 4 or month == 6 or month == 9 or month == 11):
    maxdays = 30
elif(year % 4 == 0 and year % 100 != 0 or year % 400 == 0):
    maxdays = 29
else:
    maxdays = 28
if(month < 1 or month > 12):
    print("The given date", given_date, "is not valid")
elif(day < 1 or day > maxdays):
    print("The given date", given_date, "is not valid")
elif(day == maxdays and month != 12):
    day = 1
    month = month+1
    print("The incremented given date is: ", day, month, year)
elif(day == 31 and month == 12):
    day = 1
    month = 1
    year = year+1
    print("The incremented given date is: ", day, '/', month, '/', year)
else:
    day = day + 1
    print("The incremented given date is: ",  day, '/', month, '/', year)

Output:

Enter some random day = 11
Enter some random month = 2
Enter some random year = 2001
The incremented given date is: 12 / 2 / 2001

Related Programs: