current position:Home>Python interview encyclopedia Python Foundation

Python interview encyclopedia Python Foundation

2022-07-25 17:47:59wangmcn

Python Interview book -Python Basics

Catalog

  • 1、 Enter the date , Judge the day as the day of the year ?
  • 2、 Disrupt a well ordered list object alist?
  • 3、 Existing dictionaries d = {'a':24,'g':52,'i':12,'k':33} Please press value Value to sort ?
  • 4、 Reverse string "aStr"
  • 5、 The string "k:1|k1:2|k2:3|k3:4", Deal with it as a dictionary {k:1,k1:2,...}
  • 6、 Please press alist Of the elements of age Sort from big to small
  • 7、 What will be the output of the following code ?
  • 8、 Write a list generator , Produce a tolerance of 11 Equal difference sequence of .
  • 9、 Given two lists , How to find out their same elements and different elements ?
  • 10、 Please write a paragraph Python Code implementation deletion list The repeating elements in it ?
  • 11、 Given two list A、B, Please find out with A、B The same and different elements in
  • 12、Python There are several data structures built into ?
  • 13、 Invert an integer , for example -123 --> -321
  • 14、 One line of code 1-100 The sum of the
  • 15、Python Delete elements when traversing the list
  • 16、 Variable type and immutable type
  • 17、is and == What's the difference? ?
  • 18、 Find all odd numbers in the list and construct a new list
  • 19、 Use one line Python Code writing 1+2+3+10248
  • 20、Python Scope of variable in ?( Variable lookup order )
  • 21、Python Code implementation delete a list The repeating elements in it
  • 22、 Count the number of characters in a string

1、 Enter the date , Judge the day as the day of the year ?

import datetime
def dayofyear():
    year = input(" Please enter the year : ")
    month = input(" Please enter the month : ")
    day = input(" Please enter day : ")
    date1 = datetime.date(year=int(year),month=int(month),day=int(day))
    date2 = datetime.date(year=int(year),month=1,day=1)
    return (date1-date2).days+1

Running results :

2、 Disrupt a well ordered list object alist?

import random
alist = [1,2,3,4,5]
random.shuffle(alist)
print(alist)

Running results :

3、 Existing dictionaries d = {'a':24,'g':52,'i':12,'k':33} Please press value Value to sort ?

d = {'a':24,'g':52,'i':12,'k':33}
c = sorted(d.items(),key=lambda x:x[1])
print(c)

Running results :

x[0] For key Sort ;x[1] For value Sort .

4、 Reverse string "aStr"

print("aStr"[::-1])

Running results :

5、 The string "k:1|k1:2|k2:3|k3:4", Deal with it as a dictionary {k:1,k1:2,...}

str1 = "k:1|k1:2|k2:3|k3:4"
def str2dict(str1):
    dict1 = {}
    for iterms in str1.split('|'):
        key,value = iterms.split(':')
        dict1[key] = value
    return dict1
# Dictionary derivation 
d = {k:int(v) for t in str1.split("|") for k, v in (t.split(":"), )}
print(d)

Running results :

6、 Please press alist Of the elements of age Sort from big to small

alist = [{'name':'a','age':20},{'name':'b','age':30},{'name':'c','age':25}]
def sort_by_age():
    return sorted(alist,key=lambda x:x['age'],reverse=True)
print(sort_by_age())

Running results :

7、 What will be the output of the following code ?

list = ['a','b','c','d','e']
print(list[10:])

Running results :

Output [], Will not produce IndexError error , As expected , Try using more than the number of members index To get members of a list . for example , obtain list[10] And later members , It can lead to IndexError. However , Try to get the slice of the list , At the beginning index Exceeding the number of members will not produce IndexError, It just returns an empty list .

 for example :list[10], Operation error reporting .

8、 Write a list generator , Produce a tolerance of 11 Equal difference sequence of .

print([x*11 for x in range(10)])

Running results :

9、 Given two lists , How to find out their same elements and different elements ?

list1 = [1,2,3]
list2 = [3,4,5]
set1 = set(list1)
set2 = set(list2)
print(" Same element :" + str(set1 & set2))
print(" Different elements :" + str(set1 ^ set2))

Running results :

10、 Please write a paragraph Python Code implementation deletion list The repeating elements in it ?

(1) Mode one :

l1 = ['b','c','d','c','a','a']
l2 = list(set(l1))
print(l2)

Running results :

(2) Mode two :

l1 = ['b','c','d','c','a','a']
l2 = list(set(l1))
l2.sort(key=l1.index)
print(l2)

Running results :

(3) Mode three :

l1 = ['b','c','d','c','a','a']
l2 = sorted(set(l1),key=l1.index)
print(l2)

Running results :

(4) Mode 4 :

l1 = ['b','c','d','c','a','a']
l2 = []
for i in l1:
    if not i in l2:
        l2.append(i)
print(l2)

Running results :

11、 Given two list A、B, Please find out with A、B The same and different elements in

A、B The same elements in : print(set(A)&set(B)) 
A、B Different elements in : print(set(A)^set(B))

12、Python There are several data structures built into ?

(1) integer int、 Long integer long、 floating-point float、 The plural complex b

(2) character string str、 list list、 Yuan Zu tuple、 Dictionaries dict、 aggregate set

(3)Python3 There is no long, With infinite precision int

13、 Invert an integer , for example -123 --> -321

class Solution(object):
    def reverse(self,x):
        if -10<x<10:
            return x
        str_x = str(x)
        if str_x[0] !="-":
            str_x = str_x[::-1]
            x = int(str_x)
        else:
            str_x = str_x[1:][::-1]
            x = int(str_x)
            x = -x
        return x if -2147483648<x<2147483647 else 0
if __name__ == '__main__':
    my_int = -123456789
    s = Solution()
    reverse_int = s.reverse(my_int)
    print(reverse_int)

Running results :

14、 One line of code 1-100 The sum of the

print(sum(range(0,101)))

Running results :

15、Python Delete elements when traversing the list

(1) Positive order deletion :

a = [1,2,3,4,5,6,7,8]
print(id(a))
print(id(a[:]))
for i in a[:]:
    if i > 5:
        pass
    else:
        a.remove(i)
    print(a)
print('-----------')
print(id(a))

Running results :

(2) Reverse delete :

a = [1,2,3,4,5,6,7,8]
print(id(a))
for i in range(len(a)-1,-1,-1):
    if a[i] > 5:
        pass
    else:
        a.remove(a[i])
    print(a)
print('-----------')
print(a)

Running results :

16、 Variable type and immutable type

(1) Variable types are list、dict; Immutable types are string、number、tuple.

(2) When modifying , Variable types pass addresses in memory , in other words , Directly modify the value in memory , There's no new memory .

(3) When the immutable type is changed , It doesn't change the value in the original memory address , It's about opening up a new memory , Copy the value from the original address , Operate on the value in the newly opened memory .

17、is and == What's the difference? ?

is: The comparison is between two objects id Whether the values are equal , That is to compare whether the two objects are the same instance object . Whether to point to the same memory address .

==: Compare the contents of two objects / Whether the values are equal , By default, the object will be called eq() Method .

18、 Find all odd numbers in the list and construct a new list

a = [1,2,3,4,5,6,7,8,9,10]
res = [ i for i in a if i%2==1]
print(res)

Running results :

19、 Use one line Python Code writing 1+2+3+10248

from functools import reduce

# 1、 Use sum Built in summation function 
num1 = sum([1,2,3,10248])
print(num1)

# 2、reduce function 
num2 = reduce(lambda x,y:x+y,[1,2,3,10248])
print(num2)

Running results :

20、Python Scope of variable in ?( Variable lookup order )

Function scoped LEGB The order

L:local Function internal scope

E:enclosing Between functions inside and embedded functions

G:global Global scope

B:build-in Built in function

Python The search in the function is divided into 4 Kind of , be called LEGB, It is also in this order to find .

21、Python Code implementation delete a list The repeating elements in it

def distFunc1(a):
    """ Use sets to remove duplicates """
    a = list(set(a))
    print(a)

def distFunc2(a):
    """ Take the data from one list and put it into another list , Judge in the middle """
    list = []
    for i in a:
        if i not in list:
            list.append(i)
    #  If you need to sort, use sort
    list.sort()
    print(list)

def distFunc3(a):
    """ Using dictionaries """
    b = {}
    b = b.fromkeys(a)
    c = list(b.keys())
    print(c)

if __name__ == "__main__":
    a = [1,2,4,2,4,5,7,10,5,5,7,8,9,0,3]
    distFunc1(a)
    distFunc2(a)
    distFunc3(a)

Running results :

22、 Count the number of characters in a string

def count_str(str_data):
    dict_str = {}
    for i in str_data:
        dict_str[i] = dict_str.get(i, 0) + 1
    return dict_str
dict_str = count_str("AAABBCCAC")
str_count_data = ""
for k, v in dict_str.items():
    str_count_data += k + "=" + str(v) + ","
print(str_count_data)

Running results :

copyright notice
author[wangmcn],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/206/202207251743535055.html

Random recommended