Python小屋练手②编程自测题11-20

  1. 计算并返回两个列表向量的内积,也就是对应分量乘积的和。例如对于v1=[1,2,3],v2=[4,5,6],计算14+25+3*5=32,返回32。
    1
    2
    3
    from operator import mul
    def main(vector1, vector2):
    return sum(list(map(lambda x,y: x*y, vector1, vector2)))
  2. 返回最长的字符串
    1
    2
    def main(lst):
    return sorted(lst, key=lambda x:len(x), reverse=True)[0]
  3. 返回一个包含原列表lst中所有非0整数的新列表,且其中的所有整数保持原来的相对顺序
    1
    2
    def main(lst):
    return list(filter(lambda x: x!=0, lst))
  4. 返回绝对值最大的整数
    1
    2
    3
    4
    5
    6
    7
    8
    def main(lst):
    retV = max([abs(x) for x in lst])
    try:
    index = lst.index(retV)
    return lst[index]
    except:
    index = lst.index(-retV)
    return lst[index]
  5. 返回其中所有奇数组成的新列表
    1
    2
    def main(lst):
    return [x for x in lst if x%2 !=0]
  6. 返回一个长度为20的新字符串,原字符串s的内容再新字符串中居中,如果原字符串s长度小于20,就在两侧用#填充;如果s不小于20,则直接返回s
    1
    2
    def main(s):
    return s.center(20, '#')
  7. 要求把阿拉伯数字0~9变成汉字零到九,其他非阿拉伯数字保持不变
    1
    2
    3
    4
    def main(s):
    inStr='0123456789'
    outStr='零一二三四五六七八九'
    return s.translate(s.maketrans(inStr, outStr))
  8. 要求判断是否存在重复的整数,如果所有整数完全一样,返回0;如果所有整数互不相同,返回1;如果部分相同则返回2;
    1
    2
    3
    4
    5
    6
    7
    8
    def main(lst):
    s = set(lst)
    if len(s) == 1 and len(lst) != 1:
    return 0
    elif len(s) == len(lst):
    return 1
    else:
    return 2
  9. 要求删除英文字母之外的其他所有字符,然后判断剩余的英文字母字符串是否为回文,是回文则返回True,否则返回False
    1
    2
    3
    4
    5
    6
    7
    import re
    def main(s):
    ns = re.sub(r'[^a-zA-Z]','', s)
    if ns[::-1] == ns:
    return True
    else:
    return False
  10. 要求返回其中出现次数最多的前3个字符组成的列表,并按从多到少排列
    1
    2
    3
    4
    from collections import Counter
    def main(s):
    lst_dict = Counter(s).most_common(3)
    return [lst_dict[0][0], lst_dict[1][0], lst_dict[2][0]]