Author name: Vikram Chiluka

Program to Add Two Numbers Without Using the “+” Operator

Python Program to Add Two Numbers Without Using the “+” Operator

In the previous article, we have discussed Python Program to Find out the Arc Length of an Angle
In order to add two numbers without using the ‘+’ operator, we should use a mathematical formula.

Formula :

Let x, y are the given two numbers, then

x+y = x^2-y^2 = (x+y)(x-y)  if   (x!=y).

x+y = 2*x    (  if x=y )

Given two numbers and the task is to add the given two numbers without using the ‘+’ operator.

Examples:

Example 1:

Input:

Given First Number      =  65
Given Second Number = 45

Output: 

The sum of given two numbers = 110.0

Example 2:

Input:

Given First Number      =  220.5
Given Second Number =  100

Output:

The sum of given two numbers = 320.5

Program to Add Two Numbers Without Using the “+” Operator.

Below are the ways to add the given two numbers without using the ‘+’ operator.

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Check if the first number is not equal to the second number using the if conditional statement.
  • If the statement is true, then print  the value of (fst_num*fst_num-sec_num*sec_num)/(fst_num-sec_num)
  • Else print the value of (2*fst_num).
  • The Exit of the program.

Below is the implementation:

# Give the first number as static input and store it in a variable.
fst_num = 2.5
# Give the second number as static input and store it in another variable.
sec_num = 8
# Check if the first number is not equal to the second number using the if conditional
# statement.
if fst_num != sec_num:
    # If the statement is true, then print  the value of
    # (fst_num*fst_num-sec_num*sec_num)/(fst_num-sec_num)
    print("The sum of given two numbers =",
          (fst_num*fst_num-sec_num*sec_num)/(fst_num-sec_num))
else:
    # Else print the value of (2*fst_num).
    print("The sum of given two numbers =", 2*fst_num)

Output: 

The sum of given two numbers = 10.5

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Give the first number as user input using the float(input()) function and store it in a variable.
  • Give the second number as user input using the float(input()) function and store it in another variable.
  • Check if the first number is not equal to the second number using the if conditional statement.
  • If the statement is true, then print  the value of (fst_num*fst_num-sec_num*sec_num)/(fst_num-sec_num)
  • Else print the value of (2*fst_num).
  • The Exit of the program.

Below is the implementation:

# Give the first number as user input using the float(input()) function and 
#store it in a variable.
fst_num = float(input("Enter some random number = "))
# Give the second number as user input using the float(input()) function and 
#store it in another variable.
sec_num = float(input("Enter some random number = "))
# Check if the first number is not equal to the second number using the if conditional
# statement.
if fst_num != sec_num:
    # If the statement is true, then print  the value of
    # (fst_num*fst_num-sec_num*sec_num)/(fst_num-sec_num)
    print("The sum of given two numbers =",
          (fst_num*fst_num-sec_num*sec_num)/(fst_num-sec_num))
else:
    # Else print the value of (2*fst_num).
    print("The sum of given two numbers =", 2*fst_num)

Output: 

Enter some random number = 50
Enter some random number = 70
The sum of given two numbers = 120.0

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

Python Program to Add Two Numbers Without Using the “+” Operator Read More »

Program to Calculate the Discriminant Value

Python Program to Calculate the Discriminant Value

In the previous article, we have discussed Python Program to Check Tech Number or Not
Discriminant:

The distinguishing feature is the naming convention applied to the mathematical expression that appears beneath the root (radical) sign up the quadratic formula.

Formula :

Discriminant = (b**2) – (4*a*c)

a, b, c are the three different points.

Given three points a, b, c, and the task is to calculate the given discriminant value.

Examples:

Example 1:

Input:

Given  x= 1
Given  y= 4
Given  z= 4

Output: 

The given Discrimant value =  0
The obtained discriminant has only one solution

Example 2:

Input:

Given  x= 5
Given  y= 20
Given  z= 7

Output: 

The given Discrimant value = 260
The obtained discriminant has two possible solutions

Program to Calculate the Discriminant Value

Below are the ways to calculate the given discriminant value.

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Give the third number as static input and store it in another variable.
  • Calculate the discriminant value for the given three points and store it in another variable.
  • Print the obtained discriminant value.
  • Check if the value of the discriminant is greater than zero using the if conditional statement.
  • If the statement is true, then print “The obtained discriminant has two possible solutions”.
  • Check if the value of the discriminant is equal to zero using the elif conditional statement.
  • If the statement is true, then print “The obtained discriminant has only one solution”.
  • Check if the value of the discriminant is less than zero using the elif conditional statement.
  • If the statement is true, then print “The obtained discriminant has No solutions”.
  • The Exit of the program.

Below is the implementation:

# Give the first number as static input and store it in a variable.
x = 2
# Give the second number as static input and store it in another variable.
y = 4
# Give the third number as static input and store it in another variable.
z = 6
# Calculate the discriminant value for the given three points and
# store it in another variable.
Disimint = (y**2) - (4*x*z)
# Print the obtained discriminant value.
print("The given Discrimant value = ", Disimint)
# Check if the value of the discriminant is greater than zero using the
# if conditional statement.
if Disimint > 0:
 # If the statement is true, then print "The given obtained has two possible solutions".
    print("The obtained discriminant has two possible solutions")
# Check if the value of the discriminant is equal to zero using the elif
# conditional statement.
elif Disimint == 0:
  # If the statement is true, then print "The obtained discriminant has only one solution".
    print("The obtained discriminant has only one solution")
# Check if the value of the discriminant is less than zero using the elif conditional
# statement.
elif Disimint < 0:
  # If the statement is true, then print "The obtained discriminant has No solutions".
    print("The obtained discriminant has No solutions")

Output: 

The given Discrimant value =  -32
The obtained discriminant has No solutions

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Give the first number as user input using the int(input()) function and store it in a variable.
  • Give the second number as user input using the int(input()) function and store it in another variable.
  • Give the third number as user input using the int(input()) function and store it in another variable.
  • Calculate the discriminant value for the given three points and store it in another variable.
  • Print the obtained discriminant value.
  • Check if the value of the discriminant is greater than zero using the if conditional statement.
  • If the statement is true, then print “The obtained discriminant has two possible solutions”.
  • Check if the value of the discriminant is equal to zero using the elif conditional statement.
  • If the statement is true, then print “The obtained discriminant has only one solution”.
  • Check if the value of the discriminant is less than zero using the elif conditional statement.
  • If the statement is true, then print “The obtained discriminant has No solutions”.
  • The Exit of the program.

Below is the implementation:

# Give the first number as user input using int(input()) function and store it in a variable.
x = int(input("Enter some random number = "))
# Give the second number as user input using int(input()) function and store it in another variable.
y = int(input("Enter some random number = "))
# Give the third number as user input using int(input()) function and store it in another variable.
z = int(input("Enter some random number = "))
# Calculate the discriminant value for the given three points and
# store it in another variable.
Disimint = (y**2) - (4*x*z)
# Print the obtained discriminant value.
print("The given Discrimant value = ", Disimint)
# Check if the value of the discriminant is greater than zero using the
# if conditional statement.
if Disimint > 0:
 # If the statement is true, then print "The given obtained has two possible solutions".
    print("The obtained discriminant has two possible solutions")
# Check if the value of the discriminant is equal to zero using the elif
# conditional statement.
elif Disimint == 0:
  # If the statement is true, then print "The obtained discriminant has only one solution".
    print("The obtained discriminant has only one solution")
# Check if the value of the discriminant is less than zero using the elif conditional
# statement.
elif Disimint < 0:
  # If the statement is true, then print "The obtained discriminant has No solutions".
    print("The obtained discriminant has No solutions")

Output: 

Enter some random number = 5
Enter some random number = 20
Enter some random number = 7
The given Discrimant value = 260
The obtained discriminant has two possible solutions

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 Calculate the Discriminant Value Read More »

Program to Remove any Non-ASCII Characters

Python Program to Remove any Non-ASCII Characters

In the previous article, we have discussed Python Program Enter ‘*’ Between two Identical Characters in a String
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 = 'abc£def'

Output:

The given string after removal of any Non-ASCII Characters = abcdef

Example2:

Input:

Given string = "££abc££kjhf"

Output:

The given string after removal of any Non-ASCII Characters = abckjhf

Program to Remove any Non-ASCII Characters

Below are the ways to remove non-ASCII characters from a given string.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Take a new empty string say ‘new_str’and store it in another variable.
  • Loop in the above-given string using the for loop.
  • Get the ASCII value of the iterator using the ord() function and store it in another variable say ‘numb’.
  • Check if the above-obtained number is greater than or equal to ‘0’ using the if conditional statement.
  • If the statement is true, check again if the given number is less than or equal to ‘127’ using the if conditional statement.
  • If the statement is true, then concatenate the ‘new_str’ with the iterator value and store it in the same variable new_str’.
  • Print the above-given string after removal of any Non-ASCII Characters.
  • The Exit of the program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = 'abc£def'
# Take a new empty string say 'new_str'and store it in another variable.
new_str = ""
# Loop in the above-given string using the for loop.
for itror in gvn_str:
    # Get the ASCII value of the iterator using the ord() function and store it in
    # another variable say 'numb'.
    numb = ord(itror)
 # Check if the above-obtained number is greater than or equal to '0' using the
# if conditional statement.
    if (numb >= 0):
        # If the statement is true, check again if the given number is less than or equal to '127'
        # using the if conditional statement.
        if (numb <= 127):
            # If the statement is true, then concat the 'new_str' with the iterator value and
            # store it in the same variable new_str'.
            new_str = new_str + itror
# Print the above-given string after removal of any Non-ASCII Characters.
print("The given string after removal of any Non-ASCII Characters = ", new_str)

Output:

The given string after removal of any Non-ASCII Characters =  abcdef

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 a new empty string say ‘new_str’and store it in another variable.
  • Loop in the above-given string using the for loop.
  • Get the ASCII value of the iterator using the ord() function and store it in another variable say ‘numb’.
  • Check if the above-obtained number is greater than or equal to ‘0’ using the if conditional statement.
  • If the statement is true, check again if the given number is less than or equal to ‘127’ using the if conditional statement.
  • If the statement is true, then concatenate the ‘new_str’ with the iterator value and store it in the same variable new_str’.
  • Print the above-given string after removal of any Non-ASCII Characters.
  • 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 a new empty string say 'new_str'and store it in another variable.
new_str = ""
# Loop in the above-given string using the for loop.
for itror in gvn_str:
    # Get the ASCII value of the iterator using the ord() function and store it in
    # another variable say 'numb'.
    numb = ord(itror)
 # Check if the above-obtained number is greater than or equal to '0' using the
# if conditional statement.
    if (numb >= 0):
        # If the statement is true, check again if the given number is less than or equal to '127'
        # using the if conditional statement.
        if (numb <= 127):
            # If the statement is true, then concat the 'new_str' with the iterator value and
            # store it in the same variable new_str'.
            new_str = new_str + itror
# Print the above-given string after removal of any Non-ASCII Characters.
print("The given string after removal of any Non-ASCII Characters = ", new_str)

Output:

Enter some random string = ££abc££kjhf
The given string after removal of any Non-ASCII Characters = abckjhf

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 Remove any Non-ASCII Characters Read More »

Python Program to Print Non Square Numbers

In the previous article, we have discussed Python Program to Remove any Non-ASCII Characters
Non-square numbers :

Non-square numbers are those that are not perfect squares of any number. When you multiply any number by itself, you get a square number. A non-square number is the inverse of the same. For example, 16 is a square number because it can be written as 4 x 4, whereas 7 is not. Other non-square numbers include 2, 3, 5, 6, 7, 8, and 10.

math module :

The math module is a standard Python module that provides access to various mathematical functions for performing mathematical operations.

The math module in Python provides access to the following mathematical functions: exp(x), pow(x,y), log10(x), sqrt(x), and so on.

Examples:

Example1:

Input:

Given range = 8

Output:

The non square numbers in a given range = 
2
3
5
6
7

Example 2:

Input:

Given range = 15

Output:

The non square numbers in a given range = 
2
3
5
6
7
8
10
11
12
13
14

Program to Print Non-Square Numbers

Below are the ways to print the non-square numbers.

Method #1: Using math Module (Static input)

Approach:

  • Import math module using the import keyword.
  • Give the range as static input and store it in a variable.
  • Loop from 0 to given number using for loop.
  • Calculate the square root of the iterator value using math.sqrt() function and store it in another variable “sqr_rt”.
  • Check if the above obtained  “sqr_rt” multiplied with itself is equal to the iterator value using the if conditional statement.
  • If the statement is true, then increase the value of the iterator by ‘1’.
  • Else print the iterator value.
  • The Exit of the program.

Below is the implementation:

# Import math module using the import keyword.
import math
# Give the range as static input and store it in a variable.
gvn_num = 15
# Loop from 0 to given number using for loop.
print("The non square numbers in a given range = ")
for itr in range(0, gvn_num):
  # Calculate the square root of the iterator value using math.sqrt() function and
  # store it in another variable "sqr_rt".
    sqr_rt = int(math.sqrt(itr))
# Check if the above obtained  "sqr_rt" multiplied with itself is equal to the iterator
# value using the if conditional statement.
    if itr == sqr_rt*sqr_rt:
   # If the statement is true, then increase the value of the iterator by '1'.
        itr = itr + 1
 # Else print the iterator value.
    else:
        print(itr)

Output:

The non square numbers in a given range = 
2
3
5
6
7
8
10
11
12
13
14

Method #2: Using math Module (User input)

Approach:

  • Import math module using the import keyword.
  • Give the range as user input using the int(input()) function and store it in a variable.
  • Loop from 0 to given number using for loop.
  • Calculate the square root of the iterator value using math.sqrt() function and store it in another variable “sqr_rt”.
  • Check if the above obtained  “sqr_rt” multiplied with itself is equal to the iterator value using the if conditional statement.
  • If the statement is true, then increase the value of the iterator by ‘1’.
  • Else print the iterator value.
  • The Exit of the program.

Below is the implementation:

# Import math module using the import keyword.
import math
# Give the range as user input using the int(input()) function and store it in a variable.
gvn_num = int(input("Enter some random number = "))
# Loop from 0 to given number using for loop.
print("The non square numbers in a given range = ")
for itr in range(0, gvn_num):
  # Calculate the square root of the iterator value using math.sqrt() function and
  # store it in another variable "sqr_rt".
    sqr_rt = int(math.sqrt(itr))
# Check if the above obtained  "sqr_rt" multiplied with itself is equal to the iterator
# value using the if conditional statement.
    if itr == sqr_rt*sqr_rt:
       # If the statement is true, then increase the value of the iterator by '1'.
        itr = itr + 1
 # Else print the iterator value.
    else:
        print(itr)

Output:

Enter some random number = 8
The non square numbers in a given range = 
2
3
5
6
7

Here we printed the nonperfect square numbers.

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 Print Non Square Numbers Read More »

Program to Generate Perfect Numbers in an Interval

Python Program to Generate Perfect Numbers in an Interval

In the previous article, we have discussed Python Program to Add Two Numbers Without Using the “+” Operator.
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 lower limit range = 1
Given upper limit range=1000

Output:

The Perfect numbers in the given range 1 and 1000 are:
1 6 28 496

Example 2:

Input:

Given lower limit range = 496
Given upper limit range=8128

Output:

The Perfect numbers in the given range 125 and 8592 are:
496 8128

Program to Generate Perfect Numbers in an Interval

Below are the ways to generate Perfect Numbers in a given interval.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the lower limit range as static input and store it in a variable.
  • Give the upper limit range as static input and store it in another variable.
  • Loop from lower limit range to upper limit range using For loop.
  • Inside the for loop take a variable to say ‘itrnumb‘ and initialize its value to the iterator value.
  • pass the itrnumb as a argument to checkPerfectNumbr() function.
  • Inside the checkPerfectNumbr() function Take a variable to say totalSum and initialize it to 1.
  • Iterator from 2 to number -1 using for loop.
  • Check if the iterator value divides the number using the If conditional statement.
  • If it is true then add the given iterator value to totalSum.
  • Check if the totalSum is equal to the given number using if conditional statement.
  • If it is true then it is a perfect number then return True.
  • Else return False.
  • Inside the main function for the loop check whether the function turns return or False.
  • If it returns true then print the itrnumb.
  • The Exit of the Program.

Below is the implementation:

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


def checkPerfectNumbr(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


# Give the lower limit range as static input and store it in a variable.
lowlimrange = 1
# Give the upper limit range as static input and store it in another variable.
upplimrange = 1000
print('The Perfect numbers in the given range',
      lowlimrange, 'and', upplimrange, 'are:')
# Loop from lower limit range to upper limit range using For loop.
for itrvalue in range(lowlimrange, upplimrange+1):
        # Inside the for loop pass the iterator value to checkNeonnumb() function.
    if(checkPerfectNumbr(itrvalue)):
        # If it returns true then print the iterator value.
        print(itrvalue, end=' ')

Output:

The Perfect numbers in the given range 1 and 1000 are:
1 6 28 496

Method #2: Using For Loop (User Input)

Approach:

  • Give the lower limit range as user input and store it in a variable.
  • Give the upper limit range as user input and store it in another variable.
  • Loop from lower limit range to upper limit range using For loop.
  • Inside the for loop take a variable to say ‘itrnumb‘ and initialize its value to the iterator value.
  • pass the itrnumb as a argument to checkPerfectNumbr() function.
  • Inside the checkPerfectNumbr() function Take a variable to say totalSum and initialize it to 1.
  • Iterator from 2 to number -1 using for loop.
  • Check if the iterator value divides the number using the If conditional statement.
  • If it is true then add the given iterator value to totalSum.
  • Check if the totalSum is equal to the given number using if conditional statement.
  • If it is true then it is a perfect number then return True.
  • Else return False.
  • Inside the main function for the loop check whether the function turns return or False.
  • If it returns true then print the itrnumb.
  • The Exit of the Program.

Below is the implementation:

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


def checkPerfectNumbr(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


# Give the lower limit range and upper limit range as
# user input using map(),int(),split() functions.
# Store them in two separate variables.
lowlimrange, upplimrange = map(int, input(
    'Enter lower limit range and upper limit range separate by spaces = ').split())
print('The Perfect numbers in the given range',
      lowlimrange, 'and', upplimrange, 'are:')
# Loop from lower limit range to upper limit range using For loop.
for itrvalue in range(lowlimrange, upplimrange+1):
        # Inside the for loop pass the iterator value to checkNeonnumb() function.
    if(checkPerfectNumbr(itrvalue)):
        # If it returns true then print the iterator value.
        print(itrvalue, end=' ')

Output:

Enter lower limit range and upper limit range separate by spaces = 125 8592
The Perfect numbers in the given range 125 and 8592 are:
496 8128

Here we printed all the perfect numbers in the range 125 to 8592

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 Generate Perfect Numbers in an Interval Read More »

Program to Find the Greatest Digit in a Number.

Python Program to Find the Greatest Digit in a Number.

In the previous article, we have discussed Python Program for Comma-separated String to Tuple
Given a number, and the task is to find the greatest digit in a given number.

Example: Let the number is 149.

The greatest digit in a given number is ‘9’

Examples:

Example1:

Input:

Given number = 639

Output:

The maximum digit in given number { 639 } =  9

Example2:

Input:

Given number = 247

Output:

The maximum digit in given number { 247 } =  7

Program to Find the Greatest Digit in a Number.

Below are the ways to find the greatest digit in a given number.

Method #1: Using list() Function (Static input)

Approach:

  • Give the number as static input and store it in a variable.
  • Convert the given number into the string using the str() function and store it in another variable.
  • Convert the above-obtained string number into a list of digits using the built-in list() method and store it in another variable.
  • Find the maximum list of digits using the built-in max() function and store it in another variable.
  • Print the greatest digit in a given number.
  • The Exit of the program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_num = 154
# Convert the given number into string using str() function and
# store it in another variable. 
str_numbr = str(gvn_num)
# Convert the above obtained string number into list of digits using bulit-in list()
# method and store it in another variable.
lst = list(str_numbr)
# Find the maximum of list of digits using bulit-in max() function
# and store it in another variable.
maxim_digit = max(lst)
# Print the greatest digit in a given number.
print("The maximum digit in given number {", gvn_num, "} = ", maxim_digit)

Output:

The maximum digit in given number { 154 } =  5

Method #2: Using list() Function (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 the string using the str() function and store it in another variable.
  • Convert the above-obtained string number into a list of digits using the built-in list() method and store it in another variable.
  • Find the maximum list of digits using the built-in max() function and store it in another variable.
  • Print the greatest digit in a given number.
  • The Exit of the program.

Below is the implementation:

#Give the number as user input using int(input()) and store it in a variable.
gvn_num = int(input("Enter some random number = "))
# Convert the given number into string using str() function and
# store it in another variable. 
str_numbr = str(gvn_num)
# Convert the above obtained string number into list of digits using bulit-in list()
# method and store it in another variable.
lst = list(str_numbr)
# Find the maximum of list of digits using bulit-in max() function
# and store it in another variable.
maxim_digit = max(lst)
# Print the greatest digit in a given number.
print("The maximum digit in given number {", gvn_num, "} = ", maxim_digit)

Output:

Enter some random number = 183
The maximum digit in given number { 183 } = 8

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 the Greatest Digit in a Number. Read More »

Program to Shuffle Elements of a Tuple

Python Program to Shuffle Elements of a Tuple

In the previous article, we have discussed Python Program to Remove Duplicate elements from a Tuple
Tuple in Python:

A tuple is an immutable list of objects. That means the elements of a tuple cannot be modified or changed while the program is running.

shuffle method in python :

A tuple is an immutable type in Python. As a result, it cannot be shuffled directly.

We can typecast it to a list (which is mutable), shuffle it, and then typecast it back to tuple to provide the output as a tuple.

We can shuffle a list in Python by using an inbuilt method called shuffle from the random module.

Examples:

Example 1:

Input:

Given Tuple = (74, 65, 8, 100, 67, 122, 132, 56, 13, 89)

Output:

The given tuple after Shuffling the elements =  (56, 122, 65, 13, 100, 74, 132, 89, 8, 67)

Example 2:

Input:

Given Tuple = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9,)

Output:

The given tuple after Shuffling the elements =  (5, 8, 6, 1, 3, 2, 9, 7, 0, 4)

Program to Shuffle Elements of a Tuple

Below are the ways to shuffle elements of a Given Tuple.

Method #1: Using random.shuffle() Method (Static input)

Approach:

  • Import the random module using the import method.
  • Give the tuple as static input and store it in a variable.
  • Convert the given tuple into a list using the list() function and store it in another variable.
  • Apply random. shuffle() method on the above-obtained list.
  • Convert the above-shuffled list into a tuple again using the tuple() function and store it in another variable.
  • Print the above-given tuple after shuffling the elements of a given tuple.
  • The Exit of the program.

Below is the implementation:

# Import the random module using import method.
import random
# Give the tuple as static input and store it in a variable.
gvn_tup = (6, 7, 8, 2, 45, 12, 63, 89)
# Convert the given tuple into list using the list() function and
# store it in another variable.
lst = list(gvn_tup)
# Apply random.shuffle() method on the above obtained list .
random.shuffle(lst)
# Convert the above shuffled list into tuple again using the tuple() function
# and store it in another variable.
shuffld_tupl = tuple(lst)
# Print the above given tuple after shuffling the elements of a given tuple.
print("The given tuple after Shuffling the elements = ", shuffld_tupl)

Output:

The given tuple after Shuffling the elements =  (45, 12, 6, 89, 63, 8, 2, 7)

Method #2: Using random.shuffle() Method (User input)

Approach:

  • Import the random module using the import method.
  • Give the tuple as user input using tuple(),map(),input(),and split() functions and Store it in a variable.
  • Convert the given tuple into a list using the list() function and store it in another variable.
  • Apply random. shuffle() method on the above-obtained list.
  • Convert the above-shuffled list into a tuple again using the tuple() function and store it in another variable.
  • Print the above-given tuple after shuffling the elements of a given tuple.
  • The Exit of the program.

Below is the implementation:

# Import the random module using import method.
import random
# Give the tuple as user input using tuple(),map(),input(),and split() functions
#and Store it in a variable.
gvn_tup = tuple(map(int, input(
   'Enter some random tuple Elements separated by spaces = ').split()))
# Convert the given tuple into list using the list() function and
# store it in another variable.
lst = list(gvn_tup)
# Apply random.shuffle() method on the above obtained list .
random.shuffle(lst)
# Convert the above shuffled list into tuple again using the tuple() function
# and store it in another variable.
shuffld_tupl = tuple(lst)
# Print the above given tuple after shuffling the elements of a given tuple.
print("The given tuple after Shuffling the elements = ", shuffld_tupl)

Output:

Enter some random tuple Elements separated by spaces = 0 1 2 3 4 5 6 7 8 9
The given tuple after Shuffling the elements = (8, 0, 5, 1, 6, 3, 7, 9, 4, 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 Shuffle Elements of a Tuple Read More »

Program to Remove Duplicate elements from a Tuple

Python Program to Remove Duplicate elements from a Tuple

In the previous article, we have discussed Python Program to Generate Perfect Numbers in an Interval
Tuple in Python:

A tuple is an immutable list of objects. That means the elements of a tuple cannot be modified or changed while the program is running.

The elements from any tuple can be removed by slicing the tuple.

Sometimes elements or objects in Python tuple are repeated; these repeated elements and objects are known as duplicate elements in Python tuple.

Counter() function in Python:

Python Counter is a container that keeps track of the count of each element in the container. The counter class is a subclass of the dictionary class.

The counter class is a subclass of the dictionary class. You can count the key-value pairs in an object, also known as a hash table object, using the Python Counter tool.

Examples:

Example 1:

Input:

Given Tuple = (3, 5, 1, 4, 5, 3, 1)

Output:

The given tuple after removal of duplicate elements =  (3, 5, 1, 4)

Example 2:

Input:

Given Tuple = (1, 2, 3, 1, 2, 3, 4, 5, 6, 7, 7, 8)

Output:

The given tuple after removal of duplicate elements = (1, 2, 3, 4, 5, 6, 7, 8)

Program to Remove Duplicate elements from a Tuple

Below are the ways to remove duplicate elements from a Given Tuple.

Method #1: Using Counter() Function (Static input)

Approach:

  • Import Counter function from collections module using the import keyword.
  • Give the tuple as static input and store it in a variable.
  • Apply the Counter function on the given tuple and store it in another variable say “freq”.
  • Get all the keys from the above-obtained counter “freq” using the freq. keys() method() (contains all unique elements ).
  • Store it in another variable say “unique_values”.
  • Convert the above got “unique_values” to tuple using the tuple() function and store it in another variable.
  • Print the above-given tuple after removal of duplicate elements.
  • The Exit of the program.

Below is the implementation:

# Import Counter function from collections module using the import keyword.
from collections import Counter
# Give the tuple as static input and store it in a variable.
gvn_tupl = (3, 5, 1, 4, 5, 3, 1)
# Apply the Counter function on the given tuple and store it in another variable.
freq = Counter(gvn_tupl)
# Get all the keys from the above-obtained counter "freq" using freq. keys() method()
# (contains all unique elements ) .
# Store it in another variable say "unique_values".
unique_values = freq.keys()
# Convert the above got "unique_values" to tuple using tuple() function and
# store it in another variable.
reslt = tuple(unique_values)
# Print the above-given tuple after removal of duplicate elements.
print("The given tuple after removal of duplicate elements = ", reslt)

Output:

The given tuple after removal of duplicate elements =  (3, 5, 1, 4)

Method #2: Using Counter() Function (User input)

Approach:

  • Import Counter function from collections module using the import keyword.
  • Give the tuple as user input using tuple(),map(),input(),and split() functions and Store it in a variable.
  • Apply the Counter function on the given tuple and store it in another variable say “freq”.
  • Get all the keys from the above-obtained counter “freq” using the freq. keys() method() (contains all unique elements ).
  • Store it in another variable say “unique_values”.
  • Convert the above got “unique_values” to tuple using the tuple() function and store it in another variable.
  • Print the above-given tuple after removal of duplicate elements.
  • The Exit of the program.

Below is the implementation:

# Import Counter function from collections module using the import keyword.
from collections import Counter
#Give the tuple as user input using tuple(),map(),input(),and split() functions 
#and Store it in a variable.
gvn_tupl = tuple(map(int, input( 'Enter some random tuple Elements separated by spaces = ').split()))
# Apply the Counter function on the given tuple and store it in another variable.
freq = Counter(gvn_tupl)
# Get all the keys from the above-obtained counter "freq" using freq. keys() method()
# (contains all unique elements ) .
# Store it in another variable say "unique_values".
unique_values = freq.keys()
# Convert the above got "unique_values" to tuple using tuple() function and
# store it in another variable.
reslt = tuple(unique_values)
# Print the above-given tuple after removal of duplicate elements.
print("The given tuple after removal of duplicate elements = ", reslt)

Output:

Enter some random tuple Elements separated by spaces = 1 2 3 1 2 3 4 5 6 7 7 8
The given tuple after removal of duplicate elements = (1, 2, 3, 4, 5, 6, 7, 8)

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 Remove Duplicate elements from a Tuple Read More »

Program for Comma-separated String to Tuple

Python Program for Comma-separated String to Tuple

In the previous article, we have discussed Python Program to Shuffle Elements of a Tuple
Tuple in Python:

A tuple is an immutable list of objects. That means the elements of a tuple cannot be modified or changed while the program is running.

split() function:

Syntax: input string.split(seperator=None, maxsplit=-1)

It delimits the string with the separator and returns a list of words from it. The maxsplit parameter specifies the maximum number of splits that can be performed. If it is -1 or not specified, all possible splits are performed.

Example:  Given string =  ‘hello btechgeeks goodmorning’.split()

Output : [‘hello’, ‘btechgeeks’, ‘goodmorning’ ]

Given a string and the task is to find a tuple with a comma-separated string.

Examples:

Example 1:

Input: 

Given String = 'good, morning, btechgeeks'     (static input)

Output:

Given input String =  good, morning, btechgeeks
A tuple with comma-separated string is :  ('good', ' morning', ' btechgeeks')

Example 2:

Input:

Given String = hello, btechgeeks, 123        (user input)

Output:

A tuple with comma-separated string is : ('hello', ' btechgeeks', ' 123')

Program for Comma-separated String to Tuple

Below are the ways to find a tuple with a comma-separated string.

Method #1: Using split() Method (Static input)

Approach:

  • Give the string as static input and store it in a variable.
  • Print the above-given input string.
  • Split the given input string separated by commas using the split() function and convert it into a tuple.
  • Store it in another variable.
  • Print the tuple with a comma-separated string.
  • The Exit of the program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = 'good, morning, btechgeeks'
# Print the above-given input string.
print("Given input String = ", gvn_str)
# Split the given input string separated by commas using the split() function
# and convert it into a tuple.
# Store it in another variable.
tupl = tuple(gvn_str.split(","))
# Print the tuple with a comma-separated string.
print("A tuple with comma-separated string is : ", tupl)

Output:

Given input String =  good, morning, btechgeeks
A tuple with comma-separated string is :  ('good', ' morning', ' btechgeeks')

Method #2: Using split() Method (User input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Print the above-given input string.
  • Split the given input string separated by commas using the split() function and convert it into a tuple.
  • Store it in another variable.
  • Print the tuple with a comma-separated string.
  • 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 = ")
# Print the above-given input string.
print("Given input String = ", gvn_str)
# Split the given input string separated by commas using the split() function
# and convert it into a tuple.
# Store it in another variable.
tupl = tuple(gvn_str.split(","))
# Print the tuple with a comma-separated string.
print("A tuple with comma-separated string is : ", tupl)

Output:

Enter some random string = hello, btechgeeks, 123
Given input String = hello, btechgeeks, 123
A tuple with comma-separated string is : ('hello', ' btechgeeks', ' 123')

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 for Comma-separated String to Tuple Read More »

Program to Check Tech Number or Not

Python Program to Check Tech Number or Not

In the previous article, we have discussed Python Program to Check Buzz Number or Not
Tech number :

A number is referred to as a tech number if it has an even number of digits and can be divided exactly into two parts from the middle. After evenly dividing the number, add the numbers together and find the square of the sum. If we get the number as a square, we know it’s a tech number; otherwise, it’s not.

Example:

Let the number = 2025

#divide the number into two equal parts

first part = 20

second part = 25

sum = first part + second part = 20 +25 = 45

#square the obtained ‘sum ‘

square_sum = 45*45 = 2025 (which is equal to given number).

Therefore 2025 is a tech number.

Note: The basic condition for checking the tech number is that it has an even number of digits. If this is the case, we will proceed to the next step; otherwise, the code will not be executed further.

Examples:

Example 1:

Input: 

Given Number = 2025

Output:

The Given Number { 2025 } is Tech number

Example 2:

Input: 

Given Number = 2025

Output:

The Given Number { 1800 } is Not a Tech number

Program to Check Tech Number or Not

Below are the ways to if the given number is a Tech number or not.

Method #1: Using Slicing (Static input)

Approach:

  • Give the number as static input and store it in a variable.
  • Convert the given number into the string using the built-in str() function and store it in another variable.
  • Calculate the length of the above string using the len() function and store it in another variable.
  • Check if the length of the given number is even or not by using the if conditional statement.
  • If the statement is True, divide the given number into two equal halves using the slicing.
  • Store it in two different variables say ‘first_half ‘ and ‘second_half’.
  • Calculate the sum of both the halves by converting string to int using int() function and store it in a variable say “total sum”.
  • Multiply the “total sum” with itself and store it in another variable.
  • Check if the “total sum” is equal to the given input number using the if conditional statement.
  • If the statement is True, then print “Tech Number”.
  • Else print “Not a Tech number”.
  • If the length of the given number is odd, then Print “Not a Tech Number”.
  • The Exit of the program.

Below is the implementation:

# Give the number as static input and store it in a variable.
n = 2025
# Convert the given number into the string using the built-in str() function
# and store it in another variable.
s = str(n)
# Calculate the length of the above string using the len() function and
# store it in another variable.
l = len(s)
# Check if the length of the given number is even or not by using the
# if conditional statement.
if(l % 2 == 0):
    # If the statement is True, divide the given number into two equal halves using the slicing.
    # Store it in two different variables say 'first_half ' and 'second_half'.
    fst_half = s[:l//2]
    scnd_half = s[l//2:]
# Calculate the sum of both the halves by converting string to int using int() function
# and store it in a variable say "total sum".
    tot_sum = (int(fst_half)+int(scnd_half))
# Multiply the "total sum" with itself and store it in another variable.
    square_sum = tot_sum*tot_sum
 # Check if the "total sum" is equal to the given input number using the
 # if conditional statement.
    if(n == square_sum):
           # If the statement is True, then print "Tech number".
        print("The Given Number {", n, "} is Tech number")
    else:
       # Else print "Not a Tech number".
        print("The Given Number {", n, "} is Not a Tech number")
# If the length of the given number is odd, then Print "Not a tech Number".
else:
    print("The Given Number {", n, "} is Not a Tech number")

Output:

The Given Number { 2025 } is Tech number

Method #2: Using Slicing (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 the string using the built-in str() function and store it in another variable.
  • Calculate the length of the above string using the len() function and store it in another variable.
  • Check if the length of the given number is even or not by using the if conditional statement.
  • If the statement is True, divide the given number into two equal halves using the slicing.
  • Store it in two different variables say ‘first_half ‘ and ‘second_half’.
  • Calculate the sum of both the halves by converting string to int using int() function and store it in a variable say “total sum”.
  • Multiply the “total sum” with itself and store it in another variable.
  • Check if the “total sum” is equal to the given input number using the if conditional statement.
  • If the statement is True, then print “Tech Number”.
  • Else print “Not a Tech number”.
  • If the length of the given number is odd, then Print “Not a Tech Number”.
  • The Exit of the program.

Below is the implementation:

# Give the number as user input using int(input()) and store it in a variable.
n = int(input("Enter some random number = "))
# Convert the given number into the string using the built-in str() function
# and store it in another variable.
s = str(n)
# Calculate the length of the above string using the len() function and
# store it in another variable.
l = len(s)
# Check if the length of the given number is even or not by using the
# if conditional statement.
if(l % 2 == 0):
    # If the statement is True, divide the given number into two equal halves using the slicing.
    # Store it in two different variables say 'first_half ' and 'second_half'.
    fst_half = s[:l//2]
    scnd_half = s[l//2:]
# Calculate the sum of both the halves by converting string to int using int() function
# and store it in a variable say "total sum".
    tot_sum = (int(fst_half)+int(scnd_half))
# Multiply the "total sum" with itself and store it in another variable.
    square_sum = tot_sum*tot_sum
 # Check if the "total sum" is equal to the given input number using the
 # if conditional statement.
    if(n == square_sum):
           # If the statement is True, then print "Tech number".
        print("The Given Number {", n, "} is Tech number")
    else:
       # Else print "Not a Tech number".
        print("The Given Number {", n, "} is Not a Tech number")
# If the length of the given number is odd, then Print "Not a tech Number".
else:
    print("The Given Number {", n, "} is Not a Tech number")

Output:

Enter some random number = 9801
The Given Number { 9801 } is Tech 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 Tech Number or Not Read More »