Numpy percentile – Python NumPy percentile() Function

Python NumPy percentile() Function

NumPy percentile() Function:

Numpy percentile: The q-th percentile of the array elements or the q-th percentile of the data along the given axis is returned by the percentile() function of the NumPy module.

Syntax:

numpy.percentile(a, q, axis=None, out=None, interpolation='linear', keepdims=False)

Parameters

a: This is required. It is the array given as input

q: This is required. It indicates the percentile or sequence of percentiles to compute that must be between 0 and 100 inclusive (array of float).

axis: This is optional. It is the axis or axes along which to operate. The axis=None operation is done on a flattened array by default.

out: This is optional. It is the output array in which the result will be stored. It must be the same shape as the expected result.

interpolation: This is optional. When the desired percentile is between two data points, it specifies the interpolation method to use. It can use values like ‘linear,’ ‘lower,’ ‘higher, ‘midpoint,’ and ‘nearest.’

keepdims: This is optional. The reduced axes are left in the output as dimensions with size one if this is set to True. The result will broadcast correctly against the input array if you use this option.

Return Value: 

The percentile points of “a” are returned. The output is a scalar if q is a single percentile and axis=None. In other cases, an array is returned.

NumPy percentile() Function in Python

Example1

Approach:

  • Import NumPy module using the import keyword
  • Pass some random list as an argument to the array() function to create an array.
  • Store it in a variable.
  • Print the above-given array.
  • Pass the given array and some random percentile say 50 as an argument to the percentile() function of NumPy module
  • Here we get the 50th percentile point of the above array
  • Similarly, we can get 25,60,75 th percentile by passing them as tuple(second argument of the percentile function)
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random list as an argument to the array() function to
# create an array. 
# Store it in a variable.
gvn_arry = np.array([[5, 25, 50],[35, 40, 60]])              
# Print the above given array.
print("The above given array is:",gvn_arry)
print()
# Pass the given array and some random percentile say 50 as an argument to the percentile() function of numpy module 
#Here we get the 50th percentile point of the above array
print("50th percentile point of the above array:", np.percentile(gvn_arry, 50))
print()
#Similarly we can get 25,60,75 th percentile by passing them as tuple(second argument of the percentile function)
print("25 th , 60th , 75th percentile points of the above array are:\n", 
       np.percentile(gvn_arry, (25, 60, 75)))

Output:

The above given array is: [[ 5 25 50]
 [35 40 60]]

50th percentile point of the above array: 37.5

25 th , 60th , 75th percentile points of the above array are:
 [27.5 40.  47.5]

Example2

NP percentile: The percentile points are calculated over the given axes when the axis parameter is provided.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random list as an argument to the array() function to
# create an array. 
# Store it in a variable.
gvn_arry = np.array([[5, 25, 50],[35, 40, 60]])              
# Print the above given array.
print("The above given array is:",gvn_arry)
print()
#Gett the 50th percentile point along 0 axis by passing 50 as second argument and axis=0
print("50th percentile point of the above array along 0 axis : ", 
       np.percentile(gvn_arry, 50, axis=0))
#Get the 50th percentile point along 0 axis by passing 50 as second argument and axis=1
print("50th percentile point of the above array along 1 axis : ", 
       np.percentile(gvn_arry, 50, axis=1))

Output:

The above given array is: [[ 5 25 50]
 [35 40 60]]

50th percentile point of the above array along 0 axis :  [20.  32.5 55. ]
50th percentile point of the above array along 1 axis :  [25. 40.]

Example3

When calculating percentile points, the interpolation option can be used to specify the interpolation method to apply. Consider the following situation:

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random list as an argument to the array() function to
# create an array. 
# Store it in a variable.
gvn_arry = np.array([[5, 25, 50],[35, 40, 60]])              
# Print the above given array.
print("The above given array is:",gvn_arry)
print()
# Pass the given array and some random percentile say 50, and say interpolation is lower as an arguments to the percentile() function a of numpy module 
#Here we get the 50th percentile point of the above array
print("50th percentile point of the above array when interpolation is lower:", np.percentile(gvn_arry, 50, interpolation='lower'))

Output:

The above given array is: [[ 5 25 50]
 [35 40 60]]

50th percentile point of the above array when interpolation is lower: 35

Python compare two numbers – Python Program to Check if Two Numbers are Equal Without using Arithmetic and Comparison Operators

Program to Check if Two Numbers are Equal Without using Arithmetic and Comparison Operators

Python compare two numbers: In the previous article, we have discussed Python Program to Check Given Two Integers have Opposite signs

Given two numbers the task is to check whether the given two numbers are equal in Python.

Examples:

Example1:

Input:

Given First Number = 10
Given Second Number = 10

Output:

The given two numbers { 10 , 10 } are Equal

Example2:

Input:

Given First Number = 8
Given Second Number = 15

Output:

The given two numbers { 8 , 15 } are Not equal

Program to Check if Two Numbers are Equal Without using Arithmetic and Comparison Operators in Python

Below are the ways to check whether the given two numbers are equal in Python:

Method #1: Using Xor(^) Operator (Static Input)

Approach:

  • Create a function isEqualNumbers() which takes the given two numbers as arguments and returns true if they are equal else returns false if they are not equal.
  • Inside the isEqualNumbers() function.
  • Apply xor to the first number and second number and store it in a variable say xor_result.
  • Check if the value of xor_result is not equal to 0 using the if conditional statement.
  • If it is true then return False
  • Else return True.
  • Inside the main code.
  • 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.
  • Pass the given two numbers as the arguments to isEqualNumbers() function and store the result in a variable Reslt.
  • Check if the Value of Reslt using the If conditional statement.
  • If it is true then print the given two numbers are equal.
  • Else print the given two numbers are not equal.
  • The Exit of the Program.

Below is the implementation:

# Create a function isEqualNumbers()
# which takes the given two numbers as arguments and
# returns true if they are equal
# else returns false if they are not equal.


def isEqualNumbers(first_numb, second_numb):
        # Inside the isEqualNumbers() function.
        # Apply xor to the first number and second number and
    # store it in a variable say xor_result.
    xor_result = first_numb ^ second_numb
    # Check if the value of xor_result is not equal to 0
    # using the if conditional statement.
    if(xor_result != 0):
        # If it is true then return False
        return False
    # Else return True.
    return True


# Inside the main code.
# Give the first number as static input and store it in a variable.
firstnumb = 10
# Give the second number as static input and store it in another variable.
secondnumb = 10
# Pass the given two numbers as the arguments to isEqualNumbers() function
# and store the result in a variable Reslt.
Reslt = isEqualNumbers(firstnumb, secondnumb)
# Check if the Value of Reslt using the If conditional statement.
if(Reslt):
        # If it is true then print the given two numbers are Equal.
    print('The given two numbers {', firstnumb,
          ',', secondnumb, '} are Equal')
# Else print the given two numbers are Not Equal.
else:
    print('The given two numbers {', firstnumb,
          ',', secondnumb, '} are Not equal')

Output:

The given two numbers { 10 , 10 } are Equal

Method #2: Using Xor(^) Operator (User Input)

Approach:

  • Create a function isEqualNumbers() which takes the given two numbers as arguments and returns true if they are equal else returns false if they are not equal.
  • Inside the isEqualNumbers() function.
  • Apply xor to the first number and second number and store it in a variable say xor_result.
  • Check if the value of xor_result is not equal to 0 using the if conditional statement.
  • If it is true then return False
  • Else return True.
  • Inside the main code.
  • 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.
  • Pass the given two numbers as the arguments to isEqualNumbers() function and store the result in a variable Reslt.
  • Check if the Value of Reslt using the If conditional statement.
  • If it is true then print the given two numbers are equal.
  • Else print the given two numbers are not equal.
  • The Exit of the Program.

Below is the implementation:

# Create a function isEqualNumbers()
# which takes the given two numbers as arguments and
# returns true if they are equal
# else returns false if they are not equal.


def isEqualNumbers(first_numb, second_numb):
        # Inside the isEqualNumbers() function.
        # Apply xor to the first number and second number and
    # store it in a variable say xor_result.
    xor_result = first_numb ^ second_numb
    # Check if the value of xor_result is not equal to 0
    # using the if conditional statement.
    if(xor_result != 0):
        # If it is true then return False
        return False
    # Else return True.
    return True


# Inside the main code.
# Give the first number as user input using the int(input()) function and store it in a variable.
firstnumb = int(input('Enter some random number ='))
# Give the second number as user input using the int(input()) function and 
# store it in another variable.
secondnumb = int(input('Enter some random number ='))
# Pass the given two numbers as the arguments to isEqualNumbers() function
# and store the result in a variable Reslt.
Reslt = isEqualNumbers(firstnumb, secondnumb)
# Check if the Value of Reslt using the If conditional statement.
if(Reslt):
        # If it is true then print the given two numbers are Equal.
    print('The given two numbers {', firstnumb,
          ',', secondnumb, '} are Equal')
# Else print the given two numbers are Not Equal.
else:
    print('The given two numbers {', firstnumb,
          ',', secondnumb, '} are Not equal')

Output:

Enter some random number =8
Enter some random number =15
The given two numbers { 8 , 15 } are Not equal

If you are learning Python then the Python Programming Example is for you and gives you a thorough description of concepts for beginners, experienced programmers.

None keyword python – Python NONE Object With Examples

Python NONE Object With Examples

NONE Object in Python:

None keyword python: In the realm of Python – Object-Oriented Programming: NONE is an object. In other programming languages, such as PHP, JAVA, and others, it is equivalent to the ‘NULL’ value.

Because the NONE object has the data type ‘NoneType,’ it cannot be used as a value of some primitive data types or boolean values.

As a result, we can assign the value NONE to any variable in use. Let us provide an example to further illustrate the requirement for NONE.

Consider a login form with Python as the backend language to connect to a database. If we want to see if we have a connection to the specified database, we may assign NONE to the database connection object and see if the connection is secure.

Syntax:

variable = NONE

Likewise, assigning a variable to NONE indicates that the variable represents a no-value or a null value.

Implementation of NONE Object

Take a look at the sample below. In this case, we have assigned NONE to the variable x.

Example1: A NONE object is assigned to a Python variable.

# Take a variable and initialize its value with None
x = None
# Print the above variable.
print("Printing the above variable:", x)

Output:

Printing the above variable: None

When we try to print the value saved in the variable, we get the following result. As a result, it is evident that the NONE object represents NONE value, which can be termed a NULL value.

In the following example, we attempted to determine whether the Python NONE object represents an equivalent boolean value.

Example2:

# Take a variable and initialize its value with None
x = None
print("NONE keyword Boolean Test:")
# Check if the variable is true or false using the if conditional statement
if x:
    # If it is true, then print "It is True"
    print("It is True")
else:
    # Else print "It is False"
    print("It is False")

The result is FALSE, as seen below. As a result, this example shows that the Python NONE object is not the same as boolean or other primitive type object values.

Output:

NONE keyword Boolean Test:
It is False

Combining primitive type and NoneType values with Python data structures such as Sets, Lists, and so on.

Example3: NONE in Python using Set

When we give other primitive type values along with NONE to data structures like sets, lists, and so on, we see that the NONE value returns ‘NONE’ as the value when printed.

# Give the set as static input and store it in a variable.
gvnset = {1, 8, None, 15, 25, 6}
# Iterate in the given set using the for loop.
for itr in gvnset:
    # Inside the for loop, print the iterator value.
    print(itr)

Output:

1
6
8
15
25
None

Example4: NONE in Python using List

# Give the list as static input and store it in a variable.
gvn_lst = [1, 8, None, 15, 25, 6]
# Iterate in the given list using the for loop.
for itr in gvn_lst:
    # Inside the for loop, print the iterator value by converting it into a string
    # using the str() function
    print(str(itr))

Output:

1
8
None
15
25
6

Area and perimeter of pentagon – Python Program to Compute the Area and Perimeter of Pentagon

Program to Compute the Area and Perimeter of Pentagon

Area and perimeter of pentagon: In the previous article, we have discussed Python Program to Compute the Area and Perimeter of Octagon
Pentagon:

Pentagon perimeter formula: A pentagon (from the Greek v Pente and gonia, which mean five and angle) is any five-sided polygon or 5-gon. A simple pentagon’s internal angles add up to 540°.

A pentagon can be simple or complex, and it can be self-intersecting. A pentagram is a self-intersecting regular pentagon (or a star pentagon).

Formula to calculate the area of a pentagon:

 In which, a= The Pentagon’s side length

Formula to calculate the perimeter of a pentagon:

perimeter = 5a
Given the Pentagon’s side length and the task is to calculate the area and perimeter of the given Pentagon.
Examples:

Example1:

Input:

Given The Pentagon's side length = 10

Output:

The Pentagon's area with given side length { 10 } = 172.0477400588967
The Pentagon's Perimeter with given side length { 10 } = 50

Example2:

Input:

Given The Pentagon's side length = 5.5

Output:

The Pentagon's area with given side length { 5.5 } = 52.04444136781625
The Pentagon's Perimeter with given side length { 5.5 } = 27.5

Program to Compute the Area and Perimeter of Pentagon in Python

Perimeter of pentagon formula: Below are the ways to Calculate the area and perimeter of a pentagon with the given Pentagon’s side length:

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Import the math module using the import keyword.
  • Give the Pentagon’s side length as static input and store it in a variable.
  • Calculate the area of the given pentagon using the above given mathematical formula and math.sqrt() function.
  • Store it in another variable.
  • Calculate the perimeter of the given pentagon using the above given mathematical formula.
  • Store it in another variable.
  • Print the Pentagon’s area with the given side length.
  • Print the Pentagon’s perimeter with the given side length.
  • The Exit of the program.

Below is the implementation:

# Import the math module using the import keyword.
import math
# Give the Pentagon's side length as static input and store it in a variable.
side_len = 10
# Calculate the area of the given pentagon using the above given mathematical formula and
# math.sqrt() function.
# Store it in another variable.
pentgn_area = (math.sqrt(5*(5+2*math.sqrt(5)))*pow(side_len, 2))/4.0
# Calculate the perimeter of the given pentagon using the above given mathematical formula.
# Store it in another variable.
pentgn_perimtr = (5*side_len)
# Print the Pentagon's area with the given side length.
print(
    "The Pentagon's area with given side length {", side_len, "} =", pentgn_area)
# Print the Pentagon's perimeter with the given side length.
print(
    "The Pentagon's Perimeter with given side length {", side_len, "} =", pentgn_perimtr)

Output:

The Pentagon's area with given side length { 10 } = 172.0477400588967
The Pentagon's Perimeter with given side length { 10 } = 50

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Import the math module using the import keyword.
  • Give the Pentagon’s side length as user input using float(input()) function and store it in a variable.
  • Calculate the area of the given pentagon using the above given mathematical formula and math.sqrt() function.
  • Store it in another variable.
  • Calculate the perimeter of the given pentagon using the above given mathematical formula.
  • Store it in another variable.
  • Print the Pentagon’s area with the given side length.
  • Print the Pentagon’s perimeter with the given side length.
  • The Exit of the program.

Below is the implementation:

# Import the math module using the import keyword.
import math
# Give the Pentagon's side length as user input using float(input()) function and
# store it in a variable.
side_len = float(input('Enter some random number = '))
# Calculate the area of the given pentagon using the above given mathematical formula and
# math.sqrt() function.
# Store it in another variable.
pentgn_area = (math.sqrt(5*(5+2*math.sqrt(5)))*pow(side_len, 2))/4.0
# Calculate the perimeter of the given pentagon using the above given mathematical formula.
# Store it in another variable.
pentgn_perimtr = (5*side_len)
# Print the Pentagon's area with the given side length.
print(
    "The Pentagon's area with given side length {", side_len, "} =", pentgn_area)
# Print the Pentagon's perimeter with the given side length.
print(
    "The Pentagon's Perimeter with given side length {", side_len, "} =", pentgn_perimtr)

Output:

Enter some random number = 5.5
The Pentagon's area with given side length { 5.5 } = 52.04444136781625
The Pentagon's Perimeter with given side length { 5.5 } = 27.5

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 countdown timer – Python Program to Create a Countdown Timer

Python Program to Create a Countdown Timer

Python countdown timer: If you are new to Java and want to learn the java coding skills too fast. Try practicing the core java programs with the help of the Java basic programs list available.

We’ll look at how to make a countdown timer in Python. The code will accept the user’s input on the length of the countdown in seconds. Following that, a countdown in the format ‘minutes: seconds’ will commence on the screen. Here, we’ll make use of the time module.

Python Program to Create a Countdown Timer

Countdown timer python: Below are the ways to Create a Countdown Timer in Python.

Method #1: Using While Loop (Static Input)

Java countdown timer: The time module and its sleep() function will be used. To make a countdown timer, follow the steps below:

Approach:

  • Import the time module using the import statement.
  • Then in seconds, Give the length of the countdown as static input and store it in a variable.
  • This value is passed to the user-defined function countdownTime() as a parameter ‘tim’ .
  • A while loop is used in this function until the time reaches zero.
  • To calculate the number of minutes and seconds, use divmod().
  • Now, using the variable timeformat, output the minutes and seconds on the screen.
  • By using end = ‘\n ‘, we force the cursor to return to the beginning of the screen (carriage return), causing the following line written to overwrite the preceding one.
  • The time. sleep() function is used to make the program wait one second.
  • Now decrement time so that the while loop can reach a finish.
  • After the loop is completed, we will print “The Given time is completed” to indicate the conclusion of the countdown.

Below is the implementation:

# Import the time module using the import statement.
import time

# creating a function time which counts the time


def countdownTime(tim):
    # A while loop is used in this function until the time reaches zero.
    while (tim):
       # To calculate the number of minutes and seconds, use divmod(). 
        timemins, timesecs = divmod(tim, 60)
    # Now, using the variable timeformat, output the minutes and seconds on the screen.
        timercount = '{:02d}:{:02d}'.format(timemins, timesecs)
    # By using end = '\n', we force the cursor to return to the
    # beginning of the screen (carriage return),
    # causing the following line written to overwrite the preceding one.
        print(timercount, end="\n")
    # The time. sleep() function is used to make the program wait one second.
        time.sleep(1)
    # Now decrement time so that the while loop can reach a finish.
        tim -= 1
    # After the loop is completed, we will print "The Given time is completed" to indicate the conclusion of the countdown.
    print('The Given time is completed')


# Then in seconds, Give the length of the countdown as static input and store it in a variable.
tim = 5

# Passing the given time as argument to the countdownTime() function
countdownTime(tim)

Output:

00:05
00:04
00:03
00:02
00:01
The Given time is completed

Method #2: Using While Loop (User Input)

The time module and its sleep() function will be used. To make a countdown timer, follow the steps below:

Approach:

  • Import the time module using the import statement.
  • Then in seconds, Give the length of the countdown as user input and store it in a variable.
  • Convert the given time in seconds to integer data type using int() function.
  • This value is passed to the user-defined function countdownTime() as a parameter ‘tim’ .
  • A while loop is used in this function until the time reaches zero.
  • To calculate the number of minutes and seconds, use divmod().
  • Now, using the variable timeformat, output the minutes and seconds on the screen.
  • By using end = ‘\n ‘, we force the cursor to return to the beginning of the screen (carriage return), causing the following line written to overwrite the preceding one.
  • The time. sleep() function is used to make the program wait one second.
  • Now decrement time so that the while loop can reach a finish.
  • After the loop is completed, we will print “The Given time is completed” to indicate the conclusion of the countdown.

Below is the implementation:

# Import the time module using the import statement.
import time

# creating a function time which counts the time


def countdownTime(tim):
    # A while loop is used in this function until the time reaches zero.
    while (tim):
       # To calculate the number of minutes and seconds, use divmod(). 
        timemins, timesecs = divmod(tim, 60)
    # Now, using the variable timeformat, output the minutes and seconds on the screen.
        timercount = '{:02d}:{:02d}'.format(timemins, timesecs)
    # By using end = '\n', we force the cursor to return to the
    # beginning of the screen (carriage return),
    # causing the following line written to overwrite the preceding one.
        print(timercount, end="\n")
    # The time. sleep() function is used to make the program wait one second.
        time.sleep(1)
    # Now decrement time so that the while loop can reach a finish.
        tim -= 1
    # After the loop is completed, we will print "The Given time is completed" to indicate the conclusion of the countdown.
    print('The Given time is completed')


# Then in seconds, Give the length of the countdown as user input and store it in a variable.
tim = input('Enter some random time = ')
# Convert the given time in seconds to integer data type using int() function.
tim = int(tim)

# Passing the given time as argument to the countdownTime() function
countdownTime(tim)

Output:

Enter some random time = 4
00:04
00:03
00:02
00:01
The Given time is completed

Related Programs:

Max element in list python – Python Program to Get the Position of Max Value in a List

Program to Get the Position of Max Value in a List

Max element in list python: In the previous article, we have discussed Python Program to Find Vertex, Focus and Directrix of Parabola
max() function :

max() is a built-in function that returns the maximum value in a list.

index() function:

This function searches the lists. It returns the index where the value is found when we pass it as an argument that matches the value in the list. If no value is found, Value Error is returned.

Given a list, the task is to Get the position of Max Value in a List.

Examples:

Example 1 :

Input :

Given List = [1, 5, 9, 2, 7, 3, 8]

Output:

Maximum Value in the above Given list = 9
Position of Maximum value of the above Given List = 3

Example 2 :

Input : 

Given List = [4, 3, 7, 1, 2, 8, 9]

Output:

Maximum Value in the above Given list = 9
Position of Maximum value of the above Given List = 7

Program to Get the Position of Max Value in a List

Below are the ways to Get the Position of Max value in a List.

Method #1: Using Max(),Index() functions  (Static Input)

Approach:

  • Give the List as static input and store it in a variable.
  • Get the maximum value of the given list using the built-in max() function and store it in another variable.
  • Print the maximum value of the above-given List.
  • Get the position of the maximum value of the given List using the built-in index() function and store it in another variable.
  • Print the position of the maximum value of the given List i.e. maximum position+1( since list index starts from zero).
  • The Exit of the program.

Below is the implementation:

# Give the List as static input and store it in a variable.
Gvn_lst = [1, 5, 9, 2, 7, 3, 8]
# Get the maximum value of the given list using the built-in max() function and
# store it in another variable
maxim_vle = max(Gvn_lst)
# Print the maximum value of the above given List.
print("Maximum Value in the above Given list = ", maxim_vle)
# Get the position of the maximum value of the List using the built-in index() function
# and store it in another variable.
maxim_positn = Gvn_lst.index(maxim_vle)
# Print the position of the maximum value of the given List i.e. maximum position+1
# ( since list index starts from zero).
print("Position of Maximum value of the above Given List = ", maxim_positn+1)

Output:

Maximum Value in the above Given list =  9
Position of Maximum value of the above Given List =  3

Method #2: Using Max(),Index() functions  (User Input)

Approach:

  • Give the list as User input using list(),map(),input(),and split() functions and store it in a variable.
  • Get the maximum value of the given list using the built-in max() function and store it in another variable.
  • Print the maximum value of the above-given List.
  • Get the position of the maximum value of the given List using the built-in index() function and store it in another variable.
  • Print the position of the maximum value of the given List i.e. maximum position+1( since list index starts from zero).
  • The Exit of the program.

Below is the implementation:

#Give the list as User input using list(),map(),input(),and split() functions and store it in a variable.
Gvn_lst = list(map(int, input('Enter some random List Elements separated by spaces = ').split()))
# Get the maximum value of the given list using the built-in max() function and
# store it in another variable
maxim_vle = max(Gvn_lst)
# Print the maximum value of the above given List.
print("Maximum Value in the above Given list = ", maxim_vle)
# Get the position of the maximum value of the List using the built-in index() function
# and store it in another variable.
maxim_positn = Gvn_lst.index(maxim_vle)
# Print the position of the maximum value of the given List i.e. maximum position+1
# ( since list index starts from zero).
print("Position of Maximum value of the above Given List = ", maxim_positn+1)

Output:

Enter some random List Elements separated by spaces = 4 3 7 1 2 8 9
Maximum Value in the above Given list = 9
Position of Maximum value of the above Given List = 7

Here we printed the index of the maximum element of the given list.

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.

Remainder in python – Python Program to Read Two Numbers and Print Their Quotient and Remainder

Program to Read Two Numbers and Print Their Quotient and Remainder

Remainder in python: Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Given two numbers , the task is to print their quotient and Remainder in  Python.

Examples:

i)Floating Division

Example1:

Input:

first number =45
second number =17

Output:

The value of quotient after dividing 45 / 17 = 2.6470588235294117
The value of remainder after dividing 45 / 17 = 11

ii)Integer Division

Input:

first number =45
second number =17

Output:

The value of quotient after dividing 45 / 17 = 2
The value of remainder after dividing 45 / 17 = 11

Program to Read Two Numbers and Print Their Quotient and Remainder in  Python

Below are the ways to print the quotient and Remainder:

1)Using / and % modulus operator in Python (User Input separated by new line, Float Division)

Approach:

  • Scan the given two numbers using int(input()) and store them in two separate variables.
  • Calculate the quotient by using the syntax first number /second number and store it in a variable.
  • Calculate the remainder by using the syntax first number %second number and store it in a variable.
  • Print the above two variables which are the result of the program
  • Exit of Program.

Below is the implementation:

# scanning the given two numbers using int(input()) function
# first number
numb1 = int(input("Enter some random number = "))
# second number
numb2 = int(input("Enter some random number = "))
# Calculate the quotient by using the syntax first number /second number
# and store it in a variable.
quotie = numb1/numb2
# Calculate the remainder by using the syntax first number %second number
# and store it in a variable.
remain = numb1 % numb2
# Print the above two variables which are the result of the program
print("The value of quotient after dividing", numb1, "/", numb2, " = ", quotie)
print("The value of remainder after dividing",
      numb1, "/", numb2, " = ", remain)

Output:

Enter some random number = 86
Enter some random number = 12
The value of quotient after dividing 86 / 12 = 7.166666666666667
The value of remainder after dividing 86 / 12 = 2

2)Using / and % modulus operator in Python (User Input separated by spaces , Float Division)

Approach:

  • Scan the given two numbers using map and split() functions to store them in two separate variables.
  • Calculate the quotient by using the syntax first number /second number and store it in a variable.
  • Calculate the remainder by using the syntax first number %second number and store it in a variable.
  • Print the above two variables which are the result of the program
  • Exit of Program.

Below is the implementation:

# Scan the given two numbers using map and split() functions
# to store them in two separate variables.
numb1, numb2 = map(int, input("Enter two random numbers separated by spaces = ").split())
# Calculate the quotient by using the syntax first number /second number
# and store it in a variable.
quotie = numb1/numb2
# Calculate the remainder by using the syntax first number %second number
# and store it in a variable.
remain = numb1 % numb2
# Print the above two variables which are the result of the program
print("The value of quotient after dividing", numb1, "/", numb2, " = ", quotie)
print("The value of remainder after dividing",
      numb1, "/", numb2, " = ", remain)

Output:

Enter two random numbers separated by spaces = 45 17
The value of quotient after dividing 45 / 17 = 2.6470588235294117
The value of remainder after dividing 45 / 17 = 11

3)Using // and % modulus operator in Python (User Input separated by spaces , Integer Division)

Approach:

  • Scan the given two numbers using map and split() functions to store them in two separate variables.
  • Calculate the integer quotient by using the syntax first number //second number and store it in a variable.
  • Calculate the remainder by using the syntax first number %second number and store it in a variable.
  • Print the above two variables which are the result of the program
  • Exit of Program.

Below is the implementation:

# Scan the given two numbers using map and split() functions
# to store them in two separate variables.
numb1, numb2 = map(int, input("Enter two random numbers separated by spaces = ").split())
# Calculate the quotient by using the syntax first number /second number
# and store it in a variable.
quotie = numb1//numb2
# Calculate the remainder by using the syntax first number %second number
# and store it in a variable.
remain = numb1 % numb2
# Print the above two variables which are the result of the program
print("The value of quotient after dividing", numb1, "/", numb2, " = ", quotie)
print("The value of remainder after dividing",
      numb1, "/", numb2, " = ", remain)

Output:

Enter two random numbers separated by spaces = 45 17
The value of quotient after dividing 45 / 17 = 2
The value of remainder after dividing 45 / 17 = 11

Related Programs:

Numpy matmul – Python NumPy matmul() Function

Python NumPy matmul() Function

NumPy matmul() Function:

Numpy matmul: Matrix product of two arrays is returned by the matmul() function of the NumPy module. Specifically,

While it gives a normal product for 2-D arrays, if either argument’s dimensions are greater than two(>2), it is considered as a stack of matrices residing in the last two indexes and broadcast as such.

If either argument is a 1-D array, it is converted to a matrix by adding a 1 to its dimension, which is then removed after multiplication.

Note: The matmul() function does not support scalar multiplication.

Syntax:

numpy.matmul(a, b, out=None)

Parameters

a: This is required. It is the first array_like parameter given as input. Scalars are not accepted.

b: This is required. It is the second array_like parameter given as input.

out: This is optional. It is the output array for the result. None is the default value. It must have the same shape as output if it is provided.

Return Value: 

The matrix product of the given two arrays is returned.

Note: If the last dimension of “a” is not the same size as the second-to-last dimension of b, or if a scalar value is provided in, a ValueError exception is thrown.

NumPy matmul() Function in Python

Example1: For 1D arrays

Matmul python: The function returns the inner product of two 1-D arrays when two 1-D arrays are used.

Approach:

  • Import numpy module using the import keyword.
  • Give the first array as static input and store it in a variable.
  • Give the second array as static input and store it in another variable.
  • Pass the given two array’s as an argument to the matmul() function of numpy module to get the inner product of the given two arrays.
  • Store it in another variable.
  • Print the inner product of the given two arrays.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Give the first array as static input and store it in a variable.
fst_arry = [1, 9, 2]
# Give the second array as static input and store it in another variable.
scnd_arry = [10, 3, 5]
# Pass the given two array's as an argument to the matmul() function of numpy module 
# to get the inner product of the given two arrays.
# (1*10 + 9*3 + 2*5) = 47
# Store it in another variable.
rslt = np.matmul(fst_arry, scnd_arry)
# Print the inner product of the given two arrays.
print("The inner product of the given two arrays = ", rslt)

Output:

The inner product of the given two arrays = 47

Example2

The function returns matrix multiplication when 2D matrices are used.

Approach:

  • Import numpy module using the import keyword.
  • Pass the random list(2D) as an argument to the array() function to create an array.
  • Store it in a variable.
  • Pass the random list(2D) as an argument to the array() function to create another array.
  • Store it in another variable.
  • Pass the given two array’s as the argument to the matmul() function of numpy module to get the matrix multiplication of given two arrays(matrices).
  • Store it in another variable.
  • Print the matrix multiplication of given two arrays(matrices).
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass the random list(2D) as an argument to the array() function 
# to create an array. 
# Store it in a variable.
fst_arry = np.array([[5, 6], 
                     [1, 3]])
# Pass the random list(2D) as an argument to the array() function 
# to create another array. 
# Store it in another variable.
scnd_arry = np.array([[12, 2], 
                      [4, 1]])
# Pass the given two array's as the argument to the matmul() function of numpy module 
# to get the matrix multiplcation of given two arrays(matrices)
# Store it in another variable.
rslt = np.matmul(fst_arry, scnd_arry)
# Print the matrix multiplication of given two arrays(matrices)
print("The matrix multiplication of given two arrays(matrices) = ")
print(rslt)

Output:

The matrix multiplication of given two arrays(matrices) = 
[[84 16]
 [24 5]]

Example3: 2D array+1D array

Approach:

  • Import numpy module using the import keyword.
  • Give the random 2D array as static input and store it in a variable.
  • Give the random 1D array as static input and store it in another variable.
  • Pass the given two array’s as an argument to the matmul() function of numpy module to get the multiplication of the given two arrays and print it.
  • Similarly print, vice-varsa by swapping two arrays.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np 
# Give the random 2D array as static input and store it in a variable.
arry_2D = [[2,1],[3,2]] 
# Give the random 1D array as static input and store it in another variable.
arry_1D = [3,1] 
# Pass the given two array's as an argument to the matmul() function of numpy module 
# to get the multiplication of given two arrays and print it.
# Similarly print, vice-varsa by swapping two arrays
print(np.matmul(arry_2D, arry_1D))
print()
print(np.matmul(arry_1D, arry_2D))

Output:

[ 7 11]

[9 5]

Oshash – Python Oshash Module with Examples

Python Oshash Module with Examples

Oshash: In this tutorial, let us see the oshash module and how we can get it into our system and use it. Also, let us analyze how this method compares to other algorithms in terms of performance. Following that, we will look at some of its examples to gain a better understanding of them.

Hashing & Hash Functions

Oshash: Hashing is the process of mapping object data to a representative integer value using a function or algorithm. It is accomplished by the use of a table with key-value pairs. It operates by passing the value through the hashing function, which returns a key, also known as hash-keys/hash-codes, corresponding to the value. The integer hash code is then mapped to the fixed size we have.

We can derive from this that a hash function is any function that can be used to map data of arbitrary size to fixed-size values. Hash values, hash codes, or simply hashes are the values returned by a hash function. So, now that we have a basic understanding of hashing, we can go on to the module “oshash.”

Oshash Module with Examples in Python

Despite the fact that there are numerous efficient algorithms, “Oshash” studied a few distinct approaches to accomplish Hashing. In contrast to other algorithms, its primary goal is to achieve high speed when others lag.

The main drawback that causes them to be slow is that they read the entire file at once, which is not recommended for “oshash.” Instead, it reads the file in chunks.

We didn’t have to worry about its internal operation or hash functions, however. We will focus more on its application.

Installation:

pip install oshash

Implementation

We may use it in two ways: first, in our program file, and second, via the command-line interface. Let’s have a look at some examples of each. In both circumstances, it returns a hash file.

Program File Syntax:

import oshash
file_hash = oshash.oshash(<path to video file>)

Command-line Interface Syntax:

$ oshash <path to file>

Despite the fact that no such technique was used in the prior example, a hash is produced in the background, as indicated in the syntax below.

Example

#open the file buffer by giving path of the file as argument to the open() function
file_buffer = open("/path/to/file/")
#Getting check sum of the file buffer head using head attribute(64kb)
head_checksum = checksum(file_buffer.head(64 * 1024))  
#Getting check sum of the file buffer tail using tail attribute(64kb)
tail_checksum = checksum(file_buffer.tail(64 * 1024))
#Adding all the sizes
file_hash = file_buffer.size + head_checksum + tail_checksum

 

 

 

Multiline strings python – 4 Methods for Creating Python Multiline Strings

4 Methods for Creating Python Multiline Strings

Multiline Strings in Python:

Multiline strings python: To generate multiline strings in Python, utilise brackets, backslashes, and triple quotes, but the user must specify the use of spaces between the strings.

The Python string.join() function is thought to be a particularly efficient way to generate multiline strings, and it also handles spaces between the strings implicitly.

We can create multiline strings in the following ways:

  • Using Triple quotes
  • Using backslash(\)
  • Using string.join() method
  • Using round brackets ()

1)Using Triple quotes

Python multiline string: In Python, triple quotes can be used to display many strings at the same time(together), i.e. multiline strings.

If our input contains string statements with too many characters, triple quotes can help us show it in a proper manner.
Everything between the triple quotes is regarded as the string itself.

Syntax:

" " " strings" " "

Example

# Give the string as static input and store it in a variable.
gvn_str = """hello this is btechgeeks
good morning this is btechgeeks. welcome to btechgeeks"""
# Print the given string
print("The given string is:\n", gvn_str)

Output:

The given string is:
 hello this is btechgeeks
good morning this is btechgeeks. welcome to btechgeeks

2)Using backslash(\)

Python multiline strings: In Python, the escape sequence backslash (“) can also be is used to construct multiline strings.

Syntax:

variable = "string_1"\"string_2"\"string_N"

When using a backslash( \) to create multiline strings, the user must explicitly mention the spaces between the strings.

Example

# Give the string as static input and store it in a variable.
gvn_str = "hello this is btechgeeks"\
"good morning this is btechgeeks"\
"welcome to btechgeeks"
# Print the given string
print("The given string is:\n", gvn_str)

Output:

The given string is:
hello this is btechgeeksgood morning this is btechgeekswelcome to btechgeeks

3)Using string.join() method

Python f string multiline: The Python string.join() function has shown to be an efficient method for creating Python multiline strings.

The string.join() method handles and manipulates all of the gaps/spaces between the strings, so the user does not need to be concerned.

Syntax:

string.join(("string_1","string_2","string_N"))

Example

# Pass multiple strings to the join() function to join all the strings(creating
# multiline strings)
gvn_str = ''.join(("hello this is btechgeeks",
                   "good morning this is btechgeeks", "welcome to btechgeeks"))
# Print the given string
print("The given string is:\n", gvn_str)

Output:

The given string is:
 hello this is btechgeeksgood morning this is btechgeekswelcome to btechgeeks

4)Using round brackets ()

Multiline string python: Python brackets can be used to generate multiline strings and split or separate the strings together.

The main disadvantage of this method is that the user must manually provide the spaces between the multiline strings.

Syntax:

variable = ("string_1""string_2""string_N")

Example

# Pass multiple strings to the join() function to join all the strings(creating
# multiline strings)
gvn_str = ("hello this is btechgeeks"
           "good morning this is btechgeeks"
           "welcome to btechgeeks")
# Print the given string
print("The given string is:\n", gvn_str)

Output:

The given string is:
 hello this is btechgeeksgood morning this is btechgeekswelcome to btechgeeks

In Brief:

  • Python multiline strings are strings that have been divided onto numerous lines to improve the readability of the code for users.
  • To generate multiline strings in Python, utilise brackets, backslashes, and triple quotes, but the user must specify the use of spaces between the strings.
  • The Python string.join() function is thought to be a particularly efficient way to generate multiline strings, and it also handles spaces between the strings implicitly.
  • Multiline strings are not subject to Python’s indentation rules.(not applicable for them)
  • If a multiline string is formed with triple quotes, all escape sequences such as newline(\n) and tab-space(\t) are treated to be part of the string.