Python

Program to Find nth Prime Number

Python Program to Find nth Prime Number

In the previous article, we have discussed Python Program to Delete Random Item from a List
Prime Number :

A prime number is one that can only be divided by one and itself.

Given a number ‘n’, and the task to find the nth prime number.

Examples:

Example1:

Input:

Given number = 8

Output:

The above given nth Prime Number is =  19

Example2:

Input:

Given number = 3

Output:

The above given nth Prime Number is =  5

Program to Find nth Prime Number

Below are the ways to find the nth prime number.

Method #1: Using While, For Loop (Static Input)

Approach:

  • Give the number say ‘n’ as static input and store it in a variable.
  • Take a list say ‘prime_numbers’ and initialize it with 2, 3 values.
  • Take a variable and initialize it with 3 say ‘x’.
  • Check if the given number is between greater than 0 and less than 3 using the if conditional statement.
  • If the statement is true, then print the value of the list “prime_numbers[n-1] “.
  • Check if the given number is greater than 2 using the elif conditional statement.
  • Iterate the loop infinite times using the while loop i.e while(True).
  • Inside the loop increment the value of the above given ‘x’ variable by ‘1’.
  • Take a variable to say ‘y’ and initialize with ‘True’.
  • Loop from 2 to int((x/2)+1) using the for loop and int function().
  • Check if the value of variable ‘x’ modulus iterator value is equal to zero or not using the if conditional statement.
  • If the statement is true, assign “False” to the variable y, break the statement and come out of the loop.
  • Check if variable y is equal to True using the if conditional statement.
  • If the statement is true, then append the value of variable ‘x’ to the above list ‘prime_numbers’.
  • Check if the length of the above list ‘prime_numbers’ is equal to the given number.
  • If the statement is true, then give a break statement and come out of the while loop.
  • Print the value of the list “prime_numbers[n-1]” to get the nth prime number.
  • Else print “Invalid number. Please enter another number “.
  • The Exit of the Program.

Below is the implementation:

# Give the number say 'n' as static input and store it in a variable.
num = 5
# Take a list say 'prime_numbers' and initialize it with 2, 3 values.
prim_numbrs = [2, 3]
# Take a variable and initialize it with 3 say 'x'.
x = 3
# Check if the given number is between greater than 0 and less than 3 using the if
# conditional statement.
if(0 < num < 3):
 # If the statement is true, then print the value of the list "prime_numbers[n-1] ".
    print('The above given nth Prime Number is =', prim_numbrs[num-1])
# Check if the given number is greater than 2 using the elif conditional statement.
elif(num > 2):
  # Iterate the loop infinite times using the while loop i.e while(True).
    while (True):
     # Inside the loop increment the value of the above given 'x' variable by '1'.
        x += 1
 # Take a variable say 'y' and initialize with 'True'.
        y = True
  # Loop from 2 to int((x/2)+1) using the for loop and int function().
        for itr in range(2, int(x/2)+1):
          # Check if the value of variable 'x' modulus iterator value is equal to zero or not
          # using the if conditional statement.
            if(x % itr == 0):
                # If the statement is true, assign "False" to the variable y, break the statement and
                # come out of the loop.
                y = False
                break
 # Check if variable y is equal to True using the if conditional statement.
        if(y == True):
            # If the statement is true, then append the value of variable 'x' to the
            # above list 'prime_numbers'.
            prim_numbrs.append(x)
  # Check if the length of the above list 'prime_numbers' is equal to the given number.
        if(len(prim_numbrs) == num):
         # If the statement is true, then give a break statement and come out of the while loop.
            break
 # Print the value of the list "prime_numbers[n-1]" to get the nth prime number.
    print('The above given nth Prime Number is = ', prim_numbrs[num-1])
 # Else print "Invalid number. Please enter another number ".
else:
    print("Invalid number. Please enter another number ")

Output:

The above given nth Prime Number is =  11

Method #2: Using While, For Loop (User Input)

Approach:

  • Give the number say ‘n’ as user input using int(input()) and store it in a variable.
  • Take a list say ‘prime_numbers’ and initialize it with 2, 3 values.
  • Take a variable and initialize it with 3 say ‘x’.
  • Check if the given number is between greater than 0 and less than 3 using the if conditional statement.
  • If the statement is true, then print the value of the list “prime_numbers[n-1] “.
  • Check if the given number is greater than 2 using the elif conditional statement.
  • Iterate the loop infinite times using the while loop i.e while(True).
  • Inside the loop increment the value of the above given ‘x’ variable by ‘1’.
  • Take a variable to say ‘y’ and initialize with ‘True’.
  • Loop from 2 to int((x/2)+1) using the for loop and int function().
  • Check if the value of variable ‘x’ modulus iterator value is equal to zero or not using the if conditional statement.
  • If the statement is true, assign “False” to the variable y, break the statement and come out of the loop.
  • Check if variable y is equal to True using the if conditional statement.
  • If the statement is true, then append the value of variable ‘x’ to the above list ‘prime_numbers’.
  • Check if the length of the above list ‘prime_numbers’ is equal to the given number.
  • If the statement is true, then give a break statement and come out of the while loop.
  • Print the value of the list “prime_numbers[n-1]” to get the nth prime number.
  • Else print “Invalid number. Please enter another number “.
  • The Exit of the Program.

Below is the implementation:

# Give the number say 'n' as user input using int(input()) and store it in a variable.
num = int(input("Enter some random number = "))
# Take a list say 'prime_numbers' and initialize it with 2, 3 values.
prim_numbrs = [2, 3]
# Take a variable and initialize it with 3 say 'x'.
x = 3
# Check if the given number is between greater than 0 and less than 3 using the if
# conditional statement.
if(0 < num < 3):
 # If the statement is true, then print the value of the list "prime_numbers[n-1] ".
    print('The above given nth Prime Number is =', prim_numbrs[num-1])
# Check if the given number is greater than 2 using the elif conditional statement.
elif(num > 2):
  # Iterate the loop infinite times using the while loop i.e while(True).
    while (True):
     # Inside the loop increment the value of the above given 'x' variable by '1'.
        x += 1
 # Take a variable say 'y' and initialize with 'True'.
        y = True
  # Loop from 2 to int((x/2)+1) using the for loop and int function().
        for itr in range(2, int(x/2)+1):
          # Check if the value of variable 'x' modulus iterator value is equal to zero or not
          # using the if conditional statement.
            if(x % itr == 0):
                # If the statement is true, assign "False" to the variable y, break the statement and
                # come out of the loop.
                y = False
                break
 # Check if variable y is equal to True using the if conditional statement.
        if(y == True):
            # If the statement is true, then append the value of variable 'x' to the
            # above list 'prime_numbers'.
            prim_numbrs.append(x)
  # Check if the length of the above list 'prime_numbers' is equal to the given number.
        if(len(prim_numbrs) == num):
         # If the statement is true, then give a break statement and come out of the while loop.
            break
 # Print the value of the list "prime_numbers[n-1]" to get the nth prime number.
    print('The above given nth Prime Number is = ', prim_numbrs[num-1])
 # Else print "Invalid number. Please enter another number ".
else:
    print("Invalid number. Please enter another number ")

Output:

Enter some random number = 1
The above given nth Prime Number is = 2

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

Python Program to Find nth Prime Number Read More »

Program to Divide a String in 'N' Equal Parts

Python Program to Divide a String in ‘N’ Equal Parts

In the previous article, we have discussed Python Program to Check Evil Number or Not
Given a string and the task is to divide the given string into “N” equal parts.

Examples:

Example1:

Input:

Given string = "aaaabbbbccccddddeeee"

Output:

The given string after dividing into 5 equal halves:
aaaa
bbbb
cccc
dddd
eeee

Example2:

Input:

Given string = "hellobtechgeeks"

Output:

The given string cannot be divided into 4 equal halves

Program to Divide a String in ‘N’ Equal Parts

Below are the ways to divide the given string into “N” equal parts.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Give the number say ‘n’ as static input and store it in another variable.
  • Calculate the len of the given string using the len() function and store it in another variable.
  • Check if the length of the string modulus given number is not equal to ‘0’ or not using the if conditional statement.
  • If the statement is true, print “The given string cannot be divided into n equal halves”.
  • Else loop from 0 to length of the string with the step size of given number ‘n’ using the for loop.
  • Slice from the iterator value to the iterator +n value using slicing and print them.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = "aaaabbbbccccddddeeee"
# Give the number say 'n' as static input and store it in another variable.
num = 5
# Calculate the len of the given string using the len() function and store it
# in another variable.
len_str = len(gvn_str)
# Divide the length of the string by a given number and store it in another variable say 'k'.
k = len_str//num
# Check if the length of the string modulus given number is not equal to '0' or
# not using the if conditional statement.
if(len_str % num != 0):
    # If the statement is true, print "The given string cannot be divided into n equal halves".
    print("The given string cannot be divided into", num, "equal halves")
else:
  # Else loop from 0 to length of the string with the step size of the number 'k'
  # using the for loop.
    print("The given string after dividing into", num, "equal halves:")
    for i in range(0, len_str, k):
        # Slice from the iterator value to the iterator +n value using slicing and
        # print them.
        print(gvn_str[i:i+k])

Output:

The given string after dividing into 5 equal halves:
aaaa
bbbb
cccc
dddd
eeee

Method #2: Using For Loop (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Give the number say ‘n’ as static input and store it in another variable.
  • Calculate the len of the given string using the len() function and store it in another variable.
  • Divide the length of the string by a given number and store it in another variable say ‘k’.
  • Check if the length of the string modulus given number is not equal to ‘0’ or not using the if conditional statement.
  • If the statement is true, print “The given string cannot be divided into n equal halves”.
  • Else loop from 0 to length of the string with the step size of the number ‘k’ using the for loop.
  • Slice from the iterator value to the iterator +k value using slicing and print them.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Give the number say 'n' as user input using int(input()) and store it in another variable.
num = int(input("Enter some random number = "))
# Calculate the len of the given string using the len() function and store it
# in another variable.
len_str = len(gvn_str)
#Divide the length of the string by a given number and store it in another variable say 'k'.
k=len_str//num
# Check if the length of the string modulus given number is not equal to '0' or
# not using the if conditional statement.
if(len_str % num != 0):
    # If the statement is true, print "The given string cannot be divided into n equal halves".
    print("The given string cannot be divided into", num, "equal halves")
else:
  # Else loop from 0 to length of the string with the step size of the number 'k'
  # using the for loop.
    print("The given string after dividing into", num, "equal halves:")
    for i in range(0, len_str, k):
        # Slice from the iterator value to the iterator +n value using slicing and
        # print them.
        print(gvn_str[i:i+k])

Output:

Enter some random string = 1234567890
Enter some random number = 2
The given string after dividing into 2 equal halves:
12345
67890

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

Python Program to Divide a String in ‘N’ Equal Parts Read More »

Program to Check Strontio Number or Not

Python Program to Check Strontio Number or Not

In the previous article, we have discussed Python Program to Find nth Prime Number
Strontio numbers:

Strontio numbers are four-digit numbers that, when multiplied by two, produce the same digit in the hundreds and tens places. Keep in mind that the input number must be four digits.

example :

Let N= 1386

A number multiplied by 2= 1386*2=2772

2772%1000 =772

772/10 = 77

77/10 = 7

77%7= 7

if (77%7 == 77/10 ), then it is strontio number.

Therefore 1386 is strontio number.

some of the examples of strontio numbers are :

1111, 2222, 3333, 4444, 5555, 6666, 7777, 8888, 9999, 1001, 2002, 3003, and other numbers.

Examples:

Example1:

Input:

Given number = 1001

Output:

The given number 1001 is strontio number

Example2:

Input:

Given number = 1234

Output:

The given number 1234 is not a strontio number

Program to Check Strontio Number or Not.

Below are the ways to check a strontio number or not.

Method #1: Using modulus Operator (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Multiply the given number a store it in another variable.
  • Calculate the value of the above-obtained number modulus 1000 to get a remainder and store it in another variable say “a”.
  • Divide the variable ‘a’ by 10 to remove the last digit and store it in another variable say ‘b’.
  • Again divide the variable ‘b’ by 10 to remove the last digit (quotient)and store it in another variable say  ‘c’.
  • Calculate the value of b%10 to get the remainder and store it in another variable say  ‘d’.
  • Check if both the quotient and remainder are equal or not (c==d) using the if conditional statement.
  • If the statement is true, then print “The given number is strontio number”.
  • Else print “Not Stronio Number”.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
num = 1001
# Multiply the given number a store it in another variable.
mul_numb = num*2
# Calculate the value of the above-obtained number modulus 1000 to get a remainder
# and store it in another variable say "a".
a = mul_numb % 1000
# Divide the variable 'a' by 10 to remove the last digit and store it in
# another variable say 'b'.
b = a//10
# Again divide the variable 'b' by 10 to remove the last digit (quotient)and
# store it in another variable say  'c'.
c = b//10
# Calculate the value of b%10 to get the remainder and store it in another variable
# say 'd'.
d = b % 10
# Check if both the quotient and remainder are equal or not (c==d) using the if conditional statement.
if(c == d):
  # If the statement is true, then print "The given number is strontio number".
    print("The given number", num, "is strontio number")
else:
  # Else print "Not Stronio Number".
    print("The given number", num, "is not a strontio number")

Output:

The given number 1001 is strontio number

Method #2: Using modulus Operator  (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Multiply the given number a store it in another variable.
  • Calculate the value of the above-obtained number modulus 1000 to get a remainder and store it in another variable say “a”.
  • Divide the variable ‘a’ by 10 to remove the last digit and store it in another variable say ‘b’.
  • Again divide the variable ‘b’ by 10 to remove the last digit (quotient)and store it in another variable say  ‘c’.
  • Calculate the value of b%10 to get the remainder and store it in another variable say  ‘d’.
  • Check if both the quotient and remainder are equal or not (c==d) using the if conditional statement.
  • If the statement is true, then print “The given number is strontio number”.
  • Else print “Not Stronio Number”.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function and
# store it in a variable.
num = int(input("Enter some random Number = "))
# Multiply the given number a store it in another variable.
mul_numb = num*2
# Calculate the value of the above-obtained number modulus 1000 to get a remainder
# and store it in another variable say "a".
a = mul_numb % 1000
# Divide the variable 'a' by 10 to remove the last digit and store it in
# another variable say 'b'.
b = a//10
# Again divide the variable 'b' by 10 to remove the last digit (quotient)and
# store it in another variable say  'c'.
c = b//10
# Calculate the value of b%10 to get the remainder and store it in another variable
# say 'd'.
d = b % 10
# Check if both the quotient and remainder are equal or not (c==d) using the if conditional statement.
if(c == d):
  # If the statement is true, then print "The given number is strontio number".
    print("The given number", num, "is strontio number")
else:
  # Else print "Not Stronio Number".
    print("The given number", num, "is not a strontio number")

Output:

Enter some random Number = 5555
The given number 5555 is strontio number

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

Python Program to Check Strontio Number or Not Read More »

Program to Determine Whether one String is a Rotation of Another

Python Program to Determine Whether one String is a Rotation of Another

In the previous article, we have discussed Python Program to Shuffle a List
Given a string, and the task is to determine whether one string is a rotation of another.

Examples:

Example1:

Input:

Given first string = "btechgeeks"
Given second string = "geeksbtech"

Output:

The given second string is the rotation of the given second string

Example2:

Input:

Given first string = "pqrst"
Given second string = "sggsf"

Output:

The given second string is not the rotation of the given second string

Program to Determine Whether one String is a Rotation of Another

Below are the ways to determine whether one string is the rotation of another.

Method #1: Using String Concatenation (Static Input)

Approach:

  • Give the first string as static input and store it in a variable.
  • Give the second string as static input and store it in another variable.
  • Check if the length of the first string is not equal to the length of the second string using the if conditional statement and using the len() function.
  • If the statement is true, print “The given second string is not the rotation of the given first string”.
  • Else concatenate the first string with the first string itself using the ‘+ ‘ operator and store it in a variable say “conat_str”.
  • Check if the second string is present in the “conca_str” using the if conditional statement.
  • If the statement is true, print  “The given second string is the rotation of the given first string”.
  • Else print  “The given second string is not the rotation of the given first string”.
  • The Exit of the Program.

Below is the implementation:

# Give the first string as static input and store it in a variable.
fst_str = "pqrst"
# Give the second string as static input and store it in another variable.
secnd_str = "stpqr"
# Check if the length of the first string is not equal to the length of the second
# string using the if conditional statement and using the len() function.
if(len(fst_str) != len(secnd_str)):
    # If the statement is true, print "The given second string is not the rotation of the given first string".
    print("The given second string is not the rotation of the given first string")
else:
    # Else concatenate the first string with the first string itself using the '+ ' operator
    # and store it in a variable say "conat_str".
    conct_str = fst_str + fst_str
# Check if the second string is present in the "conca_str" using the if
# conditional statement.
    if(secnd_str in conct_str):
        # If the statement is true, print  "The given second string is the rotation of the given first string".
        print("The given second string is the rotation of the given  first string")
    else:
        # Else print  "The given second string is not the rotation of the given first string".
        print("The given second string is not the rotation of the first given string")

Output:

The given second string is the rotation of the second string

Method #2: Using String Concatenation (User Input)

Approach:

  • Give the first string as user input using the input() function and store it in a variable.
  • Give the second string as user input using the input() function and store it in another variable.
  • Check if the length of the first string is not equal to the length of the second string using the if conditional statement and using the len() function.
  • If the statement is true, print “The given second string is not the rotation of the given first string”.
  • Else concatenate the first string with the first string itself using the ‘+ ‘ operator and store it in a variable say “conat_str”.
  • Check if the second string is present in the “conca_str” using the if conditional statement.
  • If the statement is true, print  “The given second string is the rotation of the given first string”.
  • Else print  “The given second string is not the rotation of the given first string”.
  • The Exit of the Program.

Below is the implementation:

# Give the first string as user input using input() function and store it in a variable.
fst_str = input("Enter some random string = ")
# Give the second string as user input using input() function and store it in another variable.
secnd_str = input("Enter some random string = ")
# Check if the length of the first string is not equal to the length of the second
# string using the if conditional statement and using the len() function.
if(len(fst_str) != len(secnd_str)):
    # If the statement is true, print "The given second string is not the rotation of the given first string".
    print("The given second string is not the rotation of the given first string")
else:
    # Else concat the first string with the first string itself using the '+ ' operator
    # and store it in a variable say "conat_str".
    conct_str = fst_str + fst_str
# Check if the second string is present in the "conca_str" using the if
# conditional statement.
    if(secnd_str in conct_str):
        # If the statement is true, print  "The given second string is the rotation of the given first string".
        print("The given second string is the rotation of the given first string")
    else:
        # Else print  "The given second string is not the rotation of the given first string".
        print("The given second string is not the rotation of the given first string")

Output:

Enter some random string = btechgeeks
Enter some random string = geeksbtech
The given second string is the rotation of the second string

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

Python Program to Determine Whether one String is a Rotation of Another Read More »

Program to Check Automorphic Number or Not

Python Program to Check Automorphic Number or Not

In the previous article, we have discussed Python Program to Convert each Character in a String to an ASCII Value.
Automorphic Number:

An automorphic number is one whose square has the same digits as the original number. Examples: 5, 25, 76,  and so on.

Example :

let N= 6

N square = 6*6 = 36

The last digit is the same as the given number. Therefore 6 is an automorphic number.

Examples:

Example1:

Input:

Given Number = 625

Output:

The given number 625 is an Automorphic Number

Example2:

Input:

Given Number = 200

Output:

The given number 200 is not an Automorphic Number

Program to Check Automorphic Number or Not

Below are the ways to check the automorphic number or not.

Method #1: Using pow() function (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Covert the given number into a string using the str() function and find the length of the given number using the len() function.
  • Store it in another variable.
  • Calculate the square of the given number and store it in a variable.
  • Get the last n digits of the square number using modulus and pow() functions and store it in another variable.
  • Check if the last n digits are equal to the given input number using the if conditional statement.
  • If the statement is true, then print “The given number is an Automorphic Number”.
  • Else print “The given number is not an Automorphic Number”.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_numbr = 6
# Covert the given number into a string using the str() function and
# find the length of the given number using the len() function.
# Store it in another variable.
lenth = len(str(gvn_numbr))
# Calculate the square of the given number and store it in a variable.
sqr_num = gvn_numbr**2
# Get the last n digits of the square number using modulus and pow() functions and
# store it in another variable.
lst_n_digits = sqr_num % pow(10, lenth)
# Check if the last n digits are equal to the given input number using the if
# conditional statement.
if lst_n_digits == gvn_numbr:
  # If the statement is true, then print "The given number is an Automorphic Number".
    print("The given number", gvn_numbr, "is an Automorphic Number")
else:
 # Else print "The given number is not an Automorphic Number".
    print("The given number", gvn_numbr, "is not an Automorphic Number")

Output:

The given number 6 is an Automorphic Number

Method #2: Using pow() function (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Covert the given number into a string using the str() function and find the length of the given number using the len() function.
  • Store it in another variable.
  • Calculate the square of the given number and store it in a variable.
  • Get the last n digits of the square number using modulus and pow() functions and store it in another variable.
  • Check if the last n digits are equal to the given input number using the if conditional statement.
  • If the statement is true, then print “The given number is an Automorphic Number”.
  • Else print “The given number is not an Automorphic Number”.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function and store it in a variable.
gvn_numbr = int(input("Enter some random number = "))
# Covert the given number into a string using the str() function and
# find the length of the given number using the len() function.
# Store it in another variable.
lenth = len(str(gvn_numbr))
# Calculate the square of the given number and store it in a variable.
sqr_num = gvn_numbr**2
# Get the last n digits of the square number using modulus and pow() functions and
# store it in another variable.
lst_n_digits = sqr_num % pow(10, lenth)
# Check if the last n digits are equal to the given input number using the if
# conditional statement.
if lst_n_digits == gvn_numbr:
  # If the statement is true, then print "The given number is an Automorphic Number".
    print("The given number", gvn_numbr, "is an Automorphic Number")
else:
 # Else print "The given number is not an Automorphic Number".
    print("The given number", gvn_numbr, "is not an Automorphic Number")

Output:

Enter some random number = 25
The given number 25 is an Automorphic Number

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

Python Program to Check Automorphic Number or Not Read More »

Program to Check Evil Number or Not

Python Program to Check Evil Number or Not

In the previous article, we have discussed Python Program to Determine Whether one String is a Rotation of Another
Evil Number :

The Evil number is another unique positive whole number with an even number of 1s in its binary representation.

example:

1) let n= 12

binary representation = 1100

# It has an even number of 1’s.  Therefore 12 is an evil number.

2) n= 4

binary representation = 100

It has an odd number of 1’s.  Therefore 4 is not an evil number.

Examples:

Example1:

Input:

Given Number = 6

Output:

The given number 6 is an Evil Number

Example2:

Input:

Given Number = 22

Output:

The given number 22 is Not an Evil Number

Program to Check Evil Number or Not

Below are the ways to check whether the given number is an evil number or not

Method #1:Using Built-in Functions (Static input)

Approach:

  • Give the number as static input and store it in a variable.
  • Convert the given number into a binary number using the bin() function and store it in another variable.
  • Take a variable say ‘c’ and initialize its value with zero.
  • Loop in the above obtained binary number using the for loop.
  • Check if the iterator value is equal to ‘1’ using the if conditional statement.
  • If the statement is true, increase the count value of the variable ‘c’ by 1 and store it in the same variable.
  • Check for the even number of  1’s by c %2 is equal to zero or not using the if conditional statement.
  • If the statement is true, print “The given number is an Evil Number”.
  • Else print “The given number is not an Evil Number”.
  • The Exit of the program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_num = 9
# Convert the given number into a binary number using the bin() function and
# store it in another variable.
k = bin(gvn_num)[2:]
# Take a variable say 'c' and initialize its value with zero.
c = 0
# Loop in the above obtained binary number using the for loop.
for i in k:
 # Check if the iterator value is equal to '1' using the if conditional statement.
    if(i == '1'):
     # If the statement is true, increase the count value of the variable 'c' by 1 and
        # store it in the same variable.
        c += 1
 # Check for the even number of  1's by c %2 is equal to zero or not using the
# if conditional statement.
if(c % 2 == 0):
  # If the statement is true, print "The given number is an Evil Number".
    print("The given number", gvn_num, "is an Evil Number")
else:
  # Else print "The given number is not an Evil Number".
    print("The given number", gvn_num, "is Not an Evil Number")

Output:

The given number 9 is an Evil Number

Method #2: Using Built-in Functions (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Convert the given number into a binary number using the bin() function and store it in another variable.
  • Take a variable say ‘c’ and initialize its value with zero.
  • Loop in the above obtained binary number using the for loop.
  • Check if the iterator value is equal to ‘1’ using the if conditional statement.
  • If the statement is true, increase the count value of the variable ‘c’ by 1 and store it in the same variable.
  • Check for the even number of  1’s by c %2 is equal to zero or not using the if conditional statement.
  • If the statement is true, print “The given number is an Evil Number”.
  • Else print “The given number is not an Evil Number”.
  • The Exit of the program.

Below is the implementation:

# Give the number as user input using the int(input()) function and store it in a variable.
gvn_num = int(input("Enter some random number = "))
# Convert the given number into a binary number using the bin() function and
# store it in another variable.
k = bin(gvn_num)[2:]
# Take a variable say 'c' and initialize its value with zero.
c = 0
# Loop in the above obtained binary number using the for loop.
for i in k:
 # Check if the iterator value is equal to '1' using the if conditional statement.
    if(i == '1'):
     # If the statement is true, increase the count value of the variable 'c' by 1 and
        # store it in the same variable.
        c += 1
 # Check for the even number of  1's by c %2 is equal to zero or not using the
# if conditional statement.
if(c % 2 == 0):
  # If the statement is true, print "The given number is an Evil Number".
    print("The given number", gvn_num, "is an Evil Number")
else:
  # Else print "The given number is not an Evil Number".
    print("The given number", gvn_num, "is Not an Evil Number")

Output:

Enter some random number = 3
The given number 3 is an Evil Number

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

Python Program to Check Evil Number or Not Read More »

Program to Convert each Character in a String to an ASCII Value

Python Program to Convert each Character in a String to an ASCII Value

In the previous article, we have discussed Python Program to Divide a String in ‘N’ Equal Parts.
When each character in a string is converted to an ASCII value, a list of corresponding ASCII values for each character is returned. Converting each character in “dce” to an ASCII value, for example, yields [100, 99, 101].

Given a string and the task is to convert each character in a given String to an ASCII Value.

ASCII Characters:

The standard range of ASCII, which stands for American Standard Code for Information Interchange, is “Zero” to “One Hundred and Twenty Seven”.

ASCII codes are used to represent text in computers and other electronic devices. The character-encoding schemes used in most modern telecommunications equipment are based on ASCII.

As a result, everything else falls into the category of “non-ASCII” character.

ord() function: To determine the specific ASCII value of that character.

Examples:

Example1:

Input:

Given String = " btechgeeks"

Output:

The given string after convering each character to an ASCII value : [98, 116, 101, 99, 104, 103, 101, 101, 107, 115]

Example2:

Input:

Given String = "hello this is btechgeeks"

Output:

The given string after convering each character to an ASCII value : [104, 101, 108, 108, 111, 32, 116, 104, 105, 115, 32, 105, 115, 32, 98, 116, 101, 99, 104, 103, 101, 101, 107, 115]

Program to Convert each Character in a String to an ASCII Value.

Below are the ways to convert each character in a given String to an ASCII Value.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Take an empty list say “ASCII_vals” and store it in another variable.
  • Loop the above-given string using the for loop.
  • Calculate the ASCII value of the iterator using the ord() function and store it in another variable.
  • Append the above obtained ASCII value of the iterator to the above-initialized list “ASCII_vals” using the append() method.
  • Print the given string after converting each character to an ASCII value.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = "hello this is btechgeeks"
# Take an empty list say "ASCII_vals" and store it in another variable.
ASCII_vals = []
# Loop the above-given string using the for loop.
for itr in gvn_str:
  # Calculate the ASCII value of the iterator using the ord() function
  # and store it in another variable.
    a = ord(itr)
# Append the above obtained ASCII value of the iterator to the above-initialized
# list "ASCII_vals" using the append() method.
    ASCII_vals.append(a)
  # Print the given string after converting each character to an ASCII value.
print("The given string after convering each character to an ASCII value :", ASCII_vals)

Output:

The given string after convering each character to an ASCII value : [104, 101, 108, 108, 111, 32, 116, 104, 105, 115, 32, 105, 115, 32, 98, 116, 101, 99, 104, 103, 101, 101, 107, 115]

Method #2: Using For loop (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Take an empty list say “ASCII_vals” and store it in another variable.
  • Loop the above-given string using the for loop.
  • Calculate the ASCII value of the iterator using the ord() function and store it in another variable.
  • Append the above obtained ASCII value of the iterator to the above-initialized list “ASCII_vals” using the append() method.
  • Print the given string after converting each character to an ASCII value.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Take an empty list say "ASCII_vals" and store it in another variable.
ASCII_vals = []
# Loop the above-given string using the for loop.
for itr in gvn_str:
  # Calculate the ASCII value of the iterator using the ord() function
  # and store it in another variable.
    a = ord(itr)
# Append the above obtained ASCII value of the iterator to the above-initialized
# list "ASCII_vals" using the append() method.
    ASCII_vals.append(a)
  # Print the given string after converting each character to an ASCII value.
print("The given string after convering each character to an ASCII value :", ASCII_vals)

Output:

Enter some random string = btechgeeks
The given string after convering each character to an ASCII value : [98, 116, 101, 99, 104, 103, 101, 101, 107, 115]

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

Python Program to Convert each Character in a String to an ASCII Value Read More »

Program to Find Longest Word from Sentence

Python Program to Find Longest Word from Sentence

In the previous article, we have discussed Python Program to Move all Negative Elements to End in Order with Extra Space Allowed
Given a string and the task is to find the longest word from a given sentence.

split() method:

The split() method in Python divides a string into a list of strings by breaking the string with the specified separator.

Examples:

Example1:

Input:

Given String = "Hello this is btechgeeks"

Output:

The Longest Word in the above given sentence = btechgeeks
The length of the longest word = 10

Example2:

Input:

Given String = "Goodmorning this is btechgeeks"

Output:

The Longest Word in the above given sentence = Goodmorning
The length of the longest word = 11

Program to Find Longest Word from Sentence

Below are the ways to find the longest word from a given sentence.

Method #1: Using Built-in Functions (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Split the given string into a list of words using the split() function and store it in another variable say “wrd_lst”.
  • Get the longest word from a given sentence using max(), key functions, and store it in another variable.
  • Calculate the length of the above-obtained longest word using the len() function and store it in another variable.
  • Print the longest word in the above-given sentence.
  • Print the above-obtained length of the longest word.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
Gvn_str = "Hello this is btechgeeks"
# Split the given string into a list of words using the split() function and
# store it in another variable say "wrd_lst".
wrd_lst = Gvn_str.split()
# Get the longest word from a given sentence using max(), key functions, and
# store it in another variable.
longst_wrd = max(wrd_lst, key=len)
# Calculate the length of the above-obtained longest word using the len() function
# and store it in another variable.
len_longst_wrd = len(longst_wrd)
# Print the longest word in the above-given sentence.
print("The Longest Word in the above given sentence = ", longst_wrd)
# Print the above-obtained length of the longest word.
print("The length of the longest word = ", len_longst_wrd)

Output:

The Longest Word in the above given sentence =  btechgeeks
The length of the longest word =  10

Method #2: Using Built-in Functions (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Split the given string into a list of words using the split() function and store it in another variable say “wrd_lst”.
  • Get the longest word from a given sentence using max(), key functions, and store it in another variable.
  • Calculate the length of the above-obtained longest word using the len() function and store it in another variable.
  • Print the longest word in the above-given sentence.
  • Print the above-obtained length of the longest word.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
Gvn_str = input("Enter some random sentence = ")
# Split the given string into a list of words using the split() function and
# store it in another variable say "wrd_lst".
wrd_lst = Gvn_str.split()
# Get the longest word from a given sentence using max(), key functions, and
# store it in another variable.
longst_wrd = max(wrd_lst, key=len)
# Calculate the length of the above-obtained longest word using the len() function
# and store it in another variable.
len_longst_wrd = len(longst_wrd)
# Print the longest word in the above-given sentence.
print("The Longest Word in the above given sentence = ", longst_wrd)
# Print the above-obtained length of the longest word.
print("The length of the longest word = ", len_longst_wrd)

Output:

Enter some random sentence = Goodmorning this is btechgeeks
The Longest Word in the above given sentence = Goodmorning
The length of the longest word = 11

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

Python Program to Find Longest Word from Sentence Read More »

Program to Split the ArrayList and add the First Part to the End

Python Program to Split the Array/List and add the First Part to the End

In the previous article, we have discussed Python Program to Count Non Palindrome words in a Sentence
Given a list and a number N the task is to split and move the first N elements of the list to the end in Python.

Examples:

Example1:

Input:

Given List =[11 22 33 44 55 66 77 88 99 111 222 333]
Number =2

Output:

The result part after moving first [ 2 ] numbers to the end is [33, 44, 55, 66, 77, 88, 99, 111, 222, 333, 11, 22]

Example2:

Input:

Given List =[9, 3, 1, 11, 13, 18, 5, 0, 11, 35, 67, 24]
Number =4

Output:

The result part after moving first [ 4 ] numbers to the end is [13, 18, 5, 0, 11, 35, 67, 24, 9, 3, 1, 11]

Program to Split the Array/List and add the First Part to the End in Python

In Python, there are various ways to split the list and add the first portion at the end, some of them are as follows

Method #1: Using Slicing (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Give the Number N as static input and store it in another variable
  • Calculate the length of the given list and store it in a variable.
  • Slice from N to the length of the list using slicing and store it in a variable say firstpart.
  • Slice from 0 to N using slicing and store it in another variable say secondpart.
  • Add the firstpart and secondpart using the + operator and store the result in another variable say resultpart.
  • Print the resultpart.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvnlstt = [9, 3, 1, 11, 13, 18, 5, 0, 11, 35, 67, 24]
# Give the Number N as static input and store it in another variable
Numb = 4
# Calculate the length of the given list and store it in a variable.
lengthlst = len(gvnlstt)
# Slice from N to the length of the list using slicing
# and store it in a variable say firstpart.
frstpart = gvnlstt[Numb:lengthlst]
# Slice from 0 to N using slicing and
# store it in another variable say secondpart.
secndpart = gvnlstt[0:Numb]
# Add the firstpart and secondpart using the + operator
# and store the result in another variable say resultpart.
resltpart = frstpart+secndpart
# Print the resultpart.
print('The result part after moving first [',
      Numb, '] numbers to the end is', resltpart)

Output:

The result part after moving first [ 4 ] numbers to the end is [13, 18, 5, 0, 11, 35, 67, 24, 9, 3, 1, 11]

Method #2: Using Slicing (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions.
  • Store it in a variable.
  • Give the Number N as user input using the int(input()) function and store it in another variable
  • Calculate the length of the given list and store it in a variable.
  • Slice from N to the length of the list using slicing and store it in a variable say firstpart.
  • Slice from 0 to N using slicing and store it in another variable say secondpart.
  • Add the firstpart and secondpart using the + operator and store the result in another variable say resultpart.
  • Print the resultpart.
  • The Exit of the Program.

Below is the implementation:

# Give the list as user input using list(),map(),input(),and split() functions.
gvnlstt = list(map(int, input(
    'Enter some random List Elements separated by spaces = ').split()))

# Give the Number N as user input using the int(input())
# function and store it in another variable
Numb = int(input('Enter some random Number N = '))
# Calculate the length of the given list and store it in a variable.
lengthlst = len(gvnlstt)
# Slice from N to the length of the list using slicing
# and store it in a variable say firstpart.
frstpart = gvnlstt[Numb:lengthlst]
# Slice from 0 to N using slicing and
# store it in another variable say secondpart.
secndpart = gvnlstt[0:Numb]
# Add the firstpart and secondpart using the + operator
# and store the result in another variable say resultpart.
resltpart = frstpart+secndpart
# Print the resultpart.
print('The result part after moving first [',
      Numb, '] numbers to the end is', resltpart)

Output:

Enter some random List Elements separated by spaces = 11 22 33 44 55 66 77 88 99 111 222 333
Enter some random Number N = 2
The result part after moving first [ 2 ] numbers to the end is [33, 44, 55, 66, 77, 88, 99, 111, 222, 333, 11, 22]

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

 

Python Program to Split the Array/List and add the First Part to the End Read More »

Program to Count Non Palindrome words in a Sentence

Python Program to Count Non Palindrome words in a Sentence

In the previous article, we have discussed Python Program to Find Leaders in an Array/List
Given a string and the task is to count all the Non-palindromic words in a given sentence.

Palindrome:

If the reverse of a string is the same as the string, it is said to be a palindrome.

Example :

Given string = “sos asked to bring the madam “.

Output :

Explanation: In this “madam”, “sos” are the palindromic words. By sorting them we get {“madam”,”sos”}

Examples:

Example1:

Input:

Given String = "dad and mom both ordered to bring sos in malayalam"

Output:

The count of all the Non-palindromic words in a given sentence = 6

Example2:

Input:

Given String = "My mom and dad treats me in equal level"

Output:

The count of all the Non-palindromic words in a given sentence = 6

Program to Count Non-Palindrome words in a Sentence

Below are the ways to count all the Non-palindromic words in a given sentence.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Take an empty list say “lst” and store it in another variable.
  • Split the given string using the split() function and store it in another variable.
  • Loop in the above-obtained split list of words using the for loop.
  • Check if the iterator value is not equal to the reverse of the iterator value using the if conditional statement.
  • If the statement is true, then append the respective iterator value to the above initialized empty list using the append() method.
  • Calculate the length above initialized list “lst” using the len() function and store it in a variable.
  • Print the count of all the Non-palindromic words in a given sentence.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = "dad and mom both ordered to bring sos in malayalam"
# Take an empty list and store it in another variable.
lst = []
# Split the given string using the split() function and store it in another variable.
splt_str = gvn_str.split()
# Loop in the above-obtained split list of words using the for loop.
for wrd in splt_str:
    # Check if the iterator value is not equal to the reverse of the iterator value using
    # the if conditional statement.
    if wrd != wrd[::-1]:
     # If the statement is true, then append the respective iterator value to the
        # above initialized empty list using the append() method.
        lst.append(wrd)
# Calculate the length above initialized list "lst" using the len() function
# and store it in a variable.
# Print the count of all the Non-palindromic words in a given sentence.
count = len(lst)
# Print the count of all the Non-palindromic words in a given sentence.
print("The count of all the Non-palindromic words in a given sentence =", count)

Output:

The count of all the Non-palindromic words in a given sentence = 6

Method #2: Using For loop (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Take an empty list say “lst” and store it in another variable.
  • Split the given string using the split() function and store it in another variable.
  • Loop in the above-obtained split list of words using the for loop.
  • Check if the iterator value is not equal to the reverse of the iterator value using the if conditional statement.
  • If the statement is true, then append the respective iterator value to the above initialized empty list using the append() method.
  • Calculate the length above initialized list “lst” using the len() function and store it in a variable.
  • Print the count of all the Non-palindromic words in a given sentence.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Take an empty list and store it in another variable.
lst = []
# Split the given string using the split() function and store it in another variable.
splt_str = gvn_str.split()
# Loop in the above-obtained split list of words using the for loop.
for wrd in splt_str:
    # Check if the iterator value is notequal to the reverse of the iterator value using
    # the if conditional statement.
    if wrd != wrd[::-1]:
     # If the statement is true, then append the respective iterator value to the
        # above initialized empty list using the append() method.
        lst.append(wrd)
# Calculate the length above initialized list "lst" using the len() function
# and store it in a variable.
# Print the count of all the Non-palindromic words in a given sentence.
count = len(lst)
# Print the count of all the Non-palindromic words in a given sentence.
print("The count of all the Non-palindromic words in a given sentence =", count)

Output:

Enter some random string = My mom and dad treats me in equal level
The count of all the Non-palindromic words in a given sentence = 6

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

Python Program to Count Non Palindrome words in a Sentence Read More »