The paper contains 5195 words and is expected to last 10 minutes
Image by Unsplash photographer Chris Ried
Python is a non-BS programming language. Simplicity of design and readability are two reasons for its popularity. As Python says: beautiful is better than ugly, explicit is better than implicit.
It’s useful to remember some common tips to help improve your coding design. In a pinch, these tips can save you the trouble of checking Stack Overflow online. And they’ll help you in your daily programming exercises.
1. Reverse the string
The following code uses the Python slicing operation to invert the string.
# Reversing a string using slicing
my_string = “ABCDE”
reversed_string = my_string[::-1]
print(reversed_string)
# Output
# EDCBA
2. Use title classes (capitalize)
The following code can be used to convert a string to a title class. This is done by using the title() method in the string class.
my_string = “my name is chaitanya baweja”
# using the title() function of string class
new_string = my_string.title()
print(new_string)
# Output
# My Name Is Chaitanya Baweja
3. Find unique elements of the string
The following code can be used to find all unique elements in a string. We use its attributes, where all elements in a set of strings are unique.
my_string = “aavvccccddddeee”
# converting the string to a set
temp_set = set(my_string)
# stitching set into a string using join
new_string = ”.join(temp_set)
print(new_string)
4. Output a string or list for n times
You can use multiplication (*) on strings or lists. This way, you can multiply them as much as you want.
n = 3 # number of repetitions
my_string = “abcd”
My_list = [1, 2, 3]
print(my_string*n)
# abcdabcdabcd
print(my_list*n)
# [1,2,3,1,2,3,1,2,3]
import streamlit as st
An interesting use case is to define a list with constant values, assuming zero.
n = 4
my_list = [0]*n # n denotes the length of the required list
# [0, 0, 0, 0]
5. List parsing
List resolution provides an elegant way to create lists on top of other lists.
The following code creates a new list by multiplying each object of the old list twice.
# Multiplying each element in a list by 2
Original_list = [1, 2, 3, 4]
new_list = [2*x for x in original_list]
print(new_list)
# [2,4,6,8]
6. Swap values between two variables
Python can swap values between two variables quite simply, without using a third variable.
a = 1
b = 2
a, b = b, a
print(a) # 2
print(b) # 1
7. Split the string into substring lists
Using the.split() method, you can split a string into a list of substrings. You can also pass the delimiter you want to split as an argument.
string_1 = “My name is Chaitanya Baweja”
string_2 = “sample/ string 2”
# default separator ‘ ‘
print(string_1.split())
# [‘My’, ‘name’, ‘is’, ‘Chaitanya’, ‘Baweja’]
# defining separator as ‘/’
print(string_2.split(‘/’))
# [‘sample’, ‘ string 2’]
8. Consolidate the string list into a single string
The join() method consolidates the list of strings into a single string. In the following example, use the comma delimiter to separate them.
list_of_strings = [‘My’, ‘name’, ‘is’, ‘Chaitanya’, ‘Baweja’]
# Using join with the comma separator
print(‘,’.join(list_of_strings))
# Output
# My,name,is,Chaitanya,Baweja
9. Check whether the given string is a Palindrome
Reversed strings have been discussed above. Thus, palindromes become a simple program in Python.
my_string = “abcba”
m if my_string == my_string[::-1]:
print(“palindrome”)
else:
print(“not palindrome”)
# Output
# palindrome
10. List element frequency
There are several ways to do this, and my favorite is Python’s Counter class. Python counters track the frequency of each element, and Counter() feeds back to a dictionary where elements are keys and frequencies are values.
The MOST_common () function is also used to get the MOST_frequent elements in the list.
# finding frequency of each element in a list
from collections import Counter
my_list = [‘a’,’a’,’b’,’b’,’b’,’c’,’d’,’d’,’d’,’d’,’d’]
count = Counter(my_list) # defining a counter object
print(count) # Of all elements
# Counter({‘d’: 5, ‘b’: 3, ‘a’: 2, ‘c’: 1})
print(count[‘b’]) # of individual element
# 3
print(count.most_common(1)) # most frequent element
# [(‘d’, 5)]
11. Check whether the two strings are anagrams
An interesting use of the Counter class is to find anagrams.
Anagrams are new words or words made by rearranging different words or the letters of different words.
If the counter objects of two strings are equal, they are anagrams.
From collections import Counter
str_1, str_2, str_3 = “acbde”, “abced”, “abcda”
cnt_1, cnt_2, cnt_3 = Counter(str_1), Counter(str_2), Counter(str_3)
if cnt_1 == cnt_2:
print(‘1 and 2 anagram’)
if cnt_1 == cnt_3:
print(‘1 and 3 anagram’)
12. Use the try-exception-else block
Error handling in Python is easily solved by using try/except blocks. It might be useful to add an else statement to the block. If there are no exceptions in the try block, it runs normally.
If you want to run something, use finally, without considering exceptions.
A, b = 1, 0
try:
print(a/b)
# exception raised when b is 0
except ZeroDivisionError:
print(“division by zero”)
else:
print(“no exceptions raised”)
finally:
print(“Run this always”)
13. Use enumeration to get index and value pairs
The following script uses enumeration to iterate over the values in the list and their indexes.
my_list = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
for index, value in enumerate(my_list):
print(‘{0}: {1}’.format(index, value))
# 0: a
# 1: b
# 2: c
# 3: d
# 4: e
14. Check the memory usage of objects
The following script can be used to check the memory usage of an object.
import sys
num = 21
print(sys.getsizeof(num))
# In Python 2, 24
# In Python 3, 28
15. Merge two dictionaries
In Python 2, the update() method is used to merge the two dictionaries, while Python3.5 makes the process easier.
In a given script, two dictionaries are merged. We used values from the second dictionary to avoid overlapping.
dict_1 = {‘apple’: 9, ‘banana’: 6}
dict_2 = {‘banana’: 4, ‘orange’: 8}
combined_dict = {**dict_1, **dict_2}
print(combined_dict)
# Output
# {‘apple’: 9, ‘banana’: 4, ‘orange’: 8}
16. The time required to execute a piece of code
The following code uses the Time software library to calculate the time it takes to execute a piece of code.
import time
start_time = time.time()
# Code to check follows
A, b = 1, 2
c = a+ b
# Code to check ends
end_time = time.time()
time_taken_in_micro = (end_time- start_time)*(10**6)
print(” Time taken in micro_seconds: {0} ms”).format(time_taken_in_micro)
17. Lists are flat
Sometimes you’re not sure how deep a list should be nested, and you just want all elements in a single flat list.
It can be obtained by:
from iteration_utilities import deepflatten
# if you only have one depth nested_list, use this
def flatten(l):
return [item for sublist in l for item in sublist]
L = [[1, 2, 3], [3]]
print(flatten(l))
# [1, 2, 3, 3]
# if you don’t know how deep the list is nested
L = [[1, 2, 3], [4, [5], [6, 7]], [8, [9, [10]]]]
print(list(deepflatten(l, depth=3)))
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
If you have a properly formatted array, Numpy flattening is a better choice.
18. List sampling
Using the Random software library, the following code generates n random samples from a given list.
import random
my_list = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’]
num_samples = 2
samples = random.sample(my_list,num_samples)
print(samples)
# [ ‘a’, ‘e’] this will have any 2 random values
Using the Secrets software library to generate random samples for encryption is highly recommended.
The following code is for Python 3 only.
import secrets # imports secure module.
secure_random = secrets.SystemRandom() # creates a secure random object.
my_list = [‘a’,’b’,’c’,’d’,’e’]
num_samples = 2
samples = secure_random.sample(my_list, num_samples)
print(samples)
# [ ‘e’, ‘d’] this will have any 2 random values
19. Digital
The following code converts an integer to a list of numbers.
num = 123456
# using map
list_of_digits = list(map(int, str(num)))
print(list_of_digits)
# [1, 2, 3, 4, 5, 6]
# using list comprehension
list_of_digits = [int(x) for x in str(num)]
print(list_of_digits)
# [1, 2, 3, 4, 5, 6]
20. Check uniqueness
The following function checks whether all elements in a list are unique.
def unique(l):
if len(l)==len(set(l)):
print(“All elements are unique”)
else:
print(“List has duplicates”)
Unique ([1, 2, 3, 4])
# All elements are unique
Unique (,1,2,3 [1])
# List has duplicates
Recommended Reading topics
Leave a comment like follow
We share the dry goods of AI learning and development. Welcome to pay attention to the “core reading technology” of AI vertical we-media on the whole platform.
(Add wechat: DXSXBB, join readers’ circle and discuss the freshest artificial intelligence technology.)