10 Programming Problems, Every Python Programmer Should Know.

Harsh Motiramani
5 min readDec 21, 2021

Programming languages are developing every day and are bringing ease to programmers. One of which is Python, a recent developer survey resulted that Python is the second loved programming language after JavaScript. This is because the programmers get good career options if they choose Python as their favourable language. Moreover, Python syntax is comparatively easy to remember than C or C++. Demand for Python Developers are increasing day by day in the last few months.

If you are a Python programmer or trying to master it, this blog is especially for you. Here I will list out some points which will help programmers to solve everyday problems effortlessly.

Now let's look at the problems that can be faced by a programmer:

1. Find the element with the highest frequency

Here we will have a list with random elements in it. Some of the elements will be repeating and we need to find the element with the highest frequency.

new_list = [a,b,a,d,e,g,g,a,c,f,k,t,u,z,x,a]
print("Most frequent element:", max(set(new_list),key= new_list.count))

Here the output would be the element ‘a’ as it is repeated 4 times.

2. Finding sub-strings from a list of strings.

In the below code we have a list of strings and we are going to search them with just a small keyword they have. Like in Method 1 when we searched for Meta we got Mark Zuckerberg in the output as they both are a part of one string. meta is just a sub-string. The same is done in Method 2 but with a different style.

data = ["Python, Programming Language","Meta, Mark Zuckerberg","Sebastian Vettel, F1 racer","Alexa, Amazon"]# Method 1name = "Meta"for data in data:if data.find(name) >= 0:print(data)# Method 2name = "Vettel"for data in data:if name in data:print(data)

3. Merging Dictionaries

Below are two dictionaries with certain elements in them. Here we are going to merge them and show us an output. The 1st method is where the dictionaries are unpacking themselves in the result which shows a merged output. In the 2nd method, we are copying the first dictionary in the result and then updating it with the 2nd dictionary. In the 3rd method, we have used a straightforward method which is called dictionary comprehension.

dict_no1 = {'h' : 1, 'e' : 2, 'l' : 3, 'l' : 4, 'o' : 5}dict_no2 = {'s' : 6, 'i' : 7, 'r' : 8}# Method 1result = { **dict_no1, **dict_no2}print(result)# Method 2result = dict_no1.copy()result.update(dict_no2)print(result)# Method 3result = {key: value for d in (dict_no1, dict_no2) for key, value in d.items()}print(result)

4. File Handling

File handling is used in Python when the user has to read large comma-separated values. The below code has a file named “abc” where we are performing various functions like opening a file, reading a file, reading a single line, closing a file & to write a file.

# Open a file
f = open('abc.txt')
# Read from a file
f = open('abc.txt', 'r')
# To read the whole file
print(f.read())
# To read single line
print(f.readline())
# Write to a file
f = open('abc.txt', 'w')
f.write('Writing into a file \n')
# Closing a file
f.close()

5. Sorting a List of Dictionaries

In the below code we have a dictionary with lists inside it, which contains information about some people. We will sort out the list based on their ‘id’, you can do it for any you require. We are using the sort() or sorted() functionality to perform the task here.

person = [
{
'name' : 'andrew',
'age' : 25,
'id' : 72365
},
{
'name' : 'bill',
'age' : 34,
'id' : 55443
},
{
'name' : 'cassie',
'age' : 22,
'id' : 63257
}
]
# Method 1
person.sort(key=lambda item: item.get("id"))
print(person)
# Method 2
person = sorted(person, key=lambda item: item.get("id"))
print(person)

6. Calculating Execution Time

The below code will calculate the execution time. We have used the time library. We measure the runtime of our code which will be printing all even numbers till 10 and then note the time taken to execute.

import timestart = time.time()# printing all even numbers till 10
for i in range(10):
if i % 2 == 0:
print(i, end = “ “)
end = time.time()
time_taken = end — start
print(“\nTime taken: “, time_taken)

7. Error Handling

In error handling, we use the try-catch theorem where there is a sudden stoppage if one of the possibilities doesn't match. In the below code we will be dividing two numbers so if the 2nd number is zero this code will throw an error instead of executing it and alerting the user.

no1, no2 = 4,0
try:
print(no1 / no2)
except ZeroDivisionError:
print("Division by Zero is not possible!")
finally:
print("Finally block.")

8. String Formatting

In string formatting, we modify strings, there are several methods to do this. In the below code some of them are mentioned. In the first method, basic concatenation is used which simply adds the strings together. In the second method, we use f-strings where the variable name is written in braces and changed during run-time. In the third method, we use the format() function which takes the string or variable to be inserted in the string as an argument and places it wherever it sees a curly brace. In the last method, we use “%s” which shows it is a string.

language = "C++"# Method 1
print(language + " is my favourite programming language.")
# Method 2
print(f"I code in {language}")
# Method 3
print("I like the {} programming language.".format(language))
# Method 4
print("%s is very easy to learn." % (language))

9. List comprehension using If-else.

List comprehension is very advantageous to users as it helps to make the code more compound and readable. In the below code we are finding the multiples of 8 and then the multiples of 2 & 4 using the if-else conditions.

my_list = ['Multiple of 8' if i % 8== 0
else 'Multiple of 2' if i % 2 == 0
else 'Multiple of 4' if i % 4== 0
else i for i in range(1, 20)]
print(my_list)

10. Flattening a list.

To flatten a list that contains multiple lists we can use the append() functionality and extent() functionality. The only difference they have is that append() uses a single variable to add to the list such that the length of the list increases by one whereas extends() adds all the elements in the list passed as argument one by one to the end of the original list.

mylist = [10,12,36,[41,59,63],[77],81,93]
flat = []
for i in mylist:
if isinstance(i, list): flat.extend(i)
else: flat.append(i)
print(flat)

So these were some python problems that programmers come across almost every day. Hope you like the blog!

--

--