Vikram Chiluka

Python Program to Print the Natural Numbers Summation Pattern

Python Program to Print the Natural Numbers Summation Pattern

Natural Numbers:

Natural numbers are a subset of the number system that includes all positive integers from one to infinity. Natural numbers, which do not include zero or negative numbers, are also known as counting numbers. They are a subset of real numbers that include only positive integers and exclude zero, fractions, decimals, and negative numbers.

Given a number the task is to print the natural numbers summation Pattern

Examples:

Example1:

Input:

given number = 7

Output:

1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
1 + 2 + 3 + 4 + 5 + 6 = 21
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28

Example2:

Input:

given number = 9

Output:

1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
1 + 2 + 3 + 4 + 5 + 6 = 21
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45

Program to Print the Natural Numbers Summation Pattern in Python

There are several ways to print the natural numbers summation pattern in Python 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 nested for loops (Static Input)

Approach:

  • Take the value of the given number as static  and store it in a variable numb.
  • Use two for loops where the value of i is between 1 and numb and the value of j is between 1 and i
  • Take a empty list
  • Add values of i to the list using append() function.
  • While adding the value of j to a list, print the value of j and the ‘+’ operator.
  • Then compute the sum of the elements in the list using sum() function
  • Print the symbol ‘=’ followed by the total sum calculated in the above step.
  • End of program

Below is the implementation:

# given number
numb = 15
# traversing from 1 to numb using for loop
for i in range(1, numb+1):
  # taking a empty list
    emptylist = []
    # traversing from 1 to i
    for j in range(1, i+1):
      # printing the value of j
        print(j, sep=" ", end=" ")
        if(j < i):
            print("+", sep=" ", end=" ")
        # appending/adding the value to the empty list
        emptylist.append(j)
    # printing the sum of emptylist
    print("=", sum(emptylist))

Output:

1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
1 + 2 + 3 + 4 + 5 + 6 = 21
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 = 66
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 = 78
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 = 91
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 = 105
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 = 120

Explanation:

  • Consider the provided number’s value to be static
  • This number is iterated again and over.
  • An empty list has been defined.
  • A new ‘for’ loop is started.
  • The separator is set to ‘’.
  • The ‘+’ symbol is used if the value of the inner iterator is smaller than the value of the outer iterator.
  • These values are added to the existing empty list.
  • Their total is computed and shown as the output.

Method #2: Using nested for loops and mathematical formula (Static input)

Approach:

  • Take the value of the given number as static and store it in a variable numb.
  • Use two for loops where the value of i is between 1 and numb and the value of j is between 1 and i
  • print the value of j and the ‘+’ operator.
  • Then compute the sum of the element i using mathematic formula for sum of n natural numbers
  • Print the symbol ‘=’ followed by the total sum calculated in the above step.
  • End of program

Mathematical formula for sum of n natural numbers  :

( numb * (numb+1) ) /2

Below is the implementation:

# given number
numb = 9
# traversing from 1 to numb using for loop
for i in range(1, numb+1):
    # traversing from 1 to i
    for j in range(1, i+1):
      # printing the value of j
        print(j, sep=" ", end=" ")
        if(j < i):
            print("+", sep=" ", end=" ")
    # calculating sum of the n natural numbers using mathematical formula
    naturalSum = (i*(i+1))//2
    # printing the total sum
    print("=", naturalSum)

Output:

1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
1 + 2 + 3 + 4 + 5 + 6 = 21
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45

Method #3: Using nested for loops and mathematical formula (User input)

Approach:

  • Scan the input from user using input() function and store it in a variable numb
  • Convert this numb to integer using numb function
  • Use two for loops where the value of i is between 1 and numb and the value of j is between 1 and i
  • print the value of j and the ‘+’ operator.
  • Then compute the sum of the element i using mathematic formula for sum of n natural numbers
  • Print the symbol ‘=’ followed by the total sum calculated in the above step.
  • End of program

Mathematical formula for sum of n natural numbers  = ( numb * (numb+1) ) /2

Below is the implementation:

# given number
numb = input("Enter your desired number = ")
# conveerting numb to integer using int() function
numb = int(numb)
# traversing from 1 to numb using for loop
for i in range(1, numb+1):
    # traversing from 1 to i
    for j in range(1, i+1):
      # printing the value of j
        print(j, sep=" ", end=" ")
        if(j < i):
            print("+", sep=" ", end=" ")
    # calculating sum of the n natural numbers using mathematical formula
    naturalSum = (i*(i+1))//2
    # printing the total sum
    print("=", naturalSum)

Output:

Enter your desired number = 9
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
1 + 2 + 3 + 4 + 5 + 6 = 21
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36
1 +2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45

Related Programs:

Python Program to Find Whether a Number is a Power of Two

Python Program to Find Whether a Number is a Power of Two

In this tutorial, the power of 2 or not for python programming can be checked. The user gives a positive integer N and we have to check if it is equivalent to 2^x or not, where x can be zero or a number positive.

Examples:

Example1:

Input:

given number =2048

Output:

The given numb 2048 is power of 2

Example2:

Input:

given number =256

Output:

The given numb 256 is power of 2

Example3:

Input:

given number =678

Output:

The given numb 678 is not power of 2

Program to Find Whether a Number is a Power of Two in Python

There are several ways to check whether the given number is a power of 2 or not 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 log function

  • This answer is just a mathematical one.
  • If the log2(n) of the given number n is integer than it is power of 2
  • Else it is not power of 2.

Below is the implementation:

# importing log from math
from math import log
# given number
numb = 2048
# given base (here it is 2 as we have to check whether it is power of 2 or not)
bas = 2
# calculating log2 of the  given numb using log function
logvalue = log(numb, bas)
# if the value is integer then it is power of 2
if (int(logvalue) == logvalue):
    print("The given numb", numb, "is power of 2")
# else it is not power of 2
else:
    print("The given numb", numb, "is not power of 2")

Output:

The given numb 2048 is power of 2

Method #2:Using while loop

Continue dividing the number into two, i.e. do n = n/2 as long as n is 1 If n percent 2 is non-zero and n is not 1 in all iteration, then n is not 2. It is a power of 2, if n becomes 1.

Below is the implementation:

# function which returns true if the given number is power of 2 else it reeturns false


def checktwoPower(numb):
    # checking if the number is 0
    if (numb == 0):
      # if the number is 0 then it is not power of 2 hence return false
        return False
    # using while loop to iterate till the number not equal to 1
    while (numb != 1):
        # if the bit is set bit then it is not power of 2 so return False
        if (numb % 2 != 0):
            return False
            # dividing n
        numb = numb // 2
    return True


# given number
numb = 2048
# passing the given number to checktwoPower function
# if the value is integer then it is power of 2
if (checktwoPower(numb)):
    print("The given numb", numb, "is power of 2")
# else it is not power of 2
else:
    print("The given numb", numb, "is not power of 2")

Output:

The given numb 2048 is power of 2

Method #3:Using Bitwise Operators

If the number is 2 power, the binary representation of only 1 bit is set.
If we remove 1 from a power number 2, then all the bits are set and the set bit is unset after the set bits (just one bits are set according to point-1)

Therefore, if a number is 2, then

numb&(numb-1) == 0

Only if N is zero is the exception to the foregoing rule. As a power of two, it will give zero which in fact is not. Therefore, we can explicitly see this in the check.

Below is the implementation:

# function which returns true if the given number is power of 2 else it reeturns false


def checktwoPower(numb):
    return numb and (not(numb & (numb-1)))


# given number
numb = 2048
# passing the given number to checktwoPower function
# if the value is integer then it is power of 2
if (checktwoPower(numb)):
    print("The given numb", numb, "is power of 2")
# else it is not power of 2
else:
    print("The given numb", numb, "is not power of 2")

Output:

The given numb 2048 is power of 2

Method #4:By Calculating total number of set bits

A simple method is to take each bit into consideration in a number (set or unset) and hold a counter to track the set bits if the total number of set bits is 1 then the number is power of 2 else it is not the power of 2

Approach:

  • Set the variable to say count to 0 to count the total number of set bits.
  • We utilize the while loop.
  • We’ll keep going till the number is bigger than zero (Condition of while statement)
  • Using the & operator, we will determine whether the last check bit is set or not.
  • If the check bit is 1, it indicates that the bit is set, and we increment the count.
  • Divide the given number by 2.
  • If the count is 1 then it is the power of 2 hence return true
  • Else return false

We use n&1 to check whether it is set bit or not.

Below is the implementation:

# function which returns true if the given number is power of 2 else it reeturns false


def checktwoPower(numb):
    # checking if the given number is greater than 1
    if numb > 1:
      # Set the variable say setbitcount to 0 to count the total number of set bits.
        setbitcount = 0
        # looping till number greater than 0 using while loop
        while(numb > 0):
            # We will get the last check bit whether it is set bit or not using & operator
            # checking if the check bit is 1 or not
            # if the check bit is 1 then increment the setbitcount
            if(numb & 1):
                setbitcount = setbitcount+1
            # divide the number by 2
            numb = numb//2
    # checking if the total number of setbits are 1 or not
    return (setbitcount == 1)


# given number
numb = 2048
# passing the given number to checktwoPower function
# if the value is integer then it is power of 2
if (checktwoPower(numb)):
    print("The given numb", numb, "is power of 2")
# else it is not power of 2
else:
    print("The given numb", numb, "is not power of 2")

Output:

The given numb 2048 is power of 2

Related Programs:

The Difference Between == and is in Python

The Difference Between == and is in Python

In Python, the operators == and is do very similar functions, yet they are extremely different and deal with a very important concept: how Python saves its variables in memory.

There is a small distinction between the Python identity operator (is) and the equality operator (==). When you use the Python is operator to compare numbers, your code may work great until it suddenly does not. You may have heard that the Python is operator is faster than the == operator, or you may believe that it appears more Pythonic. However, it is critical to remember that these operators do not behave in the same way.

The Python is operator checks if two variables link to the same object in memory, whereas the == operator compares the value or equality of two objects. Except when comparing to None, which means you should utilise the equality operators == and!= in the vast majority of situations.

Understanding the difference Between == and ‘is’ 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.

Difference #1: Implementation

== compares the values of the two operands and returns True if they are the same, False otherwise.
is compares the object IDs of the two operands and returns True if they match.

But what exactly is an object ID? In memory, each object is assigned an ID, and two variables can point to the same item, giving them the same object ID.

listone = ["this", "is", "BTechGeeks"]
listtwo = ["this", "is", "BTechGeeks"]
print(listone == listtwo)
print(listone is listtwo)
# assigning list two with list one
listtwo = listone
print("After assigning list two with list one:")
# using is
print(listone is listtwo)

Output:

True
False
After assigning list two with list one:
True

In the preceding example, there are two lists in memory at first, but they contain the identical values.

== compares values and returns True if the operation is successful.
However, it tests to see if they point to the same object, and because these lists do not link to the same object, it returns False.
After that, we set listwo equal to listone, which causes listwo to point to where listone is pointing, and it returns True.
All of this is extremely different for integers, and in order to grasp this, we must first understand how objects are stored in memory.

Difference #2:Memory Allocation

Let us take a number and initialize it with 6 as below

number=6

We know the number has the value 6, but how does it become stored in memory? In Python, each object has four memory parts:

Size — For each object, four bytes are reserved to store the object’s size.
Reference Count – For each object, 8 bytes are reserved to store the number of variables pointing to this object. And all of these objects will have this object’s object ID.
Object Type — For each object, 8 bytes are reserved to retain information indicating the type of object.
Object Value — An additional 8 bytes are reserved for each item and contain the object’s actual value.

Object value and reference count are the two most significant items in the preceding list for this topic.

So, for number = 6, there is an object in memory with object value 6 and reference count 1, indicating that the object has a value of 6 and one variable, in this case number, is pointing towards it.

Let us now declare another variable as follows:

number = 6
number2 = number
print(number == number2)
print(number is number2)

Output:

True
True

Now, something very fascinating will happen in memory: no new objects will be generated, and number 2 will also point to where number is pointing, and the object’s reference count will increase to 2.

As a result, number and number 2 will have the same object ID, like the above output.

But what if we do as given below?

number = 6
number2 = 6
print(number == number2)
print(number is number2)

Output:

True
True

Related Programs:

Program for Bubble Sort in Python

Python Program for Bubble Sort

What exactly is sorting? What’s the big deal about it? In this part, we will attempt to answer these questions.

We’ve sorted everything from books in a library to words in a dictionary to database entries and processor instructions on a number of occasions.
This means that when we sort things, we must first determine the criteria by which we will organize the items in the sequence provided to us. For the purposes of this lesson, we’ll suppose that the criteria is a number’s value, and we’ll sort a set of numbers.

The most significant goal of sorting in computer science is to create efficient algorithms. Binary Search is a lightning-fast search algorithm that would be impossible to use in an unsorted set of objects.

On sorted data, almost all set operations are extremely fast.

Apart from creating efficient algorithms, sorting is employed when a program’s sole purpose is to sort things, such as when working with a deck of cards. As a result, sorting algorithms are one of the most important things for a programmer to understand.

Sorting algorithms are programs that reorganize a huge number of elements into a certain order, such as from highest to lowest, or vice versa, or even alphabetically.

These algorithms take an input list, process it (that is, perform operations on it), and then return a sorted list.
The importance of sorting comes from the idea that if data is kept in a sorted fashion, data searching may be greatly improved. Sorting can also be used to display data in a more legible fashion. The instances of sorting in real-life circumstances are as follows:

Telephone Directory :The telephone directory keeps track of people’s phone numbers, which are classified by their names so that they may be quickly found.

Dictionary : The dictionary organizes terms alphabetically so that searching for a specific word is simple.

Examples:

Sorting in Ascending order

Example1:

Input:

givenlist = [8, 132, 22, 34, 57, 2, 1, 9, 45, 87, 63, 80, 26, 65, 132]

Output:

printing the list before sorting :
8 132 22 34 57 2 1 9 45 87 63 80 26 65 132 
printing the list after sorting :
1 2 8 9 22 26 34 45 57 63 65 80 87 132 132

Example2:

Input:

givenlist = ["hello", "this", "is", "BTechGeeeks", "python", "new", "online",
                   "platform", "for", "all", "students", "who", "are", "excited", "about", "coding"]

Output:

printing the list before sorting :
hello this is BTechGeeeks python new online platform for all students who are excited about coding 
printing the list after sorting :
BTechGeeeks about all are coding excited for hello is new online platform python students this who

Sorting in descending order example

Example 3:

Input:

Input:

givenlist = [8, 132, 22, 34, 57, 2, 1, 9, 45, 87, 63, 80, 26, 65, 132]

Output:

printing the list before sorting :
8 132 22 34 57 2 1 9 45 87 63 80 26 65 132 
printing the list after sorting :
132 132 87 80 65 63 57 45 34 26 22 9 8 2 1

Example4:

Input:

givenlist = ["hello", "this", "is", "BTechGeeeks", "python", "new", "online",
                   "platform", "for", "all", "students", "who", "are", "excited", "about", "coding"]

Output:

printing the list before sorting :
hello this is BTechGeeeks python new online platform for all students who are excited about coding 
printing the list after sorting :
who this students python platform online new is hello for excited coding are all about BTechGeeeks

Program for Bubble Sort 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)Bubble Sort Introduction

In their Computer Science course, Bubble Sort is most likely the first sorting algorithm they learned about.

It’s very natural and simple to “translate” into code, which is vital for new software engineers who are learning how to turn their thoughts into something that can be executed on a computer. Bubble Sort, on the other hand, is one of the worst-performing sorting algorithms in all cases except when testing whether the array has previously been sorted, where it frequently beats more efficient sorting algorithms like Quick Sort.

2)Working of Bubble Sort (Brief)

Consider how the bubbles in a glass of soda climb up. The greatest/smallest element in a sequence is represented by the bubbles, and the increasing movements of the bubbles reflect how the greatest/smallest element travels to the end/beginning of the sequence.
Simply explained, we repeat the sequence numerous times, swapping numerous pairs of elements each time so that the greatest/smallest element in the sequence ends up at one of the sequence’s endpoints.

For the sake of this tutorial, we’ll use the given array and sort it in ascending order of the numbers’ values.

3)Algorithm

Below is the algorithm for Bubble Sort:

  1. Count the number of elements in total. Find out how many items there are in the provided list.
  2. Calculate the number of outer passes (n – 1) that will be required. It has a length of one less than a list.
  3. For outer pass 1, make (n – 1) inner passes. Get the value of the first element and compare it to the value of the second element. If the second value is smaller than the first, the places/positions should be swapped.
  4. Continue in this manner until you reach the outer pass (n – 1). Get the next entry in the list, then continue the process from step 3 until all of the values are in ascending order.
  5. After all passes have been completed, return the result. Return the sorted list’s results.

4)Implementation

Below is the implementation of BubbleSort:

Sorting the given list in Ascending Order:

# function which implements the bubble_sort algorithm for givenlist
def bubbleSort(givenlist):
  # finding the length of given list
    length = len(givenlist)
    # using nested for loops
    for i in range(length-1):
        for j in range(length-i-1):
          # checking if the jth element is greater than j+1 th element
            if(givenlist[j] > givenlist[j+1]):
              # if it is greater then swap the elements
                givenlist[j], givenlist[j+1] = givenlist[j+1], givenlist[j]


# given list
givenlist = [8, 132, 22, 34, 57, 2, 1, 9, 45, 87, 63, 80, 26, 65, 132]
# printing the list before sorting
print("printing the list before sorting :")
for i in givenlist:
    print(i, end=" ")
print()
# passing this given list to bubbleSort function which sorts the given list
bubbleSort(givenlist)
# printing the list after sorting
print("printing the list after sorting :")
for i in givenlist:
    print(i, end=" ")

Output:

printing the list before sorting :
8 132 22 34 57 2 1 9 45 87 63 80 26 65 132 
printing the list after sorting :
1 2 8 9 22 26 34 45 57 63 65 80 87 132 132

Sorting the given list in Descending order

Below is the implementation of BubbleSort:

# function which implements the bubble_sort algorithm for givenlist
def bubbleSort(givenlist):
  # finding the length of given list
    length = len(givenlist)
    # using nested for loops
    for i in range(length-1):
        for j in range(length-i-1):
          # checking if the jth element is less than j+1 th element
            if(givenlist[j] < givenlist[j+1]):
              # if it is greater then swap the elements
                givenlist[j], givenlist[j+1] = givenlist[j+1], givenlist[j]


# given list
givenlist = ["hello", "this", "is", "BTechGeeeks", "python", "new", "online",
             "platform", "for", "all", "students", "who", "are", "excited", "about", "coding"]
# printing the list before sorting
print("printing the list before sorting :")
for i in givenlist:
    print(i, end=" ")
print()
# passing this given list to bubbleSort function which sorts the given list
bubbleSort(givenlist)
# printing the list after sorting
print("printing the list after sorting :")
for i in givenlist:
    print(i, end=" ")

Output:

printing the list before sorting :
hello this is BTechGeeeks python new online platform for all students who are excited about coding 
printing the list after sorting :
who this students python platform online new is hello for excited coding are all about BTechGeeeks

5)Time Complexity

The bubble sort has an O time complexity (n^2)

The following are examples of time complexities:

Worst case scenario: the provided list is in descending order. The algorithm executes as many executions as possible, which is denoted as [Big-O]
Best case : When the provided list is already sorted, this is the best case scenario. The algorithm executes the fewest number of times possible, which is denoted as [Big-Omega]? (N)
Average Case :When the list is in random order, this is the average situation. [Big-theta](n^2) is a symbol for average complexity

6)Conclusion

We learnt what sorting is and how it is used in this tutorial, then we learnt how Bubble Sort works, devised an algorithm, and implemented Bubble Sort in Python.

Bubble Sort is one of many sorting algorithms available, and while it is not the greatest, it is simple to construct. The difficulty of this approach is O(n^2), which implies that if the number of elements in the list is doubled, the time it takes to sort them with this approach will increase by four times.

As a result, this technique becomes inefficient when dealing with big amounts of data. As a coder, though, understanding Bubble Sort is critical.
Related Programs:

Program for Insertion Sort in Python

Python Program for Insertion Sort

What exactly is sorting? What’s the big deal about it? In this part, we will attempt to answer these questions.

We’ve sorted everything from books in a library to words in a dictionary to database entries and processor instructions on a number of occasions.
This means that when we sort things, we must first determine the criteria by which we will organize the items in the sequence provided to us. For the purposes of this lesson, we’ll suppose that the criteria is a number’s value, and we’ll sort a set of numbers.

The most significant goal of sorting in computer science is to create efficient algorithms. Binary Search is a lightning-fast search algorithm that would be impossible to use in an unsorted set of objects.

On sorted data, almost all set operations are extremely fast.

Apart from creating efficient algorithms, sorting is employed when a program’s sole purpose is to sort things, such as when working with a deck of cards. As a result, sorting algorithms are one of the most important things for a programmer to understand.

Sorting algorithms are programs that reorganize a huge number of elements into a certain order, such as from highest to lowest, or vice versa, or even alphabetically.

These algorithms take an input list, process it (that is, perform operations on it), and then return a sorted list.
The importance of sorting comes from the idea that if data is kept in a sorted fashion, data searching may be greatly improved. Sorting can also be used to display data in a more legible fashion. The instances of sorting in real-life circumstances are as follows:

Telephone Directory :The telephone directory keeps track of people’s phone numbers, which are classified by their names so that they may be quickly found.

Dictionary : The dictionary organizes terms alphabetically so that searching for a specific word is simple.

Examples:

Sorting in Ascending order

Example1:

Input:

givenlist = [8, 132, 22, 34, 57, 2, 1, 9, 45, 87, 63, 80, 26, 65, 132]

Output:

printing the list before sorting :
8 132 22 34 57 2 1 9 45 87 63 80 26 65 132 
printing the list after sorting :
1 2 8 9 22 26 34 45 57 63 65 80 87 132 132

Example2:

Input:

givenlist = ["hello", "this", "is", "BTechGeeeks", "python", "new", "online",
                   "platform", "for", "all", "students", "who", "are", "excited", "about", "coding"]

Output:

printing the list before sorting :
hello this is BTechGeeeks python new online platform for all students who are excited about coding 
printing the list after sorting :
BTechGeeeks about all are coding excited for hello is new online platform python students this who

Sorting in descending order example

Example 3:

Input:

Input:

givenlist = [8, 132, 22, 34, 57, 2, 1, 9, 45, 87, 63, 80, 26, 65, 132]

Output:

printing the list before sorting :
8 132 22 34 57 2 1 9 45 87 63 80 26 65 132 
printing the list after sorting :
132 132 87 80 65 63 57 45 34 26 22 9 8 2 1

Example4:

Input:

givenlist = ["hello", "this", "is", "BTechGeeeks", "python", "new", "online",
                   "platform", "for", "all", "students", "who", "are", "excited", "about", "coding"]

Output:

printing the list before sorting :
hello this is BTechGeeeks python new online platform for all students who are excited about coding 
printing the list after sorting :
who this students python platform online new is hello for excited coding are all about BTechGeeeks

Program for Insertion Sort 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)Insertion Sort Introduction

While playing cards, we compare the hands of cards to one another. The majority of players choose to sort the cards in ascending order so that they can immediately see which combinations they have.

Because it’s usually taught in the first programming class, the insertion sort implementation is simple and straightforward. It’s a stable and in-place algorithm that works well with nearly-sorted or fewer elements.

Because it uses a nested loop to sort the elements, the insertion sort method is slow.

The insertion sort, on the other hand, does not require prior knowledge of the array size and only gets one member at a time.

The advantage of the insertion sort is that if we input more elements to be sorted, the algorithm puts them in their right order without having to do a full sort.

It is more efficient for tiny arrays (less than 10). Let’s look at the insertion sort concepts now.

2)Algorithm and Working of insertion Sort

In the sorted section, there is only one element at first, which is the very first one (The sorted section is at the beginning of the list).

We need an index to keep track of where the unsorted portion begins, and since the unsorted portion begins with the second element, the index must be 1. (In the case of Python).
Now we try to locate the first element from the unsorted portion (the element at the unsorted index) in the sorted part.

We do this by comparing it to each element in the sorted section one by one until we locate an element that is smaller (in ascending order) or larger (in descending order) than the new element.

Then we place it in the appropriate location and reorder all of the sorted elements to make room for the new element. The procedure is repeated until the array is completely sorted.

In the insertion sort, the array split into two parts: an unsorted component and a sorted part.

The first element of the array is in the sorted subpart, while the rest of the array is in the unsorted subpart. The initial element in the unsorted array is compared to the sorted array to determine which sub-array it belongs to.

If the right-side value is smaller than the left-side value, it focuses on inserting the elements by relocating all elements.

It will happen again and again until all of the elements are correctly put.

The algorithm for sorting an array using insertion sort is shown below.

  • divide a list into two parts: sorted and unsorted.
  • Iterate through the array from arr[1] to arr[n].
  • Compare the current element with the following element.
  • If the current element is less than the next element as compared to the previous element, To make space for the swapped element, move one position up to the bigger elements.

3)Implementation:

Below is the implementation of Insertion Sort:

Sorting the given list in Ascending Order:

# function which implements the insertion_sort  algorithm for givenlist
def insertion_sort(givenlist):

    # Traverse the list from 1 to length of the list
    for i in range(1, len(givenlist)):

        elementValue = givenlist[i]

        # List1[0..i-1] elements that are greater than value
        # should be moved one position ahead of their current location.
        j = i - 1
        while j >= 0 and elementValue < givenlist[j]:
            givenlist[j + 1] = givenlist[j]
            j -= 1
        givenlist[j + 1] = elementValue


# given list
givenlist = ["hello", "this", "is", "BTechGeeeks", "python", "new", "online",
             "platform", "for", "all", "students", "who", "are", "excited", "about", "coding"]
# printing the list before sorting
print("printing the list before sorting :")
for i in givenlist:
    print(i, end=" ")
print()
# passing this given list to insertion_sort function which sorts the given list
insertion_sort(givenlist)
# printing the list after sorting
print("printing the list after sorting :")
for i in givenlist:
    print(i, end=" ")

Output:

printing the list before sorting :
hello this is BTechGeeeks python new online platform for all students who are excited about coding 
printing the list after sorting :
BTechGeeeks about all are coding excited for hello is new online platform python students this who

Explanation : Here we can see that the given list of strings is sorted in Ascending order

Sorting the given list in Descending order

Below is the implementation of InsertionSort:

# function which implements the insertion_sort  algorithm for givenlist
def insertion_sort(givenlist):

    # Traverse the list from 1 to length of the list
    for i in range(1, len(givenlist)):

        elementValue = givenlist[i]

        # List1[0..i-1] elements that are less than value
        # should be moved one position ahead of their current location.
        j = i - 1
        while j >= 0 and elementValue > givenlist[j]:
            givenlist[j + 1] = givenlist[j]
            j -= 1
        givenlist[j + 1] = elementValue


# given list
givenlist = ["hello", "this", "is", "BTechGeeeks", "python", "new", "online",
             "platform", "for", "all", "students", "who", "are", "excited", "about", "coding"]
# printing the list before sorting
print("printing the list before sorting :")
for i in givenlist:
    print(i, end=" ")
print()
# passing this given list to insertion_sort function which sorts the given list
insertion_sort(givenlist)
# printing the list after sorting
print("printing the list after sorting :")
for i in givenlist:
    print(i, end=" ")

Output:

printing the list before sorting :
hello this is BTechGeeeks python new online platform for all students who are excited about coding 
printing the list after sorting :
who this students python platform online new is hello for excited coding are all about BTechGeeeks

Explanation : Here we can see that the given list of strings is sorted in Descending order

4)Time Complexity

An array would be sorted in reverse order in the worst-case situation. In the Insertion Sort function, the outer for loop iterates n-1 times.
The inner for loop would swap once, then two, and so on in the worst-case situation. The number of swaps is then 1 + 2 +… + (n – 3) + (n – 2) + (n – 1), giving Insertion Sort an O(n2) time complexity.

5)Conclusion

We examined how Insertion Sort is comparable to how we sort things in real life, examined the technique it employs, and implemented Insertion Sort in Python in this tutorial.

After that, we spoke about how the algorithm works and ran it on an unsorted sample to see how it works. Finally, we used the actual output of the code to verify the dry run. Insertion sort, like Bubble Sort, has an O (n^2)level of complexity .

Similarly, doubling the input size increases the time it takes to execute by four times, and tripling the input size increases the time it takes to execute by nine times.

The algorithm is inefficient for practical application as a result of this, but it is a highly intuitive approach.
Related Programs:

Program for Selection Sort in Python

Python Program for Selection Sort

What exactly is sorting? What’s the big deal about it? In this part, we will attempt to answer these questions.

We’ve sorted everything from books in a library to words in a dictionary to database entries and processor instructions on a number of occasions.
This means that when we sort things, we must first determine the criteria by which we will organize the items in the sequence provided to us. For the purposes of this lesson, we’ll suppose that the criteria is a number’s value, and we’ll sort a set of numbers.

The most significant goal of sorting in computer science is to create efficient algorithms. Binary Search is a lightning-fast search algorithm that would be impossible to use in an unsorted set of objects.

On sorted data, almost all set operations are extremely fast.

Apart from creating efficient algorithms, sorting is employed when a program’s sole purpose is to sort things, such as when working with a deck of cards. As a result, sorting algorithms are one of the most important things for a programmer to understand.

Sorting algorithms are programs that reorganize a huge number of elements into a certain order, such as from highest to lowest, or vice versa, or even alphabetically.

These algorithms take an input list, process it (that is, perform operations on it), and then return a sorted list.
The importance of sorting comes from the idea that if data is kept in a sorted fashion, data searching may be greatly improved. Sorting can also be used to display data in a more legible fashion. The instances of sorting in real-life circumstances are as follows:

Telephone Directory :The telephone directory keeps track of people’s phone numbers, which are classified by their names so that they may be quickly found.

Dictionary : The dictionary organizes terms alphabetically so that searching for a specific word is simple.

Examples:

Sorting in Ascending order

Example1:

Input:

givenlist = [8, 132, 22, 34, 57, 2, 1, 9, 45, 87, 63, 80, 26, 65, 132]

Output:

printing the list before sorting :
8 132 22 34 57 2 1 9 45 87 63 80 26 65 132 
printing the list after sorting :
1 2 8 9 22 26 34 45 57 63 65 80 87 132 132

Example2:

Input:

givenlist = ["hello", "this", "is", "BTechGeeeks", "python", "new", "online",
                   "platform", "for", "all", "students", "who", "are", "excited", "about", "coding"]

Output:

printing the list before sorting :
hello this is BTechGeeeks python new online platform for all students who are excited about coding 
printing the list after sorting :
BTechGeeeks about all are coding excited for hello is new online platform python students this who

Sorting in descending order example

Example 3:

Input:

givenlist = [8, 132, 22, 34, 57, 2, 1, 9, 45, 87, 63, 80, 26, 65, 132]

Output:

printing the list before sorting :
8 132 22 34 57 2 1 9 45 87 63 80 26 65 132 
printing the list after sorting :
132 132 87 80 65 63 57 45 34 26 22 9 8 2 1

Example4:

Input:

givenlist = ["hello", "this", "is", "BTechGeeeks", "python", "new", "online",
                   "platform", "for", "all", "students", "who", "are", "excited", "about", "coding"]

Output:

printing the list before sorting :
hello this is BTechGeeeks python new online platform for all students who are excited about coding 
printing the list after sorting :
who this students python platform online new is hello for excited coding are all about BTechGeeeks

Program for Selection Sort 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)Selection Sort Introduction

Selection Sort is a comparison sorting algorithm that uses a random list of items to sort them in ascending order. The comparison does not necessitate a lot of extra room. It just need one more memory space for the time variable.

This is referred to as in-place sorting. The temporal complexity of the selection sort is O(n^2), where n is the total number of items in the list. The number of iterations necessary to sort the list is measured by the time complexity. The list is separated into two sections: the first contains sorted items, and the second contains unsorted items.

The sorted list is empty by default, but the unsorted list contains all of the entries. The minimal value is then found in the unsorted list and entered into the sorted list. This procedure is repeated until all of the data have been sorted and compared.

2)Working of Selection Sort

To determine if the first item in the unsorted partition is the minimum value, it is compared to all of the values on the right-hand side. Its position is swapped with the minimal value if it is not the minimal value.

3)Algorithm

  • Determine the value of n, which represents the entire size of the array.
  • Divide the list into pieces that are sorted and unsorted. The sorted portion begins with an empty list, but the unsorted portion begins with the whole list.
  • Choose the smallest number from the unpartitioned segment and put it in the sorted portion.
  • Repeat the method (n – 1) times until all of the list’s elements have been sorted.

4)Implementation

  • The number of items in the list is represented by the variable n.
  • Now, I ranges from 0 to n – 2, indicating that it refers from the first to the second-to-last item. The function of I is to constantly point to the location of the next smallest item, thus we will find the smallest item from I to the end of the list and place it at i.
  • For the time being, we regard the item at I to be the smallest, because if we cannot locate a smaller element after I then I holds the correct item.
  • Inside, j ranges from I + 1 to n – 1, indicating that j will point to all things after I and will be responsible for locating the smallest item in that range.
  • Now we compare the item at j to the smallest item we’ve discovered so far, and if the thing at j is smaller, it becomes the smallest item we’ve discovered so far.
  • Following the inner loop, the smallest item from I to n – 1 is located and swapped with the item at I to return it to its proper location.
  • The outer loop will choose and sort the next smallest items one by one until the entire list has been sorted.

Below is the implementation of Selection Sort:

Sorting the given list in Ascending Order:

# function which implements the selection_sort  algorithm for givenlist
def selectionSort(givenlist):
    length = len(givenlist)
    for i in range(length):
        # To begin, consider the first element in the unsorted section to be the smallest.
        minValue = i

        for j in range(i+1, length):
            if (givenlist[j] < givenlist[minValue]):
                # If a smaller element is identified, update the position
                # of the minimum element.
                minValue = j

        # Replace the smallest(minValue) element with the first element
        # of the unsorted portion.
        givenlist[i], givenlist[minValue] = givenlist[minValue], givenlist[i]


# given list
givenlist = ["hello", "this", "is", "BTechGeeeks", "python", "new", "online",
             "platform", "for", "all", "students", "who", "are", "excited", "about", "coding"]
# printing the list before sorting
print("printing the list before sorting :")
for i in givenlist:
    print(i, end=" ")
print()
# passing this given list to selectionSort function which sorts the given list
selectionSort(givenlist)
# printing the list after sorting
print("printing the list after sorting :")
for i in givenlist:
    print(i, end=" ")

Output:

printing the list before sorting :
hello this is BTechGeeeks python new online platform for all students who are excited about coding 
printing the list after sorting :
BTechGeeeks about all are coding excited for hello is new online platform python students this who

Explanation : Here we can see that the given list of strings is sorted in Ascending order

Below is the implementation of Selection Sort:

Sorting the given list in Descending Order:

# function which implements the selection_sort  algorithm for givenlist
def selectionSort(givenlist):
    length = len(givenlist)
    for i in range(length):
        # To begin, consider the first element in the unsorted section to be the largest.
        maxValue = i

        for j in range(i+1, length):
            if (givenlist[j] > givenlist[maxValue]):
                # If a larger element is identified, update the position
                # of the larger element.
                maxValue = j

        # Replace the largest(maxValue) element with the first element
        # of the unsorted portion.
        givenlist[i], givenlist[maxValue] = givenlist[maxValue], givenlist[i]


# given list
givenlist = ["hello", "this", "is", "BTechGeeeks", "python", "new", "online",
             "platform", "for", "all", "students", "who", "are", "excited", "about", "coding"]
# printing the list before sorting
print("printing the list before sorting :")
for i in givenlist:
    print(i, end=" ")
print()
# passing this given list to selectionSort function which sorts the given list
selectionSort(givenlist)
# printing the list after sorting
print("printing the list after sorting :")
for i in givenlist:
    print(i, end=" ")

Output:

printing the list before sorting :
hello this is BTechGeeeks python new online platform for all students who are excited about coding 
printing the list after sorting :
who this students python platform online new is hello for excited coding are all about BTechGeeeks

Explanation : Here we can see that the given list of strings is sorted in Descending order

5)Time Complexity

The sort complexity expresses the number of execution times required to sort the list. There are two loops in the implementation.

The outer loop, which selects values from the list one by one, is executed n times, where n is the total number of elements in the list.

The inner loop, which compares the value from the outer loop to the remaining values, is also executed n times, where n is the total number of elements in the list.

As a result, the number of executions is (n * n), which can also be written as O. (n^2).

The difficulty of the selection sort is divided into three categories:

Worst case scenario: the provided list is in descending order. The algorithm executes as many executions as possible, which is denoted as [Big-O] O(n^2)
Best case :When the provided list is already sorted, this is the best case scenario. The algorithm executes the fewest number of times possible, which is denoted as [Big-Omega]? (n^2)
Average case: When the list is in random order, this is the average situation. [Big-theta]?O(n^2) is the average level of complexity
Because it only uses one temporal variable to exchange values, the selection sort has an O(1) space complexity.

6)Conclusion

In this tutorial, we learned how Selection Sort works, how to implement it in Python.

Selection Sort, like Bubble and Insertion Sort, has an O complexity (n^2). This indicates that doubling the input size increases the time it takes to execute the method by four times, making it an inefficient sorting method.

It is less efficient than Insertion Sort in general, but it is considerably easier to understand and apply.
Related Programs:

Program To Display Powers of 2 till N

Python Program to Display Powers of 2 till N

Given the Number N , the task is to print the powers of 2 till N.

Examples:

Example1:

Input:

Number = 10

Output:

The total terms of the number = 10
Value of 2 power 0 = 1
Value of 2 power 1 = 2
Value of 2 power 2 = 4
Value of 2 power 3 = 8
Value of 2 power 4 = 16
Value of 2 power 5 = 32
Value of 2 power 6 = 64
Value of 2 power 7 = 128
Value of 2 power 8 = 256
Value of 2 power 9 = 512

Example2:

Input:

Number = 20

Output:

The total terms of the number = 20
Value of 2 power 0 = 1
Value of 2 power 1 = 2
Value of 2 power 2 = 4
Value of 2 power 3 = 8
Value of 2 power 4 = 16
Value of 2 power 5 = 32
Value of 2 power 6 = 64
Value of 2 power 7 = 128
Value of 2 power 8 = 256
Value of 2 power 9 = 512
Value of 2 power 10 = 1024
Value of 2 power 11 = 2048
Value of 2 power 12 = 4096
Value of 2 power 13 = 8192
Value of 2 power 14 = 16384
Value of 2 power 15 = 32768
Value of 2 power 16 = 65536
Value of 2 power 17 = 131072
Value of 2 power 18 = 262144
Value of 2 power 19 = 524288

Program To Display Powers of 2 till N 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.

Method #1:Using ** operator

We can calculate the power of the 2 of the given number using ** operator.

We can take a loop from 0 to number and print the power of 2 of the given iterator value.

Print the power of 2 of given iterator value.

Below is the implementation:

# given number n
number = 10
# printing the power of 2 of the iterator value
for i in range(number):
    # calculating the power_of_2 of i
    powvalue = 2**i
    print("Value of 2 power", i, "=", powvalue)

Output:

Value of 2 power 0 = 1
Value of 2 power 1 = 2
Value of 2 power 2 = 4
Value of 2 power 3 = 8
Value of 2 power 4 = 16
Value of 2 power 5 = 32
Value of 2 power 6 = 64
Value of 2 power 7 = 128
Value of 2 power 8 = 256
Value of 2 power 9 = 512

Method #2:Using Anonymous function in Python

To determine the powers of 2 in the program below, we utilized the anonymous (lambda) function inside the map() built-in function. In Python, an anonymous function is one that is not given a name.
The def keyword is used to define conventional functions, whereas the lambda keyword is used to define anonymous functions in Python. As a result, anonymous functions are referred to as lambda functions.

Syntax:

lambda arguments: expression

Lambda functions can take any number of parameters but can only execute one expression.The result is returned once the expression has been evaluated.

Below is the implementation:

# Using the anonymous function, display the powers of two.
# given number n
number = 10
# use anonymous function to print powers of 2 till given number
resultTerms = list(map(lambda x: 2 ** x, range(number)))
print("The total terms of the number = ", number)
# print the powers of 2 till number
for i in range(number):
    print("Value of 2 power", i, "=", resultTerms[i])

Output:

The total terms of the number = 10
Value of 2 power 0 = 1
Value of 2 power 1 = 2
Value of 2 power 2 = 4
Value of 2 power 3 = 8
Value of 2 power 4 = 16
Value of 2 power 5 = 32
Value of 2 power 6 = 64
Value of 2 power 7 = 128
Value of 2 power 8 = 256
Value of 2 power 9 = 512

Explanation:

The following statement appears in the above program:

result = lambda x: 2 ** x specifies that any value we pass to result later is transferred to x, and 2 ** x is returned. result (3) returns 2 ** 3 or 2*2*2 or 8 in this case.
To make a list, use the list() function. After applying the function to each item of a provided iterable (in the example of the previous application, a list), map() produces an iterator of results.

 
Related Programs:

Count the Number of Each Vowel

Python Program to Count the Number of Each Vowel

Vowels Definition:

A vowel is a sound that you utter with your mouth open, allowing air to pass through it, and is represented in writing by the letters ‘a’, ‘e’, I ‘o’, and ‘u’.

Examples:

Example1:

Input:

string = "croyez"

Output:

a : 0
e : 1
i : 0
o : 1
u : 0

Explanation:

Here the letters o, e are vowels and o is occurred once and e is occurred once

Example2:

Input:

string ="Hello this is BTechGeeks"

Output:

a : 0
e : 4
i : 2
o : 1
u : 0

Input:

string ="ELEPHANT"

Output:

a : 1
e : 2
i : 0
o : 0
u : 0

Explanation:

Here the letters e ,a  are vowels and e is repeated twice and a is repeated once.
Here we ignore the case while counting vowels

Count the Number of Each Vowel in Python

Below are the ways to count the number of each vowel in given string 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.

Method #1:Using Dictionary

Dictionary:

A colon (:) separates each key from its value, commas separate the objects, and the whole thing is enclosed in curly braces. With just two curly braces, an incomplete dictionary with no things is written as follows:

Values may not be unique inside a dictionary, but keys are. A dictionary’s values may be any data type, but the keys must be immutable data types like strings, numbers, or tuples.

Approach:

We’ve taken a string from the ip str variable. We make it ideal for caseless comparisons by using the form casefold(). This method basically returns a lowercased version of the string.

We create a new dictionary with each vowel as its key and all values equal to 0 using the dictionary method fromkeys(). This is where the count is started.

We then use a for loop to iterate over the input string.

We check whether the character is in the dictionary keys in each iteration (True if it is a vowel) and increment the value by 1 if it is.

Below is the implementation:

# Taking a string which have total vowels
vowelstring = 'aeiou'

given_string = 'Hello this is BTechGeeks'

# making the string suitable for caseless comparisions
given_string = given_string.casefold()
# making a dictionary with keys as vowel and the value as 0
countVowels = {}.fromkeys(vowelstring, 0)

# counting the vowels in given string
for char in given_string:
  # increment the count in dictionary if it is vowel
    if char in countVowels:
        countVowels[char] += 1
# print the count
for key, value in countVowels.items():
    print(key, ":", value)

Output:

a : 0
e : 4
i : 2
o : 1
u : 0

Method #2: Using list and dictionary comprehension in python

List Comprehension:

In Python, list comprehension is a simple and elegant way to generate a new list from an existing one.

An expression is followed by a for statement enclosed in square brackets in a list comprehension.

Dictionary Comprehension:

In Python, dictionary comprehension is a simple and elegant way to construct a new dictionary from an iterable.

Dictionary comprehension is made up of an expression pair (key: value) followed by a for statement enclosed in curly braces{}.

This method produces the same output as the previous one.

  • To count the vowels in a single line, we nested a list comprehension within a dictionary comprehension.
  • The dictionary comprehension checks for all vowel characters, and the list comprehension inside the dictionary comprehension checks to see if any characters in the string fit the vowel.
  • Finally, a list of 1s for the number of vowel characters is produced. For each array, the sum() method is used to calculate the sum of the elements.

However, since we iterate over the entire input string for each vowel, this program is slower.

Below is the implementation:

# Taking a string which have total vowels
vowelstring = 'aeiou'

given_string = 'Hello this is BTechGeeks'

# making the string suitable for caseless comparisions
given_string = given_string.casefold()

# counting the vowels in given string
countVowels = {x: sum([1 for char in given_string if char == x])
               for x in 'aeiou'}
# print the count
for key, value in countVowels.items():
    print(key, ":", value)

Output:

a : 0
e : 4
i : 2
o : 1
u : 0

Related Programs:

Return Multiple Values From a Function

Python Program to Return Multiple Values From a Function

Functions in Python:

A function in Python is a set of related statements that performs a single task.

Functions aid in the division of our program into smaller, modular chunks. Functions help our program  become more structured and manageable as it increases in size.

It also eliminates duplication and makes the code reusable.

Given a function, the task is to return multiple values from the function.

Return Multiple Values From a Function in Python

There are several ways to return multiple values from a function some of them are:

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.

Method #1:Returning as Tuple

Tuple:

A tuple is an immutable, ordered set. A tuple cannot shift in this way.

For example, a tuple can be used to store information about a person’s name, age, and location.

You can return multiple values in Python by simply separating them with commas.

As an example, write the following function that returns a string and a number: Simply write each value, separated by commas, after the return.
Except where syntax requires parentheses, comma-separated values are treated as tuples in Python.
As a result, in the below example, the function returns a tuple with each value as an element.
It’s worth noting that it’s the comma, not the parentheses, that creates a tuple. Except in the case of an empty tuple or where necessary to prevent syntactic ambiguity, parentheses are optional.

Below is the implementation:

# writing a sample function which returns the multiple values
def sampleFunc():
    return 11, "Hello", 5.5, True, 353

# Driver code
print(sampleFunc())

Output:

(11, 'Hello', 5.5, True, 353)

Explanation:

Here this sampleFunc returns different datatypes and multiple values.

Writing the code to print type of values it returned:

# writing a sample function which returns the multiple values
def sampleFunc():
    return 11, "Hello", 5.5, True, 353


# Driver code
print(type(sampleFunc()))
print(type(sampleFunc()[0]))
print(type(sampleFunc()[1]))
print(type(sampleFunc()[2]))
print(type(sampleFunc()[3]))

Output:

<class 'tuple'>
<class 'int'>
<class 'str'>
<class 'float'>
<class 'bool'>

Limitations:

However, as the number of values returned grows, the above programme becomes problematic. If we want to return six or seven values, what do we do? We can keep tupling them, but it’s easy to lose track of which meaning belongs where. Also, unpacking them anywhere we want to obtain them can be a little messy.

Unpacking the tuple:

# writing a sample function which returns the multiple values
def sampleFunc():
    return 11, "Hello", 5.5, True, 353

# unpacking the tuple
print(*sampleFunc())

Output:

11 Hello 5.5 True 353

Method #2:Returning as List

List:

A list is a mutable, ordered sequence. That is to say, a list can be modified.

We can return multiple values from the function using [] .

It is quick to confuse tuples and lists. After all, they are both containers that hold items. However, keep the following differences in mind:

  • Tuples cannot be modified.
  • Lists are subject to change.

Below is the implementation:

# writing a sample function which returns the multiple values
def sampleFunc():
    return [11, "Hello", 5.5, True, 353]


# print the return values
print(sampleFunc())

Writing the code to print type of values it returned:

# writing a sample function which returns the multiple values
def sampleFunc():
    return [11, "Hello", 5.5, True, 353]


# Driver code
print(type(sampleFunc()))
print(type(sampleFunc()[0]))
print(type(sampleFunc()[1]))
print(type(sampleFunc()[2]))
print(type(sampleFunc()[3]))

Output:

<class 'list'>
<class 'int'>
<class 'str'>
<class 'float'>
<class 'bool'>

Unpacking the list:

# writing a sample function which returns the multiple values
def sampleFunc():
    return [11, "Hello", 5.5, True, 353]

# unpacking the tuple
print(*sampleFunc())

Output:

11 Hello 5.5 True 353

Method #3: Returning as Dictionary

When you use a dictionary to return values, it’s simple to keep track of the returned values by using the keys.

Here we return multiple values as dictionary.

Below is the implementation:

# writing a sample function which returns the multiple values
def sampleFunc():
    return {1: 11, 2: "Hello", 3: 5.5, 4: True, 5: 353}


# Driver code
print(sampleFunc())

Output:

{1: 11, 2: 'Hello', 3: 5.5, 4: True, 5: 353}

Here it returns multiple values as dictionary.
Related Programs:

Check If Two Strings are Anagram

Python Program to Check If Two Strings are Anagram

String:

Arrays are Strings. Strings in Python, like many other common programming languages, are sequences of bytes that represent unicode characters. However, since Python lacks a character data form, a single character is simply a one-length string. Square brackets may be used to access the string’s components.

Anagrams:

A condition in which one string or number is rearranged in such a way that each character of the rearranged string or number must be a part of another string or number is known as an anagram. In other words, if the second string is a simple rearrangement of the first, it is said to be an anagram of the first.

Example :1)The words cricket and crikte are anagrams

2)The words pink and nipk.

Note :

Here we can ignore the case while checking anagrams like  BTechGeeks and geeksechtb are anagrams by ignoring the case.

Examples:

Example1:

Input:

string 1 = "skyis"    string2= "ssyki"

Output:

Both the strings are anagrams

Explanation:

Here these two strings are equal after rearranging the letters.

Example2:

Input:

string 1 = "kaswpink"    string2= "krwsa"

Output:

Both the strings are not anagrams

Explanation:

Here these two strings are not equal after rearranging the letters and also both are not having same number
of letters.

Example3:

Input:

string 1 = "BTechGeeks"   string 2 = "geeksechtb"

Output:

Both the strings are anagrams

Explanation:

Here both the strings are same by rearranging the words and by ignoring the case of it.

Checking If Two Strings are Anagrams in Python

Below are the ways to check if both the strings are anagrams.

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.

Method #1:Using sorted() method

Approach:

  • Scan the both strings.
  • Convert the both strings to lowercase using lower() function since we ignore the case.
  • Then sort both strings  with sorted().
  • Check if the sorted strings are identical by comparing them.
  • If both the strings are equal then they are anagrams
  • Else both the strings are not anagrams.

Below is the implementation:

# given two strings
string1 = "skyis"
string2 = "ssyki"
# converting the both strings to lowercase using lower() function.
string1 = string1.lower()
string2 = string2.lower()
# checking if both the strings are equal using sorted() function
if(sorted(string1) == sorted(string2)):
    print("Both the strings are anagrams")
else:
    print("Both the strings are not anagrams")

Output:

Both the strings are anagrams

Explanation:

  • Both strings must be entered and stored in different variables.
  • Use the lower() and upper() functions to convert all strings to lowercase or uppercase.
  • Since we don’t consider the case when comparing,
  • Both strings’ characters are separated into different lists.
  • Using an if statement, they are then compared to see if they are equal.
  • They’re anagrams if they’re identical and the characters are literally jumbled in anagrams.
  • The strings aren’t anagrams if they aren’t equal.

Method #2:Using Counter() function

Counter:

The Counter class in Python3 is a special type of object data-set that comes with the collections module. The Collections module offers specialised container datatypes as an alternative to Python’s general-purpose built-ins such as dictionaries, lists, and tuples.

Hashable objects are counted using the Counter subclass. When called, it generates an iterable hash table implicitly.

Approach:

  • Scan the both strings.
  • Convert the both strings to lowercase using lower() function since we ignore the case.
  • Find the frequency of each character in the string using Counter function.
  • Repeat the same for second string.
  • If both the frequencies and keys are equal then it is anagram.
  • Else it is not anagram.
  • We can check if both frequencies are equal using == operator.

Below is the implementation:

# importing counter from collections
from collections import Counter
# given two strings
string1 = "skyis"
string2 = "ssyki"
# converting the both strings to lowercase using lower() function.
string1 = string1.lower()
string2 = string2.lower()
# finding the frequencies of both string using Counter()
freqstring1 = Counter(string1)
freqstring2 = Counter(string2)
# checking if both the strings are equal by comparing the frequencies.
if(freqstring1 == freqstring2):
    print("Both the strings are anagrams")
else:
    print("Both the strings are not anagrams")

Output:

Both the strings are anagrams

Related Programs: