Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ### 1. 请填写下列Python代码运行后, b3和b4的结果
- ```python
- b1 = [1, 2, 3]
- b2 = [2, 3, 4]
- b3 = [val for val in b1 if val in b2]
- b4 = [val for val in b1 if val not in b2]
- b3 = [2, 3] # 求交集
- b4 = [1] # 求差集
- ```
- ### 2. 假设 condition = True 或 False
- 以下两条语句是否等价 ?
- ```python
- result = 1 if condition else 0
- result = condition and 1 or 0
- ```
- 什么情况下不等价 ?
- 以所给的例子来说是等价的,但需要注意如下情况,
- ```python
- result = 0 if condition else 1
- result = condition and 0 or 1
- ```
- 此时不等价,第二个三元表达式返回的永远是1
- ### 3. 类
- ```python
- class Foo(object):
- def __init__(self):
- pass
- ```
- 对于 `class FooExt(Foo)`, 请比较以下两种构造函数写法的异同
- ```python
- def __init__(self):
- Foo.__init__(self)
- def __init__(self):
- super(FooExt, self).__init__()
- ```
- 对于单继承没有太大的区别,对于多重继承,super涉及mro(顺序查找),调用继承的第一个父类的初始化方法
- ### 4. 请实现以下功能
- 读入一个文本文件,统计并输出其中出现频率最高的10个英文单词及其出现的频次。文本文件中均为英文单词,单词之间通过一个,或.分割。
- ```python
- import re
- from collections import Counter
- content = open('workspace/outsourcing/models.py').read() # 读入文件内容
- words = re.split(',|\.', content) # 按,和.分词
- counter = Counter(words) # 计数
- for word, count in sorted(counter.items(), key=lambda (x, y): y, reverse=True)[:10]: # 倒序并取前十个元素
- print word, count
- ```
- ### 5. 请实现一个函数,判断一个字符串中的括号是否匹配。
- 给出一个字符串,其中只包含括号(大中小括号“()[]{}”),括号可以任意嵌套。如果同样的左右括号成对出现并且嵌套正确,那么认为它是匹配的。例如:
- ```
- () -> TRUE (匹配)
- [()] -> TRUE (匹配,括号可以嵌套)
- ()() -> TRUE (匹配,括号可以并列排列)
- ({}([])) -> TRUE (匹配,括号可以任意嵌套,大括号不必在外)
- ) -> FALSE (不匹配,缺少左括号)
- (} -> FALSE (不匹配,左右括号不一样)
- {)(} -> FALSE (不匹配,左右括号相反)
- ```
- list具备栈的功能,对([{进行入栈,遇到)]}时,检查栈顶元素是否匹配,以及完成最后list是否为空
- ```python
- def check(content):
- lst = []
- for i in content:
- if i in ['(', '[', '{']:
- lst.append(i)
- else:
- if i == ')':
- if not lst[-1] == '(':
- return False
- elif i == ']':
- if not lst[-1] == '[':
- return False
- elif i == '}':
- if not lst[-1] == '{':
- return False
- lst.pop()
- if not lst:
- return True
- return False
- ```
- ## 6. Microsoft Excel use letters to denote column labels. Write a function to convert that from and to numerical representation.
- Example
- ```
- input: A
- output: 1
- input: Z
- output: 26
- input: AA
- output: 27
- ```
- ```python
- letter2num_dict = dict(zip(map(chr, range(65, 91)), range(0, 26))) #对应成字典
- def to_num(label):
- num = 0
- for i, letter in enumerate(label[::-1]): # 倒序遍历
- num += 26**i+letter2num_dict.get(letter) # 26进制
- return num
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement