CheckIO题解:OLD LIBRAY 里的部分题目

来源:互联网 发布:eregi() 网页源码 编辑:程序博客网 时间:2024/05/16 19:04

这里只有OLD LIBRAY 里的部分题目,其他的还没做。

Dot in numbers

我的方法就一行:

re.sub(r'(\d)(?=(\d\d\d)+(?!(\d|th)))', r'\1.', txt)
用到正则表达式里环视功能。具体可以参考《精通正则表达式》的环视部分章节。

简单来说就是,匹配一个数字后有且仅有3的倍数个数字的位置


All in row

def checkio(arr):    'convert all elements in arr in one row'    l = [i for i in list_iter(arr)]    return ldef list_iter(nested):    try:        for sublist in nested:            for element in list_iter(sublist):                yield element    except TypeError:        yield nested

这里用到了生成器,可以参考《Python基础教程》里递归生成器部分。

代码里精炼的使用try、except 而不必使用 if isinstance() 也是参考的书上的例子。


Transposed Matrix

#最短的方法list(map(list, zip(*matr)))#我的方法[[matr[i][j] for i in range(len(matr))] for j in range(len(matr[0]))]
这里是我没有理解内建函数zip,以至于写了这几层嵌套。
zip()函数接受多个列表作为参数,将各个列表的元素按相同索引组成组元并形成新的列表。各个组元的长度为参数中最短的列表长。如:

>>> list(zip(['a', 'b'], [1, 2], ['c', 'd', 'e']))[('a', 1, 'c'), ('b', 2, 'd')]



原创粉丝点击