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:

Two integers with the same sign – Python Program to Check Given Two Integers have Opposite signs

Program to Check Given Two Integers have Opposite signs

Two integers with the same sign: In the previous article, we have discussed Python Program to Clear nth Bit of a Number

Given two numbers the task is to check whether the given two numbers have opposite signs in Python.

Examples:

Example1:

Input:

Given First Number =3
Given Second Number = -17

Output:

The given two numbers { 3 , -17 } have opposite signs

Example2:

Input:

Given First Number =4
Given Second Number = 9

Output:

The given two numbers { 4 , 9 } have same signs

Program to Detect Given Two Integers have Opposite signs in Python

Below are the ways to check whether the given two numbers have opposite signs in Python:

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

Approach:

  • Create a function isOppositeSign() which takes the given two numbers as arguments and returns true if they have opposite sign else returns false if they have the same sign.
  • Inside the isOppositeSign() 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 less than 0 using the if conditional statement.
  • If it is true then return True
  • Else return False.
  • 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 isOppositeSign() function and store the result in a variable signResult.
  • Check if the Value of SignResult using the If conditional statement.
  • If it is true then print the given two numbers have opposite signs.
  • Else print the given two numbers have the same sign.
  • The Exit of the Program.

Below is the implementation:

# Create a function isOppositeSign()
# which takes the given two numbers as arguments and
# returns true if they have opposite sign
# else returns false if they have the same sign.


def isOppositeSign(first_numb, second_numb):
        # Inside the isOppositeSign() 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 less than 0
    # using the if conditional statement.
    if(xor_result < 0):
        # If it is true then return True
        return True
    # Else return False.
    return False


# Inside the main code.
# Give the first number as static input and store it in a variable.
firstnumb = 3
# Give the second number as static input and store it in another variable.
secondnumb = -17
# Pass the given two numbers as the arguments to isOppositeSign() function
# and store the result in a variable signResult.
signResult = isOppositeSign(firstnumb, secondnumb)
# Check if the Value of SignResult using the If conditional statement.
if(signResult):
        # If it is true then print the given two numbers have opposite signs.
    print('The given two numbers {', firstnumb,
          ',', secondnumb, '} have opposite signs')
# Else print the given two numbers have the same sign.
else:
    print('The given two numbers {', firstnumb,
          ',', secondnumb, '} have same signs')

Output:

The given two numbers { 3 , -17 } have opposite signs

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

Approach:

  • Create a function isOppositeSign() which takes the given two numbers as arguments and returns true if they have opposite sign else returns false if they have the same sign.
  • Inside the isOppositeSign() 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 less than 0 using the if conditional statement.
  • If it is true then return True
  • Else return False.
  • 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 using the int(input()) function and store it in another variable.
  • Pass the given two numbers as the arguments to isOppositeSign() function and store the result in a variable signResult.
  • Check if the Value of SignResult using the If conditional statement.
  • If it is true then print the given two numbers have opposite signs.
  • Else print the given two numbers have the same sign.
  • The Exit of the Program.

Below is the implementation:

# Create a function isOppositeSign()
# which takes the given two numbers as arguments and
# returns true if they have opposite sign
# else returns false if they have the same sign.


def isOppositeSign(first_numb, second_numb):
        # Inside the isOppositeSign() 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 less than 0
    # using the if conditional statement.
    if(xor_result < 0):
        # If it is true then return True
        return True
    # Else return False.
    return False


# 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 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 isOppositeSign() function
# and store the result in a variable signResult.
signResult = isOppositeSign(firstnumb, secondnumb)
# Check if the Value of SignResult using the If conditional statement.
if(signResult):
        # If it is true then print the given two numbers have opposite signs.
    print('The given two numbers {', firstnumb,
          ',', secondnumb, '} have opposite signs')
# Else print the given two numbers have the same sign.
else:
    print('The given two numbers {', firstnumb,
          ',', secondnumb, '} have same signs')

Output:

Enter some random number =4
Enter some random number =9
The given two numbers { 4 , 9 } have same signs

Grab the opportunity and utilize the Python Program Code Examples over here to prepare basic and advanced topics too with ease and clear all your doubts.

Simple calculator in python – Python Program to Make a Simple Calculator

Write a Program to Implement Simple Calculator

Simple calculator in python: Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language

When it comes to working with numbers and evaluating mathematical equations, the Python programming language is an excellent choice. This quality can be used to create beneficial software.

This tutorial will walk you through creating a simple command-line calculator app in Python 3. While we’ll go over one method for creating this software, there are several ways to modify the code and develop a more sophisticated calculator.

To create our calculator, we’ll employ math operators, variables, conditional statements, functions, and user input.

Program to Implement Simple Calculator

Below are the steps to implement the simple calculator in python:

1)Taking input from user

When a human enters equations for the computer to solve, it works best. We’ll begin developing our program where the human enters the numbers that they want the computer to operate with.

To accomplish this, we’ll use Python’s built-in input() function, which accepts user-generated keyboard input. We can supply a string to prompt the user inside the parenthesis of the input() function. The user’s input will be assigned to a variable.

We want the user to enter two numbers for this application, so make the software prompt for two numbers. We should include a space at the end of our string when asking for input so that the user’s input is separated from the prompting string.

# given two numbers
number1 = input("Enter the first number of which we wan to do perform calculation: ")
number2 = input("Enter the first number of which we wan to do perform calculation: ")

If you run this program a few times with different input, you’ll find that when prompted, you can enter anything you want, including words, symbols, whitespace, or just the enter key. This is due to the fact that input() accepts data as strings and is unaware that we are seeking for a number.

We want to utilize a number in this software for two reasons:

  1. To allow it to execute mathematical calculations.
  2. To ensure that the user’s input is a numerical string.

Depending on the calculator’s requirements, we may want to convert the string returned by the input() function to an integer or a float. We’ll wrap the input() function in the int() method to convert the input to the integer data type, as whole numbers suit our needs.

# given two numbers
number1 = int(input("Enter the first number of which we wan to do perform calculation: "))
number2 = int(input("Enter the first number of which we wan to do perform calculation: "))

2)Defining and implementing mathematical operators

Let’s now add operators to our Calculator software, such as addition, multiplication, division, and subtraction.

Below is the implementation:

# given two numbers
number1 = int(
    input("Enter the first number of which we wan to do perform calculation: "))
number2 = int(
    input("Enter the first number of which we wan to do perform calculation: "))
# adding the given two numbers
print('{} + {} = '.format(number1, number2))
print(number1 + number2)

# subtracting the given two numbers
print('{} - {} = '.format(number1, number2))
print(number1 - number2)

# multiplying the given two numbers
print('{} * {} = '.format(number1, number2))
print(number1 * number2)

# dividing the given two numbers
print('{} / {} = '.format(number1, number2))
print(number1 / number2)

Output:

Enter the first number of which we wan to do perform calculation: 19
Enter the first number of which we wan to do perform calculation: 13
19 + 13 = 
32
19 - 13 = 
6
19 * 13 = 
247
19 / 13 = 
1.4615384615384615

If you look at the result above, you’ll note that as soon as the user enters number 1 as 19 and number 2 as 13, the calculator does all of its operations.
We’ll have to utilize conditional statements and make the entire calculator software a user-choice based operation program if we want to limit the program to only performing one operation at a time.

3)Using conditional statements for user-choice based operation Program

So, to make the user realize what he or she is expected to choose, we’ll start by adding some information at the top of the program, along with a decision to make.

Below is the implementation:

givenChoice = input('''
Please select which type of operation which we want to apply\n
enter + for addition operation\n
enter - for subtraction  operation\n
enter * for multiplication  operation\n
enter / for division  operation\n''')
# given two numbers
number1 = int(
    input("Enter the first number of which we wan to do perform calculation: "))
number2 = int(
    input("Enter the first number of which we wan to do perform calculation: "))
if givenChoice == "+":
    # adding the given two numbers
    print('{} + {} = '.format(number1, number2))
    print(number1 + number2)
elif givenChoice == "-":
    # subtracting the given two numbers
    print('{} - {} = '.format(number1, number2))
    print(number1 - number2)
elif givenChoice == "*":
    # multiplying the given two numbers
    print('{} * {} = '.format(number1, number2))
    print(number1 * number2)
elif givenChoice == "/":
    # dividing the given two numbers
    print('{} / {} = '.format(number1, number2))
    print(number1 / number2)
else:
    print("You have entered the invalid operation")

Output:

Please select which type of operation which we want to apply

enter + for addition operation

enter - for subtraction operation

enter * for multiplication operation

enter / for division operation
+
Enter the first number of which we wan to do perform calculation: 19
Enter the first number of which we wan to do perform calculation: 13
19 + 13 = 
32

Related Programs:

Merge two list in python – Python Program to Merge Two Lists and Sort it | How to Create a Sorted Merged List of Two Unsorted Lists in Python?

Program to Merge Two Lists and Sort it

Merge two list in python: Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

There are many instances in our programming where we need to merge two unsorted lists and we might feel it difficult to write a program. If so, you need not worry anymore as we have discussed all on how to create a sorted merged list from two unsorted lists in python, methods for merging two lists and sorting them. In this Tutorial covers Each and every method for combining two unsorted lists and then how to obtain the sorted list considering enough examples.

Lists in Python

How to merge two lists in python: A list is exactly what it sounds like: a container for various Python objects such as integers, words, values, and so on. In other programming languages, it is equal to an array. It is denoted with square brackets (and this is one of the attributes that differentiates it from tuples, which are separated by parentheses). It is also mutable, which means it can be changed or altered, as opposed to tuples, which are immutable.

Given two lists the task is to merge the two given lists and sort them in Python

Combining Two Unsorted Lists and then Sort them Examples

String List:

Example 1:

Input:

given list one = ['hello', 'this', 'is', 'BTechGeeks']
given list two = ['online', 'platform', 'for', 'coding', 'students']

Output:

printing the merged list after sorting them = 
['BTechGeeks', 'coding', 'for', 'hello', 'is', 'online', 'platform', 'students', 'this']

Integer List:

Example 2

Input:

given list one = [17, 11, 13, 9, 8, 22, 29]
given list two = [3, 23, 29, 11, 98, 23, 15, 34, 37, 43, 47]

Output:

printing the merged list after sorting them = 
[3, 8, 9, 11, 11, 13, 15, 17, 22, 23, 23, 29, 29, 34, 37, 43, 47, 98]

How to Merge Two Lists in Python and Sort it?

Merge two list python: There are several ways to merge the two given lists and sort them some of them are. This tutorial can be helpful while you are dealing with multiple lists. + Operator is used to merge and then sort them by defining a method called the sort method. You can check the examples for python programs in both cases be it static input or user input and how it gets the sorted list.

  • Using + operator and sort() function (Static Input)
  • Using + operator and sort() function (User Input)

Method #1: Using + operator and sort() function(Static Input)

Approach:

  • Give two lists input as static and store them in two separate variables.
  • Using the ‘+’ operator, merge both the first list and the second list, store it in a variable.
  • Sort the lists using the sort() function.
  • Print the list after sorting them.
  • The exit of Program.

i)String List

Write a Program to Merge Two Lists and Sort them on giving Static Input in Python?

# given first list
given_list1 = ['hello', 'this', 'is', 'BTechGeeks']
# given second list
given_list2 = ['online', 'platform', 'for', 'coding', 'students']
# merging both lists and storing it in a variable
mergedList = given_list1+given_list2
# sorting the merged list using sort() function
mergedList.sort()

# printing the merged list after sorting them
print('printing the merged list after sorting them = ')
print(mergedList)

Python Program to Merge Two Lists and Sort them(Static Input)

Output:

printing the merged list after sorting them = 
['BTechGeeks', 'coding', 'for', 'hello', 'is', 'online', 'platform', 'students', 'this']

ii)Integer List

Below is the implementation:

# given first list
given_list1 = [17, 11, 13, 9, 8, 22, 29]
# given second list
given_list2 = [3, 23, 29, 11, 98, 23, 15, 34, 37, 43, 47]
# merging both lists and storing it in a variable
mergedList = given_list1+given_list2
# sorting the merged list using sort() function
mergedList.sort()

# printing the merged list after sorting them
print('printing the merged list after sorting them = ')
print(mergedList)

Output:

printing the merged list after sorting them = 
[3, 8, 9, 11, 11, 13, 15, 17, 22, 23, 23, 29, 29, 34, 37, 43, 47, 98]

Method #2: Using + operator and sort() function (User Input)

Approach:

  • Scan the two lists using user input functions.
  • Using ‘+’ operator, merge both the first list, the second list and store them in a variable.
  • Sort the lists using the sort() function.
  • Print the sorted list.
  • The exit of Program.

i)String List

Merge two list in python: Scan the list using split() ,input() and list() functions.

Write a python program to merge two lists and sort it take input from the user and display the sorted merged list?

Below is the implementation to merge two lists and sort them

# scanning the first string list using split() and input() functions
given_list1 = list(input(
    'Enter some random string elements in list one separated by spaces = ').split())
# scanning the second string list using split() and input() functions
given_list2 = list(input(
    'Enter some random string elements in list one separated by spaces = ').split())
# merging both lists and storing it in a variable
mergedList = given_list1+given_list2
# sortin the merged list using sort() function
mergedList.sort()

# printing the merged list after sorting them
print('printing the merged list after sorting them = ')
print(mergedList)

Python Program to Merge Two Lists and Sort them(User Input)

Output:

Enter some random string elements in list one separated by spaces = hello this is btechgeeks
Enter some random string elements in list one separated by spaces = online coding platoform for coding students
printing the merged list after sorting them = 
['btechgeeks', 'coding', 'coding', 'for', 'hello', 'is', 'online', 'platoform', 'students', 'this']

ii)Integer List

Scan the list using split() ,map(),input() and list() functions.

map() function converts the every string element in the given list to integer.

Below is the implementation:

# scanning the first string list using split() and input() functions
given_list1 = list(map(int,input(
    'Enter some random string elements in list one separated by spaces = ').split()))
# scanning the second string list using split() and input() functions
given_list2 = list(map(int,input(
    'Enter some random string elements in list one separated by spaces = ').split()))
# merging both lists and storing it in a variable
mergedList = given_list1+given_list2
# sorting the merged list using sort() function
mergedList.sort()

# printing the merged list after sorting them
print('printing the merged list after sorting them = ')
print(mergedList)

Output:

Enter some random string elements in list one separated by spaces = 48 79 23 15 48 19 7 3 5 4 2 98 75 123 456 81 8 5
Enter some random string elements in list one separated by spaces = 1 3 5 11 58 23 97 17 19 23 29 75 36 43
printing the merged list after sorting them = 
[1, 2, 3, 3, 4, 5, 5, 5, 7, 8, 11, 15, 17, 19, 19, 23, 23, 23, 29, 36, 43, 48, 48, 58, 75, 75, 79, 81, 97, 98, 123, 456]

Similar Tutorials:

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:

Numpy ptp – Python NumPy ptp() Function

Python NumPy ptp() Function

NumPy ptp() Function:

Numpy ptp: The ptp() function of the NumPy module returns an array’s range of values (maximum – minimum) or a range of values along a specified axis.

The function’s name is derived from the abbreviation for peak to peak.

Syntax:

numpy.ptp(a, axis=None, out=None, keepdims=<no value>)

Parameters

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

axis: This is optional. It indicates the axis or axes along which we want the range value. The input array is flattened by default axis=None (that is working on all the axis). Axis = 0 denotes working along the column, while axis = 1 denotes working along the row.

out: This is optional. It specifies an alternate array in which the function’s result or output should be stored. The array’s dimensions must match those of the desired output.

keepdims: This is optional. The reduced axes are left in the outcome 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:

Numpy ptp: The ptp() function returns a range of “a” values. The output is a scalar value if the axis is None. If the axis is specified, an array of size a.ndim – 1 is returned.

NumPy ptp() Function in Python

Example1

np.ptp: Here, the array’s range of values is returned using the ptp() method.

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 as an argument to the ptp() function of numpy module to get the range of values(maximum-minimum) of the given array.
  • Store it in another variable.
  • Print the above result.
  • 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],[35, 40]])              
# Print the above given array.
print("The above given array is:")
print(gvn_arry)
# Pass the given array as an argument to the ptp() function of numpy module 
# to get the range of values(maximum - minimum) of the given array 
# Store it in another variable.
rslt = np.ptp(gvn_arry)
# Print the above result
print("The range =", rslt)

Output:

The above given array is:
[[ 5 25]
 [35 40]]
The range = 35

Example2

Here, the ptp() function of numpy module is used to get the range of values(maximum – minimum) of the given array along axis=0

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, axis=0 as the arguments to the ptp() function of numpy module to get the range of values(maximum – minimum) of the given array along axis=0.
  • Store it in another variable.
  • Print the values range of the given array along axis=0.
  • 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:")
print(gvn_arry)
# Pass the given array, axis=0 as the arguments to the ptp() function of numpy module 
# to get the range of values(maximum - minimum) of the given array along axis=0 
# Store it in another variable.
rslt = np.ptp(gvn_arry, axis=0 )
# Print the values range of the given array along axis=0
print("The values range along axis=0 is: ", rslt)

Output:

The above given array is:
[[ 5 25 50]
 [35 40 60]]
The values range along axis=0 is: [30 15 10]

Example3

Here, the ptp() function of numpy module is used to get the range of values(maximum – minimum) of the given array along axis=1

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:")
print(gvn_arry)
# Pass the given array, axis=1 as the arguments to the ptp() function of numpy module 
# to get the range of values(maximum - minimum) of the given array along axis=1 
# Store it in another variable.
rslt = np.ptp(gvn_arry, axis=1 )
# Print the values range of the given array along axis=1
print("The values range along axis=1 is: ", rslt)

Output:

The above given array is:
[[ 5 25 50]
 [35 40 60]]
The values range along axis=1 is: [45 25]