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)