Confusion matrix in python – Python Confusion Matrix With Examples

Python Confusion Matrix With Examples

Confusion matrix in python: The process of categorizing a given set of data into classes is known as classification.
In Machine Learning, you frame the problem, gather and clean the data, add any essential feature variables, train the model, test its performance, improve it using some cost function, and then it is ready to deploy.
But how do we measure its effectiveness? Is there anything, in particular, to look for?

A simple and broader solution would be to compare the actual and expected values. However, this does not tackle the problem.

Confusion Matrix is one such Error metric for evaluating a model’s performance.

Confusion Matrix in Python:

We occasionally encounter scenarios in which we must apply specific ML algorithms to forecast the outcome of a classification challenge, i.e. business difficulties where the outcome/target/response variable is categorical data. To determine whether an email is SPAM or NOT-SPAM, for example.

So, in the given scenario, we require a specific Error Metric to measure the correctness and exactness of the model for optimum fit.

The Confusion Matrix is an Error Metric used to test the efficiency of Classification Machine Learning Algorithms. It gives us detailed information about the model’s accuracy level, precision rate, and error percentage.

We can distinguish between the actual accurate and predicted outcome of the categorical answer variable by employing a confusion matrix.

So, now that we’ve established the importance of the Confusion Matrix, let’s look at the numerous components that might help us judge and forecast the best-fit algorithm for every model.

Confusion Matrix Components

It is a summary of the predictions made by the classification models.

True Negative (TN): Values that are actually negative and predicted to be negative.

False Negative (FN): A value that is truly positive but is predicted to be negative.

False Positive (FP): A value that is truly negative but is predicted to be positive.

True Positive (TP): Values that are actually positive and predicted to be positive.

Here is the additional information that the Confusion Matrix provides on the model:

1)Accuracy:

Accuracy is defined as the percentage of successful predictions based on the input provided.

Formula:

Accuracy = TP + TN / (TP + TN + FP + FN)

2)Precision score: This is the value that identifies the set of values that are correctly predicted as True and are also True in the actual set.

By precision, we imply that the positive values are indeed predicted to be positive.

precision = TP/(TP+FP)

3)Recall score: This is the value that indicates a set of values that are actually True and also predicted to be True,

By recall, we mean that the specific class of samples is accurately predicted.

Recall= TP/(TP+FN)

4)F1 score:

When the data is skewed or unbalanced, the F1 score allows us to evaluate the model’s accuracy and efficiency. It is the harmonic mean of the Precision and Recall scores.

F1 score  = 2*(Recall * Precision)/(Recall + Precision)

Implementation of Confusion Matrix

The classification_matrix() method represents the set of values that have been identified properly and incorrectly. Furthermore, the classification_report() function represents the metrics value for each of the input categories, namely ‘F’ and ‘T’.

Approach:

  • Import metrics from sklearn module using the import Keyword from sklearn import metrics.
  • Give the list of predicted values as static input and store it in a variable.
  • Give the list of actual values as static input and store it in another variable.
  • Build the confusion matrix using the confusion_matrix() function by passing the given predicted and actual values list and labels as the arguments.
  • Store it in another variable.
  • Print the confusion matrix.
  • Pass the predicted, actual values list and labels as the arguments to the classification_report() function of the metrics and store it in a variable.
  • Print the above report.
  • The Exit of the Program.

Below is the implementation:

# Import metrics from sklearn module using the import Keyword
from sklearn import metrics
#  Give the list of predicted values as static input and store it in a variable.
predctd_vals = ["F", "T", "F", "T", "F"] 
#  Give the list of actual values as static input and store it in another variable.
actul_vals = ["F", "T", "F", "F", "T"] 
# Build the confusion matrix using the confusion_matrix() function by passing the 
# given predicted and actual values list and labels as the arguments
# Store it in another variable.
rslt_Confusn_matx = metrics.confusion_matrix(predctd_vals, actul_vals, labels=["F", "T"]) 
# Print the confusion matrix 
print(rslt_Confusn_matx)
# Pass the predicted, actual values list and labels as the arguments to the classification_report()
# function of the metrics and store it in a variable 
rslt_report = metrics.classification_report(predctd_vals, actul_vals, labels=["F", "T"]) 
# Print the above report.
print(rslt_report)

Output:

[[2 1]
 [1 1]]
              precision    recall  f1-score   support

           F       0.67      0.67      0.67         3
           T       0.50      0.50      0.50         2

    accuracy                           0.60         5
   macro avg       0.58      0.58      0.58         5
weighted avg       0.60      0.60      0.60         5

 

Python NULL – How to Identify Null values in Python?

NULL – How to Identify Null values in Python

Python null value: Here we see, what Python null means and what the NONE type is. In various computer languages, the term ‘null‘ refers to an empty variable or a reference that points to nothing. ‘null’ is the same as ‘zero.’ In Python, however, there is no ‘null’ keyword. Instead, the object ‘None‘ is utilized for this purpose.

NULL in Python:

What is null in python: When a function does not have anything to return, i.e. does not have a return statement, the output is None.

In other words, the None keyword is used here to define a null variable or object. None is an object and a data type of the NoneType class.

Example

Approach:

  • Create a function say null_fun().
  • Inside the function, take a variable and initialize it with some random number.
  • Take another variable and initialize it with some random number.
  • In the main function, call the above-declared function null_fun() and print it.
  • The Exit of the Program.

Below is the implementation:

# Create a function say null_fun()
def null_fun():
    # Inside the function, take a variable and initialize it with some random number
    num1 = 5
    # Take another variable and initialize it with some random number
    num2 = 7
# In the main function, call the above declared function null_fun() and print it
print(null_fun())

Output:

None

Explanation:

Here the function doesn't return anything hence it prints 'None' as output

Example

Null value in python: When we assign None to a variable, it points to the same object as all the variables that are assigned to it. There are no new instances created.

In Python, unlike in other languages, null is an object in itself, not just a synonym for 0.

type(None)

Output:

NoneType

Python Declaration of Null Variables

Null value python: Python does not declare null variables by default. In other words, an undefined variable is not the same as a null variable.

Example

print(x)

Output:

Output showing an Error due to Undeclaration of Variable

Explanation:

Here the variable x is undefined, hence it raises an error

Python Code to Check whether the variable is none

Null check in python: We use the ‘is’ operator or the ‘==’ operator to determine whether a variable is None or not

1)Check Using ‘is’ operator:

Example

Approach:

  • Take a variable and initialize its value with None.
  • Check if the above variable value is None using the ‘is’ operator and if conditional statement.
  • If it is true, then print ‘The Output is None’.
  • Else print “The Output is not None’.
  • The Exit of the Program.

Below is the implementation:

# Take a variable and initialize its value with None
x = None
# Check if the above variable value is None using the 
# 'is' operator and if conditional statement
if x is None :
    # If it is true, then print 'The Output is None'                 
    print("The Output is None")
else :
    # Else print "The Output is not None'
    print("The Output is not None")

Output:

The Output is None

2)Check Using ‘==’ operator:

Approach:

  • Take a variable and initialize its value with None.
  • Check if the above variable value is None using the ‘==’ operator and if conditional statement.
  • If it is true, then print ‘The Output is None’.
  • Else print “The Output is not None’.
  • The Exit of the Program.

Below is the implementation:

# Take a variable and initialize its value with None
x = None
# Check if the above variable value is None using the 
# '==' operator and if conditional statement
if (x == None):
    # If it is true, then print 'The Output is None'                 
    print("The Output is None")
else :
    # Else print "The Output is not None'
    print("The Output is not None")

Output:

The Output is None

A Brief Recall

  • A null variable is defined with the None keyword.
  • None is not same as zero.
  • None as an immutable type.
  • None can be used to indicate missing values as well as default parameters.

 

Python min function – Python : min() Function Tutorial with Examples

min() Function Tutorial with Examples

Python min function: We’ll go through the details of Python’s min() function with examples in this article.

The min() function in Python is used to find the smallest element in a collection of elements.

Python min() function

1)min() function

min() python: The min() function returns the lowest-valued object, or the lowest-valued item in an iterable.

If the values are strings, they are compared alphabetically.

Syntax:

min(iterable, *[, key, default])
min(arg1, arg2, *args[, key])

Parameters:

Iterable : An Iterable object is one that can be traversed, such as a list or a tuple.
arg1,arg2 ...... :  Multiple elements are essential.
key  :  A function that is applied to and object in the Iterable and returns a value based on the argument passed in.

Return:

It returns the Iterable or assigned elements element with the lowest value. If the main function is not available,
 the minimum value is determined by comparing the given objects. If a key function is given, instead of explicitly
 comparing objects, it will first call the key function on each one before comparing it to others.

Exceptions:

When two forms are compared, TypeError is returned.

2)Finding min value in list

Consider the following scenario: we have a list of numbers.

Since the list is an Iterable, we may directly transfer it to the min() function to find the list’s minimum value.

Below is the implementation:

# given list
givenlist = [98, 234, 21, 45, 55, 12, 988]
# finding min value in list using min function
minvalue = min(givenlist)
# print the min value
print(minvalue)

Output:

12

3)Finding min ascii character in string using min() function

Python minimum function: Assume we have a string.
Since String is an Iterable, we can use the min() function to find the character with the lowest ASCII value in the string.

Below is the implementation:

# given string
string = "onlinebtechgeeks"
# finding min ascii value character in given string
minchar = min(string)
# print the min ascii character
print(minchar)

Output:

b

The min() function compared the ASCII values of the characters in the string and returned the character with the smallest ASCII value.

4)Finding min string from list of strings using min() function

Assume we have a list of strings.
Since list is an Iterable, we may directly transfer it to the min() function to find the minimum string based on alphabetical order in the list.

Below is the implementation:

# given list of strings
strings_list = ["hello", "this", "is", "BTechGeeks"]
# finding min string  in given list of strings
minstring = min(strings_list)
# print the min string
print(minstring)

Output:

BTechGeeks

5)Finding min value and key in dictionary

We can get min value in dictionary by using lambda function as given below.

Below is the implementation:

# given dictionary
dictionary = {'Hello': 238, 'This': 135,
              'is': 343, 'BTechGeeks': 50, 'Platform': 688}
# fet the min value and key in dictionary using lambda and min () function
min_Value = min(dictionary.items(), key=lambda x: x[1])
print('Min value in dictionary : ', min_Value)

Output:

Min value in dictionary :  ('BTechGeeks', 50)

6)min() function with multiple arguments

We may also transfer individual elements to the min function rather than any Iterable.

Below is the implementation:

# min() function with multiple arguments
minvalue = min(100, 24, 454, 22, 989, 12, 5, 467)
# print the min value
print(minvalue)

Output:

5

Related Programs:

Python Program to Print All Co-binary Palindromic Numbers in a Range

Program to Print All Co-binary Palindromic Numbers in a Range

Binary palindrome: Given the lower limit range and upper limit range, the task is to print all Co-binary Palindromic Numbers in the given range in Python.

Co-binary Palindromic Numbers:

A co-binary palindrome is a number that is a palindrome both as a decimal number and after being binary transformed.

Examples:

Example1:

Input:

Given upper limit range =11
Given lower limit range =2426

Output:

The Co-binary palindrome numbers in the given range 11 and 2426 are:
33 99 313 585 717

Example2:

Input:

Given upper limit range =5
Given lower limit range =12564

Output:

The Co-binary palindrome numbers in the given range 5 and 12564 are:
5 7 9 33 99 313 585 717 7447 9009

Program to Print All Co-binary Palindromic Numbers in a Range in

Python

Below are the ways to print all Co-binary Palindromic Numbers in the given range in Python.

Practice Java programming from home without using any fancy software just by tapping on this Simple Java Programs for Beginners tutorial.

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.
  • Create a function checkpalindromicNumb() which accepts the string as an argument and returns true if the string is palindrome else it returns False.
  • Create a function convertBinar() which converts the given number to binary and returns it.
  • Loop from lower limit range to upper limit range using For loop.
  • Convert this iterator value to binary by passing it as an argument to convertBinar() function and store it in a variable say binarystrng.
  • Convert this iterator value to a string using the str() function say strngnumb.
  • Check if the strngnumb is palindrome or not by giving the given strngnumb as an argument to checkpalindromicNumb().
  • Check if the binarystrng is palindrome or not by giving the given binarystrng as an argument to checkpalindromicNumb().
  • Check if both statements are true using the and operator and If conditional Statement.
  • If it is true then print it.
  • The Exit of the Program.

Below is the implementation:

# Create a function checkpalindromicNumb() which accepts the string as an argument and
# returns true if the string is palindrome else it returns False.
def checkpalindromicNumb(val):
    return val == val[::-1]
# Create a function convertBinar() which converts the given number to binary and returns it.
def convertBinar(orinumb):
    return bin(orinumb)[2:]
# Give the lower limit range as static input and store it in a variable.
lowlimrange = 11
# Give the upper limit range as static input and store it in another variable.
upplimrange = 2426
print('The Co-binary palindrome numbers in the given range',
      lowlimrange, 'and', upplimrange, 'are:')
# Loop from lower limit range to upper limit range using For loop.
for itervalu in range(lowlimrange, upplimrange+1):
    # Convert this iterator value to binary by passing it as an argument
    # to convertBinar() function and store it in a variable say binarystrng.
    binarystrng = convertBinar(itervalu)
    # Convert this iterator value to a string
    # using the str() function say strngnumb.
    strngnumb = str(itervalu)
    # Check if the strngnumb is palindrome or not by giving the given strngnumb
    # as an argument to checkpalindromicNumb().
    # Check if the binarystrng is palindrome or not by giving the given binarystrng
    # as an argument to checkpalindromicNumb().
    # Check if both statements are true using the and operator and If conditional Statement.
    if(checkpalindromicNumb(binarystrng) and checkpalindromicNumb(strngnumb)):
        # If it is true then print it.
        print(strngnumb, end=' ')

Output:

The Co-binary palindrome numbers in the given range 11 and 2426 are:
33 99 313 585 717

Method #2: Using For Loop (User Input)

Approach:

  • Give the lower limit range and upper limit range as user input using map(),int(),split() functions.
  • Store them in two separate variables.
  • Create a function checkpalindromicNumb() which accepts the string as an argument and returns true if the string is palindrome else it returns False.
  • Create a function convertBinar() which converts the given number to binary and returns it.
  • Loop from lower limit range to upper limit range using For loop.
  • Convert this iterator value to binary by passing it as an argument to convertBinar() function and store it in a variable say binarystrng.
  • Convert this iterator value to a string using the str() function say strngnumb.
  • Check if the strngnumb is palindrome or not by giving the given strngnumb as an argument to checkpalindromicNumb().
  • Check if the binarystrng is palindrome or not by giving the given binarystrng as an argument to checkpalindromicNumb().
  • Check if both statements are true using the and operator and If conditional Statement.
  • If it is true then print it.
  • The Exit of the Program.

Below is the implementation:

# Create a function checkpalindromicNumb() which accepts the string as an argument and
# returns true if the string is palindrome else it returns False.
def checkpalindromicNumb(val):
    return val == val[::-1]
# Create a function convertBinar() which converts the given number to binary and returns it.
def convertBinar(orinumb):
    return bin(orinumb)[2:]

# 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 bt spaces = ').split())
print('The Co-binary palindrome numbers in the given range',
      lowlimrange, 'and', upplimrange, 'are:')
# Loop from lower limit range to upper limit range using For loop.
for itervalu in range(lowlimrange, upplimrange+1):
    # Convert this iterator value to binary by passing it as an argument
    # to convertBinar() function and store it in a variable say binarystrng.
    binarystrng = convertBinar(itervalu)
    # Convert this iterator value to a string
    # using the str() function say strngnumb.
    strngnumb = str(itervalu)
    # Check if the strngnumb is palindrome or not by giving the given strngnumb
    # as an argument to checkpalindromicNumb().
    # Check if the binarystrng is palindrome or not by giving the given binarystrng
    # as an argument to checkpalindromicNumb().
    # Check if both statements are true using the and operator and If conditional Statement.
    if(checkpalindromicNumb(binarystrng) and checkpalindromicNumb(strngnumb)):
        # If it is true then print it.
        print(strngnumb, end=' ')

Output:

Enter lower limit range and upper limit range separate bt spaces = 5 12564
The Co-binary palindrome numbers in the given range 5 and 12564 are:
5 7 9 33 99 313 585 717 7447 9009

Related Programs:

Python significant digits – Python Program to Form an Integer that has the Number of Digits at Ten’s Place and the Least Significant Digit of the Entered Integer at One’s Place

Program to Form an Integer that has the Number of Digits at Ten’s Place and the Least Significant Digit of the Entered Integer at One’s Place

Python significant digits: Given a number which is integer , the task is to create an integer with the number of digits at ten’s place and the least significant digit of the entered integer at one’s place.

Examples:

Example1:

Input:

given number = 37913749

Output:

The required number = 89

Example2:

Input:

 given number =78329942

Output:

The required number = 82

Create an integer with the number of digits at ten’s place and the least significant digit of the entered integer at one’s place in Python

There are several ways to create an integer with the number of digits at ten’s place and the least significant digit of the entered integer at one’s place some of them are:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

Method #1:Using while loop and String Conversion ( Static Input)

Approach:

  • Give a number as static input and store it in a variable.
  • Make a duplicate of the integer.
  • Take a variable which stores the count of digits and initialize it with 0
  • Using a while loop, calculate the number of digits in the given integer.
  • Convert the integer copy and the number of digits count to string.
  • Concatenate the integer’s last digit with the count.
  • The newly created integer should be printed.
  • Exit of program.

Below is the implementation:

# given number numb
numb = 37913749
# Taking a temporary variable which stores the given number
tempNum = numb
# Take a variable which stores the count of digits and initialize it with 0
countTotalDigits = 0
# looping till the given number is greater than 0
while(numb > 0):
    # increasing the count of digits by 1
    countTotalDigits = countTotalDigits+1
    # Dividing the number by 10
    numb = numb//10
# converting the temporary variable to string
strnum = str(tempNum)
# Extracting least significant digit
leastSigDigit = strnum[-1]
# converting the count Total Digits to string
countTotalDigits = str(countTotalDigits)
# calculating required number
resnum = countTotalDigits+leastSigDigit
print("The required number =", resnum)

Output:

The required number = 89

Explanation:

  • Give a number as static input and store it in a variable.
  • Because the original value of the variable would be modified for counting the number of digits, a copy of the variable is created.
  • The while loop is employed, and the modulus operator is utilized to get the last digit of the number.
  • The count value is incremented each time a digit is obtained.
  • The variable’s number of digits and the number are transformed to string for simplicity of concatenation.
  • The string’s final digit is then retrieved and concatenated to the count variable.
  • The newly generated number is then printed.

Method #2:Using while loop and String Conversion ( User Input)

Approach:

  • Scan the given number using int(input()) and store it in a variable.
  • Make a duplicate of the integer.
  • Take a variable which stores the count of digits and initialize it with 0
  • Using a while loop, calculate the number of digits in the given integer.
  • Convert the integer copy and the number of digits count to string.
  • Concatenate the integer’s last digit with the count .
  • The newly created integer should be printed.
  • Exit of program.

Below is the implementation:

# given number numb
numb = int(input("enter any number = "))
# Taking a temporary variable which stores the given number
tempNum = numb
# Take a variable which stores the count of digits and initialize it with 0
countTotalDigits = 0
# looping till the given number is greater than 0
while(numb > 0):
    # increasing the count of digits by 1
    countTotalDigits = countTotalDigits+1
    # Dividing the number by 10
    numb = numb//10
# converting the temporary variable to string
strnum = str(tempNum)
# Extracting least significant digit
leastSigDigit = strnum[-1]
# converting the count Total Digits to string
countTotalDigits = str(countTotalDigits)
# calculating required number
resnum = countTotalDigits+leastSigDigit
print("The required number =", resnum)

Output:

enter any number = 78329942
The required number = 82

Method #3: Using len() and indexing by converting number to string (Static Input)

Approach:

  • Give a number as static input and store it in a variable.
  • Using the str() method, convert the given number to a string.
  • Determine the number of digits in the given number by computing the length of the string with the len() function.
  • Concatenate the integer’s last digit with the count.
  • The newly created integer should be printed.
  • Exit of program.

Below is the implementation:

# given number numb
numb = 82179
# Using the str() method, convert the given number to a string.
strnum = str(numb)

# Determine the number of digits in the given number by computing
# the length of the string with the len() function.
countTotalDigits = len(strnum)

# Extracting least significant digit
leastSigDigit = strnum[-1]
# converting the count Total Digits to string
countTotalDigits = str(countTotalDigits)
# calculating required number
resnum = countTotalDigits+leastSigDigit
print("The required number =", resnum)

Output:

The required number = 59

Related Programs:

All possible combinations python – Python Program to Accept Three Digits and Print all Possible Combinations from the Digits

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

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

Examples:

Example1:

Input:

given three numbers = 1 9 2

Output:

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

Example2:

Input:

given three numbers = 3 7 5

Output:

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

Example3:

Input:

given three numbers = 44 389 72

Output:

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

Python Program to Print all Possible Combinations of the three Digits

Python every combination of a list: There are several methods to print all the possible combinations of the three numbers some of them are:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

General Approach

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

Method #1: Using Nested loops (Static input)

Approach:

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

Below is the implementation:

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

Output:

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

Note:

This method also works for three numbers as shown below

Below is the implementation:

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

Output:

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

Method #2: Using Nested loops (User input)

Approach:

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

Below is the implementation:

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

Output:

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

Method #3:Using permutations() function

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

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

We will pass the digitsList as argument to permutations function

Below is the implementation:

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

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

Output:

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

Note:

This method also works for three numbers as shown below

Below is the implementation:

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

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

Output:

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

Related Programs:

Python cryptography example – Python Cryptography with Example

Python Cryptography with Example

Cryptography

Python cryptography example: The art of communicating between two people via coded messages is known as cryptography. The science of cryptography originated with the primary goal of providing security to secret messages sent from one party to another.

Cryptography is described as the art and science of hiding a communication in order to introduce privacy and secrecy in information security.

Powerful encryption technology is also required to ensure that the encrypted text is considerably more difficult to hack through and that your information does not fall into the wrong hands.

Modern Cryptography’s Characteristics

Cryptography python example: The following are the fundamental characteristics of modern cryptography:

  • It works with bit sequences.
  • Cryptography secures information by the application of mathematical algorithms.
  • It necessitates the participation of parties interested in establishing a secure communication channel in order to achieve privacy.

Importance of Cryptography

The following are some of the reasons why cryptography is important:

  • Protecting sensitive information and communication data from unauthorized people and preventing them from gaining access to it.
  • Have digital signatures to help protect vital information from frauds.
  • It is also critical to protect the information’s integrity.

Before going to the implementation part we should first install the cryptography module

Installation

pip install cryptography

Output:

Collecting cryptography
Downloading cryptography-36.0.1-cp36-abi3-manylinux_2_24_x86_64.whl (3.6 MB)
|████████████████████████████████| 3.6 MB 4.9 MB/s 
Requirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages 
(from cryptography) (1.15.0)
Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages
 (from cffi>=1.12->cryptography) (2.21)
Installing collected packages: cryptography
Successfully installed cryptography-36.0.1

Cryptography in Python

1)Import the Modules

# Import Fernet from fernet of the cryptography module
# using the import keyword
from cryptography.fernet import Fernet

2)Implementation

To implement cryptography, we will generate a Fernet key (sometimes known as the “secret key”) and then use the key to create a Fernet object.

This key is vital, and it must be kept secure. If someone discovers your key, he or she will be able to decode all of our secret messages; if we lose it, we will no longer be able to decrypt your own messages.

# Import Fernet from fernet of the cryptography module
from cryptography.fernet import Fernet
#Getting the value of the key using the generate_key() function
keyvalue = Fernet.generate_key()

The next step is to encrypt the text, which we do by calling the encrypt function and passing the message to it. The encrypted message will be returned by the function.

Along with this, we use the decrypt function to extract the decrypted message from the encrypted message and pass the encrypted message.

#Pass some random string by adding b as prefix to it for the encrypt function of the above fernet object 
#Here we get encrypted text
Encrypted_text = Fernet_object.encrypt(b"Hello Good morning this is BTechgeeks ")
#Getting the original Text using the decrypt function of the above fernet object 
Original_text= Fernet_object.decrypt(Encrypted_text)

3)Print the Result

Approach:

  • Import Fernet from fernet of the cryptography module
  • Getting the value of the key using the generate_key() function
  • Getting the fernet object by passing the above key value to the Fernet function
  • Pass some random string by adding b as the prefix to it for the encrypt function of the above fernet object
  • Here we get encrypted text
  • Getting the original Text using the decrypt function of the above fernet object
  • The Exit of the Program.

Full Implementation of Code

# Import Fernet from fernet of the cryptography module
from cryptography.fernet import Fernet
#Getting the value of the key using the generate_key() function
keyvalue = Fernet.generate_key()
#Getting the fernet object by passing the above key value to the Fernet function
Fernet_object= Fernet(keyvalue)
#Pass some random string by adding b as prefix to it for the encrypt function of the above fernet object 
#Here we get encrypted text
Encrypted_text = Fernet_object.encrypt(b"Hello Good morning this is BTechgeeks ")
#Getting the original Text using the decrypt function of the above fernet object 
Original_text= Fernet_object.decrypt(Encrypted_text)
print("The Encrypted Text of the Above String is:\n\n", Encrypted_text)
print("\nThe Original Text (Decrypted text) of the above string is:\n\n",Original_text)

Output:

The Encrypted Text of the Above String is:

 b'gAAAAABh-UQKPMVWcGWNdlZ5h2aeCsJIxQTTW40X9820cBKCgCcVPs2sSVT8lHLT8BgXeHLEJkJSCRQ0yPTkdw9iII_bZ3bTUA5mFKmBzAWaU_mr-7-oHrB4R-Uh3E2HysG_tTJ_O8hi'

The Original Text (Decrypted text) of the above string is:

 b'Hello Good morning this is BTechgeeks '

 

Binary search implementation python – Binary Search Algorithm in Python

Binary Search Algorithm in Python

Binary search implementation python: Practice Java programming from home without using any fancy software just by tapping on this Simple Java Programs for Beginners tutorial.

Binary Search:

A binary search is an algorithm for finding a specific element in a list. Assume we have a list of a thousand elements and we need to find the index location of a specific element. Using the binary search algorithm, we can quickly determine the index location of an element.

There are several search algorithms, but binary search is the most widely used.

To use the binary search algorithm, the elements in the list must be sorted. If the elements are not already sorted, sort them first.

Examples:

Input:

given_elements =[2, 7, 3, 4, 9, 15]   key= 9

Output:

Element 9 is found at index 4

Binary Search Algorithm in Python

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

1)Algorithm

  • We write a function that takes two arguments, the first of which is of which is the list and the second of which is the objective to be found.
  • We declare two variables start and end, which point to the list’s start (0) and end (length – 1), respectively.
  • Since the algorithm would not accept items outside of this range, these two variables are responsible for removing items from the quest.
  • The next loop will continue to locate and delete items as long as the start is less than or equal to the end, since the only time the start exceeds the end is if the item is not on the list.
  • We find the integer value of the mean of start and end within the loop and use it as the list’s middle object.

2)Implementation

Below is the implementation of linear search:

# function which return index if element is present else return -1
def binarySearch(given_list, key):
    lowindex = 0
    highindex = len(given_list) - 1
    midindex = 0
    # loop till lowindex is less than or equal to highindex
    while lowindex <= highindex:
       # Modify midindex with average of high index and lowindex
        midindex = (highindex + lowindex) // 2

        # If key is greater than mid element ignore left half side of list
        if given_list[midindex] < key:
            lowindex = midindex + 1

        # If key is less than mid element ignore right half side of list
        elif given_list[midindex] > key:
            highindex = midindex - 1

        # Else the element is present at mid index
        else:
            return midindex

    # if any value is not returned then element is not present in list
    return -1


# given_list
given_list = [2, 7, 3, 4, 9, 15]
# given key
key = 9
# sort the list
given_list.sort()
# passing the given_list and key to binarySearch function
res = binarySearch(given_list, key)
# if result is equal to -1 then element is not present in list
if(res == -1):
    print("Given element(key) is not found in list")
else:
    print("Element", key, "is found at index", res)

Output:

Element 9 is found at index 4

3)Time Complexity

Consider a basic searching algorithm such as linear search, in which we must go through each element one by one before we find what we’re looking for. This means that for larger input sizes, the time it takes to find an element grows in lockstep with the input size. Its time complexity is O measurably (n).

The term “time complexity” refers to the measurement of how quick or efficient an algorithm is. The time complexity of Binary Search is “O(log2n),” which means that if we double the size of the input list, the algorithm can only perform one additional iteration.

In the same way, if the input size is multiplied by a thousand, the loop would only need to run 10 times more.

Remember that half of the list is removed with each iteration, so eliminating the entire list won’t take long.
Related Programs:

How to print a range of numbers in python – Python Program to Print Numbers in a Range (1,upper) Without Using any Loops or by Using Recursion

Program to Print Numbers in a Range (1,upper) Without Using any Loops or by Using Recursion

How to print a range of numbers in python: Interested in programming and want to excel in it by choosing the short ways. Then, practicing with the available Java Program list is mandatory.

If we examine closely at this problem, we can see that the concept of “loop” is to track some counter value, such as “i=0″ till I = higher”. So, if we aren’t permitted to use loops, how can we track something in Python?
One option is to use ‘recursion,’ however we must be careful with the terminating condition. Here’s a solution that uses recursion to output numbers.

Examples:

Example1:

Input:

Enter some upper limit range = 11

Output:

The numbers from 1 to 11 without using loops : 
1
2
3
4
5
6
7
8
9
10
11

Example2:

Input:

Enter some upper limit range = 28

Output:

The numbers from 1 to 28 without using loops : 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

Program to Print Numbers in a Range (1,upper) Without Using any Loops/Recursive Approach

Below are the ways to print all the numbers in the range from 1 to upper without using any loops or by using recursive approach.

Method #1:Using Recursive function(Static Input)

Approach:

  • Give the upper limit range using static input.
  • Create a recursive function.
  • Create a basic case for that function in when the integer is greater than zero.
  • If the number is more than zero, call the function again with the input set to the number -1.
  • Print the number.
  • Exit of program.

Below is the implementation:

# function which prints numbers from 1 to gievn upper limit range
# without loop/by using recursion


def printNumbers(upper_limit):
  # checking if th upper limit value is greater than 0 using if statement
    if(upper_limit > 0):
      # If the number is more than zero, call the function again with
      # the input set to the number -1.
        printNumbers(upper_limit-1)
        # Print the upper limit
        print(upper_limit)


# giveen upper limt range
upper_limit = 28
print('The numbers from 1 to', upper_limit, 'without using loops : ')
# passing the given upper limit range to printNumbers
printNumbers(upper_limit)

Output:

The numbers from 1 to 28 without using loops : 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

Method #2:Using Recursive function(User Input)

Approach:

  • Scan the upper limit range using int(input()).
  • Create a recursive function.
  • Create a basic case for that function in when the integer is greater than zero.
  • If the number is more than zero, call the function again with the input set to the number -1.
  • Print the number.
  • Exit of program.

Below is the implementation:

# function which prints numbers from 1 to gievn upper limit range
# without loop/by using recursion


def printNumbers(upper_limit):
  # checking if th upper limit value is greater than 0 using if statement
    if(upper_limit > 0):
      # If the number is more than zero, call the function again with
      # the input set to the number -1.
        printNumbers(upper_limit-1)
        # Print the upper limit
        print(upper_limit)


# giveen upper limt range
upper_limit = int(input('Enter some upper limit range = '))
print('The numbers from 1 to', upper_limit, 'without using loops : ')
# passing the given upper limit range to printNumbers
printNumbers(upper_limit)

Output:

Enter some upper limit range = 11
The numbers from 1 to 11 without using loops : 
1
2
3
4
5
6
7
8
9
10
11

Explanation:

  • The user must enter the range’s top limit.
  • This value is supplied to the recursive function as an argument.
  • The recursive function’s basic case is that number should always be bigger than zero.
  • If the number is greater than zero, the function is called again with the argument set to the number minus one.
  • The number has been printed.
  • The recursion will continue until the number is less than zero.

Python divisor – Python Program to Find Smallest Prime Divisor of a Number

Program to Find Smallest Prime Divisor of a Number

Prime Divisor:

Python divisor: The prime divisor of a polynomial is a non-constant integer that is divisible by the prime and is known as the prime divisor.

Some prime divisors are 2 , 3 , 5 ,7 , 11 ,13 ,17 ,19 and 23 etc.

Divisors can be both positive and negative in character. A divisor is an integer and its negation.

Given a number, the task is to print the smallest divisor of the given number in Python.

Examples:

Example1:

Input:

Given number =91

Output:

The smallest prime divisor the number [ 91 ] is [ 7 ]

Example2:

Input:

Given number =240

Output:

The smallest prime divisor the number [ 240 ] is [ 2 ]

Program to Find Smallest Prime Divisor of a Number in Python

Below are the ways to print the smallest divisor of the given number in Python.

Enhancing programming skills is very important no matter what language you have chosen. So, practice frequently with these simple java programs examples and excel in coding the complex logic.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Take an empty list and initialize it’s with an empty list using list() and [].
  • Loop from 2 to the given number using the For loop.
  • Check if the iterator value divides the given number using the % operator and the If statement.
  • If It is true then append it to the list.
  • Print the first element of the list using the index 0.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
numb = 91
# Take an empty list and initialize it's with an empty list using list() and [].
nwlist = []
# Loop from 2 to the given number using the For loop.
for m in range(2, numb+1):
        # Check if the iterator value divides the given number
    # using the % operator and the If statement.
    if(numb % m == 0):
        # If It is true then append it to the list.
        nwlist.append(m)
smalldivisor = nwlist[0]
# Print the first element of the list using the index 0.
print(
    'The smallest prime divisor the number [', numb, '] is [', smalldivisor, ']')

Output:

The smallest prime divisor the number [ 91 ] is [ 7 ]

Method #2: Using For Loop (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Take an empty list and initialize it’s with an empty list using list() and [].
  • Loop from 2 to the given number using the For loop.
  • Check if the iterator value divides the given number using the % operator and the If statement.
  • If It is true then append it to the list.
  • Print the first element of the list using the index 0.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function and store it in a variable.
numb = int(input('Enter some random number ='))
# Take an empty list and initialize it's with an empty list using list() and [].
nwlist = []
# Loop from 2 to the given number using the For loop.
for m in range(2, numb+1):
        # Check if the iterator value divides the given number
    # using the % operator and the If statement.
    if(numb % m == 0):
        # If It is true then append it to the list.
        nwlist.append(m)
smalldivisor = nwlist[0]
# Print the first element of the list using the index 0.
print(
    'The smallest prime divisor the number [', numb, '] is [', smalldivisor, ']')

Output:

Enter some random number =240
The smallest prime divisor the number [ 240 ] is [ 2 ]

Related Programs: