Python

Python Program to Count Set Bits in a Number

Python Program to Count Set Bits in a Number

Given a number ,the task is to count the set bits of the given number in its binary representation.

Examples:

Example1:

Input:

given number =235

Output:

The total number of set bits in the given number  235  : 
6

Example2:

Input:

given number =8

Output:

The total number of set bits in the given number  8  : 
1

Example3:

Input:

given number =375

Output:

The total number of set bits in the given number  375  : 
7

Program to Count Set Bits in a Number in Python

There are several ways to count set bits in the binary representation of the given number 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: By checking bit by bit from end using modulus operator

A simple method is to take each bit into consideration in a number (set or unset) and hold an counter to track the set bits.

Approach:

  • Set the variable say count to 0 to count the total number of set bits.
  • We utilize the while loop.
  • We’ll keep going till the number is bigger than zero (Condition of while statement)
  • Using the % operator, we will determine whether the last check bit is set or not.
  • If the check bit is 1, it indicates that the bit is set, and we increment the count.
  • Divide the given number by 2.
  • Print the count.

Below is the implementation:

def countSetBit(numb):
    # checking if the given number is greater than 1
    if numb > 1:
      # Set the variable say setbitcount to 0 to count the total number of set bits.
        setbitcount = 0
        # looping till number greater than 0 using while loop
        while(numb > 0):
            # We will get the last check bit whether it is set bit or not using % operator
            checkbit = numb % 2
            # checking if the check bit is 1 or not
            # if the check bit is 1 then increment the setbitcount
            if(checkbit == 1):
                setbitcount = setbitcount+1
            # divide the number by 2
            numb = numb//2
    # return the setbitcount
    return setbitcount


# Driver code
given_numb = 235
# passing given number to countSetBit function to
# count the total number of set bits in the given number
print("The total number of set bits in the given number ", given_numb, " : ")
print(countSetBit(given_numb))

Output:

The total number of set bits in the given number  235  : 
6

Method #2: By checking bit by bit from end using & operator

A simple method is to take each bit into consideration in a number (set or unset) and hold an counter to track the set bits.

Approach:

  • Set the variable say count to 0 to count the total number of set bits.
  • We utilize the while loop.
  • We’ll keep going till the number is bigger than zero (Condition of while statement)
  • Using the & operator, we will determine whether the last check bit is set or not.
  • If the check bit is 1, it indicates that the bit is set, and we increment the count.
  • Divide the given number by 2.
  • Print the count.

We use n&1 to check whether it is set bit or not.

Below is the implementation:

def countSetBit(numb):
    # checking if the given number is greater than 1
    if numb > 1:
      # Set the variable say setbitcount to 0 to count the total number of set bits.
        setbitcount = 0
        # looping till number greater than 0 using while loop
        while(numb > 0):
            # We will get the last check bit whether it is set bit or not using & operator
            # checking if the check bit is 1 or not
            # if the check bit is 1 then increment the setbitcount
            if(numb & 1):
                setbitcount = setbitcount+1
            # divide the number by 2
            numb = numb//2
    # return the setbitcount
    return setbitcount


# Driver code
given_numb = 235
# passing given number to countSetBit function to
# count the total number of set bits in the given number
print("The total number of set bits in the given number ", given_numb, " : ")
print(countSetBit(given_numb))

Output:

The total number of set bits in the given number  235  : 
6

Method #3: By converting into binary using bin() and using count() function to count set bits

Approach:

  • First we convert the given number into binary using bin() function.
  • Then we count total number of ‘1’s in the binary string using count() function
  • Print the count

Below is the implementation:

def countSetBit(numb):
    # converting given number to binary reepresentatioon using bin()
    binNum = bin(numb)
    # we count total number of '1's in the binary string using count() function
    setbitcount = binNum.count('1')
    # return the setbitcount
    return setbitcount


# Driver code
given_numb = 235
# passing given number to countSetBit function to
# count the total number of set bits in the given number
print("The total number of set bits in the given number ", given_numb, " : ")
print(countSetBit(given_numb))

Output:

The total number of set bits in the given number  235  : 
6

Method #4: By converting into binary using bin() and using sum() function to count set bits

Approach:

  • First we convert the given number into binary using bin() function.
  • We slice from 2 to end of the binary string using slicing (to remove 0b characters from binary string)
  • Convert every character of binary string to integer using map and then convert it to list
  • Then we count total number of ‘1’s in the binary string list using sum() function(because the binary string contains only 0 and 1)
  • Print the count

Below is the implementation:

def countSetBit(numb):
    # converting given number to binary reepresentatioon using bin()
    binNum = bin(numb)
    # We will slice from 2 index to last index of the result returned by binary string
    binNum = binNum[2:]
    # Convert every character of binary string to integer using map
    # and then convert it to list
    binList = list(map(int, binNum))
    # we count total number of '1's in the binary string using sum() function
    setbitcount = sum(binList)
    # return the setbitcount
    return setbitcount


# Driver code
given_numb = 235
# passing given number to countSetBit function to
# count the total number of set bits in the given number
print("The total number of set bits in the given number ", given_numb, " : ")
print(countSetBit(given_numb))

Output:

The total number of set bits in the given number  235  : 
6

Related Programs:

Python Program to Count Set Bits in a Number Read More »

Brian Kernighan’s Algorithm to Count Set bits of a Number in C++ and Python

Brian Kernighan’s Algorithm to count set bits in an integer in C++ and Python

Brian Kernighan’s Algorithm to count the number of set bits in an integer: Given a number, the task is to count the set bits of the given number using Brian Kernighan’s Algorithm in C++ and Python.

Brian Kernighan’s Algorithm to Count Set bits of a Number in C++ and Python

We’ll look at Brian Kernighan’s Algorithm and see how it works 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.

Example1:

Input:

given number =43

Output:

The total number of set bits in the given number  43  : 
4

Example2:

Input:

given number =64

Output:

The total number of set bits in the given number  64  : 
1

Example3:

Input:

given number =4322

Output:

The total number of set bits in the given number  4322  : 
5

First, we implement the brute force solution for the above program

Brute-Force Approach (Naïve Approach)

A simple method is to take each bit into consideration in a number (set or unset) and hold a counter to track the set bits.

Approach:

  • Set the variable to say count to 0 to count the total number of set bits.
  • We utilize the while loop.
  • We’ll keep going till the number is bigger than zero (Condition of while statement)
  • Using the % operator, we will determine whether the last check bit is set or not.
  • If the check bit is 1, it indicates that the bit is set, and we increment the count.
  • Divide the given number by 2.
  • Print the count.

Below is the implementation:

def countSetBit(numb):
    # checking if the given number is greater than 1
    if numb > 1:
      # Set the variable say setbitcount to 0 to count the total number of set bits.
        setbitcount = 0
        # looping till number greater than 0 using while loop
        while(numb > 0):
            # We will get the last check bit whether it is set bit or not using % operator
            checkbit = numb % 2
            # checking if the check bit is 1 or not
            # if the check bit is 1 then increment the setbitcount
            if(checkbit == 1):
                setbitcount = setbitcount+1
            # divide the number by 2
            numb = numb//2
    # return the setbitcount
    return setbitcount


# Driver code
given_numb = 235
# passing given number to countSetBit function to
# count the total number of set bits in the given number
print("The total number of set bits in the given number ", given_numb, " : ")
print(countSetBit(given_numb))

Output:

The total number of set bits in the given number  235  : 
6

The brute-force strategy described above requires one repetition per bit until no more set bits remain. So it goes through 32 iterations on a 32–bit word with only the high-bit set.

Brian Kernighan’s Algorithm to calculate set bits in an integer

We may apply Brian Kernighan’s technique to improve the performance of the naive algorithm described above. The concept is to only consider an integer’s set bits by turning off its rightmost set bit (after counting it) so that the next iteration of the loop only considers the next rightmost bit.

To turn off the rightmost set bit of a number n, use the formula n & (n-1). This is because the formula n-1 flips all the bits following the rightmost set bit of n, including the rightmost set bit itself. As a result, n & (n-1) results in the last bit of n being flipped.

Implementing Brian Kernighan’s Algorithm to count the number of set bits in an integer in Python

implementation of Brian Kernighan's Algorithm in Python

Below is the implementation of Brian Kernighan’s Algorithm to set bits in a Python:

def countSetBit(numb):
    # checking if the given number is greater than 1
    if numb > 1:
      # Set the variable say setbitcount to 0 to count the total number of set bits.
        setbitcount = 0
        # looping till number greater than 0 using while loop
        while(numb > 0):
            numb = numb & (numb-1)
            # increment the set bit count
            setbitcount = setbitcount+1
    # return the setbitcount
    return setbitcount


# Driver code
given_numb = 4322
# passing given number to countSetBit function to
# count the total number of set bits in the given number
print("The total number of set bits in the given number ", given_numb, " : ")
print(countSetBit(given_numb))

Output:

The total number of set bits in the given number  4322  :  5

Time Complexity: O(logn)

Implementing Brian Kernighan’s Algorithm to count the number of set bits in an integer in C++

Brian Kernighan’s Algorithm to count number of set bits in an integer in c++
Below is the implementation of Brian Kernighan’s Algorithm to set bits in a C++:

#include <iostream>
using namespace std;
// function which returns the total number of set bits in
// the given number
int countSetBit(int numb)
{ // Set the variable say setbitcount to 0 to count the
  // total number of set bits.
    int setbitcount = 0;
    // checking if the given number is greater than 1
    if (numb > 1) {
        // looping till number greater than 0 using while
        // loop
        while (numb > 0) {          
            numb = numb & (numb - 1);
            // increment the set bit count
            setbitcount++;
        }
    }
    // return the setbitcount
    return setbitcount;
}
int main()
{
    // given number
    int given_numb = 4322;
    // passing given number to countSetBit function to
    // count the total number of set bits in the given
    // number
    cout << "The total number of set bits in the given "
            "number "
         << given_numb << " : " << endl;
    cout << countSetBit(given_numb);

    return 0;
}

Output:

The total number of set bits in the given number  4322  : 
5

Brian Kernighan’s algorithm iterates as many times as there are set bits. So, if we have a 32–bit word with only the high bit set, it will only be looped once.

To Count Set Bits in an Integer Using GCC built-in function

GCC also implements a built-in function to get no of set bits in an integer,int __builtin_popcount(unsigned int n) that returns the total number of set bits in n. The below C++ program illustrates it clearly:

#include <iostream>
using namespace std;
 
int main()
{
    int n = 16;
    cout << "The total number of set bits in " << n << " is "
         << __builtin_popcount (n) << endl;
 
    return 0;
}

Output: 

The total number of set bits in 16 is 1

Also, GCC furnishes two other built-in functions, int __builtin_popcountl (unsigned long) and int __builtin_popcountll (unsigned long long), same as __builtin_popcount, except their argument type is unsigned long and unsigned long long, each.

Related Programs:

Brian Kernighan’s Algorithm to count set bits in an integer in C++ and Python Read More »

Program to Accept Three Digits and Print all Possible Combinations from the Digits

Python Program to Accept Three Digits and Print all Possible Combinations from the Digits

We will learn how to print all combinations of three different numbers in this python programming lesson. The application will accept three digits from the user / we give input as static and print out every possible combination of the three digits.

Examples:

Example1:

Input:

given three numbers = 1 9 2

Output:

1 9 2
1 2 9
9 1 2
9 2 1
2 1 9
2 9 1

Example2:

Input:

given three numbers = 3 7 5

Output:

Enter first digit = 3
Enter second digit = 7
Enter third digit = 5
3 7 5
3 5 7
7 3 5
7 5 3
5 3 7
5 7 3

Example3:

Input:

given three numbers = 44 389 72

Output:

44 389 72
44 72 389
389 44 72
389 72 44
72 44 389
72 389 44

Python Program to Print all Possible Combinations of the three Digits

There are several methods to print all the possible combinations of the three numbers 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.

General Approach

  • To print out the combination of all digits, we shall utilize three loops.
  • Take the user’s numbers as input. These values should be saved in three distinct variables.
  • Put all of these numbers in a list.
  • Print out the combination of these numbers using three for loops.
  • While printing the numerals, all three loops represent the three-position. As a result, if the current index of these loops is not the same, we shall print any value.

Method #1: Using Nested loops (Static input)

Approach:

  • We give the three digits input as static
  • For ease of comparison, all of the items are appended to a list.
  • The for loops have a value between 0 and 2, which corresponds to the indexes of the three elements in the list.
  • If none of the indexes match, the element associated with the specific element in the list is printed.

Below is the implementation:

# given three digits here we took the input as static
firstDigit = 1
secondDigit = 9
thirdDigit = 2
# Taking a empty list to store the given three digits
digitsList = []
# appending all the three digits to the digitsList
digitsList.append(firstDigit)
digitsList.append(secondDigit)
digitsList.append(thirdDigit)
# Using nested loops
for i in range(3):
    for j in range(3):
        for k in range(3):
            if(i != j & j != k & k != i):
                print(digitsList[i], digitsList[j], digitsList[k])

Output:

1 9 2
1 2 9
9 1 2
9 2 1
2 1 9
2 9 1

Note:

This method also works for three numbers as shown below

Below is the implementation:

# given three digits here we took the input as static
firstDigit = 44
secondDigit = 53
thirdDigit = 456
# Taking a eempty list to store the given three digits
digitsList = []
# appending all the three digits to the digitsList
digitsList.append(firstDigit)
digitsList.append(secondDigit)
digitsList.append(thirdDigit)
# Using nested loops
for i in range(3):
    for j in range(3):
        for k in range(3):
            if(i != j & j != k & k != i):
                print(digitsList[i], digitsList[j], digitsList[k])

Output:

44 53 456
44 456 53
53 44 456
53 456 44
456 44 53
456 53 44

Method #2: Using Nested loops (User input)

Approach:

  • The first, second, and third digits must be entered by the user.
  • For ease of comparison, all of the items are appended to a list.
  • The for loops have a value between 0 and 2, which corresponds to the indexes of the three elements in the list.
  • If none of the indexes match, the element associated with the specific element in the list is printed.

Below is the implementation:

# given three digits here we took the input as static
firstDigit = int(input("Enter first digit = "))
secondDigit = int(input("Enter second digit = "))
thirdDigit = int(input("Enter third digit = "))
# Taking a eempty list to store the given three digits
digitsList = []
# appending all the three digits to the digitsList
digitsList.append(firstDigit)
digitsList.append(secondDigit)
digitsList.append(thirdDigit)
# Using nested loops
for i in range(3):
    for j in range(3):
        for k in range(3):
            if(i != j & j != k & k != i):
                print(digitsList[i], digitsList[j], digitsList[k])

Output:

Enter first digit = 3
Enter second digit = 7
Enter third digit = 5
3 7 5
3 5 7
7 3 5
7 5 3
5 3 7
5 7 3

Method #3:Using permutations() function

Python has built-in techniques for finding permutations and combinations of a sequence. These techniques are included in the itertools package.

To implement the permutations function in Python, first import the itertools package. This method accepts a list as input and returns an object list of tuples containing all permutations in list form.

We will pass the digitsList as argument to permutations function

Below is the implementation:

# importing permutations from itertools
from itertools import permutations
# given three digits here we took the input as static
firstDigit = 4
secondDigit = 3
thirdDigit = 7
# Taking a eempty list to store the given three digits
digitsList = []
# appending all the three digits to the digitsList
digitsList.append(firstDigit)
digitsList.append(secondDigit)
digitsList.append(thirdDigit)
# Using permutations function

totalcombs = permutations(digitsList, 3)
# printing all combinations
for i in totalcombs:
    print(*i)

Output:

4 3 7
4 7 3
3 4 7
3 7 4
7 4 3
7 3 4

Note:

This method also works for three numbers as shown below

Below is the implementation:

# importing permutations from itertools
from itertools import permutations
# given three digits here we took the input as static
firstDigit = 44
secondDigit = 389
thirdDigit = 72
# Taking a eempty list to store the given three digits
digitsList = []
# appending all the three digits to the digitsList
digitsList.append(firstDigit)
digitsList.append(secondDigit)
digitsList.append(thirdDigit)
# Using permutations function

totalcombs = permutations(digitsList, 3)
# printing all combinations
for i in totalcombs:
    print(*i)

Output:

44 389 72
44 72 389
389 44 72
389 72 44
72 44 389
72 389 44

Related Programs:

Python Program to Accept Three Digits and Print all Possible Combinations from the Digits Read More »

Python Program to Print the Natural Numbers Summation Pattern

Python Program to Print the Natural Numbers Summation Pattern

Natural Numbers:

Natural numbers are a subset of the number system that includes all positive integers from one to infinity. Natural numbers, which do not include zero or negative numbers, are also known as counting numbers. They are a subset of real numbers that include only positive integers and exclude zero, fractions, decimals, and negative numbers.

Given a number the task is to print the natural numbers summation Pattern

Examples:

Example1:

Input:

given number = 7

Output:

1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
1 + 2 + 3 + 4 + 5 + 6 = 21
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28

Example2:

Input:

given number = 9

Output:

1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
1 + 2 + 3 + 4 + 5 + 6 = 21
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45

Program to Print the Natural Numbers Summation Pattern in Python

There are several ways to print the natural numbers summation pattern in 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 nested for loops (Static Input)

Approach:

  • Take the value of the given number as static  and store it in a variable numb.
  • Use two for loops where the value of i is between 1 and numb and the value of j is between 1 and i
  • Take a empty list
  • Add values of i to the list using append() function.
  • While adding the value of j to a list, print the value of j and the ‘+’ operator.
  • Then compute the sum of the elements in the list using sum() function
  • Print the symbol ‘=’ followed by the total sum calculated in the above step.
  • End of program

Below is the implementation:

# given number
numb = 15
# traversing from 1 to numb using for loop
for i in range(1, numb+1):
  # taking a empty list
    emptylist = []
    # traversing from 1 to i
    for j in range(1, i+1):
      # printing the value of j
        print(j, sep=" ", end=" ")
        if(j < i):
            print("+", sep=" ", end=" ")
        # appending/adding the value to the empty list
        emptylist.append(j)
    # printing the sum of emptylist
    print("=", sum(emptylist))

Output:

1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
1 + 2 + 3 + 4 + 5 + 6 = 21
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 = 66
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 = 78
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 = 91
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 = 105
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 = 120

Explanation:

  • Consider the provided number’s value to be static
  • This number is iterated again and over.
  • An empty list has been defined.
  • A new ‘for’ loop is started.
  • The separator is set to ‘’.
  • The ‘+’ symbol is used if the value of the inner iterator is smaller than the value of the outer iterator.
  • These values are added to the existing empty list.
  • Their total is computed and shown as the output.

Method #2: Using nested for loops and mathematical formula (Static input)

Approach:

  • Take the value of the given number as static and store it in a variable numb.
  • Use two for loops where the value of i is between 1 and numb and the value of j is between 1 and i
  • print the value of j and the ‘+’ operator.
  • Then compute the sum of the element i using mathematic formula for sum of n natural numbers
  • Print the symbol ‘=’ followed by the total sum calculated in the above step.
  • End of program

Mathematical formula for sum of n natural numbers  :

( numb * (numb+1) ) /2

Below is the implementation:

# given number
numb = 9
# traversing from 1 to numb using for loop
for i in range(1, numb+1):
    # traversing from 1 to i
    for j in range(1, i+1):
      # printing the value of j
        print(j, sep=" ", end=" ")
        if(j < i):
            print("+", sep=" ", end=" ")
    # calculating sum of the n natural numbers using mathematical formula
    naturalSum = (i*(i+1))//2
    # printing the total sum
    print("=", naturalSum)

Output:

1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
1 + 2 + 3 + 4 + 5 + 6 = 21
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45

Method #3: Using nested for loops and mathematical formula (User input)

Approach:

  • Scan the input from user using input() function and store it in a variable numb
  • Convert this numb to integer using numb function
  • Use two for loops where the value of i is between 1 and numb and the value of j is between 1 and i
  • print the value of j and the ‘+’ operator.
  • Then compute the sum of the element i using mathematic formula for sum of n natural numbers
  • Print the symbol ‘=’ followed by the total sum calculated in the above step.
  • End of program

Mathematical formula for sum of n natural numbers  = ( numb * (numb+1) ) /2

Below is the implementation:

# given number
numb = input("Enter your desired number = ")
# conveerting numb to integer using int() function
numb = int(numb)
# traversing from 1 to numb using for loop
for i in range(1, numb+1):
    # traversing from 1 to i
    for j in range(1, i+1):
      # printing the value of j
        print(j, sep=" ", end=" ")
        if(j < i):
            print("+", sep=" ", end=" ")
    # calculating sum of the n natural numbers using mathematical formula
    naturalSum = (i*(i+1))//2
    # printing the total sum
    print("=", naturalSum)

Output:

Enter your desired number = 9
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
1 + 2 + 3 + 4 + 5 + 6 = 21
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36
1 +2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45

Related Programs:

Python Program to Print the Natural Numbers Summation Pattern Read More »

Python Program to Find Whether a Number is a Power of Two

Python Program to Find Whether a Number is a Power of Two

In this tutorial, the power of 2 or not for python programming can be checked. The user gives a positive integer N and we have to check if it is equivalent to 2^x or not, where x can be zero or a number positive.

Examples:

Example1:

Input:

given number =2048

Output:

The given numb 2048 is power of 2

Example2:

Input:

given number =256

Output:

The given numb 256 is power of 2

Example3:

Input:

given number =678

Output:

The given numb 678 is not power of 2

Program to Find Whether a Number is a Power of Two in Python

There are several ways to check whether the given number is a power of 2 or not 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 log function

  • This answer is just a mathematical one.
  • If the log2(n) of the given number n is integer than it is power of 2
  • Else it is not power of 2.

Below is the implementation:

# importing log from math
from math import log
# given number
numb = 2048
# given base (here it is 2 as we have to check whether it is power of 2 or not)
bas = 2
# calculating log2 of the  given numb using log function
logvalue = log(numb, bas)
# if the value is integer then it is power of 2
if (int(logvalue) == logvalue):
    print("The given numb", numb, "is power of 2")
# else it is not power of 2
else:
    print("The given numb", numb, "is not power of 2")

Output:

The given numb 2048 is power of 2

Method #2:Using while loop

Continue dividing the number into two, i.e. do n = n/2 as long as n is 1 If n percent 2 is non-zero and n is not 1 in all iteration, then n is not 2. It is a power of 2, if n becomes 1.

Below is the implementation:

# function which returns true if the given number is power of 2 else it reeturns false


def checktwoPower(numb):
    # checking if the number is 0
    if (numb == 0):
      # if the number is 0 then it is not power of 2 hence return false
        return False
    # using while loop to iterate till the number not equal to 1
    while (numb != 1):
        # if the bit is set bit then it is not power of 2 so return False
        if (numb % 2 != 0):
            return False
            # dividing n
        numb = numb // 2
    return True


# given number
numb = 2048
# passing the given number to checktwoPower function
# if the value is integer then it is power of 2
if (checktwoPower(numb)):
    print("The given numb", numb, "is power of 2")
# else it is not power of 2
else:
    print("The given numb", numb, "is not power of 2")

Output:

The given numb 2048 is power of 2

Method #3:Using Bitwise Operators

If the number is 2 power, the binary representation of only 1 bit is set.
If we remove 1 from a power number 2, then all the bits are set and the set bit is unset after the set bits (just one bits are set according to point-1)

Therefore, if a number is 2, then

numb&(numb-1) == 0

Only if N is zero is the exception to the foregoing rule. As a power of two, it will give zero which in fact is not. Therefore, we can explicitly see this in the check.

Below is the implementation:

# function which returns true if the given number is power of 2 else it reeturns false


def checktwoPower(numb):
    return numb and (not(numb & (numb-1)))


# given number
numb = 2048
# passing the given number to checktwoPower function
# if the value is integer then it is power of 2
if (checktwoPower(numb)):
    print("The given numb", numb, "is power of 2")
# else it is not power of 2
else:
    print("The given numb", numb, "is not power of 2")

Output:

The given numb 2048 is power of 2

Method #4:By Calculating total number of set bits

A simple method is to take each bit into consideration in a number (set or unset) and hold a counter to track the set bits if the total number of set bits is 1 then the number is power of 2 else it is not the power of 2

Approach:

  • Set the variable to say count to 0 to count the total number of set bits.
  • We utilize the while loop.
  • We’ll keep going till the number is bigger than zero (Condition of while statement)
  • Using the & operator, we will determine whether the last check bit is set or not.
  • If the check bit is 1, it indicates that the bit is set, and we increment the count.
  • Divide the given number by 2.
  • If the count is 1 then it is the power of 2 hence return true
  • Else return false

We use n&1 to check whether it is set bit or not.

Below is the implementation:

# function which returns true if the given number is power of 2 else it reeturns false


def checktwoPower(numb):
    # checking if the given number is greater than 1
    if numb > 1:
      # Set the variable say setbitcount to 0 to count the total number of set bits.
        setbitcount = 0
        # looping till number greater than 0 using while loop
        while(numb > 0):
            # We will get the last check bit whether it is set bit or not using & operator
            # checking if the check bit is 1 or not
            # if the check bit is 1 then increment the setbitcount
            if(numb & 1):
                setbitcount = setbitcount+1
            # divide the number by 2
            numb = numb//2
    # checking if the total number of setbits are 1 or not
    return (setbitcount == 1)


# given number
numb = 2048
# passing the given number to checktwoPower function
# if the value is integer then it is power of 2
if (checktwoPower(numb)):
    print("The given numb", numb, "is power of 2")
# else it is not power of 2
else:
    print("The given numb", numb, "is not power of 2")

Output:

The given numb 2048 is power of 2

Related Programs:

Python Program to Find Whether a Number is a Power of Two Read More »

Pandas: Create Dataframe from List of Dictionaries

Methods of creating a dataframe from a list of dictionaries

In this article, we discuss different methods by which we can create a dataframe from a list of dictionaries. Before going to the actual article let us done some observations that help to understand the concept easily. Suppose we have a list of dictionary:-

list_of_dict = [
{'Name': 'Mayank' , 'Age': 25, 'Marks': 91},
{'Name': 'Raj', 'Age': 21, 'Marks': 97},
{'Name': 'Rahul', 'Age': 23, 'Marks': 79},
{'Name': 'Manish' , 'Age': 23},
]

Here we know that dictionaries consist of key-value pairs. So we can analyze that if we make the key as our column name and values as the column value then a dataframe is easily created. And we have a list of dictionaries so a dataframe with multiple rows also.

pandas.DataFrame

This methods helps us to create dataframe in python

syntax: pandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)

Let us see different methods to create dataframe from a list of dictionaries

  • Method 1-Create Dataframe from list of dictionaries with default indexes

As we see in in pandas.Datframe() method there is parameter name data.We have to simply pass our list of dictionaries in this method and it will return the dataframe.Let see this with the help of an example.

import pandas as pd
import numpy as np

list_of_dict = [
    {'Name': 'Mayank' ,  'Age': 25,  'Marks': 91},
    {'Name': 'Raj',  'Age': 21,  'Marks': 97},
    {'Name': 'Rahul',  'Age': 23,  'Marks': 79},
    {'Name': 'Manish' ,  'Age': 23,  'Marks': 86},
]
#create dataframe
df=pd.DataFrame(list_of_dict)
print(df)

Output

   Age  Marks    Name
0   25     91  Mayank
1   21     97     Raj
2   23     79   Rahul
3   23     86  Manish

Here we see that dataframe is created with default indexes 0,1,2,3….

Now a question may arise if from any dictionary key-value pair is less than other dictionaries.So in this case what happened.Let understand it with the help of an example.

import pandas as pd
import numpy as np

list_of_dict = [
    {'Name': 'Mayank' ,  'Age': 25,  'Marks': 91},
    {'Name': 'Raj',  'Age': 21,  'Marks': 97},
    {'Name': 'Rahul',  'Marks': 79},
    {'Name': 'Manish' ,  'Age': 23},
]
#create dataframe
df=pd.DataFrame(list_of_dict)
print(df)

Output

    Age  Marks    Name
0  25.0   91.0  Mayank
1  21.0   97.0     Raj
2   NaN   79.0   Rahul
3  23.0    NaN  Manish

Here we see in case of missing key value pair NaN value is there in the output.

  • Method 2- Create Dataframe from list of dictionary with custom indexes

Unlike the previous method where we have default indexes we can also give custom indexes by passes list of indexes in index parameter of pandas.DataFrame() function.Let see this with the help of an example.

import pandas as pd
import numpy as np

list_of_dict = [
    {'Name': 'Mayank' ,  'Age': 25,  'Marks': 91},
    {'Name': 'Raj',  'Age': 21,  'Marks': 97},
    {'Name': 'Rahul',  'Marks': 79},
    {'Name': 'Manish' ,  'Age': 23},
]
#create dataframe
df=pd.DataFrame(list_of_dict,index=['a','b','c','d'])
print(df)

Output

    Age  Marks    Name
a  25.0   91.0  Mayank
b  21.0   97.0     Raj
c   NaN   79.0   Rahul
d  23.0    NaN  Manish

Here we see that instead of default index 1,2,3….. we have now indes a,b,c,d.

  • Method 3-Create Dataframe from list of dictionaries with changed order of columns

With the help of pandas.DataFrame() method we can easily arrange order of column by simply passes list ozf columns in columns parameter in the order in which we want to display it in our dataframe.Let see this with the help of example.

import pandas as pd
import numpy as np

list_of_dict = [
    {'Name': 'Mayank' ,  'Age': 25,  'Marks': 91},
    {'Name': 'Raj',  'Age': 21,  'Marks': 97},
    {'Name': 'Rahul',  'Age': 23,  'Marks': 79},
    {'Name': 'Manish' ,  'Age': 23,  'Marks': 86},
]
#create dataframe
df=pd.DataFrame(list_of_dict,columns=['Name', 'Marks', 'Age'])
print(df)

Output

     Name  Marks  Age
0  Mayank     91   25
1     Raj     97   21
2   Rahul     79   23
3  Manish     86   23

Here also a question may arise if we pass less column in columns parameter or we pass more column in parameter then what happened.Let see this with the help of an example.

Case 1: Less column in column parameter

In this case the column which we don’t pass will be drop from the dataframe.Let see this with the help of an example.

import pandas as pd
import numpy as np

list_of_dict = [
    {'Name': 'Mayank' ,  'Age': 25,  'Marks': 91},
    {'Name': 'Raj',  'Age': 21,  'Marks': 97},
    {'Name': 'Rahul',  'Age': 23,  'Marks': 79},
    {'Name': 'Manish' ,  'Age': 23,  'Marks': 86},
]
#create dataframe
df=pd.DataFrame(list_of_dict,columns=['Name', 'Marks'])
print(df)

Output

     Name  Marks
0  Mayank     91
1     Raj     97
2   Rahul     79
3  Manish     86

Here we see that we didn’t pass Age column that’s why Age clumn is also not in our dataframe.

Case 2: More column in column parameter

In this case a new column will be added in dataframe but its all the value will be NaN.Let see this with the help of an example.

import pandas as pd
import numpy as np

list_of_dict = [
    {'Name': 'Mayank' ,  'Age': 25,  'Marks': 91},
    {'Name': 'Raj',  'Age': 21,  'Marks': 97},
    {'Name': 'Rahul',  'Age': 23,  'Marks': 79},
    {'Name': 'Manish' ,  'Age': 23,  'Marks': 86},
]
#create dataframe
df=pd.DataFrame(list_of_dict,columns=['Name', 'Marks', 'Age','city'])
print(df)

Output

     Name  Marks  Age  city
0  Mayank     91   25   NaN
1     Raj     97   21   NaN
2   Rahul     79   23   NaN
3  Manish     86   23   NaN

So these are the methods to create dataframe from list of dictionary in pandas.

Pandas: Create Dataframe from List of Dictionaries Read More »

Pandas: Add Two Columns into a New Column in Dataframe

Methods to add two columns into a new column in Dataframe

In this article, we discuss how to add to column to an existing column in the dataframe and how to add two columns to make a new column in the dataframe using pandas. We will also discuss how to deal with NaN values.

  • Method 1-Sum two columns together to make a new series

In this method, we simply select two-column by their column name and then simply add them.Let see this with the help of an example.

import pandas as pd 
import numpy as np 
students = [('Raj', 24, 'Mumbai', 95) , 
            ('Rahul', 21, 'Delhi' , 97) , 
            ('Aadi', 22, np.NaN, 81) , 
            ('Abhay', 25,'Rajasthan' , 90) , 
            ('Ajjet', 21, 'Delhi' , 74)] 
# Create a DataFrame object 
df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Marks']) 
print("Original Dataframe\n") 
print(df,'\n') 
total = df['Age'] + df['Marks']
print("New Series \n") 
print(total)
print(type(total))

Output

Original Dataframe

    Name  Age       City  Marks
0    Raj   24     Mumbai     95
1  Rahul   21      Delhi     97
2   Aadi   22        NaN     81
3  Abhay   25  Rajasthan     90
4  Ajjet   21      Delhi     74 

New Series 

0    119
1    118
2    103
3    115
4     95
dtype: int64
<class 'pandas.core.series.Series'>

Here we see that when we add two columns then a series will be formed.]

Note: We can’t add a string with int or float. We can only add a string with a string or a number with a number.

Let see the example of adding string with string.

import pandas as pd 
import numpy as np 
students = [('Raj', 24, 'Mumbai', 95) , 
            ('Rahul', 21, 'Delhi' , 97) , 
            ('Aadi', 22, 'Kolkata', 81) , 
            ('Abhay', 25,'Rajasthan' , 90) , 
            ('Ajjet', 21, 'Delhi' , 74)] 
# Create a DataFrame object 
df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Marks']) 
print("Original Dataframe\n") 
print(df,'\n') 
total = df['Name'] + " "+df['City']
print("New Series \n") 
print(total)
print(type(total))

Output

Original Dataframe

    Name  Age       City  Marks
0    Raj   24     Mumbai     95
1  Rahul   21      Delhi     97
2   Aadi   22    Kolkata     81
3  Abhay   25  Rajasthan     90
4  Ajjet   21      Delhi     74 

New Series 

0         Raj Mumbai
1        Rahul Delhi
2       Aadi Kolkata
3    Abhay Rajasthan
4        Ajjet Delhi
dtype: object
<class 'pandas.core.series.Series'>
  • Method 2-Sum two columns together having NaN values to make a new series

In the previous method, there is no NaN or missing values but in this case, we also have NaN values. So when we add two columns in which one or two-column contains NaN values then we will see that we also get the result as NaN. Let see this with the help of an example.

import pandas as pd 
import numpy as np 
students = [('Raj', 24, 'Mumbai', 95) , 
            ('Rahul', 21, 'Delhi' , 97) , 
            ('Aadi', 22, 'Kolkata', np.NaN) , 
            ('Abhay', np.NaN,'Rajasthan' , 90) , 
            ('Ajjet', 21, 'Delhi' , 74)] 
# Create a DataFrame object 
df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Marks']) 
print("Original Dataframe\n") 
print(df,'\n') 
total = df['Marks'] + df['Age']
print("New Series \n") 
print(total)
print(type(total))

Output

Original Dataframe

    Name   Age       City  Marks
0    Raj  24.0     Mumbai   95.0
1  Rahul  21.0      Delhi   97.0
2   Aadi  22.0    Kolkata    NaN
3  Abhay   NaN  Rajasthan   90.0
4  Ajjet  21.0      Delhi   74.0 

New Series 

0    119.0
1    118.0
2      NaN
3      NaN
4     95.0
dtype: float64
<class 'pandas.core.series.Series'>
  • Method 3-Add two columns to make a new column

We know that a dataframe is a group of series. We see that when we add two columns it gives us a series and we store that sum in a variable. If we make that variable a column in the dataframe then our work will be easily done. Let see this with the help of an example.

import pandas as pd 
import numpy as np 
students = [('Raj', 24, 'Mumbai', 95) , 
('Rahul', 21, 'Delhi' , 97) , 
('Aadi', 22, 'Kolkata',76) , 
('Abhay',23,'Rajasthan' , 90) , 
('Ajjet', 21, 'Delhi' , 74)] 
# Create a DataFrame object 
df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Marks']) 
print("Original Dataframe\n") 
print(df,'\n') 
df['total'] = df['Marks'] + df['Age']
print("New Dataframe \n") 
print(df)
 
print(df)

Output

Original Dataframe

    Name  Age       City  Marks
0    Raj   24     Mumbai     95
1  Rahul   21      Delhi     97
2   Aadi   22    Kolkata     76
3  Abhay   23  Rajasthan     90
4  Ajjet   21      Delhi     74 

New Dataframe 

    Name  Age       City  Marks  total
0    Raj   24     Mumbai     95    119
1  Rahul   21      Delhi     97    118
2   Aadi   22    Kolkata     76     98
3  Abhay   23  Rajasthan     90    113
4  Ajjet   21      Delhi     74     95
  • Method 4-Add two columns with NaN values to make a new column

The same is the case with NaN values. But here NaN values will be shown.Let see this with the help of an example.

import pandas as pd 
import numpy as np 
students = [('Raj', 24, 'Mumbai', 95) , 
            ('Rahul', 21, 'Delhi' , 97) , 
            ('Aadi', 22, 'Kolkata', np.NaN) , 
            ('Abhay', np.NaN,'Rajasthan' , 90) , 
            ('Ajjet', 21, 'Delhi' , 74)] 
# Create a DataFrame object 
df = pd.DataFrame( students, columns=['Name', 'Age', 'City', 'Marks']) 
print("Original Dataframe\n") 
print(df,'\n') 
df['total'] = df['Marks'] + df['Age']
print("New Dataframe \n") 
print(df)

Output

Original Dataframe

    Name   Age       City  Marks
0    Raj  24.0     Mumbai   95.0
1  Rahul  21.0      Delhi   97.0
2   Aadi  22.0    Kolkata    NaN
3  Abhay   NaN  Rajasthan   90.0
4  Ajjet  21.0      Delhi   74.0 

New Dataframe 

    Name   Age       City  Marks  total
0    Raj  24.0     Mumbai   95.0  119.0
1  Rahul  21.0      Delhi   97.0  118.0
2   Aadi  22.0    Kolkata    NaN    NaN
3  Abhay   NaN  Rajasthan   90.0    NaN
4  Ajjet  21.0      Delhi   74.0   95.0

So these are the methods to add two columns in the dataframe.

Pandas: Add Two Columns into a New Column in Dataframe Read More »

Matplotlib: Line plot with markers

Methods to draw line plot with markers with the help of Matplotlib

In this article, we will discuss some basics of matplotlib and then discuss how to draw line plots with markers.

Matplotlib

We know that data that is in the form of numbers is difficult and boring to analyze. But if we convert that number into graphs, bar plots, piecharts, etc then it will be easy and interesting to visualize the data. Here Matplotlib library of python came into use. Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.

For using this library we have to first import it into the program. For importing this we can use

from matplotlib import pyplot as plt or import matplotlib. pyplot as plt.

In this article, we only discuss the line plot. So let see the function in matplotlib to draw a line plot.

syntax:  plt.plot(x,y, scalex=True, scaley=True, data=None, marker=’marker style’, **kwargs)

Parameters

  1. x,y: They represent vertical and horizontal axis.
  2. scalex, scaley: These parameters determine if the view limits are adapted to the data limits. The default value is True.
  3. marker: It contains types of markers that can be used. Like point marker, circle marker, etc.

Here is the list of markers used in this

  • “’.’“           point marker
  • “’,’“           pixel marker
  • “’o’“          circle marker
  • “’v’“          triangle_down marker
  • “’^’“          triangle_up marker
  • “'<‘“          triangle_left marker
  • “’>’“          triangle_right marker
  • “’1’“          tri_down marker
  • “’2’“          tri_up marker
  • “’3’“          tri_left marker
  • “’4’“          tri_right marker
  • “’s’“          square marker
  • “’p’“          pentagon marker
  • “’*’“          star marker
  • “’h’“          hexagon1 marker
  • “’H’“         hexagon2 marker
  • “’+’“          plus marker
  • “’x’“          x marker
  • “’D’“         diamond marker
  • “’d’“          thin_diamond marker
  • “’|’“           vline marker
  • “’_’“          hline marker

Examples of Line plot with markers in matplotlib

  • Line Plot with the Point marker

Here we use marker='.'.Let see this with the help of an example.

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-5,40,.5)
y = np.sin(x)
plt.plot(x,y, marker='.')
plt.title('Sin Function')
plt.xlabel('x values')
plt.ylabel('y= sin(x)')
plt.show()

Output

  • Line Plot with the Point marker and give marker some color

In the above example, we see the color of the marker is the same as the color of the line plot. So there is an attribute in plt.plot() function marker face color or mfc: color which is used to give color to the marker. Let see this with the help of an example.

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-5,40,.5)
y = np.sin(x)
plt.plot(x,y, marker='.',mfc='red')
plt.title('Sin Function')
plt.xlabel('x values')
plt.ylabel('y= sin(x)')
plt.show()

Output

Here we see that color of the pointer changes to red.

  • Line Plot with the Point marker and change the size of the marker

To change the size of the marker there is an attribute in pointer ply.plot() function that is used to achieve this. marker size or ms attribute is used to achieve this. We can pass an int value in ms and then its size increases or decreases according to this. Let see this with the help of an example.

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-5,40,.5)
y = np.sin(x)
plt.plot(x,y, marker='.',mfc='red',ms='17')
plt.title('Sin Function')
plt.xlabel('x values')
plt.ylabel('y= sin(x)')
plt.show()

Output

Here we see that size of the pointer changes.

  • Line Plot with the Point marker and change the color of the edge of the marker

We can also change the color of the edge of marker with the help of markeredgecolor or mec attribute. Let see this with the help of an example.

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-5,40,.5)
y = np.sin(x)
plt.plot(x,y, marker='.',mfc='red',ms='17', mec='yellow')
plt.title('Sin Function')
plt.xlabel('x values')
plt.ylabel('y= sin(x)')
plt.show()

Output

Here we see that the color of the edge of the pointer changes to yellow.

So here are some examples of how we can work with markers in line plots.

Note: These examples are applicable to any of the marker.

Matplotlib: Line plot with markers Read More »

Read Csv File to Dataframe With Custom Delimiter in Python

Different methods to read CSV files with custom delimiter in python

In this article, we will see what are CSV files, how to use them in pandas, and then we see how and why to use custom delimiter with CSV files in pandas.

CSV file

A simple way to store big data sets is to use CSV files (comma-separated files).CSV files contain plain text and is a well know format that can be read by everyone including Pandas. Generally, CSV files contain columns separated by commas, but they can also contain content separated by a tab, or underscore or hyphen, etc. Generally, CSV files look like this:-

total_bill,tip,sex,smoker,day,time,size
16.99,1.01,Female,No,Sun,Dinner,2
10.34,1.66,Male,No,Sun,Dinner,3
21.01,3.5,Male,No,Sun,Dinner,3
23.68,3.31,Male,No,Sun,Dinner,2
24.59,3.61,Female,No,Sun,Dinner,4

Here we see different columns and their values are separated by commas.

Use CSV file in pandas

read_csv() method is used to import and read CSV files in pandas. After this step, a CSV file act as a normal dataframe and we can use operation in CSV file as we use in dataframe.

syntax:  pandas.read_csv(filepath_or_buffer, sep=‘, ‘, delimiter=None, header=‘infer’, names=None, index_col=None, ….)

',' is default separator in read_csv() method.

Let see this with an example

import pandas as pd
data=pd.read_csv('example1.csv')
data.head()

Output

total_billtipsexsmokerdaytimesize
016.991.01FemaleNoSunDinner2
110.341.66MaleNoSunDinner3
221.013.50MaleNoSunDinner3
323.683.31MaleNoSunDinner2
424.593.61FemaleNoSunDinner4

Why use separator or delimiter with read_csv() method

Till now we understand that generally, CSV files contain data separated data that is separated by comma but sometimes it can contain data separated by tab or hyphen, etc. So to handle this we use a seperator. Let understand this with the help of an example. Suppose we have a CSV file separated by an underscore and we try to read that CSV file without using a separator or with using default separator i.e. comma. So let see what happens in this case.

"total_bill"_tip_sex_smoker_day_time_size
16.99_1.01_Female_No_Sun_Dinner_2
10.34_1.66_Male_No_Sun_Dinner_3
21.01_3.5_Male_No_Sun_Dinner_3
23.68_3.31_Male_No_Sun_Dinner_2
24.59_3.61_Female_No_Sun_Dinner_4
25.29_4.71_Male_No_Sun_Dinner_4
8.77_2_Male_No_Sun_Dinner_2

Suppose this is our CSV file separated by an underscore.

total_bill_tip_sex_smoker_day_time_size
016.99_1.01_Female_No_Sun_Dinner_2
110.34_1.66_Male_No_Sun_Dinner_3
221.01_3.5_Male_No_Sun_Dinner_3
323.68_3.31_Male_No_Sun_Dinner_2
424.59_3.61_Female_No_Sun_Dinner_4

Now see when we didn’t use a default separator here how unordered our data look like. So to solve this issue we use Separator. Now we will see when we use a separator to underscore how we get the same data in an ordered manner.

import pandas as pd 
data=pd.read_csv('example2.csv',sep = '_',engine = 'python') 
data.head()

Output

total_billtipsexsmokerdaytimesize
016.991.01FemaleNoSunDinner2
110.341.66MaleNoSunDinner3
221.013.50MaleNoSunDinner3
323.683.31MaleNoSunDinner2
424.593.61FemaleNoSunDinner4

So this example is sufficient to understand why there is a need of using a separator of delimiter in pandas while working on a CSV file.

Now suppose there is a CSV file in while data is separated by multiple separators. For example:-

totalbill_tip,sex:smoker,day_time,size
16.99,1.01:Female|No,Sun,Dinner,2
10.34,1.66,Male,No|Sun:Dinner,3
21.01:3.5_Male,No:Sun,Dinner,3
23.68,3.31,Male|No,Sun_Dinner,2
24.59:3.61,Female_No,Sun,Dinner,4
25.29,4.71|Male,No:Sun,Dinner,4

Here we see there are multiple seperator used. So here we can not use any custom delimiter. To solve this problem regex or regular expression is used. Let see with the help of an example.

import pandas as pd 
data=pd.read_csv('example4.csv',sep = '[:, |_]') 
data.head()

Output

totalbilltipsexsmokerdaytimesize
016.991.01FemaleNoSunDinner2
110.341.66MaleNoSunDinner3
221.013.50MaleNoSunDinner3
323.683.31MaleNoSunDinner2
424.593.61FemaleNoSunDinner4

When we notice we pass a list of separators in the sep parameter that is contained in our CSV file.

Want to expert in the python programming language? Exploring Python Data Analysis using Pandas tutorial changes your knowledge from basic to advance level in python concepts.

Read Csv File to Dataframe With Custom Delimiter in Python Read More »

The Difference Between == and is in Python

The Difference Between == and is in Python

In Python, the operators == and is do very similar functions, yet they are extremely different and deal with a very important concept: how Python saves its variables in memory.

There is a small distinction between the Python identity operator (is) and the equality operator (==). When you use the Python is operator to compare numbers, your code may work great until it suddenly does not. You may have heard that the Python is operator is faster than the == operator, or you may believe that it appears more Pythonic. However, it is critical to remember that these operators do not behave in the same way.

The Python is operator checks if two variables link to the same object in memory, whereas the == operator compares the value or equality of two objects. Except when comparing to None, which means you should utilise the equality operators == and!= in the vast majority of situations.

Understanding the difference Between == and ‘is’ in 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.

Difference #1: Implementation

== compares the values of the two operands and returns True if they are the same, False otherwise.
is compares the object IDs of the two operands and returns True if they match.

But what exactly is an object ID? In memory, each object is assigned an ID, and two variables can point to the same item, giving them the same object ID.

listone = ["this", "is", "BTechGeeks"]
listtwo = ["this", "is", "BTechGeeks"]
print(listone == listtwo)
print(listone is listtwo)
# assigning list two with list one
listtwo = listone
print("After assigning list two with list one:")
# using is
print(listone is listtwo)

Output:

True
False
After assigning list two with list one:
True

In the preceding example, there are two lists in memory at first, but they contain the identical values.

== compares values and returns True if the operation is successful.
However, it tests to see if they point to the same object, and because these lists do not link to the same object, it returns False.
After that, we set listwo equal to listone, which causes listwo to point to where listone is pointing, and it returns True.
All of this is extremely different for integers, and in order to grasp this, we must first understand how objects are stored in memory.

Difference #2:Memory Allocation

Let us take a number and initialize it with 6 as below

number=6

We know the number has the value 6, but how does it become stored in memory? In Python, each object has four memory parts:

Size — For each object, four bytes are reserved to store the object’s size.
Reference Count – For each object, 8 bytes are reserved to store the number of variables pointing to this object. And all of these objects will have this object’s object ID.
Object Type — For each object, 8 bytes are reserved to retain information indicating the type of object.
Object Value — An additional 8 bytes are reserved for each item and contain the object’s actual value.

Object value and reference count are the two most significant items in the preceding list for this topic.

So, for number = 6, there is an object in memory with object value 6 and reference count 1, indicating that the object has a value of 6 and one variable, in this case number, is pointing towards it.

Let us now declare another variable as follows:

number = 6
number2 = number
print(number == number2)
print(number is number2)

Output:

True
True

Now, something very fascinating will happen in memory: no new objects will be generated, and number 2 will also point to where number is pointing, and the object’s reference count will increase to 2.

As a result, number and number 2 will have the same object ID, like the above output.

But what if we do as given below?

number = 6
number2 = 6
print(number == number2)
print(number is number2)

Output:

True
True

Related Programs:

The Difference Between == and is in Python Read More »