- Problem-solving with algorithm and data structures using Python
- The steps involved in problem-solving are
- Data structures in Python
- Problem Solving in Python
- Step 1 – Understanding the Problem
- Example : Write a function that takes two numbers and returns their sum.
- Step 2 – Explore Examples
- Example : Write a function that takes a string as input and returns the count of each character
- Step 3 – Breaking the Problem Down
- Example : Write a function that takes a string as input and returns the count of each character
- Step 4 – Solving or Simplification
- Example : Write a function that takes a string as input and returns the count of each character
- Step 5 – Looking back and Refactoring
- Example : Write a function that takes a string as input and returns the count of each character
- Saved searches
- Use saved searches to filter your results more quickly
- License
- ivanmmarkovic/Problem-Solving-with-Algorithms-and-Data-Structures-using-Python
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
Problem-solving with algorithm and data structures using Python
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
- Identify problem statement
- Gather information and design the solution
- Set of solutions
- Select the optimal solution
- Evaluate the solution and the approach
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:
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:
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)
[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)
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 = 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))
dictionary created is : 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)
set created : after adding an unique element :
Problem Solving in Python
Problem-solving is the process of identifying a problem, creating an algorithm to solve the given problem, and finally implementing the algorithm to develop a computer program.
An algorithm is a process or set of rules to be followed while performing calculations or other problem-solving operations. It is simply a set of steps to accomplish a certain task.
In this article, we will discuss 5 major steps for efficient problem-solving. These steps are:
- Understanding the Problem
- Exploring Examples
- Breaking the Problem Down
- Solving or Simplification
- Looking back and Refactoring
Step 1 – Understanding the Problem
While understanding the problem, we first need to closely examine the language of the question and then proceed further. The following questions can be helpful while understanding the given problem at hand.
- Can the problem be restated in our own words?
- What are the inputs that are needed for the problem?
- What are the outputs that come from the problem?
- Can the outputs be determined from the inputs? In other words, do we have enough information to solve the given problem?
- What should the important pieces of data be labeled?
Example : Write a function that takes two numbers and returns their sum.
- Can the problem be restated in our own words?
- Implement addition
- Integer, Float, etc.
- Integer, Float, etc.
- Yes
- Add, Sum
Step 2 – Explore Examples
Once we have understood the given problem, we can look up various examples related to it. The examples should cover all situations that can be encountered while the implementation.
- Start with simple examples.
- Progress to more complex examples.
- Explore examples with empty inputs.
- Explore examples with invalid inputs.
Example : Write a function that takes a string as input and returns the count of each character
# Start with simple examples charCount("bbbb") # charCount("hello") # # Progress to more complex examples charCount("My name is Rachel") # Explore examples with empty inputs charCount("") # Explore examples with invalid inputs charCount(10)
Step 3 – Breaking the Problem Down
After exploring examples related to the problem, we need to break down the given problem. Before implementation, we write out the steps that need to be taken to solve the question.
Example : Write a function that takes a string as input and returns the count of each character
def charCount(tempString): # Declare an object to return at the end # Loop over the string # If the char is a letter and it is in our object, add one to the value # If the char is a letter and it is not in our object, # add that char to our object with the value of one # Return the object
Step 4 – Solving or Simplification
Once we have laid out the steps to solve the problem, we try to find the solution to the question. If the solution cannot be found, try to simplify the problem instead.
The steps to simplify a problem are as follows:
- Find the core difficulty
- Temporarily ignore the difficulty
- Write a simplified solution
- Then incorporate that difficulty
Example : Write a function that takes a string as input and returns the count of each character
def charCount(tempString): # Declare an object to return at the end result = <> # Loop over the string for i in tempString: # If the char is a letter and it is in our object, add one to the value if i in result: result[i] += 1 # If the char is a letter and it is not in our object, # add that char to our object with the value of one else: result[i] = 1 # Return the object return result print(charCount("hello")) #Output
Step 5 – Looking back and Refactoring
Since we have completed the implementation of the problem, we now look back at the code and refactor it if required. It is an important step to refactor the code so as to improve efficiency.
The following questions can be helpful while looking back at the code and refactoring:
- Can we check the result?
- Can we derive the result differently?
- Can we understand it at a glance?
- Can we use the result or mehtod for some other problem?
- Can you improve the performance of the solution?
- How do other people solve the problem?
Example : Write a function that takes a string as input and returns the count of each character
def charCount(tempString): # Declare an object to return at the end result = <> # Loop over the string for i in tempString.lower(): # If the char is a lowercase letter and it is in our object, add one to the value if isinstance(i, str) and not(i.isspace()): if i in result: result[i] += 1 # If the char is a lowercase letter and it is not in our object, # add that char to our object with the value of one else: result[i] = 1 # Return the object return result print(charCount("hello")) #Output
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Code from Problem Solving with Algorithms and Data Structures using Python
License
ivanmmarkovic/Problem-Solving-with-Algorithms-and-Data-Structures-using-Python
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
I started the project by learning data structures and algorithms from a book Problem Solving with Algorithms and Data Structures using Python. It does not contain everything from the book, nor is everything implemented in the same way, but it also contains other data structures, algorithms and problems.
- Convert number — recursive solution
- Convert number — iterative solution
- Factorial
- Fibonacci — iterative solution
- Fibonacci — recursive worst solution
- Fibonacci — memoization
- Fibonacci — recursive solution
- Fibonacci sum
- Maze — path finder
- Palindrome
- Reverse linked list — recursive solution
- Reverse linked list — iterative solution
- Reverse linked list — iterative solution stack
- Reverse list
- Reverse string
- Sum numbers — binary recursion
- Sum numbers — recursion with pointer
- Sum numbers — recursion with slicing
- Towers of Hanoi
- Breadth first search
- Depth first search
- Depth first search — stack
- Depth first search — recursive
- Cycle detection directed graph
- Cycle detection undirected graph
- Priority Queue implementation
- Matrix implementation
- Minimum Spanning Tree in undirected graph
- Prim’s algorithm — Minimum Spanning Tree in undirected weighted graph
- Kruskal’s algorithm — Minimum Spanning Tree in undirected weighted graph
- Number of connected components
- Union find path compression