A complete set of Python Classic interview questions, strength, do not do the content of the title Party!

Source: Internet
Author: User

Python learning materials at the end of the text

1:python How to implement singleton mode?

There are two ways Python can implement a singleton pattern, the following two examples use different ways to implement a singleton pattern:

1.

Class Singleton (Type):

Def __init__ (CLS, name, bases, Dict):

Super (Singleton, CLS). __INIT__ (name, bases, Dict)

Cls.instance = None

Def __call__ (CLS, *args, **kw):

If Cls.instance is None:

Cls.instance = Super (Singleton, CLS). __call__ (*args, **kw)

Return cls.instance

Class MyClass (object):

__metaclass__ = Singleton

Print MyClass ()

Print MyClass ()

2. Use decorator to implement Singleton mode

Def Singleton (CLS):

instances = {}

Def getinstance ():

If CLS not in instances:

INSTANCES[CLS] = CLS ()

return INSTANCES[CLS]

Return getinstance

@singleton

Class MyClass:

...

2: What is a lambda function?

Python allows you to define a small single-line function. The form of a lambda function is defined as follows: Labmda parameter: The expression lambda function returns the value of the expression by default. You can also assign it to a variable. A lambda function can accept any parameter, including optional arguments, but the expression has only one:

>>> g = lambda x, y:x*y

>>> g (3,4)

12

>>> g = lambda x, y=0, z=0:x+y+z

>>> g (1)

1

>>> g (3, 4, 7)

14

You can also use a lambda function directly without assigning it to a variable:

>>> (Lambda x,y=0,z=0:x+y+z) (3,5,6)

14

If your function is very simple and has only one expression and no command, you can consider a lambda function. Otherwise, you can define the function, after all, the function does not have so many restrictions.

How does a 3:python convert to a type?

Python provides built-in functions that convert a variable or value from one type to another type. The INT function converts a numeric string that conforms to a mathematical format into an integer. Otherwise, an error message is returned.

>>> int ("34″")

34

>>> int ("1234AB") #不能转换成整数

Valueerror:invalid literal for int (): 1234ab

The function int can also convert a floating-point number to an integer, but the fractional part of the float is truncated.

>>> Int (34.1234)

34

>>> Int (-2.46)

-2

The function °oat converts integers and strings into floating-point numbers:

>>> float ("12″")

12.0

>>> float ("1.111111″")

1.111111

Function STR Converts a number to a character:

>>> STR (98)

' 98′

>>> Str ("76.765″")

' 76.765′

The integer 1 and the floating-point number 1.0 are different in Python. Although their values are equal, they belong to different types. These two numbers are also different in the way the computer is stored.

4:python How to define a function

Functions are defined in the form of

Under

def <name> (arg1, arg2,... ArgN):

<statements>

The name of the function must also start with a letter, which can include an underscore "", but not the python

The keyword is defined as the name of the function. The number of statements within a function is arbitrary, and each statement has at least

The indentation of a space to indicate that the statement belongs to this function. Where the indentation ends, the function

Natural end.

The following defines a function that adds two numbers:

>>> def Add (P1, p2):

Print P1, "+", p2, "=", p1+p2

>>> Add (1, 2)

1 + 2 = 3

The purpose of the function is to hide some complex operations to simplify the structure of the program, making it easy to

Read. Functions must be defined before they are called. You can also define functions within a function, inside

A part function can be executed only when an external function is called. When the program calls the function, go to the function

Inside the inner execution of the function statement, after the function is finished, return to where it left the program,

Executes the next statement of the program.

How does the 5:python manage memory?

Python's memory management is handled by Python's interpreter, and developers can be freed from memory management transactions and committed to application development, resulting in fewer bugs, more robust programs, and shorter development cycles

6: How do I reverse a sequence of iterations? How does I iterate over a sequence in reverse order

If it is a list, the quickest solution is:

List.reverse ()

Try

For x in list:

"Do something with X"

Finally

List.reverse ()

If not list, the most common but slightly slower solution is:

For I in range (len (sequence)-1,-1,-1):

x = Sequence[i]

<do something with x>

7:python How to implement the conversion of tuple and list?

The function tuple (SEQ) converts all the iterated (iterable) sequences into a tuple, the element is unchanged, and the order is not changed.

For example, a tuple ([+]) returns ("A."), and a tuple (' abc ') returns (' a '. ') B ', ' C '). If the parameter is already a tuple, the function does not make any copy and returns the original object directly, so it is not very expensive to call the tuple () function when it is not certain that the object is not a tuple.

The function list (seq) converts all sequences and iterated objects into a list, the elements are unchanged, and the sorting is not changed.

For example, list ([+/-)] Returns ("A/C"), and the list (' abc ') returns [' A ', ' B ', ' C. ']. If the argument is a list, she will make a copy like set[:]

8:python Interview Question: Write a Python code to delete the repeating element in a list

The list can be reordered first and then scanned from the last list, with the following code:

If List:

List.sort ()

Last = List[-1]

For I in range (len (List)-2,-1,-1):

If Last==list[i]: del List[i]

Else:last=list[i]

9:python file operation of the face question

1. How do I delete a file in Python?

Use Os.remove (filename) or os.unlink (filename);

2. How does python copy a file?

The Shutil module has a CopyFile function to enable file copying

How do I generate random numbers inside 10:python?

The standard library random implements a random number generator with the following example code:

Import Random

Random.random ()

It returns a random floating-point number between 0 and 1.

11: How do I use Python to send mail?

You can use the Smtplib standard library.

The following code can be executed on a server that supports SMTP listeners.

Import SYS, smtplib

FROMADDR = Raw_input ("From:")

Toaddrs = Raw_input ("to:"). Split (', ')

Print "Enter message, End with ^d:"

msg = "

While 1:

line = Sys.stdin.readline ()

If not line:

Break

msg = msg + Line

# Send Message section

Server = Smtplib. SMTP (' localhost ')

Server.sendmail (fromaddr, Toaddrs, msg)

Server.quit ()

How do I copy an object inside 12:python?

In general, you can use the Copy.copy () method or the Copy.deepcopy () method, and almost all objects can be copied

Some objects can be copied more easily, and dictionaries has a copy method:

Newdict = Olddict.copy ()

13: Is there a tool that can help find Python bugs and perform static code analysis?

Yes, Pychecker is a static analysis tool for Python code that can help find bugs in Python code and warns of the complexity and format of the code

Pylint is another tool that can perform coding standard checks.

14: How to set a global variable in a function?

The workaround is to insert a global declaration at the beginning of the function:

def f ()

Global X

14: There are two sequences, a, B, the size is n, the value of the sequence element arbitrarily shaped number, unordered; required: To minimize the difference between [sequence A and] and [sequence B elements] by exchanging the elements in A/b.

1. Merge the two sequences into a sequence and sort the source for the sequence

2. Take out the largest element big, the second largest element small

3. Divide the remaining sequence s[:-2] to get the sequence Max,min

4. Add the small to the max sequence, add big to the min sequence, recalculate the new sequence, and large for max, small for Min.

Python code

def mean (sorted_list):

If not sorted_list:

Return (([],[]))

Big = Sorted_list[-1]

small = sorted_list[-2]

Big_list, small_list = mean (Sorted_list[:-2])

Big_list.append (small)

Small_list.append (BIG)

Big_list_sum = SUM (big_list)

Small_list_sum = SUM (small_list)

If Big_list_sum > Small_list_sum:

Return ((Big_list, small_list))

Else

Return ((Small_list, big_list))

Tests = [[1,2,3,4,5,6,700,800],

[10001,10000,100,90,50,1],

Range (1, 11),

[12312, 12311, 232, 210, 30, 29, 3, 2, 1, 1]

]

For L in tests:

L.sort ()

Print

Print "Source List:", L

L1,L2 = Mean (l)

Print "Result List:", L1, L2

Print "Distance:", ABS (SUM (L1)-sum (L2))

print '-* ' *40

Output results

Python code

Source List: [1, 2, 3, 4, 5, 6, 700, 800]

Result List: [1, 4, 5, 800] [2, 3, 6, 700]

distance:99

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

Source List: [1, 50, 90, 100, 10000, 10001]

Result List: [50, 90, 10000] [1, 100, 10001]

distance:38

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

Source List: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Result List: [2, 3, 6, 7, 10] [1, 4, 5, 8, 9]

Distance:1

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

Source List: [1, 1, 2, 3, 29, 30, 210, 232, 12311, 12312]

Result List: [1, 3, 29, 232, 12311] [1, 2, 30, 210, 12312]

Distance:21

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

15: What is the difference between,<.*> and <.*?> when matching HTML tags with python?

When a regular expression is repeatedly matched, such as <.*>, the maximum matching value is returned when the program executes the match.

For example:

Import re

s = '

Print (Re.match (' <.*> ', s). Group ())

will return a match

and

Import re

s = '

Print (Re.match (' <.*?> ', s). Group ())

will return to the

<.*> This match is called greedy match <.*?> called non-greedy match

16:python the difference between search () and match ()?

The match () function only detects if the re is matched at the start of the string, and search () scans the entire string lookup match, which means that match () is returned only if the 0-bit match succeeds, and if the match is not successful, match () Just return to None

For example:

Print (Re.match (' super ', ' superstition '). span ()) will return (0, 5)

Print (Re.match (' super ', ' insuperable ') returns none

Search () scans the entire string and returns the first successful match

For example: Print (Re.search (' super ', ' superstition '). span ()) return (0, 5)

Print (Re.search (' super ', ' insuperable '). span ()) return (2, 7)

17: How do I use Python to query and replace a text string?

You can use the sub () method to query and replace the sub method in the format: Sub (replacement, string[, count=0])

Replacement is replaced with text

String is the text that needs to be replaced

Count is an optional parameter that refers to the maximum number of replacements

Example:

Import re

p = re.compile (' (blue|white|red) ')

Print (P.sub (' Colour ', ' blue socks and red shoes ')

Print (P.sub (' Colour ', ' blue socks and red shoes ', count=1))

Output:

Colour socks and colour shoes

Colour socks and Red shoes

The Subn () method performs the same effect as a sub (), but it returns a two-dimensional array, including the replacement of the new string and the total number of replacements

For example:

Import re

p = re.compile (' (blue|white|red) ')

Print (P.SUBN (' Colour ', ' blue socks and red shoes ')

Print (P.SUBN (' Colour ', ' blue socks and red shoes ', count=1))

Output

(' Colour socks and colour shoes ', 2)

(' Colour socks and Red shoes ', 1)

18: Introduce the usage and function of except?

Python's except is used to catch all exceptions, because each error in Python throws an exception, so each program's error is treated as a run-time error.

Here is an example of using except:

Try

Foo = opne ("file") #open被错写为opne

Except

Sys.exit ("Could not open file!")

Because this error is caused by the spelling of open Opne and then captured by except, it's easy to know what's wrong with the debug program.

The following example is a better point:

Try

Foo = opne ("file") # this time except only captures IOError

Except IOError:

Sys.exit ("Could not open file")

What is the function of the pass statement in 19:python?

Pass statement does nothing, generally as a placeholder or create a placeholder, the pass statement will not perform any action, such as:

While False:

Pass

Pass is often used to create the simplest class:

Class Myemptyclass:

Pass

Pass is also often used as a todo in the software design phase, reminding you to implement the corresponding implementation, such as:

def initlog (*args):

Pass #please Implement this

20: Describe the use of the range () function under Python?

If you need to iterate over a sequence of numbers, you can use the range () function, and the range () function can generate arithmetical progression.

As an example:

For I in range (5)

Print (i)

This code will output 0, 1, 2, 3, 45 digits

A range (10) produces 10 values, or you can have range () start with another number, or define a different increment, or even a negative increment

Range (5, 10) five digits from 5 to 9

Range (0, 10, 3) increments of three, including 0,3,6,9 four digits

Range (-10,-100,-30) increments of-30, including-10,-40,-70

You can use range () and Len () together to iterate over an index sequence

For example:

A = [' Nina ', ' Jim ', ' Rainman ', ' Hello ']

For I in range (Len (a)):

Print (I, a[i])

A complete set of Python Classic interview questions, strength, do not do the content of the title Party!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.