5 Python Exercises

5 Python Exercises

<strong>Originally published by </strong><a href="https://medium.com/@farhadmalik84" target="_blank">Farhad Malik</a><strong> </strong><em>at&nbsp;</em><a href="https://medium.com/fintechexplained/5-python-exercises-35b36f1ca742" target="_blank"><em>Medium</em></a>

Best Way To Strengthen And Practice Your Python Skills

Here are 5 Python exercises.

For each exercise, I will also mention the topics it is intending to test. By the end of the exercise, you will feel that you have gained a much superior end-to-end understanding of the language.

Remember, there are multiple ways to peel an orange so solve the questions how you understand them. I will post the answers in an upcoming blog soon.### 1. Logging Using Python Decorator

  1. Implement a calculator class with following functions:

Sum(a,b), Multiply(a,b), Divide(a,b) and Subtract(a,b)

  1. Import logging library

  2. Decorate each method of the calculator class with a custom method that logs the values of a and b. Implement the logger custom method too.

  3. Execute calculator.Sum(a,b) and it should print out the values of a and b. For example:

The Input Values Of A and B Are '123' and '234' # if a =123 and b=234

What Will It Test?

  • It will test whether you understood Pip commands that are required to import the libraries
  • How to create class and functions with arguments in Python
  • How to use decorators

    2. Tree Traversal Using Python Recursion

  1. Implement a class: *Node *which will be used to represent a tree. For example:
class Node(object):
    def __init__(self, name):
        self.name= name
        self.children = []
 def add_child(self, obj):
        self.children.append(obj)

Each node has a name and children e.g.

a = Node('A')
a_goal = Node('Goal')
a.add_child(a_goal)
  1. Print out all of the paths of the tree which can lead you to the node named “Goal”.

  2. The tree can have N number of levels (1>N>100). Goal node can have children too.

For example, for tree below, your code should print out following paths:

A->Goal

A->B->Goal

A->D->Goal

A->F->H->L->Goal

All other paths do not lead you to the Goal node.

Write your code in a way that it can be unit tested.

What Will It Test?

  • It should test your understanding of recursion
  • It should also test how you prevent from going into infinite loops — it will test your loops, expression and conditional logic
  • It will also test your data structures understanding and variables scope

    3. Flatten A List Of Nested Dictionaries Into A List Of Multiple Flattened Dictionaries

  1. Create an object which contains a list of dictionaries.
  2. Each item in the list is a dictionary which contains a number of keys.
  3. Each key of the dictionary will contain a value. The value can be of type string, or it can be a of type dictionary. When the value is of type dictionary then it implies that it is a nested dictionary within a dictionary.
  4. Each dictionary can contain a variable number of keys.
  5. Loop over the items and create a single dictionary to store keys at the same level. For example, if you loop over the items and if each item contains a dictionary with two keys e.g.“Name” and “Surname” and both of the keys contain values of type string then simply return the collection of dictionaries (as it’s already flat).
  6. However if it contains “Name”, “Surname” and “PlacesVisited” keys, where PlacesVisited is itself a list of dictionaries such that each item of the dictionary contains two keys “Name of place” and “date when it was visited” then I expect to see two lists as the result. First list should contain a collection of dictionaries with keys Name and Surname. The second list should contain the keys “Name Of place”, “date when it was visited” and ParentId where ParentId will contain the key “Name” of the first dictionary.
  7. Take the value of the ParentId as the value of the first key of the parent dictionary e.g. for the example above, “Name” is chosen as the ParentId.

For each nested dictionary, create a new dictionary.

Final result should be a number of flatten dictionaries to represent a nested dictionary

For example, if this is your input:

sample_object = [
{'Name':'Farhad', 'Surname:'Malik', 'Blogs':{'BlogName:'Python1','Date1':'20180901'}},
{'Name':'Farhad2', 'Surname:'Malik2', 'Blogs':{'BlogName:'Python3','Date1':'20180101'}}
]
The result should be:

dictionary_1 = [
{'Name':'Farhad', 'Surname:'Malik'}, 
{'Name':'Farhad2', 'Surname:'Malik2'}
]
dictionary_2 = [
{'ParentId':'Farhad', 'BlogName:'Python1','Date1':'20180901'},
{'ParentId':'Farhad2','BlogName:'Python3','Date1':'20180101'}
]

The key is to ensure that the items at the same level belong to the same dictionary.

What Will It Test?

  • It should test your understanding of dictionaries, arrays and sets.
  • It should also help you understand how to check for keys and values
  • Lastly, it will help you see how you can pass in optional parameters.
  • This is how you can flatten out a JSON object.

    4. Multi-Process And Error Handling Code

  • Take the three exercises above, make the code run on multiple processes
  • Use try/catch and catch exceptions where appropriate
  • Profile and log performance of the code
  • Write unit tests for each of the exercises that perform positive and negative tests

    What Will It Test?

  • This will really help you see how to run your code on multiple processes
  • How to catch exceptions and how to enable logging in your code to an extent that it is useful.

    5. Package And Modules

  • Create the classes and code that you have implemented above into a package with multiple modules
  • Understand how the files should be placed and imported.
  • Create a main class that drives everything
  • Write out a console application that runs your unit tests via command line and informs you the tests that have passed or failed.

    What Will It Test?

  • It should help you really understand and see how packages and modules work
  • You will get a solid understanding of Python programming language

    Summary

This article presented you with 5 Python exercises.

Please post your answers in the comments section. I will post the answers in my upcoming Python blogs.

If you want more exercises, please do let me know.

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Top Python Development Companies | Hire Python Developers

After analyzing clients and market requirements, TopDevelopers has come up with the list of the best Python service providers. These top-rated Python developers are widely appreciated for their professionalism in handling diverse projects. When...

Python GUI Programming Projects using Tkinter and Python 3

Python GUI Programming Projects using Tkinter and Python 3

Guide to Python Programming Language

Guide to Python Programming Language