原文网址:https://leetcode.com/problems/unique-morse-code-words/description/
大意:求一个数组里面的字母所翻译的摩尔斯电码具体有多少种(难道莫尔斯电码的重复性这么高?=。=)
其实很简单,求一个list里面的unique list只要用set(list)就行了,再len()一下就是多少种了。
import string
class Solution:
s = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
def uniqueMorseRepresentations(self, words):
"""
:type words: List[str]
:rtype: int
"""
MoseList = []
mylist = []
for item in words:
MoseString = ''
for character in item:
index = string.ascii_lowercase.index(character)
MoseString += self.s[index]
MoseList.append(MoseString)
mylist = set(MoseList)
return len(mylist)
a = Solution()
print(a.uniqueMorseRepresentations(["gin", "zen", "gig", "msg"]))
但是这里我取巧了一下。import string
库。这个库的ascii_lowercase
方法(python 2 改为lowercase
)方法可以返回这个字母在字母表里面的顺序。当然,也可以自己写一个lamba来操作(类似于ES6里面的箭头函数,起到一个匿名函数的作用)
def uniqueMorseRepresentations2(self, words):
"""
:type words: List[str]
:rtype: int
"""
moorse = [".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.",
"---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
trans = lambda x: moorse[ord(x) - ord('a')]
map_word = lambda word: ''.join([trans(x) for x in word])
res = map(map_word, words)
return len(set(res))
网友评论