[experience sharing] 20 Python code segments, easy to cry!

Python is a non BS programming language. Design simplicity and readability are two reasons why it is so popular. Just like Python's tenet: beauty is better than ugliness, and explicit is better than implicit.

It's useful to keep in mind some common tips to help improve coding design. When necessary, these tips can reduce the trouble of checking Stack Overflow online. And they will help you in your daily programming practice.

1. Reverse string

The following code uses the Python slice operation to reverse the string.

# Reversing a string using slicing
my_string = "ABCDE"reversed_string = my_string[::-1] print(reversed_string) # Output# EDCBA

2. Use title class (capitalized)

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.

What I don't know in the learning process can add to me
 python learning qun, 855408893
 There are good learning video tutorials, development tools and e-books in the group.
Share with you the current talent needs of python enterprises and how to learn python from scratch, and what to learn

my_string = "my name is chaitanya baweja"
# using the title() function of string classnew_string = my_string.title()
print(new_string) # Output# My Name Is Chaitanya Baweja

3. Find unique elements of a string

The following code can be used to find all unique elements in a string. We use its properties, and all elements in one set of strings are unique.

my_string = "aavvccccddddeee"
# converting the string to a settemp_set = set(my_string) # stitching set into a string using joinnew_string = ''.join(temp_set)
print(new_string)

4. Output n strings or lists

You can use multiplication (*) for strings or lists. In this way, they can be multiplied as needed.

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 = 4my_list = [0]*n # n denotes the length of the required list# [0, 0, 0, 0]

5. List resolution

Based on other lists, list parsing provides an elegant way to create 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. Exchange value between two variables

Python can easily exchange values between two variables without using a third variable.

a = 1b = 2 a, b = b, a print(a) # 2print(b) # 1

7. Split a string into a list of substrings

By using the. split() method, you can divide a string into a list of substrings. You can also pass the separator you want to split as a parameter.

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. To combine a list of strings into a single string

The join() method consolidates a list of strings into a single string. In the following example, use the comma separator to separate them.

list_of_strings = ['My', 'name', 'is', 'Chaitanya', 'Baweja'] # Using join with the comma separatorprint(','.join(list_of_strings)) # Output# My,name,is,Chaitanya,Baweja

9. Check whether the given string is Palindrome

Inversion strings have been discussed above. Therefore, palindrome becomes a simple program in Python.

my_string = "abcba" m if my_string == my_string[::-1]:    print("palindrome")else:    print("not palindrome") # Output# palindrome

10. Element frequency of list

There are many ways to do this, and my favorite is to use Python's Counter class. The python Counter tracks the frequency of each element, and Counter() feeds back a dictionary, where element is key and frequency is value.

Also use the most common() function to get the most frequent element in the list.

What I don't know in the learning process can add to me
 python learning qun, 855408893
 There are good learning video tutorials, development tools and e-books in the group.
Share with you the current talent needs of python enterprises and how to learn python from scratch, and what to learn

# finding frequency of each element in a listfrom 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. Find if two strings are anagrams

An interesting application of the Counter class is to find anagrams.

anagrams are new words or words formed by reordering the letters of different words or 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. Using the try except else block

By using try/except blocks, error handling in Python can be easily resolved. It may be useful to add else statements to the block. If there is no abnormal condition in the try block, the operation is normal.

If you want to run some programs, use finally without considering exceptions.

a, b = 1,0 try:    print(a/b)    # exception raised when b is 0except ZeroDivisionError:    print("division by zero")else:    print("no exceptions raised")finally:    print("Run this always")

13. Using enumeration to get index and value pairs

The following script uses an enumeration to iterate over the values and their indexes in the list.

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 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, you use the update() method to merge two dictionaries, while Python 3.5 makes the process easier.

In the given script, the two dictionaries are merged. We used the values in the second dictionary to avoid crossing.

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. Time required to execute a piece of code

The following code uses the time library to calculate the time it takes to execute a piece of code.

import time

start_time = time.time()# Code to check followsa, b = 1,2c = a+ b# Code to check endsend_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. Flat list

Sometimes you're not sure about the nesting depth of the list and just want all the features in a single flat list.

It can be obtained by:

from iteration_utilities import deepflatten # if you only have one depth nested_list, use thisdef 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 nestedl = [[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

By using the random 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

It is highly recommended to use the secrets software library to generate random samples for encryption.

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. Digitalization

The following code converts an integer to a list of numbers.

What I don't know in the learning process can add to me
 python learning qun, 855408893
 There are good learning video tutorials, development tools and e-books in the group.
Share with you the current talent needs of python enterprises and how to learn python from scratch, and what to learn

num = 123456
# using maplist_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 features 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,1,2,3])# List has duplicates


Keywords: Programming Python

Added by dcooper on Wed, 29 Apr 2020 12:59:50 +0300