Vikram Chiluka

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

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

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

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:

Program to Convert Binary to Gray Code

Python Program to Convert Binary to Gray Code

Although binary numbers are the most common way to store numbers, they can be challenging to use in many situations, necessitating the usage of a binary number variant. This is where Gray codes come in handy.

Gray code has the property that two consecutive numbers differ in just one bit. Because of this quality, grey code cycles through multiple states with low effort and is used in K-maps, error correction, communication, and so on.

We will learn how to convert binary to grey code in Python in this tutorial. A binary number is a number written in the base-2 numeral system. As a result, a binary number is made up of only 0s and 1s. So, today, we’ll learn how to represent binary and grey code numbers, how to convert a binary number to grey code, and how to use a Python program to convert a binary number to grey code.

Examples:

Example1:

Input:

binary String = "1010110101"

Output:

The Gray Code of the binary string= 1010110101 = 1111101111

Example2:

Input:

binary string = "110001101010"

Output:

The Gray Code of the binary string= 110001101010 = 101001011111

Program to Convert Binary to Gray Code in Python

Below are the ways to convert the given binary number to gray code in python:

Method #1:Using Right shift operator and Xor (Static Input)

Approach:

  • Give the binary number as static.
  • The function binToGray is created.
  • As an argument, it accepts a binary number as a string.
  • It returns the string corresponding to its Gray codeword.
  • If b(i) is the ith bit in the binary number and g(i) is the ith bit in the associated Gray codeword, where the 0th bit is the MSB, g(0) = b(0) and g(i) = b(i) XOR b(i – 1) for I > 0.
  • Thus, b XOR (b >> 1) can be used to convert a binary number b to its corresponding Gray codeword.
  • Exit of Program.

Below is the implementation:

# function which accepts the binary string and returns the gray code of the binary string
def binToString(binStr):
    # Converting the given binary string to integer
    binStr = int(binStr, 2)
    binStr ^= (binStr >> 1)

    # Returning the binary converted string using bin() function
    return bin(binStr)[2:]


# given binary number as static
binString = "1010110101"
# passing this binString to binToString function
resultGray = binToString(binString)
print('The Gray Code of the binary string=', binString, '=', resultGray)

Output:

The Gray Code of the binary string= 1010110101 = 1111101111

Method #2:Using Right shift operator and Xor (User Input)

Approach:

  • Scan the binary string using input() function.
  • The function binToGray is created.
  • As an argument, it accepts a binary number as a string.
  • It returns the string corresponding to its Gray codeword.
  • If b(i) is the ith bit in the binary number and g(i) is the ith bit in the associated Gray codeword, where the 0th bit is the MSB, g(0) = b(0) and g(i) = b(i) XOR b(i – 1) for I > 0.
  • Thus, b XOR (b >> 1) can be used to convert a binary number b to its corresponding Gray codeword.
  • Exit of Program.

Below is the implementation:

# function which accepts the binary string and returns the gray code of the binary string
def binToString(binStr):
    # Converting the given binary string to integer
    binStr = int(binStr, 2)
    binStr ^= (binStr >> 1)

    # Returning the binary converted string using bin() function
    return bin(binStr)[2:]


# given binary number as static
binString = input("Enter some random binary string = ")
# passing this binString to binToString function
resultGray = binToString(binString)
print('The Gray Code of the binary string=', binString, '=', resultGray)

Output:

Enter some random binary string = 11100010100101
The Gray Code of the binary string= 11100010100101 = 10010011110111

Related Programs:

Convert PDF to TXT file using Python

Convert PDF to TXT file using Python

You must all be aware of what PDFs are. They are, in fact, one of the most essential and extensively utilized forms of digital media. PDF is an abbreviation for Portable Document Format. It has the.pdf extension. It is used to reliably exhibit and share documents, regardless of software, hardware, or operating system.

Text Extraction from a PDF File
The Python module PyPDF can be used to achieve what we want (text extraction), but it can also do more. This software can also produce, decrypt, and merge PDF files.

Why pdf to txt is needed?

Before we get into the meat of this post, I’ll go over some scenarios in which this type of PDF extraction is required.

One example is that you are using a job portal where people used to upload their CV in PDF format. And when

recruiters are looking for specific keywords, such as Hadoop developers, big data developers, python developers,

java developers, and so on. As a result, the keyword will be matched with the skills that you have specified in your

resume. This is another processing step in which they extract data from your PDF document and match it with the

keyword that the recruiter is looking for, and then they simply give you your name, email, or other information.

As a result, this is the use case.

Python has various libraries for PDF extraction, but we’ll look at the PyPDF2 module here. So, let’s look at how to

extract text from a PDF file using this module.

Convert PDF to TXT file using 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)PyPDF2 module

PyPDF2 is a Pure-Python package designed as a PDF toolkit. It is capable of:

obtaining document information (title, author, etc)

separating documents page by page

merging documents page by page

cropping pages

merging several pages into a single page

encoding and decrypting PDF files and more!
So, now we’ll look at how to extract text from a PDF file using the PyPDF2 module. In your Python IDE, enter the following code (check best python IDEs).

2)Creating a Pdf file

  • Make a new document in Word.
  • Fill up the word document with whatever material you choose.
  • Now, Go to File > Print > Save.
  • Remember to save your pdf file in the same folder as your Python script.
  • Your.pdf file has now been created and saved, and it will be converted to a.txt file later.

3)Install PyPDF2

First, we’ll add an external module called PyPDF2.

The PyPDF2 package is a pure Python pdf library that may be used to divide, merge, crop, and alter PDF files. PyPDF2 may also be used to add data, viewing choices, and passwords to PDFs, according to the PyPDF2 website.

To install the PyPDF2 package, start a command prompt in Windows and use the pip command to install  PyPDF2

4)Creating and opening new Python Project

Open the Python IDLE and hit the ctrl + N keys. This launches your text editor.

You are free to use any other text editor of your choosing.

You should save the file as your pdf file_name.py.

Save this.py file in the same folder as your pdf.

5)Implementation

Below is the implementation:

import PyPDF2

# The opening procedure for a file object variable will be rb
pdffile = open(r'C:\Users\Vikram\Desktop\samplepdf.pdf', 'rb')

# create a variable called reader that will read the pdf file
pdfReader = PyPDF2.PdfFileReader(pdffile)

# The number of pages in this pdf file will be saved.
num = pdfReader.numPages

# create a variable that will select the selected number of pages
pageobj = pdfReader.getPage(num+1)

resulttext = pageobj.extractText()

newfile = open(
    r"C:\Users\Vikram\Desktop\Calender\\sample.txt", "a")
newfile.writelines(resulttext)

Output:

Python Programming Online
Tutorial | Free Beginners’ Guide on
Python Programming Language
Do you Love to Program in Python Language? Are you completely new to the Phyton programming language? Then, refer to this ultimate guide on Python Programming and become the top programmer. For detailed information such as What is Python? Why we use it? Tips to Learn Python Programming Language, Applications for Python dive into this article.

6)Explanation

We start by creating a Python file object and then opening the PDF file in “read binary (rb)” mode.
The PdfFileReader object is then created, which will read the file opened in the previous step.
The number of pages in the file is stored in a variable.
The final step saves the detected lines from the PDF to a text file you designate.
Related Programs:

Program to Print Binary Representation of a Number

Python Program to Print Binary Representation of a Number

Binary Representation:

Binary (or base-2) is a numeral system with only two digits — 0 and 1. Computers use binary to store data and execute calculations, which means they only use zeros and ones. In Boolean logic, a single binary digit can only represent True (1) or False (0). Any integer, in fact, can be represented in binary.

Given a decimal number the task is to convert the given decimal to binary

Examples:

Example1:

Input:

given number =200

Output:

The binary representation of the given number 200  : 
11001000

Example2:

Input:

given number =1

Output:

The binary representation of the given number 1: 
1

Example3:

Input:

given number =32

Output:

The binary representation of the given number 32  : 
100000

Python Program to Print Binary Representation of a Number

There are several ways to print the binary representation of a given decimal 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:Using recursive function

To find a binary equivalent, divide the decimal number recursively by the value 2 until the decimal number hits zero. The remaining must be noted after each division. The binary equivalent of the decimal number is obtained by reversing the remaining values.

Algorithm:

  1. Get the given decimal number from the user or static input.
  2. If the input is larger than zero, divide it by 2 and record the remainder.
  3. Step 2 should be repeated until the decimal number reaches zero.
  4. The residual values should be printed.
  5. End of program

Below is the implementation:

def decitoBin(numb):
    # checking if the given number is greater than 1
    if numb > 1:
        # if it is greater than 1 then use recursive approach by dividing number by 2
        decitoBin(numb // 2)
    # printing the binary representation of the given number
    print(numb % 2, end='')


# Driver code
given_numb = 200
# passing given number to decitoBin function to print binary representation of the givennumb
print("The binary representation of the given number", given_numb, " : ")
decitoBin(given_numb)

Output:

The binary representation of the given number 200  : 
11001000

Method #2:Using while loop

Approach:

  • First we take a empty string say binstr.
  • We use while loop .
  • We will iterate till the number is greater than 0 (Condition of while statement)
  • We will get the last check bit whether it is set bit or not using % operator
  • Convert the set bit to string using str() function
  • Concatenate this bit(can be 1 or 0 ) to the binstr.
  • Reverse this binstr using slicing
  • Print the binary representation of the given number that is print binstr.

Below is the implementation:

def decitoBin(numb):
    # checking if the given number is greater than 1
    if numb > 1:
      # taking a empty string
        binastring = ""
        # 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
            # converting this checkbit to string using str() function
            checkbit = str(checkbit)
            # Concatenate this bit(can be 1 or 0 ) to the binstr.
            binastring = binastring+checkbit
            # divide the number by 2
            numb = numb//2
    # reverse the binary string
    binastring = binastring[::-1]
    # return the resultant binary string
    return binastring


# Driver code
given_numb = 200
# passing given number to decitoBin function to print binary representation of the givennumb
print("The binary representation of the given number", given_numb, " : ")
print(decitoBin(given_numb))

Output:

The binary representation of the given number 200  : 
11001000

Method #3:Using Built in Python function bin()

Approach:

  • We will use bin() function to convert the given decimal number to binary representation.
  • It will return the result in the form of  0bXXXXXXXXX where XXXXXXXX is binary representation.
  • To remove that 0b characters from the string we use two methods
  • Print the resultant binary representation.

i)Using replace function

We will replace the 0b in the binary string with empty string.

Below is the implementation:

def decitoBin(numb):
  # converting it to binary representation using bin() function
    binNumb = bin(numb)
    # replacing '0b' using replace function and replacing it with empty string
    binNumb = binNumb.replace('0b', '')
  # return the binary representation of the given number
    return binNumb


# Driver code
given_numb = 200
# passing given number to decitoBin function to print binary representation of the givennumb
print("The binary representation of the given number", given_numb, " : ")
print(decitoBin(given_numb))

Output:

The binary representation of the given number 200  : 
11001000

The binary representation of the given decimal number will be printed.

ii)Using slicing

We will slice from 2 index to last index of the result returned by binary string

Below is the implementation:

def decitoBin(numb):
  # converting it to binary representation using bin() function
    binNumb = bin(numb)
    # We will slice from 2 index to last index of the result returned by binary string
    binNumb = binNumb[2:]
  # return the binary representation of the given number
    return binNumb


# Driver code
given_numb = 200
# passing given number to decitoBin function to print binary representation of the givennumb
print("The binary representation of the given number", given_numb, " : ")
print(decitoBin(given_numb))

Output:

The binary representation of the given number 200  : 
11001000

The binary representation of the given decimal number will be printed.

Related Programs:

Program to Check if a String is a Pangram or Not

Python Program to Check if a String is a Pangram or Not

Strings in Python:

A Python string is an ordered collection of characters used to express and store text-based data. Strings are saved in an adjacent memory area as individual characters. It is accessible in both directions: forward and backward. Characters are merely symbols. Strings are immutable Data Types in Python, which means they cannot be modified once they are formed.

Pangram:

If a sentence or string contains all 26 letters of the English alphabet at least once, it is considered to be a pangram.

Examples:

Example1:

Input:

given string ="Helloabcdfegjilknmporqstvuxwzy"

Output:

The given string helloabcdfegjilknmporqstvuxwzy is a pangram

Example2:

Input:

given string ="hellothisisbtechgeeks"

Output:

The given string hellothisisbtechgeeks is not a pangram

Python Program to Check if a String is a Pangram or Not

There are several ways to check if the given string is pangram 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:Naive Approach

Approach:

  • Scan the given string or provide static input.
  • Use the lower() method to convert this string to lowercase.
  • The brute force method is to take a string that contains all of the letters of the English alphabet.
  • Traverse through all of the alphabet’s characters string
  • Check to see if this character appears in the given string.
  • If it isn’t present, return False.
  • Return True at the end of the loop (which implies it is pangram)

Below is the implementation:

# Python Program to Check if a String is a Pangram or Not
def checkPangramString(string):

    # creating a new string (alphabet string which stores all the alphabets of the english language
    AlphabetString = 'abcdefghijklmnopqrstuvwxyz'

    # Traverse through the alphabets string
    for char in AlphabetString:
        # Check if this character is present in given string .
        if char not in string.lower():
            # if yes then this character is not available hence return False
            return False
    # After the end of loop return True (which implies it is pangram)
    return True


# given string
string = "Helloabcdfegjilknmporqstvuxwzy"
# converting the given string into lower case
string = string.lower()
# passing this string to checkPangramString function which returns true
# if the given string is pangram else it will return false

if checkPangramString(string):
    print("The given string", string, "is a pangram")
else:
    print("The given string", string, "is not a pangram")

Output:

The given string helloabcdfegjilknmporqstvuxwzy is a pangram

Method #2:Using set() method

The following program can be easily implemented in Python by using the set() method.

Approach:

  • Scan the given string or provide static input.
  • Use the lower() method to convert this string to lowercase.
  • Use the set() function to convert this string to a set.
  • Determine the length of the set.
  • If the length is 26, it is a pangram (since the English language has only 26 alphabets).
  • Otherwise, it is not a pangram.

Below is the implementation:

# Python Program to Check if a String is a Pangram or Not
def checkPangramString(string):

    # converting given string to set using set() function
    setString = set(string)
    # calculate the length of the set
    length = len(setString)
    # If the length is 26, it is a pangram so return true
    if(length == 26):
        return True
    else:
        return False


# given string
string = "Helloabcdfegjilknmporqstvuxwzy"
# converting the given string into lower case
string = string.lower()
# passing this string to checkPangramString function which returns true
# if the given string is pangram else it will return false

if checkPangramString(string):
    print("The given string", string, "is a pangram")
else:
    print("The given string", string, "is not a pangram")

Output:

The given string helloabcdfegjilknmporqstvuxwzy is a pangram

Note:

This method is only applicable if the given string contains alphabets.

Method #3:Using Counter() function (Hashing)

The following program can be easily implemented in Python by using the counter() function

Approach:

  • Scan the given string or provide static input.
  • Use the lower() method to convert this string to lowercase.
  • Calculate the frequency of all characters in the given string using Counter() method
  • Calculate the length of the Counter dictionary.
  • If the length is 26, it is a pangram (since the English language has only 26 alphabets).
  • Otherwise, it is not a pangram.

Below is the implementation:

# Python Program to Check if a String is a Pangram or Not
# importing counter from collections
from collections import Counter


def checkPangramString(string):

    # Calculate the frequency of all characters in the given string
    # using Counter() method
    frequ = Counter(string)
    # calculate the length of the frequency dictionary which is
    # returned from counter() function
    length = len(frequ)
    # If the length is 26, it is a pangram so return true
    if(length == 26):
        return True
    else:
        return False


# given string
string = "Helloabcdfegjilknmporqstvuxwzy"
# converting the given string into lower case
string = string.lower()
# passing this string to checkPangramString function which returns true
# if the given string is pangram else it will return false

if checkPangramString(string):
    print("The given string", string, "is a pangram")
else:
    print("The given string", string, "is not a pangram")

Output:

The given string helloabcdfegjilknmporqstvuxwzy is a pangram

Note:

This method is only applicable if the given string contains alphabets.

Related Programs:

Program to Check Whether the given Number is Strong Number or Not

Python Program to Check Whether the given Number is Strong Number or Not

Strong number:

A Strong number is a special number in which the total of all digit factorials equals the number itself.

Ex: 145 the sum of factorial of digits = 1 ! + 4 ! +5 ! = 1 + 24 +125

To determine whether a given number is strong or not. We take each digit from the supplied number and calculate its factorial , we will do this for each digit of the number.

We do the sum of factorials once we have the factorial of all digits. If the total equals the supplied number, the given number is strong; otherwise, it is not.

Given a number the task is to check whether the given number is strong number or not.

Examples:

Example1:

Input:

given number = 145

Output:

The given number 145 is strong number

Example2:

Input:

given number = 176

Output:

The given number 176 is not a strong number

Python Program to Check Whether the given Number is Strong Number or Not

There are several ways to check whether the given number is strong number 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.

To determine if a number is a strong number or not, divide it into distinct units by each of its digits. The factorial of each of the digits is then computed. Then we will add the values received after the factorial operation for each of the digits. Finally, it must be determined whether this sum equals the supplied number. If the answer is yes, the number is a strong number.

Method #1:Using While loop and writing original factorial function

Approach:

  1. Obtain the desired number as input to determine if it is a strong number, or provide the input number as static.
  2. Let’s create a variable called N to hold this input number.
  3. Put the value of N in a temporary variable called tempNum.
  4. Set a variable, say totalSum to zero. This will save the factorial sum of each of N’s digits.
  5. The number’s final digit must be saved in a variable, such as last_Digit = N % 10.
  6. last_Digit  factorial must be kept in a variable, say factNum.
  7. When the factorial of the last digit is found, it should be added to the totalSum = totalSum+ factNum
  8. Following each factorial operation, the number must be reduced in terms of units by dividing it by ten that is  N = N /10
  9. Steps 4–7 should be repeated until N > 0.

Below is the implementation:

# python program to cheeck whether the given numner is strong number or not
def checkStrongNumb(givenNumb):
    # Taking a variable totalSum and initializing it with 0
    totalSum = 0
    # Take a temporary variable and store the given number (givenNumb)
    # in the temporary variable tempNum
    tempNum = givenNumb
    # using while to extract digit by digit of the given number
    while(givenNumb):
        s = 1
        factNum = 1
        # Getting the last digit of the given number
        remainder = givenNumb % 10
        # calculating the factorial of the digit(extracted by remainder variable)
        while(s <= remainder):
            factNum = factNum * s
            s = s + 1
        # Adding the factorial to the totalSum
        totalSum = totalSum + factNum
        # Dividing the given number by 10
        givenNumb = givenNumb//10
    # checking if the totalSum is equal to the given number
    # if it is true then it is strong number then return true
    if(totalSum == tempNum):
        return True
    # if nothing is returned then it is not a strong number so return False
    return False


# Given number
given_numb = 145
# passing the givennumber to checkStrongNumb to check whether it is strong number or not
if(checkStrongNumb(given_numb)):
    print("The given number", given_numb, "is strong number")
else:
    print("The given number", given_numb, "is not a strong number")

Output:

The given number 145 is strong number

Method #2:Using While loop and factorial() function

We use the factorial() function to do the above problem quickly

Approach:

  1. Obtain the desired number as input to determine if it is a strong number, or provide the input number as static.
  2. Let’s create a variable called N to hold this input number.
  3. Put the value of N in a temporary variable called tempNum.
  4. Set a variable, say totalSum to zero. This will save the factorial sum of each of N’s digits.
  5. The number’s final digit must be saved in a variable, such as last_Digit = N % 10.
  6. Calculate the factorial of the last_Digit using math.factorial() function
  7. When the factorial of the last digit is found, it should be added to the totalSum = totalSum+ factNum
  8. Following each factorial operation, the number must be reduced in terms of units by dividing it by ten that is  N = N /10
  9. Steps 4–7 should be repeated until N > 0.

Below is the implementation:

# importing math module
import math
# python program to cheeck whether the given numner is strong number or not


def checkStrongNumb(givenNumb):
    # Taking a variable totalSum and initializing it with 0
    totalSum = 0
    # Take a temporary variable and store the given number (givenNumb)
    # in the temporary variable tempNum
    tempNum = givenNumb
    # using while to extract digit by digit of the given number
    while(givenNumb):
        s = 1
        factNum = 1
        # Getting the last digit of the given number
        remainder = givenNumb % 10
        # calculating the factorial of the digit(extracted by remainder variable)
        # using math.fatorial function
        factNum = math.factorial(remainder)
        # Adding the factorial to the totalSum
        totalSum = totalSum + factNum
        # Dividing the given number by 10
        givenNumb = givenNumb//10
    # checking if the totalSum is equal to the given number
    # if it is true then it is strong number then return true
    if(totalSum == tempNum):
        return True
    # if nothing is returned then it is not a strong number so return False
    return False


# Given number
given_numb = 145
# passing the givennumber to checkStrongNumb to check whether it is strong number or not
if(checkStrongNumb(given_numb)):
    print("The given number", given_numb, "is strong number")
else:
    print("The given number", given_numb, "is not a strong number")

Output:

The given number 145 is strong number

Related Programs:

Program to Check Whether the given Number is Perfect Number or Not in Python

Python Program to Check Whether the given Number is Perfect Number or Not

Perfect Number in python:

If the sum of a number’s appropriate divisors (excluding the number itself) equals the number, the number is said to be the perfect number.

Consider the following example: appropriate divisors of 6 are 1, 2, 3. Because the sum of these divisors equals 6 (1+2+3=6), 6 is considered a perfect number. When we consider another number, such as 12, the proper divisors of 12 are 1, 2, 3, 4, and 6. Now, because the sum of these divisors does not equal 12, 12 is not a perfect number.

Python programming is simpler and more enjoyable than programming in other languages due to its simplified syntax and superior readability. Now that we understand the concept of a perfect number, let’s construct a Python program to determine whether or not a number is a perfect number. Let’s write some Python code to see if the given user input is a perfect number or not, and have some fun with Python coding.

Examples:

Example1:

Input:

given number = 6

Output:

The given number 6 is perfect number

Example2:

Input:

given number = 179

Output:

The given number 179 is not a perfect number

Python Program to Check Whether the given Number is Perfect Number or Not

There are several ways to check whether the given number is perfect number 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: Iterating from 2 to N-1

A simple technique for determining a perfect number is to loop from 2 to given_number-1, keep track of the sum of the number’s proper divisors, and see if the sum equals the number.

Below is the implementation:

# python program to cheeck whether the given numner is perfect number or not

# function which returns true if the given number is
# perfect number else it will return False


def checkPerfectNumb(givenNumb):
    # Taking a variable totalSum and initializing it with 1
    totalSum = 1
    # Iterating from 2 to n-1
    for i in range(2, givenNumb):
        # if the iterator value is divides the number then add the given number to totalSum
        if givenNumb % i == 0:
            totalSum += i

    # if the totalSum is equal to the given number
    # then it is perfect number else it is not perfect number

    if(totalSum == givenNumb):
        # if it is true then it is perfect number then return true
        return True
    # if nothing is returned then it is not a perfect number so return False
    return False


# Given number
given_numb = 6
# passing the givennumber to checkPerfectNumb to check whether it is perfect number or not
if(checkPerfectNumb(given_numb)):
    print("The given number", given_numb, "is perfect number")
else:
    print("The given number", given_numb, "is not a perfect number")

Output:

The given number 6 is perfect number

We must determine whether n is a perfect number. It is worth noting that we are initializing the totalSum with 1 because 1 is a valid divisor for all integers (except zero), allowing us to skip an iteration in the loop and start from 2.

If it is a proper divisor, we loop over 2 to number-1 and add the integers to totalSum. Finally, when we exit the loop, we check to see if the sum obtained is equal to the number.

It requires O(n) Time Complexity.

Method #2:Iterating from 2 to N/2

After running the preceding program through its tests, we may think it would be possible to optimize it. But, without modifying the technique, we can reduce the number of iterations to number/2. We came to the conclusion that a number cannot have a suitable divisor bigger than number/2.

Below is the implementation:

# python program to cheeck whether the given numner is perfect number or not

# function which returns true if the given number is
# perfect number else it will return False


def checkPerfectNumb(givenNumb):
    # Taking a variable totalSum and initializing it with 1
    totalSum = 1
    # Iterating from 2 to given_number//2 +1
    for i in range(2, givenNumb//2 + 1):
        # if the iterator value is divides the number then add the given number to totalSum
        if givenNumb % i == 0:
            totalSum += i

    # if the totalSum is equal to the given number
    # then it is perfect number else it is not perfect number

    if(totalSum == givenNumb):
        # if it is true then it is perfect number then return true
        return True
    # if nothing is returned then it is not a perfect number so return False
    return False


# Given number
given_numb = 6
# passing the givennumber to checkPerfectNumb to check whether it is perfect number or not
if(checkPerfectNumb(given_numb)):
    print("The given number", given_numb, "is perfect number")
else:
    print("The given number", given_numb, "is not a perfect number")

Output:

The given number 6 is perfect number

The preceding excerpt is nearly identical to the previous one, with the exception of looping till number/2. It’s worth noting that we’re doing an integer division instead of converting it to a float type, and we’re looping until n/2+1 because the last integer in the range is ignored by the Python loop.

It requires O(n) Time Complexity.

Method #3: Efficient Approach (Iterating till Square root of N)

An Efficient Solution is to go through the numbers till you get to the square root of n. If a number i divides n, then sum both i and n/i.

Below is the implementation:

# python program to cheeck whether the given numner is perfect number or not

# function which returns true if the given number is
# perfect number else it will return False


def checkPerfectNumb(givenNumb):
    # Taking a variable totalSum and initializing it with 1
    totalSum = 1
    k = 2
    while k * k <= givenNumb:
        # if the iterator value is divides the number then add the given number to totalSum
        if givenNumb % k == 0:
            totalSum = totalSum + k + givenNumb/k
        k += 1

    # if the totalSum is equal to the given number
    # then it is perfect number else it is not perfect number

    if(totalSum == givenNumb):
        # if it is true then it is perfect number then return true
        return True
    # if nothing is returned then it is not a perfect number so return False
    return False


# Given number
given_numb = 6
# passing the givennumber to checkPerfectNumb to check whether it is perfect number or not
if(checkPerfectNumb(given_numb)):
    print("The given number", given_numb, "is perfect number")
else:
    print("The given number", given_numb, "is not a perfect number")

Output:

The given number 6 is perfect number

This is the efficient approach to do the same problem quickly compared to first two methods.

It requires O(Sqrt(n)) Time Complexity.

Related Programs:

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:

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:

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: