×

Problem-solving with algorithm and data structures using Python

What is problem-solving?

There is no universal method for solving problems. It's frequently a special process that balances your immediate and long-term goals with your available resources. However, several models emphasise problem-solving as a means of reaching one's objectives more quickly and intelligently.

The steps involved in problem-solving are

  1. Identify problem statement
  2. Gather information and design the solution
  3. Set of solutions
  4. Select the optimal solution
  5. Evaluate the solution and the approach

Algorithm

An algorithm is a set of clear instructions for solving a specific problem in computer programming. It generates the required result from a set of inputs.

Data structures

Data structure is a storage that is used to store the data elements. By using these data-structures, we can manipulate the data and access the data as well.

A data structure is used for more than just data organisation. Additionally, it is employed for data processing, retrieval, and archiving. Almost all software systems and applications have been built using many basic and advanced data structures. Therefore, we need to be well-versed in data structures.

Data structures are of two types:

  1. Linear Data structures
    • Array
    • Linked List
    • Stack
    • Queue
    • Matrix
  2. Non – Linear Data structures
    • Trees
    • Heap
    • Hash table
    • Graph

Data structures in Python

Several data structures come built-in with Python, which makes problem-solving using algorithms and data structures easier using Python.

These built-in data structures provide great flex in storing the data and speed up the retrieval and processing of data.

The data structures present in Python are:

  • List
  • Tuple
  • Dictionary
  • Set

These data structures are the key reason for using Python for problem-solving. These data structures have many in-built functions, which make them more efficient.

List: Like arrays in other programming languages, lists in Python are collections of data sorted in some way. It permits many element kinds in the List.

Python's version of lists is comparable to C++'s vectors or Java's array lists. As all the components must be relocated, adding or removing a member from the List's beginning is the most expensive operation. If the pre-allocated memory is all used up, insertion and deletion at the end of the List may also become expensive.

Program for list in python

list1 = []
list1.append(1)
list1.append(2)
list1.append(3)


print(list1)
print(“first element in the list :”, list1[0] )


list1.remove(1)
print(list1)

Output

[1, 2, 3]
The first element in the List: 1
[2, 3]

Tuple: A Python Tuple is a group of items that are separated by commas. The indexing, nested objects, and repetition of a tuple are somewhat similar to those of a list, however, unlike a list, a tuple is immutable.

To create a tuple, all the components (items) must be enclosed in parenthesis (), each separated by a comma. We can even create a tuple without using the parenthesis but using parenthesis is a good practice for writing the code.

Program for tuple in python

tuple1 = (10, 20, 30)


print(“ tuple : “, tuple1)
print(“first element in tuple is : ”, tuple1[0])


tuple2 = (‘a’, ‘b’, ‘c’)
tuple3 = tuple2 + tuple1
print(“combined tuple of 1 and 2 is :”, tuple3)

Output

Tuple : (10, 20, 30)
the first element in the tuple is: 10
combined tuple of 1 and 2 is : (10, 20, 30, ‘a’, ‘b’, ‘c’)

Dictionary: Unlike other data types, which can only retain a single value as an element, a dictionary in Python is a collection of keys and values used to store data like a map.

Python dictionary is used to store key-value Paris.

Dictionary is represented by {} all the key-value pairs are stored inside the {}.

Program for dictionary in python

dict = {0: ‘a’, 1: ‘b’, 2: ‘c’, 3: ‘d’}
print(“dictionary created is :”, dict)


#Acessing elements using key values
print(“value of key 1 is :”, dict[1])


#Acessing elements using get method
print(“value of key 2 is :”, dict.get(2))

Output

dictionary created is : {0: 'a', 1: 'b', 2: 'c', 3: 'd'}
value of key 1 is: b
value of key 2 is: c

Sets: A Set is an iterable, changeable, and duplicate-free unordered collection data type. Python set cannot contain duplicate items. Set is a data structure based on another data structure, a hash Table. Since a set is unordered, it is impossible to access the elements by indexing as we do in List.

Python program for sets

set1 = set([1, 2, 3, 4])
#creating set using set() method
print(“set created :”, set1)


set1.add(5)
#adding elements to the set
print(“after adding an unique element : ”, set1)

Output

set created : {1, 2, 3, 4}
after adding an unique element :  {1, 2, 3, 4, 5}

Related Topics

Python while loop

Loops are essential in Python or any other programming language, as they help to execute a block of code repetitively. Sometimes, situations arise where you would need to use a piece of code...

2 minutes read.

Convert uppercase to lowercase in Python

Python String lower() By using the built-in string lower() method, all the uppercase characters can be converted into lowercase characters in a string, The lowercased string from the given string is returned...

1 minute read.

Data Distribution in python

Before discussing data distribution, we will discuss each word that is data and Distribution. What is meant by data? A collection of raw facts and figures is called data. The word "raw"...

18 minutes read.

Implementing geometric shapes into the game in python

Geometric Drawings We are trying to draw various shapes of geometry by using pygame module to implement Geometric Drawings in game. Let us revise few syntax of basic shapes, to get started...

7 minutes read.

How to print in the same line in Python?

How to print in the same line in python By default, the print function in Python takes us to the next line and prints the desired statement in the output. In this...

5 minutes read.

Python variance() function

Variance The variance is the average of the square deviations from the mean. The variance will measure the spread of the dataset from its mean or median value. The greater the...

4 minutes read.

Create the First GUI Application using PyQt5 in Python

GUI: A graphical user interface, or GUI, is present on most personal computers. It provides a simple experience for individuals with various computing skill levels. GUI apps may take more resources...

3 minutes read.

Adding a key-value pair to dictionary in Python

Python dictionaries are collections of unsorted key-value pairs. This article will examine a method for adding new key-value teams to an existing dictionary. Dictionary in Python With the aid of curly brackets...

3 minutes read.

Python str() function

Python str() function The str() function in Python converts the specified value into a string. Syntax class str(object='')           or class str(object=b'', encoding='utf-8', errors='strict') Parameter object:  This parameter represents any object to convert the given...

1 minute read.

What is Python 2

Python is a widely used high-level language. The initial work on developing python was begun in the late 1980s. In 1989, Guido Van Rossum started to work on it. Initially,...

3 minutes read.

Read numpy array in Python

Numpy is a numerical python that deals with multidimensional arrays mostly used in storing multiple values. Python's core scientific computing package is called NumPy. This Python library provides multidimensional array...

9 minutes read.

Difference between Sort and Sorted in Python

If you new to Python, it must be confusing the distinction between the Sort and Sorted functions. However, it is important to understand the differences in order to use them...

5 minutes read.

apply() function in python

Pandas: Pandas is a library in python. It is an open source package in python. Pandas in python are used for data cleaning and data analysis. Data frame mainly consists of...

3 minutes read.

Python List reverse() method

 Python List reverse() method The list.reverse () method in Python reverses the elements of the list in place. Syntax list.reverse() Parameter NA Example 1 # Python program explaining # the list.reverse() method weekList = ['Sun','Thurs','Mon','Fri', 'Tues', 'Wed'] print("Actual week list: ",weekList) #...

1 minute read.

Subprocess Module in Python

What is a Process? Every program will have its respective system state, i.e., the state in which it is running. A program that is in a running state or in a...

7 minutes read.

Python program to check if two strings are anagram or not

Python program to check if two strings are anagram or not Problem: This is a python program that takes two strings and checks if given strings are anagram or not. Examples: Input: string1...

1 minute read.

Create First GUI Application using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.

Python Strong Number

Strong Number- Logic Divide each of the number's digits into separate units to determine if it is a strong number or not.The factorial of each digit must then be determined. The...

5 minutes read.

Important Difference between Python 2.x and Python 3.x with Example

The comparison between Python 2 and Python 3 is given in the article that follows. Python is a computer language that can perform more tasks than other languages and is...

5 minutes read.

How to develop a game in python

Fun always makes a task interesting and easy to execute. Learning in the same theoretical way at some point reaches the boring spot. In this article, using some Python knowledge,...

13 minutes read.