Python

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:

Python Program for Bubble Sort Read More »

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:

Python Program for Insertion Sort Read More »

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:

Python Program for Selection Sort Read More »

Python- How to remove files by matching pattern, wildcards, certain extensions only

Python: How to remove files by matching pattern | wildcards | certain extensions only?

In this ultimate tutorial, we are going to discuss how to remove files from a directory based on a matching pattern or wildcard, or specific extensions.

How to delete text files using different techniques?

Let’s discuss how to delete text files using different techniques, Suppose we have a directory that contains some log files and some text files and we want to delete all .txt files from that directory.

Then, continue your read so that you can successfully learn to remove files by matching patterns or wildcards by the following methods and techniques.

Remove files by pattern using glob.glob() & os.remove()

First, we will get a list of all file paths that match the specified patterns using glob.glob() and then delete all text files.

import os
import glob
# Get a list of all the file paths that ends with .txt from in specified directory
fileList = glob.glob('C://Users/HP/Desktop/A plus topper/*.txt')
# Iterate over the list of filepaths & remove each file.
for filePath in fileList:
    try:
        os.remove(filePath)
    except:
        print("Error while deleting file : ", filePath)

So you can see that it will remove all ‘.txt’ files in the directory ‘C:\\Users\HP\Desktop\A plus topper\*.txt’. It will remove all text files because we mention” *.txt “.

Get the list of files using glob.glob()

glob.glob() accepts path name and finds the path of all the files that match the specified pattern. By default recursive parameter is False, which means that it will find files in the main directory, not in a subdirectory.

glob.glob(pathname, *, recursive=False)

As we have seen by this approach we can not recursively delete files from subdirectories. For that, we will find another solution,

Read More:

Recursively Remove files by matching pattern or wildcard

It will search all the ‘txt’ files including files in subdirectories because we will use 'C://Users/HP/Desktop/A plus topper/**/*.txt'‘ **  ‘ in it.

Then we can iterate over the list and delete each file one by one using os.remove().

import os
import glob
# get a recursive list of file paths that matches pattern including sub directories
fileList = glob.glob('C://Users/HP/Desktop/A plus topper/**/*.txt', recursive=True)
# Iterate over the list of filepaths & remove each file.
for filePath in fileList:
    try:
        os.remove(filePath)
    except OSError:
        print("Error while deleting file")

It will delete all the text files from the directory and its sub-directories.

Recursively Remove files by matching pattern or wildcard using os.walk()

In this, we are going to use os.walk(). It generates filename in the given directory by walking over the tree structure in a top-down or bottom-up approach.

os.walk(top, topdown=True, onerror=None, followlinks=False)

It will return a tuple consisting of the main directory, a list of all subdirectories, and a list of all file names in the main directory.

Let’s use this os.walk() to get a list of all files in a given directory that matches a pattern. Then delete those files,

import os
import fnmatch
# Get a list of all files in directory
for rootDir, subdirs, filenames in os.walk('C://HP/Users/Desktop/A plus topper'):
    # Find the files that matches the given patterm
    for filename in fnmatch.filter(filenames, '*.txt'):
        try:
            os.remove(os.path.join(rootDir, filename))
        except OSError:
            print("Error while deleting file")

It will delete all the text files from the directory and also from its subdirectories.

Now we are going to create a Generic function to delete all the files from a given directory based on a matching pattern and it will also return the names of the files that were not deleted due to some error.

import os
import fnmatch
'''
Generic function to delete all the files from a given directory based on matching pattern
'''
def removeFilesByMatchingPattern(dirPath, pattern):
    listOfFilesWithError = []
    for parentDir, dirnames, filenames in os.walk(dirPath):
        for filename in fnmatch.filter(filenames, pattern):
            try:
                os.remove(os.path.join(parentDir, filename))
            except:
                print("Error while deleting file : ", os.path.join(parentDir, filename))
                listOfFilesWithError.append(os.path.join(parentDir, filename))
    return listOfFilesWithError
listOfErrors = removeFilesByMatchingPattern('/home/varung/Documents/python/logs/', '*.txt')
print('Files that can not be deleted : ')
for filePath in listOfErrors:
    print(filePath)

So in the above code, you can see that it will also return file names that can not be deleted.

Conclusion:

In this article, we have seen how to remove files from a directory based on matching patterns or wildcards, or certain extensions.

Python: How to remove files by matching pattern | wildcards | certain extensions only? Read More »

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:

Python Program to Display Powers of 2 till N Read More »

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:

Python Program to Count the Number of Each Vowel Read More »

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:

Python Program to Return Multiple Values From a Function Read More »

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:

Python Program to Check If Two Strings are Anagram Read More »

reverse a number

Write a Program to Reverse a Number in Python | Reverse Digits or Integers

Given a number, thee task is to reverse the given number in Python.

Examples:

Example1:

Input:

number=12345

Output:

The reversed number = 54321

Explanation:

After reversing the number we get 54321

Example2:

Input:

number=7341

Output:

The reversed number = 1437

Example3:

Input:

number=9840

Output:

The reversed number = 489

Explanation:

Here the reversed number is 0489 we neglect the leading zero so the reversed number is 489

Reverse the given Number in Python

There are several ways to reverse the given number in python 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:Using while loop

Algorithm:

  • Scan the given number
  • Set the variable reverse_number to 0.
  • Loop while number > 0 Loop while number > 0
  • Multiply reverse_number by 10 and add the remainder to reverse_number like below
  • reverse_number = (reverse_number * 10) + remainder
  • Divide the given number by 10 to remove the last digit.
  • Print the reversed number

Below is the implemenatation:

# given number
given_num = 12345

# Take a variable reverse_number and initialize it to null
reverse_number = 0

# using while loop to reverse the given number

while (given_num > 0):
    # implementing the algorithm
    # getting the last digit
    remainder = given_num % 10
    reverse_number = (reverse_number * 10) + remainder
    given_num = given_num // 10

# Display the result
print("The reversed number =", reverse_number)

Output:

The reversed number = 54321

Method #2: Using for loop and string concatenation

Approach: 

  • Scan the given number.
  • Take a empty string say revstring.
  • Convert the given number to string using str() function.
  • Traverse every character of the string using for loop in reverse order using range function.
  • Add each character to revstring using string concatenation.
  • Print the revstring.

Below is the implementation:

1)For numbers without trailing zeroes

# given number
given_num = 12345
# taking empty string
reverse_string = ""
# Convert the given_num to string using str
strnum = str(given_num)
# calculating the length of string
length = len(strnum)
# Traverse the strnum string in reverse order using for loop range function
for index in range(length-1, -1, -1):
    # add the character to reverse_string using string concatenation
    reverse_string = reverse_string+strnum[index]
# print the result
print("The reversed number =", reverse_string)

Output:

The reversed number = 54321

Note:

Here it gives the correct result as their are no trailing zeroes

Let us consider a case where the given number contains trailing zeroes .

EX: 9840

The above algorithm gives the output

The reversed number = 0489

Here it also prints the leading zeroes so to avoid this the solution is given below.

Solution:

After getting the reversed string convert the string to integer using int() function which removes the leading zeroes

as below.

2)For numbers with trailing zeroes

# given number
given_num = 9840
# taking empty string
reverse_string = ""
# Convert the given_num to string using str
strnum = str(given_num)
# calculating the length of string
length = len(strnum)
# Traverse the strnum string in reverse order using for loop range function
for index in range(length-1, -1, -1):
    # add the character to reverse_string using string concatenation
    reverse_string = reverse_string+strnum[index]
# converting the string to integer using int() function
reverse_number = int(reverse_string)
# print the result
print("The reversed number =", reverse_number)

Output:

The reversed number = 489

Method #3:Using Slicing

Approach:

  • Scan the given number.
  • Convert the given number to string using str() function.
  • Reverse the string using slicing
  • Convert this reversed string to integer to avoid leading zeros as mentioned in method #2.
  • Print the reversed string.

Below is the implementation:

# given number
given_num = 9840
# Convert the given_num to string using str
strnum = str(given_num)
# calculating the length of string
length = len(strnum)
# Reversing the string using slicing
reverse_string = strnum[len(strnum)::-1]
# converting the string to integer using int() function
reverse_number = int(reverse_string)
# print the result
print("The reversed number =", reverse_number)

Output:

The reversed number = 489

Method #4:Using list  and join functions

Approach:

  • Scan the given number.
  • Convert the given number to string using str() function.
  • Convert this string to list of digits using list() function.
  • Reverse the list using reverse() function
  • Join the list using join() function to get reversed string.
  • Convert this reversed string to integer to avoid leading zeros as mentioned in method #2.
  • Print the reversed string.

Below is the implementation:

# given number
given_num = 9840
# Convert the given_num to string using str
strnum = str(given_num)
# converting to list of digits
numberslist = list(strnum)
# reverse the list and
numberslist.reverse()
# convert this list to string using join
reverse_string = ''.join(numberslist)
# converting the string to integer using int() function
reverse_number = int(reverse_string)
# print the result
print("The reversed number =", reverse_number)

Output:

The reversed number = 489

Related Programs:

Write a Program to Reverse a Number in Python | Reverse Digits or Integers Read More »

Python: Select an Element or Sub Array by Index From a Numpy Array

Select an element or subarray by index from a Numpy array

In this article, we will discuss how we can access elements of numpy array using indexes and how to access subarray of Numpy array using slicing or range of indexes.

Access element of Numpy array using indexes

As we all know array is a data structure in which elements are stored in a contiguous memory location. Hence it is easy to access array elements using an index. The same is with the case of the Numpy array. We can access elements of the Numpy array using indexes. As we implement this in python so we can access array elements using both positive and negative indexes.

Positive index starts from 0 and it used to access the first element and using index 1,2,3………. we can access further elements. Negative index start from -1 and it used to access the last element and using index -2,-3,-4……… we can access furthermost elements. Let see this with the help of an example.

import numpy as np
#creating Numpy array
npArray=np.array([1, 2, 3, 4, 5,6,7,8,9,10])
print(npArray)
#np[0] acess first element
print(npArray[0])
#np[-1] acess last element 
print(npArray[-1])
#np[3] access 4th element from start
print(npArray[3])
#np[-3] access 3rd element from last
print(npArray[-3])

Output

[ 1  2  3  4  5  6  7  8  9 10]
1
10
4
8

Access subarray of Numpy array using slicing or range of indexes

When we study the list in python we see that we can access the subarray of the list using slicing. Its syntax looks like this:

Suppose L is a list we can access the subarray of the list using L[a:b] where a denote starting index while b-1 denotes the last index of the subarray. In a similar way, we can implement this concept in a Numpy array.

Now we see different structures of slicing for positive index

1) L[a:b]-> a denote starting index of numpy array and b-1 denotes last index of numpy array.

import numpy as np
#creating Numpy array
npArray=np.array([1, 2, 3, 4, 5,6,7,8,9,10])
print(npArray)
#Here we start from 3rd index and stop at 5th index
print(npArray[3:6])

Output

[ 1  2  3  4  5  6  7  8  9 10]
[4 5 6]

2) L[:b]-> Here a becomes starting index of the whole array i.e a is equal to zero and b-1 denotes the last index of the numpy array.

import numpy as np
#creating Numpy array
npArray=np.array([1, 2, 3, 4, 5,6,7,8,9,10])
print(npArray)
#Here we start from 0th index and stop at 5th index
print(npArray[:6])

Output

[ 1  2  3  4  5  6  7  8  9 10]
[1 2 3 4 5 6]

3) L[a:]-> a denote starting index of the numpy array and b becomes the last index of the whole array.

import numpy as np
#creating Numpy array
npArray=np.array([1, 2, 3, 4, 5,6,7,8,9,10])
print(npArray)
#Here we start from 2nd index and stop at last index
print(npArray[2:])

Output

[ 1  2  3  4  5  6  7  8  9 10]
[ 3  4  5  6  7  8  9 10]

4) L[a:b:c] -> a denote starting index of numpy array and b-1 denotes the last index of numpy array and c-1 denote how many elements we have to skip in between. The default value of c is 1.

import numpy as np
#creating Numpy array
npArray=np.array([1, 2, 3, 4, 5,6,7,8,9,10])
print(npArray)
#Here we start from 2nd index and stop at sixth index and leave 1 element in  between
print(npArray[2:7:2])

Output

[ 1  2  3  4  5  6  7  8  9 10]
[3 5 7]

5) L[a::c] -> a denote starting index of the numpy array and b becomes the last index of the whole array and c-1 denotes how many elements we have to skip in between. The default value of c is 1.

import numpy as np
#creating Numpy array
npArray=np.array([1, 2, 3, 4, 5,6,7,8,9,10])
print(npArray)
#Here we start from 2nd index and stop at last index and leave 1 element in  between
print(npArray[2::2])

Output

[ 1  2  3  4  5  6  7  8  9 10]
[3 5 7 9]

Now we see different structures of slicing for the Negative index

1) L[a:b:c]-> a denote starting index of numpy array and b denotes last index of numpy array.Here c=-1 means we have to skip 0 elements,c=-2 means we have to skip 1 element, and so on

import numpy as np
#creating Numpy array
npArray=np.array([1, 2, 3, 4, 5,6,7,8,9,10])
print(npArray)
#Here we start from 1st index from last and stop at 5th index from last 
print(npArray[-1:-5:-1])

Output

[ 1  2  3  4  5  6  7  8  9 10]
[10  9  8  7]

2) L[a::c]-> a denote starting index of the numpy array and b becomes the last index of the whole array. Here c=-1 means we have to skip 0 elements,c=-2 means we have to skip 1 element, and so on.

import numpy as np
#creating Numpy array
npArray=np.array([1, 2, 3, 4, 5,6,7,8,9,10])
print(npArray)
#Here we start from last index and stop at 5th index from last leaving 1 element
print(npArray[:-5:-2])

Output

[ 1  2  3  4  5  6  7  8  9 10]
[10  8]

3) 5) L[a::c] -> a denote starting index of the numpy array and b becomes the last index of the whole array. Here c=-1 means we have to skip 0 elements,c=-2 means we have to skip 1 element, and so on.

import numpy as np
#creating Numpy array
npArray=np.array([1, 2, 3, 4, 5,6,7,8,9,10])
print(npArray)
#Here we start from second index from last and stop at last index from last leaving 1 element
print(npArray[-2::-2])

Output

[ 1  2  3  4  5  6  7  8  9 10]
[9 7 5 3 1]

So these are the methods select an element or subarray by index from a Numpy array.

Python: Select an Element or Sub Array by Index From a Numpy Array Read More »