# Scoring criteria:
# 5: pythonic meeting grade 4, and coding in pythonic way
# 4: complete correct logic and result. no bug
# 3: minor bug very close to correct answer. missing corner case or a bit format/cosmetic issue
# 2: medium bug algorithm can run but answer not right, missing conditions, logical flaw etc
# 1: major bug algorithm totally wrong or very bad coding practice
# 0: nothing unfinished major body of the code
Quiz 1:
Goal: Convert all text longer than 8 chars in all cells of the given csv file to end with '…’ with same length alignment (8 chars) and print out.
Hints: - Text length in cell could be of any length - For text shorter or equal to 8 characters, you should not make any change
目标:
将给定csv文件的所有单元格中超过8个字符的所有文本转换为以“…”结尾,并使用相同的长度对齐方式(8个字符)打印出来。 提示:
-单元格中的文本长度可以是任意长度 -对于短于或等于8个字符的文本,不应进行任何更改
import csv
def csv_filter(data_list):
# print(len(data_list))
if len(data_list) > 8:
data_list = data_list[:8] + '...'
# pass
return data_list.ljust(11)
def print_truncated_csv(csv_file):
with open(csv_file, newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',', quotechar='|')
with open('sample_filter.csv', 'w', newline='') as csvfile_write:
pamwriter = csv.writer(csvfile_write, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
for row in spamreader:
if row:
row_iter = map(csv_filter, list(row))
pamwriter.writerow(list(row_iter))
source_csv = 'H:\面试\sample.csv'
print_truncated_csv(source_csv)
Quiz 2:
Goal: Calculate N factorial and print in the format of three-digits-segmentation, e.g. 123,456 计算N阶乘,并以三位数分割的格式打印,例如123,456
Hint: 1. n! = n * (n-1)! 2. 0! = 1 3. 1! = 1
from functools import reduce
def factorial(n):
# Add your code here
if n:
return reduce(lambda x,y: x*y, range(1, n+1))
return 1
def reformat(s):
# Add your code here
return ",".join([s[i:i+3] for i in range(0, len(s), 3)])
print(reformat(str(factorial(10))))
Quiz 3: 两个列表a, b, 设计一个函数分别返回对方不存在的元素
解题思路: 继承了字典的Counter类, 返回每个
from collections import Counter
list_1 = ['a', 'b', 'c']
list_2 = ['a', 'b', 'd']
def func(a, b):
a_count = Counter(a)
b_count = Counter(b)
return [k for k in b_count if not a_count.get(k, None)], [k for k in a_count if not b_count.get(k, None)]
print(func(list_1, list_2))
Quiz4: 字符串a="()()", b="())(()",设计一个函数输入一个值, 返回字符串是否符号规则 例: a真, b假
a = "()()"
b = "())(()"
class Stack:
"""
栈:后进先出
"""
def __init__(self) -> None:
self.list_stack = []
def append(self, data):
"""
进栈
"""
self.list_stack.append(data)
def pop(self):
"""
出栈
"""
return self.list_stack.pop()
def judgment_empty(self):
"""
空判断
"""
return self.list_stack
stack = Stack()
def process_parentheses(a):
for i in a:
if i == "(":
stack.append(i)
if i == ")":
if stack.judgment_empty():
stack.pop()
else:
return False
return stack.list_stack == []
print(process_parentheses(a))
解题思路:
设计一个栈(后进, 先出):
值为(时进入栈, 值为)时出栈
最后为栈为空表示符合规则, 有值或者提前返回False为不符合规则