soy-curd's blog

へぼプログラマーです [https://twitter.com/soycurd1]

python3で言語処理100本ノックの最初のほう

以下のかんじ。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from functools import *

def main():
    print(revstr("mojimoji"))
    print(patoka("パタトクカシーー"))
    print(patatokukasi("パトカー", "タクシー"))
    print(pi("Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."))
    pp(element("Hi He Lied Because Boron Could Not Oxidize Fluorine. New Nations Might Also Sign Peace Security Clause. Arthur King Can.",
               [1, 5, 6, 7, 8, 9, 15, 16, 19]))


# 00 文字列の逆順
def revstr(moji):
    return moji[::-1]


# 01 ぱたとくかしーー
def patoka(string):
    ret = ""
    for i, x in enumerate(string):
        if i%2 == 0:
            ret = ret + x

    return ret


# 02 ぱたとくかしーー2
def patatokukasi(str1, str2):
    strings = zip(str1, str2)
    return reduce(lambda a, x: a + x[0] + x[1], strings, "")


# 03 円周率
def pi(string):
    nodot_txt = string.replace(".", "")
    nocommma_txt = nodot_txt.replace(",", "")
    splited_txt = nocommma_txt.split(" ")
    return list(map(len, splited_txt))


# 04 元素記号
def element(string, indexes):
    nodot_txt = string.replace(".", "")
    splited_txt = nodot_txt.split(" ")

    element_map = {}
    for i, x in enumerate(splited_txt):
        if i + 1 in indexes:
            element_map[x[0]] = i + 1
        else:
            element_map[x[:2]] = i + 1

    return element_map


def pp(foo):
    if foo is list:
        map(pp, foo)
    elif foo is dict:
        map(pp, foo)
    else:
        print(foo)


if __name__=='__main__':
    main()

python3、reduceデフォルトで使えなくてびびった。ぱたとくかしー。