Bra*_*itt -1 python user-input morse-code
我正在写一个小函数,它检查输入的字符串是否是莫尔斯码.该函数应该执行类似"If" - "或"的操作."仅在Inputted_string中:"但我似乎无法找到在Python3上执行唯一操作的方法.我实现这一目前的方式是非常混乱,而不是非常Pythonic
if "-" in message:
# message might be morse code so check even more
if "." in message:
# Message IS morse code so return true
return True
else:
# TODO you can use a REGEX for the below things
if '--' in message:
# if the messsage contains only hyphens, then check to see if
# message contans hyphen only morse code by checking all hyphen
# only morse code against message
return True
elif '-----' in message:
# if message contains 0 in morse code, return True
return True
if "." in message:
# message might contain morse code
if "-" in message:
# message IS morse code.
return True
else:
# check to see if message is dots only morse code
# TODO you can use a REGEX for the below things
if ".." in message:
# message IS Morse Code
return True
elif "..." in message:
# message IS Morse Code
return True
elif "....":
# message IS Morse Code
return True
# if dots or dash not in message, return none
return("Message has no hyphens or full stops")
Run Code Online (Sandbox Code Playgroud)
我粘贴时格式略有偏差,但这是一般的要点.当它检查消息是否是"----"或".."等时,这是因为一些莫尔斯代码字母只是那些字符,但我确信有一个更容易的方法来解决这个问题!
def is_morse(message):
allowed = {".", "-", " "}
return allowed.issuperset(message)
Run Code Online (Sandbox Code Playgroud)
但因为消息包含所有字符并不意味着它是有效的.您需要检查每个是否有效,您可以使用字母映射字母到莫尔斯,您还需要一些明确的格式,即字母之间的空格和单词之间的2个或更多空格:
morse = {'---': 'O', '--.': 'G', '-...': 'B', '-..-': 'X', '.-.': 'R', '--.-': 'Q',
'--..': 'Z', '.--': 'W', '..---': '2', '.-': 'A', '..': 'I', '-.-.': 'C',
'..-.': 'F', '-.--': 'Y', '-': 'T', '.': 'E', '.-..': 'L', '...': 'S',
'..-': 'U', '.----': '1', '-----': '0', '-.-': 'K', '-..': 'D', '----.':
'9', '-....': '6', '.---': 'J', '.--.': 'P', '....-': '4', '--': 'M',
'-.': 'N', '....': 'H', '---..': '8', '...-': 'V', '--...': '7', '.....':
'5', '...--': '3',"":" "}
msg = ".... . .-.. .-.. ----- .-- --- .-. .-.. -.."
def is_morse(message):
spl = message.split(" ")
return all(m in morse for m in spl)
if is_morse(msg):
print("".join([morse[ch] for ch in msg.split(" ")]))
Run Code Online (Sandbox Code Playgroud)
可以将其解析为单个字符串来获取所有变体,它只需要做更多的工作.
如果你想转向其他方式,那么你只需反转映射:
to_morse = {v: k for k, v in morse.items()}
def can_morse(msg):
return all(ch in to_morse for ch in msg.upper())
msg = "Hello World"
if can_morse(msg):
print(" ".join([to_morse[ch] for ch in msg.upper()]))
Run Code Online (Sandbox Code Playgroud)
我选择额外的空格来分隔单词,你可以选择你喜欢的任何东西,只需确保将字符添加到dict映射然后添加到空格或任何你想要的单词分隔.
| 归档时间: |
|
| 查看次数: |
255 次 |
| 最近记录: |