047-Python测试题02

第一份2017-2018

01.

What is the characteristics of recursive method

1.it calls itself

2.it breaks the problem into identical but smaller problems. When it calls itself, it does so to solve a smaller problem

3.at least one of the problems should have a solution that is easy enough to be solved within the method without calling itself.

02.

Is recursive method efficient?

Recursive method is not efficient in terms time, in fact, it involves extra overheads such as control overhead.

03.

Why is recursive method good for some problems?

Recursive is usually used because it simplifies a problem conceptually, not because it is more efficient.

04.

what is regular expression?

a regular expression is a special sequence of characters that are used to search and match a set of strings.

05.

in what area we find regular expression useful

1.parsing

2.searching

3.searching and replacing

4.splitting strings

5.validating

1a.

Course

strings[0] is (‘Dog’,’Cat’)...

strings[2][2:] is ‘rse’

so we have above result.

 

1b.

2,4,6,8

[[2,2],[4,4,4,4],[6,6,6,6,6,6],[8,8,8,8,8,8,8,8]]

in the for loop, the i in each iterations are 2,4,6,8, so the [i]*i are [2]*2,[4]*4 and so on, append these list to arr, so we have the above result.

 

1c.

if 4==10-1  if 9==10-1

list[4+1] += list[4]  list[5]=1+1   1,1,1,1,1,   2,1,1,1,1

list[6]=list[6]+list[5] 1,1,1,1,1 2,3,1,1,1

7=7+6  23411

8=8+7  23451

9=9+8  23456

[1,1,1,1,1,2,3,4,5,6]

in each iteration, pa2[pa1+1] += pa2[pa1], so it adds the next element to previous element, for example in the first iteration, pa2[5] += pa2[4] so pa2[5]=2, in the second iteration, pa2[6]+=pa2[5], so pa2[6]=3, in the last iteration, pa1 is 9 and the length of pa2 is 10, so it returns, so we have above result.

 

1d.

a:aa, b:bb

the ClassB is a child class of ClassA, so it inherits the methods defined in ClassA, when print() is called, it invocates the __str__() method, so it returns ‘a:aa,b:bb’.

 

 

 

 

2a.

01.

What is the characteristics of recursive method

1.it calls itself

2.it breaks the problem into identical but smaller problems. When it calls itself, it does so to solve a smaller problem

3.at least one of the problems should have a solution that is easy enough to be solved within the method without calling itself.

 

02.

Is recursive method efficient?

Recursive method is not efficient in terms time, in fact, it involves extra overheads such as control overhead.

 

 

03.

Why is recursive method good for some problems?

Recursive is usually used because it simplifies a problem conceptually, not because it is more efficient.

 

2b.

function iamrecursive() receive 2 parameters alist and ind, firstly, if ind equals the length of alist minus one, it returns, then assign ind to loc, in summary, it uses selection sort method to sort the alist.

it is a sorting algorithm, sorting the element in the list in a descending order.

 

O(n^2)

It has two loops, the outer loop loops n times and the inner loop loops n-i-1 times, so the running time is O(n^2)

[9,7,6,4,3,2,1]

 

def iamrecursive(alist):

for i in range(len(alist)):

max=i

for j in range(i+1,len(alist)):

if max<alist[j]:

max=j

alist[max],alist[i]=alist[i],alist[max]

return alist

 

2d.

a=node

a.next=d

d.next=c

c.next=b

b.next=e

 

3a.

a regular expression is a special sequence of characters that are used to search or match a set of strings.

purpose of using re

  1. parsing
  2. searching
  3. searching and replacing
  4. splitting strings
  5. validating

 

3b.

def getsmartest(text):

arr=text.split(‘,’)

kvs={}

for item in arr:

kv=item.strip().split(‘ is smarter than ‘)

key=kv[0]

value=kv[1]

kvs[key]=value

last=

for k,v in kvs.items():

 

the version using regular expression is the shorter one of the two. regular expression is much more powerful than using string operations. it is much easier and more precise to specify which part of the string you like to catch and findall() function allows you to catch all of them in tuples in one single command.

第二份2016-2017

1a.

0,111,222,333,444,555

in the while loop, once i is divisible by 111, print() will be called, and once i is 580, the loop end, so we have above result.

 

1b.

[20,16,12,8,4,0]

alist is [0,4,8,12,16,20],m is 5,the length of alist //2 is 3, in the iterations, i is 0,1,2 respectively, so it swap alist[0],alist[5]and alist[1],alist[4] and alist[2],alist[3],so we have the above result.

 

1c.

[[1],[2,2],[3,3,3],[4,4,4,4]]

listC is created from a and b, for each element, it based on listA[x-1]*x, and x is 1,2,3,4 respectively, so elements are [1]*1,[2]*2,[3]*3,[4]*4, so we have the above result.

 

1d.

*CAT*DOG*COW*

three methods are defined in MyClass, init initiate a list as self.mylist,str method returns a string which is made of items in the mylist, and add() method is a special method which support ‘+’ operator, so mylist is [‘CAT’,’DOG’,’COW’], when print() is called, ret=’*’.....and we have above result.

 

2a.

why do we say that the worst-case running time is the main concern of algorithm analysis?

many factors may affect the execution of an algorithm, such as code efficiency, machine, compiler, input data etc. An algorithm may run different times given different machines, different inputs. Thus, when we say how an algorithm is, we don’t refer to exact running time.

worst-case running time concerns the maximum execution time for all input sizes, it is easy to analyze, and it is always guaranteed that an algorithm that performs well in its worst-case performs well in general.

 

using an unsorted list is fast and simple to store data O(1), but the search operation takes O(n).

using a sorted list, storing may take O(logn) time, but search takes O(logn) using binary search.

using bst, store and search takes O(logn), but if the tree is not balanced, takes O(n)

 

a dictionary is the most suitable data structure for the data set. the reason is ids and the data can be seen as key-value pairs. python dic is a hash table, and key-based search takes O(1) time which is very fast.

 

2b.

a stack is a container for objects that is inserted and removed according to first-in-last-out order. it supports push and pop.

a queue is a container for objects that is inserted and removed according to first-in-first-out order. it supports enqueue and dequeue.

stack is suitable, for example, when we are removing dog, we should take cat out first, and take cow and owl, so it is like ..., and when we put these back, it is first-in-last-out order. and if we use queue, cat will be the first one.

class Stack():

def __init__(self):

self.list=[]

def pop(self):

return self.list.pop()

def push(self,element):

self.list.append(element)

s=Stack() dog...

t=Stack()

while True:

a=s.pop()

if a==’dog’:

break

else:

b.push(a)

while len(t)>0:

s.push(t.pop)

 

there are two loops involved, in the worst case, the first loop have n iterations, the second loop have n iterations, so it is 2*n iterations, so the running time is O(n)

 

 

3a.

GRFBWCVEY

 

3b.

def traverse(self)

arr=[]

for item in self.list:

arr.extend(traverse_sub(item))

return arr

 

def traverse_sub(sub)

arr=[]

if sub is element:

arr.append(element)

elif sub is subroot:

arr.extend(traverse_sub(sub))

return arr

 

3c.

def find_max(sub)

if sub.right is element:

return sub.right

elif sub.right is sub:

return find_max(sub.right)

 

 

 

 

 

 

 

 

第三份2015-2016

1a.

s1 is s2

s1 and s2 point to same memory space which is ‘Hello’ so the id of s1 same as the id of s2, so the answer() method returns ‘is’ so the output is s1 is s2.

 

1b.

[(1,’one’), (2,’two’), (3,’three’), (4,’four’)]

seq3 created from seq1 and seq2, each element based on (seq1[i], seq2[i]), in the for loop, i is 0,1,2,3 because the length of seq1 is 4, and range(4) range from 0 to 3. so first element is (1,’one’) and second element is (2,’two’), so we have above result.

 

1c.

1 2 2 4 3 6 4 8

in the outer loop, i is 1,2,3,4 respectively, in the inner loop, j is 1,2, so the i*j will be 1*1,1*2 and 2*1,2*2 and so on and we have above result.

 

1d.

[‘TOM’]

in the dic, the key is 11 and 12, value is .. so in the for loop, v[2] is ‘M’ in the first iteration and v[2] is ‘F’ in the second iteration, so alist append v[0] which is ‘TOM’, so we have alist as [‘TOM’]

 

2a.

dynamic typing is when variables can be dynamically bound and rebound to a data object of any type.

for example, we set a=23, but we can always change variable a to a string type by a =’hello’ in the same program.

duck typing is that when we design functions or operations for python data objects, we don’t care what types the data objects are, as long as they behave in a certain way.

for example, we can use ‘+’ operation for strings as well as for lists and tuples.

 

2b.

L1 is created from L2, L1 append elements from L2 from index 0 to end. so L1=[[4,5],[6,7],8],they have same content, but they have different id.

 

l2 changes too, because the copy using slicing is a shallow copy, a shallow copy constructs the sequence object and then, recursively, inserts references into it to the objects found in the original. since both l1 and l2 stores the same reference to the nested list[4,5].

because this is a shallow copy, it constructs the sequence object and inserts references, so l1 and l2 have the same pointer of [4,5],which means l2=[address,address,address]

 

2c.

in python, everything is an object and an object normally has attributes and methods. a python object has a unique id associated with it. it belongs to a certain type and normally has a value associated with it. other attributes of a python object may contain other data items and methods.

 

i support sara,

  1. tuple is immutable, so it is hard to modify if we are going to add some new attributes.
  2. tuple use index as key, so we have to do customer[0]=’Alice’,but if we use class, we can do customer.name=’Alice’, it is more readable.

 

2d.

functions are the most basic program structure that contains a sequence of instructions. it performs a certain task on the input auguments and returns the result. functions package up and parameterize functionality and are good for maximizing code reuse.

 

in the while loop, it will execute condition statement first, so in the last iteration, when x=1, x=1-1, so decrement() method returns False, and the loop breaks, so the output should be 9 8 7 6 5 4 3 2

def decrement():

x=x-1

return True if x>=0 else False

 

 

3a.

[a,[b,[],[e,g,[]]],[c,[],[d,f,[]]]]

 

3b.

def get_height(tree):

height_left=0

height_right=0

if type(tree[1]) is list:

height_left+=get_height(tree[1])

else:

height_left=1

if type(tree[2]) is list:

height_right+=get_height(tree[2])

else:

height_right=1

return height_left if height_left>height_right else height_right

 

there are two loops for the algorithm, in the worst case, the first loop loops n times, the second loop loops n times, so it is 2*n times, so the running time is O(n).

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

发布了1081 篇原创文章 · 获赞 42 · 访问量 21万+

猜你喜欢

转载自blog.csdn.net/qq_33781658/article/details/103942883
今日推荐