Learn these Python art skills and wait for your girlfriend to praise you

Keywords: Python pip less OpenCV

1, Foreword

Python has many libraries for image processing, such as pilot or OpenCV. Most of the time, it's useless to learn these image processing modules, but you don't know how to use them. Today, I've brought you some art skills to make your art come true. The circle of friends is full of praise. My girlfriend also praises you. How powerful are you!

Many people study python and don't know where to start.

Many people learn python, master the basic syntax, do not know where to find cases to start.

Many people who have already done cases do not know how to learn more advanced knowledge.

Then for these three types of people, I will provide you with a good learning platform, free access to video tutorials, e-books, and the source code of the course!

QQ group: 1097524789

2, Module installation

We mainly use OpenCV and pilot. In addition, we also use wordcloud and paddlehub. Let's install the following:


pip install opencv-python
pip install pillow
python -m pip install paddlepaddle -i https://mirror.baidu.com/pypi/simple
pip install -i https://mirror.baidu.com/pypi/simple paddlehub
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple/ myqr

In addition, the Python environment I use is 3.7. Knowing this, we can start our journey of beauty map.

3, Picture beautification

1. Acne elimination

Still have trouble for acne, dare not take photos? With this, you don't need to be afraid (although there is p-chart software, please don't expose me):


import cv2
level = 22    #Noise reduction level
img = cv2.imread('girl.jpg')    #Read original
img = cv2.bilateralFilter(img, level, level*2, level/2)    #Beauty
cv2.imwrite('result.jpg', img)    

In fact, on a smooth face, acne can be regarded as a noise, and we can achieve the effect of eliminating acne and freckle through noise reduction. In OpenCV, we provide the corresponding filter, which we just need to call. The comparison between the original drawing and the realization effect drawing is as follows:

You can see that the spots on your face are obviously less. Gentlemen should notice that the skin under the neck is much smoother. But the details of the hair were erased. We can adjust the effect by adjusting the level parameter. If you want better results, you can combine face recognition, local acne treatment.


2. Word cloud - I'm not just a picture

In fact, the word cloud is a cliche, but it is necessary to list the beautiful ones in the painting, because a word cloud can contain too much information:


from PIL import Image
import numpy as np
from wordcloud import WordCloud, ImageColorGenerator

#Read background picture
mask = np.array(Image.open('rose.png'))

#Define word cloud objects
wc = WordCloud(
    #Set word cloud background to white
    #Set the font with the largest word cloud
    #Set word cloud outline
    #Font path. If you need to generate Chinese word cloud, you need to set this property. The font you set needs to support Chinese
#Read text
text = open('article.txt', 'r', encoding='utf-8').read()
#Generative word cloud
#Color words
wc = wc.recolor(color_func=ImageColorGenerator(mask))
#Save word cloud

among article.txt For our word cloud text material, and rose.png It is the outline of the word cloud (the background of the picture should be strict white or transparent). The original picture and implementation effect are as follows:

It's still very beautiful. For more details, please refer to https://blog.csdn.net/ZackSock/article/details/103517841 .


3. Style transfer - try to be what you like

Style transfer, as the name implies, is to transfer the style of one image to another. For example, I took a picture of the day, but I want a picture of the night scene, so what should we do? Of course, we'll wait until the evening, but in addition to this method, we can download a night view picture to transfer the night view effect to our original picture.

The implementation of style migration can only be realized by using deep learning, but the vegetable chicken like me will not learn in depth, so we directly use the implemented model library in paddlehub:


import cv2
import paddlehub as hub
#Load model library
stylepro_artistic = hub.Module(name="stylepro_artistic")
#Style transfer
im = stylepro_artistic.style_transfer(
            'content': cv2.imread("origin.jpg"),
            #Style map
            'styles': [cv2.imread("style.jpg")]
    alpha = 0.1
#Get the darray object of the picture from the returned data
im = im[0]['data']
#Save result picture
cv2.imwrite('result.jpg', im)

The style and effect of the original drawing are as follows:

On the left is the original picture, in the middle is the style picture, and on the right is the effect picture. The above effect is OK, but it's not always successful. Try more.


4. In the picture - every pixel is you

This is a little more complicated than the above. We need to prepare a gallery, make these pictures as materials, and then make the most appropriate replacement according to the main tone of an area of the picture. The code is as follows:


import os
import cv2
import numpy as np

def getDominant(im):
    """Get main tone"""
    b = int(round(np.mean(im[:, :, 0])))
    g = int(round(np.mean(im[:, :, 1])))
    r = int(round(np.mean(im[:, :, 2])))
    return (b, g, r)

def getColors(path):
    """Get the tone table of the picture list"""
    colors = []

    filelist = [path + i for i in os.listdir(path)]
    for file in filelist:
        im = cv2.imdecode(np.fromfile(file, dtype=np.uint8), -1)
        dominant = getDominant(im)
    return colors

def fitColor(color1, color2):
    """Returns the difference between two colors"""
    b = color1[0] - color2[0]
    g = color1[1] - color2[1]
    r = color1[2] - color2[2]
    return abs(b) + abs(g) + abs(r)

def generate(im_path, imgs_path, box_size, multiple=1):
    """Generate picture"""

    #Read picture list
    img_list = [imgs_path + i for i in os.listdir(imgs_path)]

    #Read picture
    im = cv2.imread(im_path)
    im = cv2.resize(im, (im.shape[1]*multiple, im.shape[0]*multiple))

    #Get picture width and height
    width, height = im.shape[1], im.shape[0]

    #Traverse image pixels
    for i in range(height // box_size+1):
        for j in range(width // box_size+1):

            #Block start coordinates
            start_x, start_y = j * box_size, i * box_size

            #Initialize the width and height of the picture block
            box_w, box_h = box_size, box_size

            box_im = im[start_y:, start_x:]
            if i == height // box_size:
                box_h = box_im.shape[0]
            if j == width // box_size:
                box_w = box_im.shape[1]

            if box_h == 0 or box_w == 0:

            #Get main tone
            dominant = getDominant(im[start_y:start_y+box_h, start_x:start_x+box_w])

            img_loc = 0
            #Difference, the maximum difference with the main color is 255 * 3
            dif = 255 * 3

            #Traverse the color table to find the picture with the smallest difference
            for index in range(colors.__len__()):
                if fitColor(dominant, colors[index]) < dif:
                    dif = fitColor(dominant, colors[index])
                    img_loc = index

            #Read the picture with the smallest difference
            box_im = cv2.imdecode(np.fromfile(img_list[img_loc], dtype=np.uint8), -1)

            #Convert to appropriate size
            box_im = cv2.resize(box_im, (box_w, box_h))

            #Bedding color block
            im[start_y:start_y+box_h, start_x:start_x+box_w] = box_im

            j += box_w
        i += box_h

    return im

if __name__ == '__main__':

    #Get tone list
    colors = getColors('emoticon/')
    result_im = generate('main.jpg', 'emoticon/', 50, multiple=5)
    cv2.imwrite('C:/Users/zaxwz/Desktop/result.jpg', result_im)

About the implementation, I will write an article to analyze in detail later. Let's look at the renderings:

We can still see the characters in the pictures, but the colors in some places are not right, which is based on our gallery. We can see hundreds of small pictures when we enlarge the picture. (of course, you can't see it when you zoom in, because the resolution is too low.)


5. Switch backgrounds - take you on a trip

Recently, many photos have been taken at home. Unfortunately, the background is all sofa. Meet me is your girlfriend's blessing, see how I change 10 lines of code for the picture background:


from PIL import Image
import paddlehub as hub
#Load model
humanseg = hub.Module(name='deeplabv3p_xception65_humanseg')
results = humanseg.segmentation(data={'image':['xscn.jpeg']})
#Read background picture
bg = Image.open('bg.jpg')
#Read original
im = Image.open('humanseg_output/xscn.png').convert('RGBA')
im.thumbnail((bg.size[1], bg.size[1]))
#Separation channel
r, g, b, a = im.split()
#Paste the picked picture on the background
bg.paste(im, (bg.size[0]-bg.size[1], 0), mask=a)

Let's look at our results:

6. Jiugongge - a picture can't hold your beauty

Many people like to send nine palace pictures, but they usually don't have so many pictures. At this time, they need to use expression packs to occupy the space. For the technical house, this unreasonable way is not allowed, so we write the following code:


from PIL import Image
#Read picture
im = Image.open('xscn.jpeg')
#Divide the width and height by 3 to get the size of a single image after clipping
width = im.size[0]//3
height = im.size[1]//3
#Top left corner coordinates of crop image
start_x = 0
start_y = 0
#Used to name pictures
im_name = 1
#Cycle crop picture
for i in range(3):
    for j in range(3):
        #Crop picture and save
        crop = im.crop((start_x, start_y, start_x+width, start_y+height))
        crop.save(str(im_name) + '.jpg')
        #Move the x axis of the upper left coordinate to the right
        start_x += width
        im_name += 1
    #When the first line is cut, x continues to cut from 0
    start_x = 0
    #Cut the second line
    start_y += height

After executing the above code, we can generate pictures named 1-9. These pictures are our nine palace pictures. Let's see the test results:

Insert picture description here

It has to be said that Komatsu is really beautiful.


7. Picture QR Code: the cold picture is full of deep feelings

Do you dare to say something if you want to? Let's try QR code. The small picture is full of deep feelings:


from MyQR import myqr
    words='http://www.baidu.com , including information
    picture='lbxx.jpg',            #Background picture
    colorized=True,            #Is there a color? If it is False, it is black and white
    save_name='code.png'    #Output filename

The renderings are as follows:

Insert picture description here

Because the two-dimensional code above has been specially processed by me, when you scan the code, you will find that the code above is the code in the code. You need to scan many times to get the final result. You can play your imagination and make something interesting.

This article lists 53 Python interview questions and provides answers for several scientists and software engineers. Not long ago, I started a new role as a "data scientist", actually a "Python engineer".
If I had known Python's thread life cycle before the interview, rather than its Recommender System, I might have done better in the interview.
In order to help you pass the interview, I sorted out my questions for Python interview / job preparation and provided answers. Most data scientists write a lot of code, so these questions / answers apply to both scientists and engineers.
Whether you're an interviewer, preparing for a job, or just trying to improve your Python skills, this list will be invaluable to you.
The problem is out of order. Let's start.

Classic interview questions and answers
1. What's the difference between a list and a tuple?

In every interview I have for a Python data scientist, this question is asked. So the answer to this question, I can say, is very clear.

  • The list is variable. It can be modified after creation.
  • Tuples are immutable. Once a tuple is created, it cannot be changed.
  • The list represents the order. They are ordered sequences, usually objects of the same type. For example, all user names sorted by creation date, such as ["Seth", "Ema", "Eli"].
  • Tuples represent structures. Can be used to store elements of different data types. For example, in memory database records, such as (2, "Ema", "2020 – 04 – 16") (ාid, name, creation date).

2. How to perform string interpolation?
There are three methods for string interpolation without importing the Template class.

name =  Chris # 1. f stringsprint(f Hello {name} )# 2. % operatorprint( Hey %s %s  % (name, name))# 3. formatprint( "My name is {}".format((name)))

3. What's the difference between "is" and "= ="?
Early in my Python career, I thought they were the same, creating some bug s. So please listen, "is" is used to check the ID of the object, and "= =" is used to check whether two objects are equal. We will illustrate it with an example. Create some lists and assign them to different names. Notice that b below points to the same object as a.

a = [1,2,3]b = ac = [1,2,3]

Let's check if they are equal. You will notice that the results show that they are all equal.

print(a == b)print(a == c)#=> True#=> True

But do they have the same id? The answer is No.

print(a is b)print(a is c)#=> True#=> False

We can verify this by printing their object IDs.

print(id(a))print(id(b))print(id(c))#=> 4369567560#=> 4369567560#=> 4369567624

You can see that c and a and b have different IDs.
4. What is a decorator?
This is another question I get asked in every interview. It's worth writing an article on its own. If you can write an example with it, you are ready.
A decorator allows you to add some additional functionality to an existing function by passing an existing function to the decorator, which performs the functionality of the existing function and the additional functionality added.
We will write a decorator that logs when another function is called.
Write the decorator function logging. It takes a function func as an argument. It also defines a log_ function_ The function of called, which first executes printing some information called "function func is called" (print(f {func} called.)), and then calls function func(). Finally, return the defined function.

def logging(func):  def log_function_called():    print(f {func} called. )    func()  return log_function_called

Let's write two other functions that we will eventually add the decorator to (but not yet).

def my_name():  print( chris )def friends_name():  print( naruto )my_name()friends_name()#=> chris#=> naruto

Now add the decorator to the two functions you wrote above.

@loggingdef my_name(): print( chris )@loggingdef friends_name(): print( naruto )my_name()friends_name()#=> <function my_name at 0x10fca5a60> called.#=> chris#=> <function friends_name at 0x10fca5f28> called.#=> naruto

Now you've learned how to easily add logs to any function we write by simply adding @ logging (decorator) to it.
5. Explain Range function
The Range function can be used to create a list of integers, which is usually used in a for loop. There are three ways to use it.
The Range function can take 1 to 3 parameters, which must be integers.
Note: I've wrapped each use of range in a list compression so we can see the generated values.
Usage 1 - range(stop): generates an integer from 0 to the parameter 'stop'.

[i for i in range(10)]#=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Usage 2 - range(start, stop): generates an integer from the parameter "start" to "stop"

[i for i in range(2,10)]#=> [2, 3, 4, 5, 6, 7, 8, 9]

Usage 3 - range(start, stop, step): generates an integer from "start" to "stop" in steps of parameter "step".

[i for i in range(2,10,2)]#=> [2, 4, 6, 8]

6. Define a class called car, which has two properties: "color" and "speed". Then create an instance and return to speed.

class Car :    def __init__(self, color, speed):        self.color = color        self.speed = speedcar = Car( red , 100mph )car.speed#=>  100mph

7. What's the difference between instance method, static method and class method in Python?
Instance method: accepts the self parameter and is related to a specific instance of the class.
Static method: use the decorator @ staticmethod, which is independent of a specific instance and self-contained (you cannot modify the properties of a class or instance).
Class method: accepts cls parameters and can modify the class itself. We will illustrate the difference between them through a fictional CoffeeShop class.

class CoffeeShop:    specialty =  espresso 
def __init__(self, coffee_price): self.coffee_price = coffee_price
# instance method def make_coffee(self): print(f Making {self.specialty} for ${self.coffee_price} )
# static method @staticmethod def check_weather(): print( Its sunny ) # class method @classmethod def change_specialty(cls, specialty): cls.specialty = specialty print(f Specialty changed to {specialty} )

The CoffeeShop class has an attribute particularity, which is set to "Expresso" by default. Each instance of the coffee shop class is initialized with coffee_price. At the same time, it has three methods, an instance method, a static method and a class method.
Let's take the coffee_ The value of price is set to 5 to initialize an instance of CoffeeShop. Then call the instance method make_. coffee.

coffee_shop = CoffeeShop( 5 )coffee_shop.make_coffee()#=> Making espresso for $5

Now let's call the static method. Static methods cannot modify the state of a class or instance, so they are often used for utility functions, such as adding 2 numbers. We use it here to check the weather. It's sunny. Excellent!

coffee_shop.check_weather()#=> Its sunny

Now let's use the class method to modify the attribute specialty of CoffeeShop, and then call make_. Coffee () method to make coffee.

coffee_shop.change_specialty( drip coffee )#=> Specialty changed to drip coffeecoffee_shop.make_coffee()#=> Making drip coffee for $5

Notice, make_coffee used to be used for espresso, but now it's used for drip coffee!
8. What's the difference between "func" and "func()"?
The purpose of this question is to see if you understand that all functions are also objects in Python.

def func():    print( Im a function )
func#=> function __main__.func>func() #=> Im a function

Func is an object representing a function that can be assigned to a variable or passed to another function. The parenthesized func() calls the function and returns its output.
9. Explain the working principle of map function.
The Map function returns a list of values returned when a function is applied to each element in the sequence.

def add_three(x):    return x + 3li = [1,2,3][i for i in map(add_three, li)]#=> [4, 5, 6]

Above, I added 3 to the value of each element in the list.
10. Explain how the reduce function works.
It's a tricky problem. Before you use it a few times, you have to try to understand it. reduce takes a function and a sequence, and then iterates over the sequence. In each iteration, the output of the current and previous elements is passed to the function. Finally, a value is returned.

from functools import reducedef add_three(x,y):    return x + y    li = [1,2,3,5]    reduce(add_three, li)#=> 11

Returns 11, which is the sum of 1 + 2 + 3 + 5.

11. Explain the working principle of filter function
As the name implies, the Filter function is used to Filter elements in order.
Each element is passed to a function, which returns True in the output sequence, and False in the output sequence.

def add_three(x):    if x % 2 == 0:        return True            else:        return Falseli = [1,2,3,4,5,6,7,8][i for i in filter(add_three, li)]#=> [2, 4, 6, 8]

Notice how all the above elements that cannot be divided by 2 are deleted.
12. Is Python called by reference or by value?
If you Google the question and read the first few pages, you're ready to enter the semantic maze. You'd better just understand how it works.
Immutable objects, such as strings, numbers, tuples, and so on, are called by value. Note the following example, when modifying inside a function, the value of name does not change outside the function. The value of name has been assigned to a new block in memory for the function scope.

name =  chr def add_chars(s):   s +=  is    print(s)add_chars(name)    print(name)#=> chris#=> chr

Mutable objects, such as lists, are called by reference. Notice in the following example how changes to the list of external definitions within a function affect the list of external definitions. The parameters in the function point to the original block in memory where the li value is stored.

li = [1,2]def add_element(seq):   seq.append(3)   print(seq)add_element(li)    print(li)#=> [1, 2, 3]#=> [1, 2, 3]

13. how to use the reverse function to reverse a list?
The following code calls the reverse() function on a list to modify it. The method does not return a value, but sorts the elements of the list in reverse.

li = [ a , b , c ]print(li)li.reverse()print(li)#=> [ a ,  b ,  c ]#=> [ c ,  b ,  a ]

14. How does string multiplication work?

Let's look at the result of multiplying the string "cat" by 3.

 cat  * 3#=>  catcatcat

The string will connect itself three times.
15. How does list multiplication work?
Let's look at the result of multiplying the list [1,2,3] by 2.

[1,2,3] * 2#=> [1, 2, 3, 1, 2, 3]

The output list contains the contents of the list [1,2,3] that is repeated twice.
16. What does "self" in a class mean?
"self" refers to an instance of the class itself. This is our ability to give method access and update the objects to which the method belongs.
Next, pass self to__ init__ (), enabling us to set the instance color at initialization time.

class Shirt:    def __init__(self, color):        self.color = color
s = Shirt( yellow )s.color#=> yellow

17. How to connect lists in Python?
To add two lists is to join them together. Note, however, that arrays do not work this way.

a = [1,2]b = [3,4,5]
a + b#=> [1, 2, 3, 4, 5]

18. What's the difference between a shallow copy and a deep copy?
We will discuss this problem in the context of a variable object (list). For immutable objects, the difference between shallow copy and deep copy is not important.
We will introduce three situations.
1. Reference the original object. This points the new object li2 to the same location in memory that li1 points to. Therefore, any changes we make to li1 will also happen in li2.

li1 = [[ a ],[ b ],[ c ]]li2 = li1li1.append([ d ])print(li2)#=> [[ a ], [ b ], [ c ], [ d ]]

2. Create a shallow copy of the original object. We can do this using the list() constructor. A shallow copy creates a new object, but populates it with a reference to the original object. Therefore, adding new objects to the original list li3 will not propagate to li4, but modifying an object in li3 will propagate to li4.

li3 = [[ a ],[ b ],[ c ]]li4 = list(li3)li3.append([4])print(li4)#=> [[ a ], [ b ], [ c ]]li3[0][0] = [ X ]print(li4)#=> [[[ X ]], [ b ], [ c ]]

3. Create a deep copy. This is for copy.deepcopy() completed. Now, the two objects are completely independent, and changes made to one object have no effect on the other.

import copyli5 = [[ a ],[ b ],[ c ]]li6 = copy.deepcopy(li5)li5.append([4])li5[0][0] = [ X ]print(li6)#=> [[ a ], [ b ], [ c ]]

19. What's the difference between a list and an array?
Note: Python's standard library has an array object, but here I specifically refer to the commonly used Numpy array.

  • The list exists in python's standard library. The array is defined by Numpy.
  • The list can be populated with different types of data at each index. Array requires isomorphic elements.
  • Arithmetic operations on a list add or remove elements from the list. Arithmetic operations on arrays work in a linear algebraic fashion.
  • Lists also use less memory and significantly more functionality.

20. How to connect two arrays?
Remember, arrays are not lists. Arrays come from Numpy and arithmetic functions, such as linear algebra. We need to use Numpy's connect function concatenate() to do this.

import numpy as npa = np.array([1,2,3])b = np.array([4,5,6])np.concatenate((a,b))#=> array([1, 2, 3, 4, 5, 6])

21. What do you like about Python?
Python is very readable, and there is a python way to handle almost everything, which means it has a concise preferred method.
I'll compare Python with ruby. Ruby usually has many ways to do something, but there is no guide to which is the preferred way.
22. Which library of Python do you like best?
When dealing with large amounts of data, there is nothing more helpful than panda, because panda makes it easy to operate and visualize data.
23. What are some examples of mutable and immutable objects?
Immutability means that the state cannot be modified after creation. For example: int, float, bool, string, and tuple.
Mutability means that the state can be modified after creation. For example, list, dict and set.
24. How to round a number to three decimal places?

Use round (value, decimal_ Place) function.

a = 5.12345round(a,3)#=> 5.123

25. How to split a list?
Split syntax uses three parameters, list[start:stop:step], where step is the interval that returns the element.

a = [0,1,2,3,4,5,6,7,8,9]print(a[:2])#=> [0, 1]print(a[8:])#=> [8, 9]print(a[2:8])#=> [2, 3, 4, 5, 6, 7]print(a[2:8:2])#=> [2, 4, 6]

26. What is pickling?
Pickling is a common method for serializing and deserializing objects in Python. In the following example, we serialize and deserialize a dictionary list.

import pickleobj = [   { id :1,  name : Stuffy },   { id :2,  name :  Fluffy }]with open( file.p ,  wb ) as f:   pickle.dump(obj, f)with open( file.p ,  rb ) as f:   loaded_obj = pickle.load(f)print(loaded_obj)#=> [{ id : 1,  name :  Stuffy }, { id : 2,  name :  Fluffy }]

27. What's the difference between a dictionary and JSON?
Dict is a data type in Python, a collection of indexed but unordered keys and values.
JSON is just a string in the specified format for data transfer.
28. What ORM do you use in Python?
ORM (object relational mapping) maps data models (usually in applications) to database tables and simplifies database transactions.
SQLAlchemy is usually used in the context of Flask, while Django has its own ORM.
29. How do any() and all() work?
Any accepts a sequence and returns true if any element in the sequence is true. All returns true only if all elements in the sequence are true.

a = [False, False, False]b = [True, False, False]c = [True, True, True]print( any(a) )print( any(b) )print( any(c) )#=> False#=> True#=> Trueprint( all(a) )print( all(b) )print( all(c) )#=> False#=> False#=> True

30. Which is faster to find dictionaries or lists?
It takes O (n) time to find a value in a list, because you need to traverse the entire list until you find the value.
It takes only O (1) time to find a value in the dictionary because it is a hash table.
If there are many values, this can cause a big time difference, so it is usually recommended to use a dictionary to improve speed. But dictionaries have other limitations, such as the need for unique keys.
31. What's the difference between module and package?
Modules are files (or collections of files) that can be imported together.

import sklearn

A package is a directory of modules.

from sklearn import cross_validation

Therefore, a package is a module, but not all modules are packages.
32. How to increment and decrement an integer in Python?
You can use "+ =" and "-" to increment and decrement integers.

value = 5value += 1print(value)#=> 6value -= 1value -= 1print(value)#=> 4

33. How to return binary value of an integer?
Use the bin() function.

bin(5)#=>  0b101

34. How to remove duplicate elements from the list?

You can do this by converting a list to a collection and then back to a list.

a = [1,1,1,2,3]a = list(set(a))print(a)#=> [1, 2, 3]

35. How to check whether a value exists in the list?

Use in.

 a  in [ a , b , c ]
#=> True a in [1,2,3]#=> False

36. What's the difference between append and extend?

Append adds a value to one list, and extend adds the value of another list to one.

a = [1,2,3]b = [1,2,3]a.append(6)print(a)#=> [1, 2, 3, 6]b.extend([4,5])print(b)#=> [1, 2, 3, 4, 5]

37. How to take the absolute value of an integer?
This can be done through the abs() function.

abs(2#=> 2
abs(-2)#=> 2

38. How to combine two lists into a tuple list?

You can use the zip function to combine the list into a tuple list. This is not limited to using two lists. It is also suitable for 3 or more lists.

a = [ a , b , c ]b = [1,2,3]
[(k,v) for k,v in zip(a,b)]#=> [( a , 1), ( b , 2), ( c , 3)]

39. How to sort dictionaries alphabetically?

You can't sort dictionaries because they don't have an order, but you can return a sorted list of tuples that contain the keys and values in the dictionary.

d = { c :3,  d :4,  b :2,  a :1}
sorted(d.items())#=> [( a , 1), ( b , 2), ( c , 3), ( d , 4)]

40. How does a class inherit another class of Python?

In the following example, Audi inherits from Car. Inheritance brings the instance method of the parent class.

class Car():    def drive(self):        print( vroom )class Audi(Car):    passaudi = Audi()audi.drive()

41. How to delete all blanks in the string?

The easiest way to do this is to use white space to split the string and then reconnect the split string.

s =  A string with     white space   .join(s.split())#=>  Astringwithwhitespace

42. Why use enumerate() when iterating sequences?
enumerate() allows indexes to be tracked when iterating over a sequence. It's more Python like than defining and incrementing an integer that represents an index.

li = [ a , b , c , d , e ]for idx,val in enumerate(li):   print(idx, val)#=> 0 a#=> 1 b#=> 2 c#=> 3 d#=> 4 e

43. What's the difference between pass, continue and break?
pass means doing nothing. We usually use it because Python doesn't allow you to create classes, functions, or if statements without code.
In the following example, if there is no code in I > 3, an error will be thrown, so we use pass.

a = [1,2,3,4,5]for i in a:   if i > 3:       pass   print(i)#=> 1#=> 2#=> 3#=> 4#=> 5

Continue continues to the next element and stops execution of the current element. So when I < 3, print(i) will never be reached.

for i in a:   if i < 3:       continue   print(i)#=> 3#=> 4#=> 5

The break breaks the loop and the sequence is no longer repeated. So it will not be printed after 3.

for i in a:   if i == 3:       break   print(i)    #=> 1#=> 2

44. How to convert a for loop to a list compression?
The For loop is as follows:

a = [1,2,3,4,5]
a2 = []for i in a: a2.append(i + 1)print(a2)#=> [2, 3, 4, 5, 6]

Modify the for loop with a recursive construction list. The code is as follows: a

a3 = [i+1 for i in a]
print(a3)#=> [2, 3, 4, 5, 6]

Recursively constructed lists are generally considered to be more Python like and still easy to read.
45. Take an example of using a ternary operator.
The ternary operator is a single line if/else statement. The syntax looks like "if condition else b".

x = 5y = 10 greater  if x > 6 else  less #=>  less  greater  if y > 6 else  less #=>  greater

46. Check if a string contains only numbers?
You can use the isnumeric() method.

 123abc... .isalnum()#=> False 
123abc .isalnum()#=> True

47. Check if a string contains only letters?
You can use isalpha().

 123a .isalpha()#=> False a .isalpha()#=> True

48. Check that the string contains only numbers and letters?
You can use isalnum().


 123abc... .isalnum()#=> False 123abc .isalnum()#=> True

49. Return key list from dictionary


This can be done by passing the dictionary to Python's list() constructor, list().

d = { id :7,  name : Shiba ,  color : brown ,  speed : very slow }list(d)#=> [ id ,  name ,  color ,  speed ]

50. How to convert a string to all uppercase and all lowercase?
You can use the upper() and lower() string methods.

small_word =  potatocake big_word =  FISHCAKE small_word.upper()#=>  POTATOCAKE big_word.lower()#=>  fishcake

51. What's the difference between remove, del and pop?
remove() deletes the first matching value.

li = [ a , b , c , d ]
li.remove( b )li#=> [ a , c , d ]

del deletes elements by index.

li = [ a , b , c , d ]
del li[0]li#=> [ b , c , d ]

pop() deletes an element by index and returns it.

li = [ a , b , c , d ]
li.pop(2)#=> c
li#=> [ a , b , d ]

52. An example of recursive construction

Next, we will create a dictionary with the letters in the alphabet as the key and the letter index as the value.

# creating a list of lettersimport stringlist(string.ascii_lowercase)alphabet = list(string.ascii_lowercase)# list comprehensiond = {val:idx for idx,val in enumerate(alphabet)}d#=> { a : 0,#=>   b : 1,#=>   c : 2,#=> ...#=>   x : 23,#=>   y : 24,#=>   z : 25}

53. How does exception handling work in Python?
Python provides three keywords to handle exceptions, try, except, and finally. The syntax is as follows:

try:        # try to do thisexcept:        # if try block fails then do thisfinally:        # always do this

In the following simple example, the try block fails because we cannot add strings to integers. Set val=10 in the except block, and print "complete" in the finally block.

try:    val = 1 +  A except:    val = 10finally:    print( complete )
print(val)#=> complete#=> 10

You never know what problems will appear in the interview. The best way to prepare is to have a lot of experience in coding.
That is, the list should cover most of the data scientist or junior / intermediate Python developer roles required by python.
I hope it will help you as well.

Posted by neutra on Fri, 12 Jun 2020 22:59:48 -0700