Python basic interview questions

Posted by ghost007 on Wed, 09 Feb 2022 23:12:37 +0100

1. Comparison between PHP, C + +, Python and other languages such as C #?
C language
  C language has the characteristics of both high-level language and assembly language. It is a structural language. C language application pointer: it can directly operate close to the hardware, but the pointer operation of C is not protected, which also brings many unsafe factors to it. C + + has made improvements in this aspect, which not only retains the pointer operation, but also enhances the security, and has been supported by some users. However, these improvements increase the complexity of the language, which is also criticized by another part. Java has learned from the lessons of C + +, cancelled pointer operation and some controversial aspects in the improvement of C + +, and achieved good results in terms of security and suitability, but its own explanation runs in virtual machine, and its running efficiency is lower than that of C++/C. Generally speaking, C, C + + and Java are regarded as the same family of languages, and they have long occupied the top three in the program usage list.
Advantages of   C language: simplicity, compactness, flexibility and convenience; Rich operators; Rich data types; Flexible and practical expression; Allow direct access to the physical address and operate the hardware; High quality of generated object code and high efficiency of program execution; Good portability; Strong expression;
   disadvantages of C language: the disadvantages of C language are mainly reflected in the encapsulation of data, which makes C have great defects in data security, which is also a big difference between C and C + +. The syntax restriction of C language is not too strict, the type restriction of variables is not strict, which affects the security of the program, and the array subscript is not checked for out of bounds. From the perspective of application, C language is more difficult to master than other high-level languages. That is to say, some people are more proficient in C language.

C++
  it is the inheritance of C language. It can not only carry out procedural programming of C language, but also object-based programming characterized by abstract data types, but also object-oriented programming characterized by inheritance and polymorphism. While C + + is good at object-oriented programming, it can also carry out process based programming. Therefore, C + + can adapt to the problem scale. C + + not only has the practical characteristics of efficient computer operation, but also aims to improve the programming quality of large-scale programs and the problem description ability of programming language.

  C + + programs are compiled because they want to reflect high performance. However, its development environment, in order to facilitate testing, makes the debugging environment interpretive. That is, in the development process, the debugging is carried out in the way of interpretive sentence by sentence execution, and the final execution code of the program is generated in the way of compiling and running away from the development environment.

  generating program refers to the process of converting the source code (C + + statements) into a running application. If the program is written correctly, it usually only needs to press a function key to complete the process. The process is actually divided into two steps.
  the first step is to compile the program, which requires a compiler. The compiler converts C + + statements into machine code (also known as object code); If this step is successful,

  the second step is to link the program, which requires a linker. The linker combines the compiled machine code with the code in the C + + library. The C + + library contains functions that perform some common tasks ("function" is another term for subroutines). For example, a C + + library contains the standard square root function sqrt, so you don't have to calculate the square root yourself. The C + + library also contains some subroutines, which send data to the display and know how to read and write data files on the hard disk.

C# language
  C # is a kind of object - oriented software released by Microsoft NET Framework. C # looks strikingly similar to Java; It includes such as single inheritance, interface, almost the same syntax as Java and the process of compiling into intermediate code and then running. However, C # is obviously different from Java. It draws lessons from a feature of Delphi and is directly integrated with COM (component object model), and it is Microsoft NET windows network framework. First of all, C # and Java simply copy part of the syntax of C + +. Therefore, it is easy for a large number of C + + programmers to learn. In addition, it is simpler for novices than C + +. Secondly, windows is a monopoly platform, and the voice of Microsoft cannot be ignored in developing Windows applications. Most importantly, compared with C + +, using C # to develop application software can greatly shorten the development cycle and make use of the original C + + code other than the user interface code.

Java language
  Java is an object-oriented programming language that can write cross platform application software. It is the general name of Java programming language and Java platform (i.e. JavaSE, JavaEE, JavaME) launched by Sun Microsystems in May 1995. Java technology has excellent versatility, efficiency, platform portability and security. It is widely used in personal PC s, data centers, game consoles, scientific supercomputers, mobile phones and the Internet. At the same time, it has the world's largest professional community of developers. In the global industrial environment of cloud computing and mobile Internet, Java has more significant advantages and broad prospects.
  the advantages of Java are different from traditional programs. Sun took Java as an open technology when it was launched. Tens of thousands of java development companies around the world are required to design java software that must be compatible with each other. "Java language depends on the power of the group rather than the power of the company" is one of the slogans of Sun company and has been recognized by the majority of software developers. This is completely different from the elite and closed model advocated by Microsoft. Sun's explanation of Java programming language is that Java programming language is a simple, object-oriented, distributed, interpretive, robust, security independent, portable, high-performance, multithreaded and dynamic language.

php language
  PHP (abbreviation of PHP: Hypertext Preprocessor, Chinese Name: "PHP: Hypertext Preprocessor") is a general open source scripting language. The syntax absorbs the characteristics of C language, Java and Perl. It has low entry threshold, is easy to learn and is widely used. It is mainly applicable to the field of Web development.
  features: PHP's unique syntax combines C, Java, Perl and PHP's self innovative syntax; PHP can execute dynamic web pages faster than CGI or Perl. In terms of dynamic pages, compared with other programming languages, PHP embeds programs into HTML documents for execution, and the execution efficiency is much higher than that of CGI that completely generates HTML tags. PHP has very powerful functions, and PHP can realize all the functions of CGI; PHP supports almost all popular databases and operating systems; The most important thing is that PHP can be extended with C and C + +.

python language
  it is an object-oriented, literal translation computer programming language. Python syntax is concise and clear, with rich and powerful class library. It is often nicknamed glue language. It can easily connect various modules made in other languages (especially C/C + +). A common application is to use Python to quickly generate the prototype of the program (sometimes even the final interface of the program), and then rewrite the parts with special requirements in a more appropriate language.
  Python is a completely object-oriented language. Functions, modules, numbers, and strings are objects. It fully supports inheritance, overloading, derivation and multi inheritance, which is beneficial to enhance the reusability of source code. Python supports overloaded operators and dynamic types. Compared with Lisp, a traditional functional programming language, python only provides limited support for functional design. Two standard libraries (functools, itertools) provide the proven functional programming tools in Haskell and Standard ML. Python itself is designed to be extensible. Not all features and functions are integrated into the language core. Python provides rich API s and tools so that programmers can easily use C language, C + +, and python to write expansion modules. The python compiler itself can also be integrated into other programs that need scripting language. Therefore, many people also use Python as a "glue language". Use Python to integrate and encapsulate programs written in other languages.

2. Brief description of interpretive and compiled programming languages?
Compiled language (requires compiler, equivalent to Google translation): compiled language has fast execution speed, does not depend on the language environment, and has poor cross platform. For example, C, C + + has fast execution speed and troublesome debugging
Interpretive (requires interpreter, equivalent to simultaneous interpretation): interpretive cross platform is good. One piece of code can be used everywhere. The disadvantage is that the execution speed is slow and depends on the interpreter. For example, python and JAVA have slow execution speed and convenient debugging

3. Python interpreter types and features?

  CPython is the most widely used and widely used Python interpreter. After downloading and installing Python 2.7 from the official Python website, we directly obtained an official version of the interpreter: CPython. This interpreter is developed in C language, so it is called CPython. Running Python on the command line starts the CPython interpreter.

  IPython is an interactive interpreter based on CPython. That is to say, IPython only enhances the interactive mode, but the function of executing Python code is exactly the same as CPython. For example, although many domestic browsers have different appearance, the kernel actually calls IE. CPython uses > > > as the prompt, while IPython uses In [serial number]: as the prompt.

  PyPy is another Python interpreter whose goal is execution speed. PyPy adopts JIT technology to dynamically compile Python code (note not interpretation), so it can significantly improve the execution speed of Python code.

  most Python code can be run under PyPy, but PyPy and CPython are different, which leads to different results when the same Python code is executed under the two interpreters. If your code is to be executed under PyPy, you need to understand the differences between PyPy and CPython.

  Jython is a Python interpreter running on the Java platform, which can directly compile Python code into Java bytecode for execution.

  IronPython is similar to Jython, but IronPython runs on Microsoft Net platform, which can directly compile Python code into Net bytecode.

4. The relationship between bits and bytes?
8 bit = 1bytes

5. Relationship between B, B, KB, MB and GB?
8bit = 1B
1024B = 1KB
1024KB = 1MB
1024MB = 1GB

6. Please list at least 5 PEP8 specifications (the more the better)

  1. Use space instead of tab to indicate indentation
  2. Each level of indentation related to syntax is represented by four spaces
  3. The number of characters per line should not exceed 79
  4. For long expressions that occupy multiple lines, all lines except the first line should be added with four spaces above the usual indentation level
  5. Functions and classes in the file should be separated by two empty lines
  6. In the same class, the methods should be separated by a blank line
  7. Functions, variables and attributes should be spelled in lowercase letters, and the words should be underlined, such as lowercase_underscore
  8. For instance method in class, the first parameter should be named self to represent the object itself
  9. The first parameter of a class method should be named cls to represent the class itself
  10. Do not judge whether the somelist is a null value such as [] or "" by detecting the length (such as if len(somelist) == 0). Instead, use if not somelist, which assumes that the null value will be automatically evaluated as False '

7. Result: or and

v1 = 1 or 3
v2 = 1 and 3
v3 = 0 and 2 and 1
v4 = 0 and 2 or 1
v5 = 0 and 2 or 1 or 4
v6 = 0 or False and 1
>>>1 3 0 1 1 False

8. What are the differences between ascii, unicode, utf-8 and gbk?
Code introduction differences

  • ASCII code: inside the computer, all information is ultimately A binary value. Each binary bit has two states: 0 and 1. Therefore, eight binary bits can be combined into 256 States, which is called byte. In the 1960s, the United States developed A set of character codes to link English characters with binary, which is called ASCII code and has been used until now. ASCII code specifies A total of 128 characters. For example, SPACE is 32 and A is 65. These 128 symbols only occupy the last seven bits of A byte, and the first bit is uniformly specified as 0.
  • Unicode: there are many coding methods in the world. The same binary number can be interpreted as different symbols. Therefore, when opening A text file, you must know its encoding method. If you open it in the wrong encoding method, there will be garbled code. Unicode encoding, which is the encoding of all symbols. Unicode is obviously A huge collection, and its current scale can accommodate more than 1 million symbols. The codes of each symbol are different. For example, U+0041 represents the capital letter A of English, and U+4e25 represents the Chinese character Yan. Given the huge character set of Unicode, there is still A problem. For example, for A Chinese character, the Unicode of "Yan" is hexadecimal 4e25, and there are 15 bits to convert into binary. That is, this symbol needs 2 bytes, indicating that there are 3 bytes or more for other characters. How can A computer tell that three bytes represent the same symbol instead of three separate bytes? If Unicode uniformly stipulates that each symbol is represented by three bytes, but some letters obviously do not need three, it will waste space, and the size of text file exceeds A lot, which is obviously unreasonable. Until UTF8 character encoding appeared.
  • UTF8: the biggest feature of UTF8 is that it is a variable length coding, which can use 1-4 bytes to represent a symbol, and the byte length can be changed according to different symbols. There are only two UTF8 encoding rules: 1) for single byte symbols, the first bit of the byte is set to 0, and the following 7 bits are the Unicode code of the symbol. Therefore, for English letters, UTF8 coding and ASCII coding are the same. 2) For symbols that are not single bytes (assuming that the byte length is n), the first n bits of the first byte are set to 1, the N+1 is set to 0, and the first two bits of the following bytes are all set to 10. The remaining binaries not mentioned are all Unicode codes of this symbol.
  • GBK: the full name of GBK is "Chinese character internal code extension specification". GBK coding is an extension of GB2312 and is fully compatible with GB2312. Using the double byte coding scheme, the xx7F code points are excluded, a total of 23940 code points are included, and 21886 Chinese characters and graphic symbols are included. The GBK coding scheme was released on December 15, 1995. It almost perfectly supports Chinese characters, so we often encounter the conversion between GBK and Unicode.

difference:

  • The binary codes between various codes cannot be recognized each other, which will produce garbled codes.
  • The storage and transmission of files cannot be unicode (only UTF-8, utf-16, GBK, gbk2312, ASCII, etc.)

9. What is the difference between bytecode and machine code?
  bytecode is a binary code (file) in an intermediate state (intermediate code). It needs to be translated by a literal translator before it can become a machine code.

10. Ternary operation writing format.
  condition holds if condition else condition does not hold

11. List all the differences between Python 2 and python 3 you know?

# py2
>>> print("hello", "world")
('hello', 'world')
# py3
>>> print("hello", "world")
hello world

py2: input_raw()
py3: input()

1/2 Results
py2: Return 0
py3: Return 0.5

py2: Default encoding ascii
py3: Default encoding utf-8

character string
py2: unicode Type represents a sequence of strings, str Type represents a sequence of bytes
py3:: str Type represents a sequence of strings, byte Type represents a sequence of bytes

py2 Keywords for functions in global Declare a variable as a global variable, but in nested functions, it is impossible to declare a variable as a nonlocal variable.
py3 Keywords are added in nonlocal,Make nonlocal variables possible

range and xrange
dict of item()Method and iteritems()

12. Exchange of values in one line of code:

a = 1 b = 2
------------------
a,b = b,a

13. What is the difference between int and long in Python 3 and python 2?

Python2: int() # integer
long() # Long integer

python3 Not in long Type, only int type

14. What is the difference between xrange and range?

  1. difference
    In py2, range gets a list and xrange gets a generator object
    There is no xrange in Python 3 (there is a range, but this range is actually xrange in py2, not range), because using generators can save memory.

  2. common ground
    Their use is the same. For example, you can use the for loop to traverse all values

15. How to reverse a string? For example: name = "full egg" please reverse to name = "full egg"

name="Zhang quandan"
name[::-1]
> 'Egg sheet'

16. What is the difference between: xreadlines and readlines in file operation?

  readlines() reads all the contents of the file into memory and parses it into a list. When the volume of the file is large, it needs to occupy a lot of memory

  xreadlines() directly returns an iter(file) iterator, which is not recommended after Python 2.3 Iterate over file objects directly using the for loop

17. List common values whose Boolean value is False?

0, [] , () , {} , '' , False , None

18. What is the difference between is and = =?
  is compares id
  = = value compared

19. Under what circumstances, Y= X - (X-Y) will be established?
  x,y are two unequal nonempty sets

20. Existing dictionary dict = {a ': 24,' g ': 52,' i ': 12,' k ': 33} please sort by the value value in the dictionary?
 sorted(dict.items(),key = lambda x:x[1])

21. What's the difference between dictionary and json?
  dictionary is a data structure, and json is a form of data representation. As long as the key value of dictionary can be hash, the key value of json must be string.

22. What are variable and immutable types?

  variable and immutable refer to whether the value in the memory can be changed. Immutable type refers to the value in the memory block where the object is located can not be changed. There are numbers, strings, tuples and immutable sets;
Variable types can be changed, mainly including lists, dictionaries and collections.

23. Is the data stored in the dictionary sorted in order?
In Python, the dictionary is implemented through hash table or hash table. The stored data will not be sorted automatically. You can use the sort function to sort the dictionary.

24. Dictionary derivation?
 dict = {key: value for (key, value) in iterable}

25. Describe the difference between item() method of dict and iteritems()
  the function of the items method of the dictionary is to return all items in the dictionary in a list. Because the dictionary is out of order, there is no order to return all the items of the dictionary with the items method.

  the function of the iteritems method of the dictionary: compared with the items method, the function is roughly the same, except that its return value is not a list, but an iterator.

  in Python 2 In X, iteritems() is used to return the iterator [Returns an iterator on all items(key/value pairs)] after its own dictionary list operation, which does not occupy additional memory.

  in Python 3 In X, the iteritems() method has been abolished. In 3 Replacing iteritems() with items() in X can be used for loop traversal.

26. Please reverse the string "aStr"?
print("aStr"[::-1])

27. Please sort by the age of the elements in list1 from large to small
list1 = [{'name':'a','age':20},{'name':'b','age':30},{'name':'c','age':25}]
sorted(list1,key=lambda x:x['age'],reverse=True)

28. What are the commonly used string formats?
name = "Zhang San"

placeholder  s1 = "%s DSB Hello"%name
format s2 = '{} DSB Hello'.format(name)
f-string(python3.6 Later features) s3 = f'{name} DSB Hello'

29. Brief description of string resident mechanism
  for a short string, when it is assigned to multiple different objects, there is only one copy in memory and multiple objects share the copy.

  long strings do not comply with the resident mechanism. Scope of application: composed of numbers, characters and underscores () Composed of python identifier and integer [- 5256].

30. What will be the output result of the following code?

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

The following code will output [], and no IndexError error will be generated. As expected, try to get the members of a list with an index that exceeds the number of members. For example, trying to get the members after list[10] and will result in IndexError.

31. Write a list generating formula to generate an equal difference sequence with a tolerance of 11

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

32. 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(set1&set2)
print(set1^set2)

33. Please write a piece of Python code to delete duplicate elements in a list?
Easy to remember is to use the built-in set:

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

If you want to keep their original sorting, use the sort method of the list class:

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

You can also use traversal:

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

34. What is the output result of the following code? Please explain?

def extendlist(val, list=[]):
    list.append(val)
    return list


list1 = extendlist(10)
list2 = extendlist(123, [])
list3 = extendlist('a')
print("list1 = %s" % list1)
print("list2 = %s" % list2)
print("list3 = %s" % list3)
#  Output result:
list1 = [10, 'a']
list2 = [123]
list3 = [10, 'a']

  the new default list is created only once when the function is defined. When extendList is called by a list that does not specify a specific parameter, the values of this set of lists will then be used. This is because expressions with default parameters are evaluated when the function is defined, not when called.

35. Sort the following three functions according to their execution efficiency

def f1(lIn):
    l1 = sorted(lIn)
    l2 = [i for i in l1 if i < 0.5]
    return [i*i for i in l2]


def f2(lIn):
    l1 = [i for i in lIn if i < 0.5]
    l2 = sorted(l1)
    return [i*i for i in l2]


def f3(lIn):
    l1 = [i*i for i in lIn]
    l2 = sorted(l1)
    return [i for i in l1 if i < (0.5*0.5)]

In order of execution efficiency from high to low: f2, f1 and f3.
To prove that the answer is correct, you should know how to analyze the performance of your code.
Python has a good program analysis package that can meet this requirement.

import random
import cProfile


lIn = [random.random() for i in range(100000)]
cProfile.run('f1(lIn)')
cProfile.run('f2(lIn)')
cProfile.run('f3(lIn)')

36. There is a list ["This", "is", "a", "Boy", "!"], All elements are strings, which are sorted case independent

l1 = ['This','is','a','Boy','!']
print(sorted(l1, key=str.lower))

37. List the five commonly used methods of string, list, tuple and dictionary?

character string: repleace,strip,split,reverse,upper,lower,join.....

List: append,pop,insert,remove,sort,count,index.....

Tuple: index,count,len(),dir()

Dictionaries: get,keys,values,pop,popitems,clear,update,items.....

38. What is reflection? And application scenarios?
  reflection mechanism exists in most languages. You can use string to access the properties of objects and call the methods of objects (but you can't access the methods). All objects in Python can use reflection
Reflection mechanism exists in most languages. You can use string to access the properties of objects and call the methods of objects (but you can't access the methods). All objects in Python can use reflection

python involves four built-in functions: hasattr, getattr, setattr and delattr

  1. You can get the properties of the module
  2. Reflection mechanism is the cornerstone of many frameworks.

39. Briefly describe the deep and shallow copy of Python?
deepcopy is in the copy package
copy(): shallow copy refers to copying only the first layer data of the data set
Deep copy (): deep copy refers to copying all layers of the data set

40. Python garbage collection mechanism?

Garbage collection mechanism is a tool that automatically helps us manage memory and clean up garbage

  1. Reference count
    When the reference of an object is created or copied, the reference count of the object is increased by 1;
    When the referenced object is destroyed, the count is reduced by 1;
    When the reference count of the object is reduced to 0, it means that the object has not been used by anyone, and the memory occupied by it can be released.
    Advantages: simple, intuitive and real-time. As long as there is no reference, resources will be released.
    Disadvantages: maintaining reference count requires certain resources, which cannot be recycled during cyclic application. It is precisely for this reason that the reference counting mechanism needs to be assisted by tag cleanup and generational collection mechanisms.

  2. Mark - clear
    Mark clear does not change the actual reference count, but copies the reference count of the object in the collection and changes the copy of the object reference. Any changes made to the replica will not affect the maintenance of the object life cycle.

  3. Generation recycling
    All memory blocks in the system are divided into different sets according to their survival time. Each set becomes a "generation", and the frequency of garbage collection decreases with the increase of the survival time of the "generation". In other words, the longer an object lives, the less likely it is to be garbage, and the frequency of garbage collection should be reduced.
    So how to measure this survival time: it is usually measured by several garbage collection actions,
    If an object passes through more garbage collection times, it can be concluded that the object will survive longer.

41. The method to obtain the Python interpreter version is

import sys
print(sys.version)

42. In Python, which statement can be directly displayed to release memory resources

import gc

gc.collect()

43. lambda expression format and application scenario?

Anonymity means no name
def func(x,y,z=1):
    return x+y+z

anonymous
lambda x,y,z=1:x+y+z #It has the same scope as the function, but anonymity means that the reference count is 0 and will be released once used, unless it has a name
func=lambda x,y,z=1:x+y+z 
func(1,2,3)

44, * arg and * * kwarg action

*args is used to receive overflow location parameters and organize the received parameters into primitives
**kwargs is used to receive the overflow keyword parameters and organize the accepted parameters into a dictionary

45. Find the result

v = dict.fromkeys(['k1','k2'],[])
v['k1'].append(666)
print(v) #{'k1': [666], 'k2': [666]}
v['k1'] = 777
print(v)#{'k1': 777, 'k2': [666]}
#For the first time, the two k in the dictionary point to the same memory address, so the memory address of k1 is added with 666,
k2 The value of will also be 666,
And when to k1 During assignment, the k1 Point to the memory address, so at this time, k2 It will not change

46. One line of code realizes 9 * 9 multiplication table

print(''.join([f'{y}*{x}={x*y}\n' if x == y else f'{y}*{x}={x*y}\t' for x in range(1, 10) for y in range(1, x+1)]))

47. Compare the difference between a = [1,2,3] and b = [(1),(2),(3)] and c = [(1,),(2,),(3,)]?

The values of a and b are equal, while each element of the list in c is a primitive form
a. b elements are all numbers, and there is no comma in brackets in b, so they are still numbers

48. What are the results of 1 < (2 = = 2) and 1 < 2 = = 2 respectively and why

print(1 < (2 == 2))  --> False
print(1 < 2 == 2)  --> True

49. How to disrupt an ordered list object alias

import random
random.shuffle(alist)

50. How to find a specific character in a string? What is the difference between find and index?

  1. find() method: find the substring, return the subscript value starting from 0 if found, and - 1 if not found
  2. index() method: find the first occurrence position of the substring in the string, similar to the find method of the string, but better than the find method, if the substring cannot be found, an exception will be thrown instead of returning - 1
  3. The usage of rfind and rindex methods is the same as above, only starting from the end of the string

51. Compress the string in the form of aaabbcccd into the form of a3b2c3d1.

# my
s = 'aaabbcccd'+'#'
res = ''
last, cnt = s[0], 0
for char in s:
    if char != last:
        res += last + str(cnt)
        last = char
        cnt = 1
    else:
        cnt += 1
print(res)
# Gaudy
b = {}
c = ""
a = "aaabbcccd"
for i in a:
    b[i] = b.get(i, 0)+1
for i, t in b.items():
    c += str(i)
    c += str(t)
print(c)

52. If a number is exactly equal to the sum of its factors, it is called "perfect". For example, 6 = 1 + 2 + 3 Program to find all completions within 1000.

from functools import reduce


def sum(a, b):
    return a + b


for i in range(2, 1001):
    l = [1]
    for j in range(2, int(i / 2 + 1)):
        if i % j == 0:
            l.append(j)
    if i == reduce(sum, l):
        print(i)
        print(l)

53. Give you a string, such as' abc ', please print out all permutations and combinations of the string:
Take 'abc' as an example. The output should be 'abc', 'acb', 'bac', 'bca', 'cab', 'cba'

Fancy code

def perm(s=''):
    if len(s) <= 1:
        return [s]
    sl = []  
    for i in range(len(s)):  
        for j in perm(s[0:i] + s[i + 1:]):  
            sl.append(s[i] + j)  
    return sl


def main():
    perm_nums = perm('abb')  
    no_repeat_nums = list(set(perm_nums))  # duplicate removal
    print('perm_nums', len(perm_nums), perm_nums)
    print('no_repeat_nums', len(no_repeat_nums), no_repeat_nums)
    pass


if __name__ == '__main__':
    main()

My code

s = input()
res = []

def dfs(u, now, state):
    if u == len(s):
        res.append(now)
        return
    for i in range(0, len(s)):
        if (state >> i & 1) == 0:
            dfs(u + 1, now + s[i], state | (1 << i))

dfs(0, '', 0)
print(res, set(res), sep='\n')

54. After executing the following code segment, the value of x is

x = 10
x += x
x -= x - x
print(x)

"""
20
"""

57. Introduce the usage and function of try except?

Python's except is used to catch all exceptions, because every error in Python will throw an exception, so the error of each program is treated as a runtime error.

try:
    pass
except BaseException as e:
 
    print(e)
 
finally:
 
    pass

58. How to throw, catch and handle exceptions in python?

raise Exception Trigger throw exception
 use try and except Statement to catch exceptions
 Methods for handling exceptions are:
try ... except...else sentence
finally Clause,
with sentence

59. What is the function of enumerate?

  enumerate function is to add an index value to each element in an iterative object according to the element order, and form it into an index sequence. It can be used to obtain the index and value at the same time. The purpose of this is to form the elements in an iterative object into a "index, value" pair for subsequent operations.

60. lambda expression format and application scenario?

# Anonymity means no name
def func(x,y,z=1): return x+y+z
# anonymous
lambda x,y,z=1:x+y+z # It has the same scope as the function, but anonymity means that the reference count is 0 and is released after one use,
Unless you give it a name func=lambda x,y,z=1:x+y+z

func(1,2,3)
# It is meaningless to give it a name. It is used together with built-in functions

61. What is the maximum number of layers of Python recursion?

The default maximum is 998
You can set setrecursionlimit in sys package

62. What are the output results of list derivation and generator expressions [I% 2 for I in range (10)] and (I% 2 for I in range (10))?

print([i % 2 for i in range(10)])
print((i % 2 for i in range(10)))

63. List common built-in functions?

Mathematical type
abs(a) : Find the absolute value. abs(-1)
max(list) : seek list Maximum value. max([1,2,3])
min(list) : seek list Minimum value. min([1,2,3])
sum(list) : seek list The sum of the elements. sum([1,2,3]) >>> 6
sorted(list) : Sorting, return the sorted list. 
len(list) : list length,len([1,2,3])
divmod(a,b): Get quotient and remainder. divmod(5,2) >>> (2,1)
pow(a,b) : Gets the power. pow(2,3) >>> 8
round(a,b) : Gets the number of decimal places specified. a Represents a floating point number, b Represents the number of digits to be reserved. round(3.1415926,2) >>> 3.14
range(a[,b]) : Generate a a reach b Array of,Close left and open right. range(1,10) >>> [1,2,3,4,5,6,7,8,9]

Type conversion
int(str) : Convert to int Type. int('1') >>> 1
float(int/str) : take int Convert type or character type to floating point type. float('1') >>> 1.0
str(int) : Convert to character type. str(1) >>> '1'
bool(int) : Convert to boolean type. str(0) >>> False str(None) >>> False
bytes(str,code) : Receive a string and the format to be encoded, and return a byte stream type. bytes('abc', 'utf-8') >>> b'abc' bytes(u'Reptile', 'utf-8') >>> b'\xe7\x88\xac\xe8\x99\xab'
list(iterable) : Convert to list.  list((1,2,3)) >>> [1,2,3]
iter(iterable):  Returns an iteratable object. iter([1,2,3]) >>> <list_iterator object at 0x0000000003813B00>
dict(iterable) : Convert to dict.  dict([('a', 1), ('b', 2), ('c', 3)]) >>> {'a':1, 'b':2, 'c':3}
enumerate(iterable) : Returns an enumeration object.
tuple(iterable) : Convert to tuple.  tuple([1,2,3]) >>>(1,2,3)
set(iterable) : Convert to set.  set([1,4,2,4,3,5]) >>> {1,2,3,4,5} set({1:'a',2:'b',3:'c'}) >>> {1,2,3}
hex(int) : Convert to hexadecimal. hex(1024) >>> '0x400'
oct(int) : Convert to octal. oct(1024) >>> '0o2000'
bin(int) : Convert to binary. bin(1024) >>> '0b10000000000'
chr(int) : Convert numbers to corresponding ASCI Code character. chr(65) >>> 'A'
ord(str) : transformation ASCI character
 Is the corresponding number. ord('A') >>> 65

Related operation
eval() : Executes an expression or string as an operation. eval('1+1') >>> 2
exec() : implement python sentence. exec('print("Python")') >>> Python
filter(func, iterable) : By judging function fun,Filter eligible elements. filter(lambda x: x>3, [1,2,3,4,5,6]) >>> <filter object at 0x0000000003813828>
map(func, *iterable) : take func For each iterable Object. map(lambda a,b: a+b, [1,2,3,4], [5,6,7]) >>> [6,8,10]
zip(*iterable) : take iterable Group merge. Return a zip Object. list(zip([1,2,3],[4,5,6])) >>> [(1, 4), (2, 5), (3, 6)]
type(): Returns the type of an object.
id():  Returns the unique identification value of an object.
hash(object): Returns the of an object hash Value, with the same value object Have the same hash Value. hash('python') >>> 7070808359261009780
help(): Call the built-in help system of the system.
isinstance(): Judge whether an object is an instance of this class.
issubclass(): Determine whether a class is a subclass of another class.
globals() : Returns the dictionary of the current global variable.
next(iterator[, default]) : Receive an iterator and return the value in the iterator. If set default,When the elements in the iterator are traversed, the output default Content.
reversed(sequence) :  An iterator that generates an inverted sequence. reversed('abc') >>> ['c','b','a']

64. What are the functions of filter, map and reduce?

filter(func, iterable) : By judging function fun,Filter eligible elements. 
filter(lambda x: x>3, [1,2,3,4,5,6]) 
>>> <filter object at 0x0000000003813828>

map(func, *iterable) : take func For each iterable Object. map(lambda a,b: a+b, 
map(lambda a,b: a+b, [1,2,3,4], [5,6,7])
>>> [6,8,10]
                       
reduce(): The function accumulates the elements in the parameter sequence.
reduce(lambda x, y: x+y, [1,2,3,4,5])  # Using lambda anonymous functions                                                
>>> 15
65,One line of code 9*9 multiplication table
Copy
# answer
'''
print('\n'.join(['\t'.join(["%2s*%2s=%2s"%(j,i,i*j) for j in range(1,i+1)]) for i in range(1,10)]))
'''

Topics: Python Interview