|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
# 输入一个单词
Xword = list(input("Enter a word to code:"))
# 保留首字母,在剩下的字母中,删除所有出现的a,e,i,o,u,h,y,w.
word = Xword[1:]
lst = []
for item in word:
if item not in ['a','e','i','o','u','h','y','w']:
lst.append(item)
# 将其他字母按照规则变换成数字
for item in lst:
if item in ['b','f','p','v']:
lst[lst.index(item)] = '1'
elif item in ['c','g','j','k','q','s','x','z']:
lst[lst.index(item)] = '2'
elif item in ['d','t']:
lst[lst.index(item)] = '3'
elif item in ['l']:
lst[lst.index(item)] = '4'
elif item in ['m','n']:
lst[lst.index(item)] = '5'
elif item in ['r']:
lst[lst.index(item)] = '6'
# 如果两个或多个字母被替换为相同的数字,并且它们在原始单词中相邻,则只保留一个
for i in range(len(lst) - 1):
if lst == lst[i + 1]:
lst.remove(lst)
# 只保留结果的前4个字符,如果结果少于4个字符,添加0补充至4位
word = [Xword[0]] + lst
if len(word) >= 4:
word = word[:4]
else:
while len(word) < 4:
word += ['0']
word = "".join(word)
print("The coded word is {0}.".format(word))
红色部分出现3个问题:
(1)连续三个相同就会保留两个
(2)也许他们在原始单词中并不相邻
(3)运行时会出现错误,说列表指针超出范围
我的写法可能比较啰嗦。针对红色部分,以字符串为例,结果仍为字符串。
- str1 = 'tz1aawaaa3ee4rrrr5t'
- s = str2 = str1[0]
- for item in range(1, len(str1)):
- if str1[item] != s:
- s = str1[item]
- str2 += str1[item]
- print(str1)
- print(str2)
复制代码
- tz1aawaaa3ee4rrrr5t
- tz1awa3e4r5t
复制代码
|
|