Some recent interview questions Python has encountered (iii)

Source: Internet
Author: User
Tags generator iterable serialization

Some recent interview questions Python has encountered (iii)
Sort out some of the high-frequency interview questions that were recently asked. Summarize the convenience of future review and consolidation, and hope to help some friends.
First two points this ↓
Some recent interview questions Python has encountered (i)
Some recent interview questions from Python (ii)

1. Please write a regular expression for a mailbox

The e-mail address has a uniform standard format: username @ Server domain name. The user name represents the user ID of the mail box, the registered name, or the recipient of the letter, followed by the domain name of the mail server you are using. @ can be read as "at", which means "in". The entire e-mail address can be understood as the address of a user on a server in the network.

Answer

1. User name, you can choose your own. Consists of letter a~z (case insensitive), numeric 0~9, dots, minus signs, or underscores; can only start and end with numbers or letters
2. In connection with the website you use, on behalf of the mailbox service provider. For example, NetEase has @163.com Sina has @vip.sina.com and so on
On the internet to see a variety of versions, are not sure which, so they simply summed up one. We have a better welcome message.

r"^[a-zA-Z0-9]+[a-zA-Z0-9_.+-][email protected][a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"

Here's an explanation of the above expression
1. First emphasize a little about the meaning of \w, \w matches the English alphabet and Russian letters or numbers or underscores or kanji
2. Note the difference between ^[] and [^], [] denotes the character set, ^[] means that any character set in [] has started, [^] represents
3.^[a-za-z0-9]+: Notice here ^[] and [^], the first ^ indicates what has started, the second [] ^ means not equal to [] inside.
So this paragraph means to start with the English letters and numbers, followed by the +, limit the number of >=1.
4.[a-za-z0-9_.+-]+: Represents any character that matches the beginning of an English letter and number and _.+-, and limits its number to >=1.
In order to consider that the @ front may appear. +-(but not at the beginning).
[Email protected] is the mailbox must-have symbol
[Email protected] [a-za-z0-9-]+.: The front is needless to say, the latter. Represents. Escaped, also a must-have symbol.

[a-zA-Z0-9-.]+$

:d the ollar symbol shows what ends with, expressed here in English text and numbers or-. 1 or more endings.
Here's an example to verify a wave:

import replt=re.compile(r"^[a-zA-Z0-9]+[a-zA-Z0-9_.+-][email protected][a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$")b=plt.findall(‘[email protected]‘)print(b)

A generic regular expression for verifying e-mail addresses is found on the Web (RFC 5322 compliant)

(?:[a-z0-9!#$%&‘*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&‘*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
2. Are the following two pieces of code running after the same result? Why?

First paragraph

l=[]for i in range(10):    l.append({‘num‘:i})print(l)  

Second paragraph

l=[]a={‘num‘:0}for i in range(10):    a[‘num‘]=i    l.append(a)print(l)

Answer

First, the first paragraph, {' num ': i} loops, each cycle produces a new dictionary type, so this relatively simple result is

[{‘num‘: 0}, {‘num‘: 1}, {‘num‘: 2}, {‘num‘: 3}, {‘num‘: 4}, {‘num‘: 5}, {‘num‘: 6}, {‘num‘: 7}, {‘num‘: 8}, {‘num‘: 9}]

The second paragraph is a little bit special, a={' num ': 0} indicates that a reference to a mapping type dictionary is given to a, and when the Loop a[' num ']=i, A's reference address is not changed, so the value of the last loop is taken.

[{‘num‘: 9}, {‘num‘: 9}, {‘num‘: 9}, {‘num‘: 9}, {‘num‘: 9}, {‘num‘: 9}, {‘num‘: 9}, {‘num‘: 9}, {‘num‘: 9}, {‘num‘: 9}]
3. Please write out the output of the following code:
def test1():   for i in range(2):       print(‘+‘+str(i))       yield str(i)for a in test1():       print(‘-‘+a)for a in list(test1()):      print(‘-‘+a)   

Answer

First we analyze what test1 () prints,

<generator object test1 at 0x7faf31262d70>

You can see that it is a generator.
First for Loop

+0 -0 +1 -1

The second for loop, first we see List (Test1 ()) to know, first need to run through the generator in the loop to get and then go out of the list that [0,1].
And then in the loop this list so the result is.

+0 +1 -0 -1
4. Please write out the following code output memory:

A=zip (' A ', ' B ', ' C '), (1,2,3,4))
Print (Dict (a))

Answer

The zip () function uses an iterative object as an argument, packages the corresponding elements in the object into tuples, and then returns a list of those tuples.

If the number of elements of each iterator is inconsistent, the returned list is the same length as the shortest object, and with the * operator, the tuple can be decompressed as a list.
The zip method differs in Python 2 and Python 3: in Python 3.x in order to reduce memory, zip () returns an object.
So here the dictionary output is composed of the shortest elements.

{‘a‘:1,‘b‘:2,‘c‘:3}
5. Implement the sequence number and deserialization of the following objects.
class User():     name=‘user1‘     age=30

Answer

The process of changing a variable from memory to a storage or transfer is called serialization.
In turn, the variable content is read back from the serialized object into memory called deserialization
In addition, the modules we use are pickle

1, only used in Python, only support the basic Python data type. 2. Complex serialization syntax can be handled. (such as the method of a custom class, the game's archive, etc.) 3, when serialized, only serializes the entire sequence object, not the memory address.

The Pickle.dumps () method serializes an arbitrary object into a bytes. So we first need to create an object that is U=user ()
Then we'll serialize this object. That

bytes=pickle.dumps(u)

Then the deserialization:
Deserializes the object with the Pickle.loads () method.

object=pickle.loads(bytes)
6. Write out the following code:
for n in filter(lambda n:n%5,[n for n in range(100) if n%5==0]):    print(n)else:   print(‘12345‘)

Answer

First we know the use of filter
Filter (function, iterable)
which also
Function-------judging functions.
Iterable--Can iterate over objects.
Returns True or False
But this question compares the difference between pit n%5 and n%5==0, n%5 is n divided by 5 for the remaining number. N%5==0 is 5 divisible by N.
Lambda n:n%5 This returns a number instead of a Boolean type that does not conform to the filter requirement, so the output is 12345.
To achieve the filter effect we can change this.

for n in filter(lambda n:n%5==0,[n for n in range(100) if n%5==0]):    print(n)

But if we change this,

for i in filter(lambda n:n%5==0,[n for n in range(100) if n%5==0]):    print(n)

The result is more interesting, you can consider why.

Some recent interview questions Python has encountered (iii)

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.