Advanced Usage of Python

In this tutorial, we will learn how to use Python in an advanced way to solve common coding problems. We will follow the see two approaches - The basic and the advanced approaches.

All the coding problems presented here are based on the Advent of Code challenge puzzles. These problems are commonly used in various coding challenges and assessments, including job interviews, and have been reused in multiple iterations of the Advent of Code challenge. Instead of providing complete solutions to the Advent of Code puzzles, we will concentrate on a specific portion of a puzzle that serves as a good indicator of a developer's skill level. It will help to differentiate between non-experienced and experienced developers.

1. Use Enum instead of If-elif-else

In this problem; we will solve the rock-paper-scissors game. The problem involves assigning different point values (1, 2, and 3) to three shapes (rock, paper, and scissors). Two different methods have been presented below to solve this problem. Let's understand the following example.

Input

X

Y

Z

Desired

1

2

3

Example - Basic Approach

Example - Advance Approach

Explanation -

The code snippet above defines an enumeration class RockPoints with three members X, Y, and Z, each with an associated integer value (1, 2, and 3, respectively). The rock_paper_scissor() function takes a string shape as input and returns the corresponding integer value of the RockPoints member that has the same name as the input string.

2. Use lookup tables instead of dictionaries reshape

As we know, letters have different values. The lowercase a-z starts from 1 to 26, and the uppercase A-Z starts from 27 to 52. Using an enumeration class like RockPoints can result in much code, especially when many possible values exist. Using a lookup table is a more practical approach. A lookup table maps each possible input to its corresponding output value, allowing for quick and easy retrieval of the desired value without needing a complex class hierarchy or conditional statements.

Let's understand the following example.

Example -

Input

Output:

3
52
1

Example - Basic Approach

Example - Advance Approach

Explanation -

The letter_value() function takes a string ltr as input and returns an integer representing the alphabetical position of the given letter in the English alphabet. Here's how it works:

  • The string 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' represents all the letters of the English alphabet, in both lower and upper case.
  • The index method of a string returns the index of the first occurrence of the given substring in the string. In this case, ltr is used as the substring to search for in the alphabet string.
  • Since the English alphabet is arranged in alphabetical order, the index of the letter in the alphabet string corresponds to its alphabetical position. However, since indexing in Python starts from 0 rather than 1, we need to add 1 to the index to get the correct alphabetical position.

The resulting integer is then returned as the output of the function.

For example, letter_value('A') would return 1, while letter_value('Z') would return 26. Note that the function assumes that the input letter is a valid English alphabet letter; otherwise, an exception may be raised. We can also solve the rock, paper, scissors problem using lookup table.

Example -

3. Advance Slicing

In this problem, we need to read letters from lines. In this scenario, every fourth letter of a given string should be selected, starting from the first letter. Although most Python programmers are familiar with string and list slicing. Advance slicing is possible to specify the step size using slicing.

Input

[D]
[N] [C]
[Z] [M] [P]

Output

[' D ', 'NC', 'ZMP']

Example - Basic Approach

Example - Advance Approach

4. Use a class attribute to store a class instance

In Python, a class attribute is a variable that is shared by all instances of a class. To store class instance in a class attribute, we can define the class attribute as a list or a dictionary, and then add each instance to that list or dictionary when it is created. Let's understand the following example.

Example -

Output:

[<__main__.MyClass object at 0x7f3c978c4f50>, <__main__.MyClass object at 0x7f3c978c5110>, <__main__.MyClass object at 0x7f3c978c5150>]

Explanation -

In this example, the MyClass class has a class attribute instance that is initially an empty list. In the __init__ method, each class instance adds itself to the instances list using the append() method. Finally, after creating some instances of the class, the instances list is printed to show all instances of the class.

5. Self-Documenting Expression

In this approach, we define the self documenting expression in which we use print(f"{x = }) to print the with a specification of what we are printing. Let's understand the following example.

Input

x = 10 * 2

y = 3 * 7

max(x,y)

Output

x = 20

y = 21

max(x,y) = 21

Example - Basic Approach

Example - Advance Approach

6. Read in a file effectively with comprehensions and splits

Suppose we have a file that includes the numbers separated by the '/n'. We can read effectively in less line number of code. Let's understand the following example.

Example -

Input

10

20

30

50

60

70

Output

[[10, 20, 30], [50, 60 70]]

Example - Basic Approach

Example - Advance Approach

As we can see that, we reduce the 10 lines of previous example into two lines without losing significant understandability or readability and gaining performance.

Conclusion

This tutorial included the some important techniques which differentiate experience and junior developer. These tricks won't make any junior to experience developer overnight but gives insight how we can improve as a junior developer.






Latest Courses