Written test-Gold software Limited python questions and answers

Source: Internet
Author: User
Tags date1 print object

the Python question and answer of the German Software Co., Ltd.
This address: http://blog.csdn.net/caroline_wendy/article/details/25230835

by Spike 2014.5.7

This topic is for academic exchange only, strictly prohibited for other purposes, the answer is for reference only.



1. In Python, what is the difference between list, tuple, dict, set, and what is the main application in the scenario?

Answer:

Defined:

list: linked lists, ordered items, searched by index, using square brackets "[]";

Tuple: Tuples , tuples combine various objects together, cannot be altered, are searched by index, and use parentheses "()";

dict: A dictionary is a set of keys (key) and a combination of values (value) that are searched by key (key), without order, using curly braces "{}";

Set: set, unordered, elements appear only once, their own initiative to go heavy, using "set ([])";

Application Scenarios:

List , a simple data set, the ability to use the index;

tuple , some data as a whole to use, can not be changed;

Dict , using key values and values to correlate the data;

Set , the data only appears once, only concerned about whether the data appear, do not care about its location;

Code:

MyList = [1, 2, 3, 4, ' Oh ']mytuple = (1, 2, ' Hello ', (4, 5)) Mydict = {' Wang ': 1, ' Hu ': 2, ' Liu ': 4}myset = set ([' Wang ', ' Hu ', ' Liu ', 4, ' Wang '])



2. What are the differences between static functions, class functions, and member functions?

Answer:

Defined:

static Functions (@staticmethod) : The static method, which mainly deals with the logical association with this class;

class Functions (@classmethod) : A class method that focuses more on invoking a method from a class than invoking a method in an instance, being able to be used as a method overload, passing in a parameter CLS;

member functions : The method of an instance can only be invoked by an instance;

Detailed application:

Date of the method, can be instantiated (__init__) data output, the input parameters self;

to pass method of the Class (@classmethod) data conversion, the input of the CLS;

to pass static Methods (@staticmethod) into row data validation;

Code:

#-*-Coding:utf-8-*-#eclipse pydev, python 3.3#by c.l.wangclass Date (object): Day = 0 month = 0 year = 0 de            F __init__ (self, day=0, month=0, year=0): Self.day = Day Self.month = Month Self.year = year def display (self): return "{0}*{1}*{2}". Format (Self.day, Self.month, self.year) @classmethod def from_ String (CLS, date_as_string): Day, month, year = map (int, date_as_string.split ('-")) Date1 = CLS (Day, Month, Year) return date1 @staticmethod def is_date_valid (date_as_string): Day, month, year = map (int, da Te_as_string.split ('-')) return day <= and month <= and year <= 3999 date1 = Date (' 12 ', ' 11 ', ' 20 Date2 = date.from_string (' 11-13-2014 ') print (Date1.display ()) print (Date2.display ()) Print (Date2.is_date_valid ( ' 11-13-2014 ') print (Date.is_date_valid (' 11-13-2014 '))


3. A=1, b=2, exchange values of a and B without intermediate variables

Answer:

Two forms: addition or XOR

Code:

A = 1b = 2a = a + BB = A-ba = A-bprint (' A = {0}, B = {1} '. Format (A, b)) a = a ^ bb = a ^ ba = a ^ bprint (' A = {0}, B = {1} '. Format (A, b))


4. Write a function, enter a string, return the result in reverse order: such as: String_reverse (' abcdef '), return: ' FEDCBA '

(Please use a variety of methods to achieve, and compare the implementation method)

Answer:

5 different methods Comparison of:

1. The simple step is-1, that is, the string flip;

2. Position of letters before and after exchange;

3. Recursively output one character at a time;

4. Double-ended queue, using extendleft () function;

5. Use for loop, from left to right output;

Code:

string = ' abcdef ' def string_reverse1 (string):    return string[::-1]def String_reverse2 (string):    t = List (string )    L = Len (t)    for I,J in Zip (range (l-1, 0,-1), Range (L//2)):        T[i], t[j] = T[j], T[i]    return "". Join (t) def STRING_REVERSE3 (String):    If Len (string) <= 1:        return string    return String_reverse3 (string[1:]) + String[0]from Collections Import Dequedef String_reverse4 (string):    d = deque ()    d.extendleft (String)    Return '. Join (d) def string_reverse5 (string):    #return '. Join (String[len (String)-i] for I in range (1, len (string) +1)    return '. Join (String[i] for I in Range (len (String)-1,-1,-1)) Print (String_reverse1 (string)) print (String_ Reverse2 (String)) print (String_reverse3 (string)) print (String_reverse4 (string)) print (String_reverse5 (string))



5. Use your own algorithm to merge in ascending order such as the following two list, and remove the repeated elements:

List1 = [2, 3, 8, 4, 9, 5, 6]

List2 = [5, 6, 10, 17, 11, 2]

Answer:

merge Linked lists , recursive high-speed sequencing, to redirect links;

Code:

Import Randomlist1 = [2, 3, 8, 4, 9, 5, 6]list2 = [5, 6, ten,, one, 2]def qsort (L):   If Len (l) <2:return L   pivo T_element = Random.choice (L)   small = [i-I in L if i< pivot_element]   large = [i-I in L if i> pivot_el Ement]   return qsort (small) + [pivot_element] + qsort (Large) def merge (List1, list2):    return qsort (List1 + list2) Print (merge (List1, List2))

Note: If you use the Set method, List (set (List1 + List2)), you can.


6. Please write out the printed results

x = [0, 1]

i = 0

I, x[i] = 1, 2

Print (x)

Printing results: [0, 2], Python can use continuous assignment, from left to right.

g = lambda x, y=2, z:x + y**z

G (1, z=10) =?

Printing results: exception, the end of the form is sufficient to have a default number of parameters, Z needs to provide a default number of parameters.



7. Describe the problem with the following code snippet

From amodule Import * # Amodule is a exist Moduleclass Dummyclass (object):    def __init__ (self):        self.is_d = true
   pass    class Childdummyclass (Dummyclass):    def __init__ (self, Isman):        Self.isman = Isman            @ Classmethod    def can_speak (self): return True        @property    def man: return Self.isman    if __name __ = = "__main__":    object = new Childdummyclass (True)    print object.can_speak ()    print Object.man ()    Print Object.is_d

Answer:

1. Warning: Object is a basic class of the new Python form, and should not be defined again;

2. Warning: A class method (Classmethod) is a method owned by a class, and the passed-in argument should be CLS, not self;

3. Error: Python does not have newkeyword, if need to change new, such as singleton mode, can override (override) __new__;

4. Error: @property, represents a property, not a method, you do not need to add parentheses "()", directly call Object.man, you can;

5. Error: If you want to use the members of the base class, you need to initialize the base class, such as dummyclass.__init__ (self), you can;

6. Extra: Use uppercase as much as possible for class names.

Code:

Class Dummyclass (object):    def __init__ (self):        self.is_d = True        pass    class Childdummyclass ( Dummyclass):    def __init__ (self, Isman):        dummyclass.__init__ (self) #__init__        Self.isman = Isman            @ Classmethod    def can_speak (CLS): Return True #cls        @property    def man: return Self.isman    if __ name__ = = "__main__":    o = Childdummyclass (True) #new, Object    print o.can_speak ()    Print O.man # Propertyprint O.is_d



8. Introduction to Python's exception handling mechanism and its own experience in the development process

Answer:

Python's exception handling mechanism:

Try : attempt to throw an exception;

raise: throws an exception;

except: handling Exceptions;

finally: What happens if an exception is required;


To create a new exception type, you need to inherit the exception class, be able to define the properties of the class, easy to handle exceptions;


Development experience:

The exception is the main processing of reading files, but also can be used with the method of reading files; can also be used for network connections where exceptions can include a large number of error messages for error handling.


Code:

Class Shortinputexception (Exception):    def __init__ (self, length, atleast):        exception.__init__ (self)        self.length = length        self.atleast = atleast while        True:    try:        text = raw_input (' Enter somthing--> ') C7/>if len (Text) < 3:            raise Shortinputexception (Len (text), 3)    except Eoferror:        print (' Why didn't you do a E of On Me ')    except shortinputexception as ex:        print (' shortinputexception the input is {0} long, excepted at LEAs t {1}. '. Format (ex.length, ex.atleast))    else:        print (' No exception was raised. ')    finally:        print (' over ')




Written test-Gold software Limited python questions and answers

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.