The Vowel Code---codewar刷题总结

thanks a lot for codewar

Description:

Step 1: Create a function called encode() to replace all the lowercase vowels in a given string with numbers according to the following pattern:

a -> 1
e -> 2
i -> 3
o -> 4
u -> 5

For example, encode("hello") would return "h2ll4". There is no need to worry about uppercase vowels in this kata.

Step 2: Now create a function called decode() to turn the numbers back into vowels according to the same pattern shown above.

For example, decode("h3 th2r2") would return "hi there".

For the sake of simplicity, you can assume that any numbers passed into the function will correspond to vowels.

 我的解决方案:

vowel_dict={'a':1,'e':2,'i':3,'o':4,'u':5}
def encode(st):
    for i in st:
        if i in vowel_dict.keys():
            vowel_values=vowel_dict.get(i)
            st=st[:st.index(i)]+str(vowel_values)+st[st.index(i)+1:]
    return st

def decode(st):
    key_value=list(vowel_dict.items())
    for i in st:
        for j in key_value:
            try:
                if int(i)==j[1]:
                    st=st[:st.index(i)]+j[0]+st[st.index(i)+1:]
            except ValueError:
                continue
    return st

 看看别人都是如何解决的:

a={'a':'1','e':'2','i':'3','o':'4','u':'5'}
b=('a','e','i','o','u')
def encode(st):
    return "".join(a[c] if c in a else c for c in st)
    
def decode(st):
    return "".join(b[int(c)-1] if c.isdigit() else c for c in st)

 这个方法不错,我只创建了个字典,用值取键还挺麻烦的,有一个方法还创建了两个字典,但是键值对正好是相反的,处理此问题就很方便,代码就不贴了。

再看这个,让人惊叹的解题思路。

def cipher(mode):
    table = str.maketrans(*['aeiou', '12345'][::mode])
    return lambda s: s.translate(table)

encode, decode = cipher(1), cipher(-1)

 还有这个:

encoder = {
    'a': '1',
    'e': '2',
    'i': '3',
    'o': '4',
    'u': '5'    
}

decoder = {k: v for v, k in encoder.items()}

def encode(st):
    return ''.join([encoder[c] if c in encoder else c for c in st])
    
def decode(st):
    return ''.join([decoder[c] if c in decoder else c for c in st])

 我为什么要用int数据,多此一举。

 再贴一个:

def encode(s, t=str.maketrans("aeiou", "12345")):
    return s.translate(t)
    
def decode(s, t=str.maketrans("12345", "aeiou")):
    return s.translate(t)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值