문자열 형식으로 입력 받은 모스코드(dot: . dash:-)를 해독하여 영어 문장으로 출력하는 프로그램을 작성하시오.
글자와 글자 사이는 공백 하나, 단어와 단어 사이는 공백 두개로 구분한다.
예를 들어 다음 모스부호는 "he sleeps early"로 해석해야 한다.
.... . ... .-.. . . .--. ... . .- .-. .-.. -.--
모스부호 규칙 표
| 문자 | 부호 | 문자 | 부호 |
|---|---|---|---|
| A | .- | N | -. |
| B | -... | O | --- |
| C | -.-. | P | .--. |
| D | -.. | Q | --.- |
| E | . | R | .-. |
| F | ..-. | S | ... |
| G | --. | T | - |
| H | .... | U | ..- |
| I | .. | V | ...- |
| J | .--- | W | .-- |
| K | -.- | X | -..- |
| L | .-.. | Y | -.-- |
| M | -- | Z | --.. |
181개의 풀이가 있습니다.
dic = {
'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'
}
def morse(src):
result = []
for word in src.split(" "):
for char in word.split(" "):
result.append(dic[char])
result.append(" ")
return "".join(result)
print morse('.... . ... .-.. . . .--. ... . .- .-. .-.. -.--')
dic={'':' ','.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F','--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L','--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R','...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X','-.--':'Y','--..':'Z'}
morse=".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"
word=morse.split(" ")
for i in word:
print(dic[i],end="")
간단하게 C++11 unordered_map을 이용해봤습니다. C++에서 스트링을 공백으로 나누는 것이 Python처럼 간단하지 않아 C 스타일로 그냥 해봤습니다. 찾아보면 istringstream을 쓸 수도 있지만 이게 더 직관적이고 효율적이지 않나 생각합니다. 명시적으로 공백을 처리하려고 해시 맵에 엔트리를 추가했고요. 테이블에 없는 이상한 모스 부호는 ?를 출력했습니다. 입력 스트링 끝에 공백을 더 해서 마지막 토큰이 루프 내에서 그냥 처리 되도록 했습니다.
#include <iostream>
#include <unordered_map>
#include <string>
static const std::unordered_map<std::string, char> kMorseCode = {
{".-", 'a'}, {"-...", 'b'}, {"-.-.", 'c'}, {"-..", 'd'}, {".", 'e'},
{"..-.", 'f'}, {"--.", 'g'}, {"....", 'h'}, {"..", 'i'}, {".---", 'j'},
{"-.-", 'k'}, {".-..", 'l'}, {"--", 'm'}, {"-.", 'n'}, {"---", 'o'},
{".--.", 'p'}, {"--.-", 'q'}, {".-.", 'r'}, {"...", 's'}, {"-", 't'},
{"..-", 'u'}, {"...-", 'v'}, {".--", 'w'}, {"-..-", 'x'}, {"-.--", 'y'},
{"--..", 'z'},
{"", ' '}, // For explicit handling of ""
};
void decodeMorseCode(std::string input) {
// Append a trailing ' ' marker.
input.push_back(' ');
std::string token;
for (auto c : input) {
if (c != ' ') {
token.push_back(c);
} else {
auto found = kMorseCode.find(token);
std::cout << (found != kMorseCode.end() ? found->second : '?');
token.erase();
}
}
std::cout << std::endl;
}
int main() {
decodeMorseCode(".... . ... .-.. . . .--. ... . .- .-. .-.. -.--");
return 0;
}
심심해서 suffix tree를 만들어서 해봤습니다. 아마도 이보다 더 효율적이고 빠르게 하기는 어렵지 않나 생각합니다. 소스 자체는 이해하기 쉬울 겁니다. 루트부터 시작해서 '.', '-'에 따라 트리를 만들고 종착점에 해당 알파벳을 기입합니다. 디코딩은 그냥 트리 순회만 하면 되기에 해시 테이블 찾는 것보다 빠릅니다 (스트링 해시 계산 만큼의 비용만 필요).
#include <iostream>
#include <string>
#include <memory>
#include <cassert>
// A simple suffix tree for morse code decoding.
class MorseDecodeTree {
private:
struct Node {
char alphabet;
std::unique_ptr<Node> dot;
std::unique_ptr<Node> dash;
Node() : alphabet('?'), dot(nullptr), dash(nullptr) {};
} root_;
public:
MorseDecodeTree() : root_{} {}
bool insertCode(const std::string &code, char alphabet) {
Node *curNode = &root_;
for (auto c : code) {
if (c == '.') {
if (curNode->dot == nullptr)
curNode->dot = std::unique_ptr<Node>{new Node};
curNode = curNode->dot.get();
} else if (c == '-') {
if (curNode->dash == nullptr)
curNode->dash = std::unique_ptr<Node>{new Node};
curNode = curNode->dash.get();
} else {
return false;
}
}
curNode->alphabet = alphabet;
return true;
}
std::string decodeCode(const std::string &input) const {
const Node *cur = &root_;
std::string decoded;
for (auto i : input) {
if (i == ' ') {
decoded.push_back(cur->alphabet);
cur = &root_;
} else if (i == '.')
cur = cur->dot.get();
else if (i == '-')
cur = cur->dash.get();
else
return "<invalid>";
}
decoded.push_back(cur->alphabet);
return decoded;
}
};
int main() {
static const std::unordered_map<std::string, char> kMorseCode = {
{".-", 'a'}, {"-...", 'b'}, {"-.-.", 'c'}, {"-..", 'd'}, {".", 'e'},
{"..-.", 'f'}, {"--.", 'g'}, {"....", 'h'}, {"..", 'i'}, {".---", 'j'},
{"-.-", 'k'}, {".-..", 'l'}, {"--", 'm'}, {"-.", 'n'}, {"---", 'o'},
{".--.", 'p'}, {"--.-", 'q'}, {".-.", 'r'}, {"...", 's'}, {"-", 't'},
{"..-", 'u'}, {"...-", 'v'}, {".--", 'w'}, {"-..-", 'x'}, {"-.--", 'y'},
{"--..", 'z'}, {"", ' '}, // For explicit handling of ""
};
// Build the tree.
MorseDecodeTree tree;
for (auto pair : kMorseCode)
tree.insertCode(pair.first, pair.second);
std::cout << tree.decodeCode(".... . ... .-.. . . .--. ... . .- .-. .-.. -.--");
return 0;
}
###python 입니다.
#dictionary 활용
dic={'.-':'a','-...':'b','-.-.':'c','-..':'d','.':'e','..-.':'f',
'--.':'g','....':'h','..':'i','.---':'j','-.-':'k','.-..':'l',
'--':'m','-.':'n','---':'o','.--.':'p','--.-':'q','.-.':'r',
'...':'s','-':'t','..-':'u','...-':'v','.--':'w','-..-':'x',
'-.--':'y','--..':'z','':' '}
#dic 만들고, 입력값과 key 값을 차례대로 비교해서 value 값을 출력해야됨.
def morse(a): #함수로 a를 입력받는다.
list_a=a.split(' ') #입력받은 a를 리스트로 만들고,... #띄어쓰기 2칸 인식하게 하려면, (' ')기준으로 split
for i in range(len(list_a)):
if list_a[i] in dic:
b=dic.get(list_a[i]) #key값과 입력값 list값을 비교하기
print b,
Perl
%a=(".-", 'a', "-...", 'b', "-.-.", 'c', "-..", 'd', ".", 'e',
"..-.", 'f', "--.", 'g', "....", 'h', "..", 'i', ".---", 'j',
"-.-", 'k', ".-..", 'l', "--", 'm', "-.", 'n', "---", 'o',
".--.", 'p', "--.-", 'q', ".-.", 'r', "...", 's', "-", 't',
"..-", 'u', "...-", 'v', ".--", 'w', "-..-", 'x', "-.--", 'y',
"--..", 'z');
$_=<>;chomp;
s/([\.\-]+)\s?/$a{$1}/g;
print
mo = {
'.-':'a','-...':'b','-.-.':'c','-..':'d','.':'e','..-.':'f',
'--.':'g','....':'h','..':'i','.---':'j','-.-':'k','.-..':'l',
'--':'m','-.':'n','---':'o','.--.':'p','--.-':'q','.-.':'r',
'...':'s','-':'t','..-':'u','...-':'v','.--':'w','-..-':'x',
'-.--':'y','--..':'z', '':' '
}
def morse(buho):
sent = ""
bu = buho.split(" ")
for b in bu:
sent = sent + mo[b]
return sent
import java.util.HashMap;
import java.util.Scanner;
public class Mose {
public static void main(String [] args){
HashMap<Character, String> map = new HashMap<Character, String>();
String mos[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--",
"-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", " "};
char Alpabat[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' '};
for(int i =0; i < mos.length; i ++){
map.put(Alpabat[i], mos[i]);;
}
Scanner sc = new Scanner(System.in);
char str[] = sc.nextLine().toCharArray();
for(int i =0; i < str.length; i++){
System.out.print(map.get(str[i]) + " ");
}
}
}
public class Prob469
{
static string[] alpah = new string[26] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
static string[] mosah = new string[26] { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." };
static string results = "";
// [email protected].
public static string Answers(string Str)
{
string Temp = Str.Replace(" ", "!");
Temp = Temp.Replace(" ", "@");
string[] Spit = Temp.Split('!'); // .-
// [email protected].
for (int i = 0; i < Spit.Length; i++)
{
results += getMos(Spit[i]) + " ";
}
return results;
}
// 단어를 짤름
private static string getMos(string Str)
{
string Word = "";
string[] Temp = Str.Split('@');
for (int i = 0; i < Temp.Length; i++)
{
Word += getWord(Temp[i]);
}
return Word;
}
private static string getWord(string Str)
{
string Wrd = "";
for (int i = 0; i < mosah.Length; i++)
{
if (Str.Equals(mosah[i]))
{
Wrd = alpah[i];
}
}
return Wrd;
}
}
mosdic = {'A':'.-', 'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.', 'F':'..-.',
'G':'--.', 'H':'....', 'I':'..', 'J':'.---', 'K':'-.-', 'L':'.-..',
'M':'--', 'N':'-.', 'O':'---', 'R':'.-.', 'S':'...', 'T':'-', 'U':'..-',
'V':'...-', 'W':'.--', 'X':'-..-', 'Y':'-.--', 'Y':'--..', 'Z':'--..'}
a = list(input("Word or Sentence : "))
for count in range(0,len(a)):
print(mosdic[a[count]],end='')
javascript
var dic = {
"" : " ", ".-" : "A", "-..." : "B", "-.-." : "C",
"-.." : "D", "." : "E", "..-." : "F", "--." : "G",
"...." : "H", ".." : "I", ".---" : "J", "-.-" : "K",
".-.." : "L", "--" : "M", "-." : "N", "---" : "O",
".--." : "P", "--.-" : "Q", ".-." : "R", "..." : "S",
"-" : "T", "..-" : "U", "...-" : "V", ".--" : "W",
"-..-" : "X", "-.--" : "Y", "--.." : "Z"
};
var code = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
var morse = function (c) {
return c.split(" ").map(v => dic[v]).join("");
}
console.log(morse(code));
파이선 입니다. 간단할줄 알았는데 역시 약간의 변수들이 있네요.
import unittest
dic = {'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F','--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L','--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R','...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X','-.--':'Y','--..':'Z'}
def func(s):
result = ''
x = 0
for i in range(len(s)):
if s[i] == ' ' or (i == len(s)-1) :
if not s[i-1] == ' ' :
if i == len(s)-1 :
i = i + 1
morse = s[x:i]
ch = dic[morse]
result = result + ch
x = i + 1
else :
result = result + " "
x = i + 1
return result
class CommaTest(unittest.TestCase):
def test1(self):
self.assertEqual('HE SLEEPS EARLY',func('.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'))
if __name__ == "__main__":
unittest.main()
Java 입니다.
import java.util.HashMap;
import java.util.Map;
public class Test_469 {
Map<String,String> mossMap=new HashMap<String,String>();
String[] alphabets={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
String[] marks={".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
public Test_469(){
for(int i=0; i<alphabets.length;i++)
mossMap.put(marks[i],alphabets[i]);
}
public void parse(String moss){
StringBuffer result=new StringBuffer();
String[] m=moss.split(" ");
for(String ladder : m){
System.out.println(ladder);
if(mossMap.containsKey(ladder))
result.append(mossMap.get(ladder));
else if("".equals(ladder))
result.append(" ");
}
System.out.println("result :"+result.toString());
}
public static void main(String args[]){
new Test_469().parse(".... . ... .-.. . . .--. ... . .- .-. .-.. -.--");
}
}
class Morse
TRANS = {
'.-' => 'A','-...' => 'B','-.-.' => 'C','-..' => 'D','.' => 'E','..-.' => 'F',
'--.' => 'G','....' => 'H','..' => 'I','.---' => 'J','-.-' => 'K','.-..' => 'L',
'--' => 'M','-.' => 'N','---' => 'O','.--.' => 'P','--.-' => 'Q','.-.' => 'R',
'...' => 'S','-' => 'T','..-' => 'U','...-' => 'V','.--' => 'W','-..-' => 'X',
'-.--' => 'Y','--..' => 'Z'
}
def self.translate(morse)
Morse.new(morse).to_s
end
attr_reader :words
def initialize(morse)
@words = morse.split(" ")
end
def to_s
words.map { |word| translate(word) }.join(" ")
end
private
def translate(word)
chars = word.split(" ")
chars.map { |char| TRANS[char] }.join
end
end
puts Morse.translate(".... . ... .-.. . . .--. ... . .- .-. .-.. -.--")
기존 풀이 참조했으며, 예외 처리 추가하는 방식으로 바꿔봤습니다. (Python 2.7.8)
dic = {
'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'
}
def morse(src):
result = ""
for say in src.split(" "):
try:
result += dic[say]
except KeyError:
result += " "
print result
morse('.... . ... .-.. . . .--. ... . .- .-. .-.. -.--')
dic = {'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F','--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L','--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R','...':'S','-':'T','..-':'U','...-':'V', '.--':'W','-..-':'X','-.--':'Y','--..':'Z'}
def decipher(morse):
ans = ""
sent = morse.split(" ")
for c in sent:
if c != '':
ans += dic[c]
else :
ans += " "
return ans
morse = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
print (decipher(morse))
(def alpha->code
{\ ""
\A ".-" \N "-."
\B "-..." \O "---"
\C "-.-." \P ".--."
\D "-.." \Q "--.-"
\E "." \R ".-."
\F "..-." \S "..."
\G "--." \T "-"
\H "...." \U "..-"
\I ".." \V "...-"
\J ".---" \W ".--"
\K "-.-" \X "-..-"
\L ".-.." \Y "-.--"
\M "--" \Z "--.."})
(def code->alpha
(clojure.set/map-invert alpha->code))
(defn decode [x]
(->> (clojure.string/split x #" ")
(map code->alpha)
(apply str)))
(decode ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--")
;=> "HE SLEEPS EARLY"
$array = array(
'.- ' => 'A','-... ' => 'B','-.-. ' => 'C','-.. ' => 'D','. ' => 'E','..-. ' => 'F',
'--. ' => 'G','.... ' => 'H','.. ' => 'I','.--- ' => 'J','-.- ' => 'K','.-.. ' => 'L',
'-- ' => 'M','-.' => 'N','--- ' => 'O','.--. ' => 'P','--.- ' => 'Q','.-. ' => 'R',
'... ' => 'S','- ' => 'T','..- ' => 'U','...- ' => 'V','.-- ' => 'W','-..- ' => 'X',
'-.-- ' => 'Y','--.. ' => 'Z'
);
$str = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
echo strtr($str,$array);
치환용 배열자체에 ' ' 빈공간을 넣어놓으면 치환될때 다 처리가 됩니다.
array를 자세히 보시면 빈칸이 한개씩 들어있습니다.ㅋㅋㅋㅋ
자바 입니다.
public class MosSignal {
// .... . ... .-.. . . .--. ... . .- .-. .-.. -.-- => "he sleeps early"
public static void main(String[] args) {
String signal = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
System.out.println(decoding(signal));
}
static String decoding(String signal){
StringBuffer signalDecoding = new StringBuffer();
String []tmp = signal.split(" ");
String[] mosCode = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
"....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.",
"--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-",
"-.--", "--.." };
boolean isblank = true;
for(int i = 0; i < tmp.length; i++){
for(int j = 0; j < mosCode.length; j++){
if(tmp[i].equals(mosCode[j])){
signalDecoding.append((char)(j+97));
isblank = true;
break;
}
else
isblank = false;
}
if (!isblank)
signalDecoding.append(" ");
isblank = true;
}
return signalDecoding.toString();
}
}
val letters = Array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z")
val morse = Array(".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..")
val morseWithIndex = morse.zipWithIndex.toMap
def decode(line: String) = {
val words = line.split("(\\s)(\\s)").map(word => word.split("\\s"))
words.map(codes => codes.map(code => letters(morseWithIndex(code))).mkString).mkString(" ")
}
decode(".... . ... .-.. . . .--. ... . .- .-. .-.. -.--")
자바입니다. 입력받는 형태로 작성하였습니다만... 모스 부호에 맞지 않은 문자는 ?로 찍히게 하였습니다.
import java.util.HashMap;
import java.util.Scanner;
class MossTran {
public static void main(String[] args){
HashMap<String, String> map = new HashMap<String, String>();
map.put(".-","A");
map.put("-...","B");
map.put("-.-.","C");
map.put("-..","D");
map.put(".","E");
map.put("..-.","F");
map.put("--.","G");
map.put("....","H");
map.put("..","I");
map.put(".---","J");
map.put("-.-","K");
map.put(".-..","L");
map.put("--","M");
map.put("-.","N");
map.put("---","O");
map.put(".--.","P");
map.put("--.-","Q");
map.put(".-.","R");
map.put("...","S");
map.put("-","T");
map.put("..-","U");
map.put("...-","V");
map.put(".--","W");
map.put("-..-","X");
map.put("-.--","Y");
map.put("--..","Z");
System.out.println("enter the code : ");
String moss = (new Scanner(System.in)).nextLine();
if("".equals(moss)) return;
String[] space = moss.split(" ");
String[] tran;
StringBuffer sb = new StringBuffer();
for(String spaceTxt:space){
tran = spaceTxt.split(" ");
for(String key:tran){
if(map.containsKey(key)) {
sb.append(map.get(key));
} else {
sb.append("?");
}
}
sb.append(" ");
}
System.out.println("result : ");
System.out.println(sb.toString());
}
}
coding by python beginner
t0 = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
rs = ''
cw = {
'.-' :'a', '-...':'b', '-.-.':'c', '-..' :'d', '.' :'e',
'..-.':'f', '--.' :'g', '....':'h', '..' :'i', '.---':'j',
'-.-' :'k', '.-..':'l', '--' :'m', '-.' :'n', '---' :'o',
'.--.':'p', '--.-':'q', '.-.' :'r', '...' :'s', '-' :'t',
'..-' :'u', '...-':'v', '.--' :'w', '-..-':'x', '-.--':'y',
'--..':'z'
}
for world in t0.split( ' ' * 2 ):
if rs != '': rs += ' '
for key in world.split():
try: rs += cw[key]
except: rs += key
print(rs)
펄입니다 거의 비슷하게 푼 사람이 있어서 그냥 for문사용..
my %morse=('.-'=>'A','-...'=>'B','-.-.'=>'C','-..'=>'D',
'.'=>'E','..-.'=>'F','--.'=>'G','....'=>'H','..'=>'I',
'.---'=>'J','-.-'=>'K','.-..'=>'L','--'=>'M','-.'=>'N',
'---'=>'O','.--.'=>'P','--.-'=>'Q','.-.'=>'R','...'=>'S',
'-'=>'T','..-'=>'U','...-'=>'V','.--'=>'W','-..-'=>'X','-.--'=>'Y','--..'=>'Z',' '=>' ');
for($ARGV[0]=~/(\S+) *?|( ) /sg){print $morse{$_}}
Scala 입니다.
val input = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"
val code = Map(
".-" -> "a",
"-..." -> "b",
"-.-." -> "c",
"-.." -> "d",
"." -> "e",
"..-." -> "f",
"--." -> "g",
"...." -> "h",
".." -> "i",
".---" -> "j",
"-.-" -> "k",
".-.." -> "l",
"--" -> "m",
"-." -> "n",
"---" -> "o",
".--." -> "p",
"--.-" -> "q",
".-." -> "r",
"..." -> "s",
"-" -> "t",
"..-" -> "u",
"...-" -> "v",
".--" -> "w",
"-..-" -> "x",
"-.--" -> "y",
"--.." -> "z"
)
def morse(src: String): String = {
src.split(" ").map(_.split(" ").map(code.apply).mkString).mkString(" ")
}
println(morse(input))
파이썬
def main():
dic = {
'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'}
result = ''
Morse_code = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
m_list = Morse_code.split(' ')
for code in m_list:
if code == '':
result += ' '
else:
result += dic[code]
print(result.lower())
if __name__ == '__main__':
main()
자바입니다. 아스키코드 활용해서 짜봤습니다.
public class CD469 {
public static void main(String[] args){
String[] dic = {".-","-...","-.-.","-...",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
String original = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
String decode = "";
for(String word : original.split(" ")){
for(String cha : word.split(" ")){
for (int i = 0; i < dic.length; i++) {
if(cha.equals(dic[i])){
decode = decode + String.valueOf((char)(i + 'a'));
}
}
}
decode = decode + " ";
}
System.out.println(decode);
}
}
morse={'.-':'A', '-...':'B', '-.-.':'C', '-..':'D', '.':'E', '..-.':'F', '--.':'G', '....':'H', '..':'I', '.---':'J', '-.-':'K', '.-..':'L', '--':'M', '-.':'N', '---':'O', '.--.':'P', '--.-':'Q', '.-.':'R', '...':'S', '-':'T', '..-':'U','...-':'V', '.--':'W', '-..-':'X', '-.--':'Y', '--..':'Z'}
s1 = input("Input Morse Code: ")
s1 = s1.split(' ')
decode=''
for code in s1:
s2 = code.split()
for c in s2:
try:
decode += morse[c]
except KeyError:
break
decode += ' '
print(decode)
Swift로 두가지로 O(n), 고차계수 형태로 구현해보았습니다.
import Foundation
let mosTable: [String:String] = [".-":"A","-...":"B","-.-.":"C","-..":"D",".":"E","..-.":"F",
"--.":"G","....":"H","..":"I",".---":"J","-.-":"K",".-..":"L",
"--":"M","-.":"N","---":"O",".--.":"P","--.-":"Q",".-.":"R",
"...":"S","-":"T","..-":"U","...-":"V",".--":"W","-..-":"X",
"-.--":"Y","--..":"Z", "Space":" "]
var mosSignalStream = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"
extension String {
subscript (i: Int) -> Character {
return self[advance(self.startIndex, i)]
}
}
enum state: String {
case Char = "Char"
case Space = "Space"
}
var mosState:state = .Char
var word = "", totalWord = ""
for var index = 0; index < countElements(mosSignalStream); index++ {
let str = String(mosSignalStream[index])
if (index > countElements(mosSignalStream) - 1) {
totalWord += mosTable[word]!
} else {
switch (mosState, str) {
case (.Char, _) where str != " " :
word += str
case (.Char, _) where str == " " :
totalWord += mosTable[word]!
mosState = .Space
word = ""
case (.Space, _) where str != " " :
word = str
mosState = .Char
case (.Space, _) where str == " " :
totalWord += " "
default:
break
}
}
}
println("Translate Result : \(totalWord)")
import Foundation
let mosTable: [String:String] = [".-":"A","-...":"B","-.-.":"C","-..":"D",".":"E","..-.":"F",
"--.":"G","....":"H","..":"I",".---":"J","-.-":"K",".-..":"L",
"--":"M","-.":"N","---":"O",".--.":"P","--.-":"Q",".-.":"R",
"...":"S","-":"T","..-":"U","...-":"V",".--":"W","-..-":"X",
"-.--":"Y","--..":"Z", "Space":" "]
var mosSignalStream = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"
let mosSignalSigalArray = mosSignalStream.componentsSeparatedByString(" ")
let result = mosSignalSigalArray
.map { str -> [String] in return str.componentsSeparatedByString(" ") }
.map { obj -> String in
return obj
.map { str -> String in return mosTable[str]! }
.reduce("") { $0 + $1 }
+ " " }
.reduce("", combine: +)
println(result)
Using python
#!/usr/bin/python
#-*- coding: utf-8 -*-
mosTable = {".-":'A',"-...":'B',"-.-.":"C","-..":"D",
".":"E","..-.":"F","--.":"G","....":"H",
"..":"I",".---":"J","-.-":"K",".-..":"L",
"--":"M","-.":"N","---":"O",".--.":"P",
"--.-":"Q",".-.":"R","...":"S","-":"T",
"..-":"U","...-":"V",".--":"W","-..-":"X",
"-.--":"Y","--..":"Z"}
a = ".. ... .-.. . . .--. ... . .- .-. .-.. -.--"
a = a.split(" ")
b =[]
for i in a:
if len(i.split(" ")) >=2:
for j in i.split(" "):
b.append(mosTable[j])
b.append(" ")
elif i.find(" ") == -1:
b.append(mosTable[i])
b.append(" ")
print "".join(b)
dic = {
'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'
}
def morse(src):
result = []
for word in src.split(" "):
for char in word.split(" "):
result.append(dic[char])
result.append(" ")
return "".join(result)
print(morse('.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'))
java
package rootcucu.codefight;
public class Morse {
private final static String CONVERTER
= " T - E . A .- B -... C -.-. D -.. F ..-. G --. H .... I .. J .--- K -.- L .-.. M -- N -. O --- P .--. Q --.- R .-. S ... U ..- V ...- W .-- X -..- Y -.-- Z --..";
public String decode(String code){
StringBuilder originalTemp = new StringBuilder();
for (String segment:code.split(" ")){
int find = CONVERTER.indexOf(" " + segment + " ", 1);
originalTemp.append(CONVERTER.charAt(find - 1));
}
return originalTemp.toString();
}
public static void main(String[] args){
String sequence = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
System.out.println("original message = " + new Morse().decode(sequence));
}
}
너무 쉬어요.
mos_dic = {'.-':'a', '-...':'b', '-.-.':'c', '-..':'d', '.':'e', '..-.':'f',\
'--.':'g', '....':'h', '..':'i', '.---':'j', '-.-':'k', '.-..':'l',\
'--':'m', '-.':'n', '---':'o', '.--.':'p', '--.-':'q', '.-.':'r',\
'...':'s', '-':'t', '..-':'u', '...-':'v', '.--':'w', '-..-':'x',\
'-.--':'y', '--..':'z', '':'', ' ':'', ' ':' '}
msg = input("Input moss msg: ")
msg_list = msg.split(' ')
msg = ''
try:
for i in msg_list:
msg_word = i.split(' ')
for j in msg_word:
msg += mos_dic[j]
msg += ' '
except:
print ("Moss unrecognisable!")
print (msg)
dic을 이런식으로 쓰는군요!! 배워갑니다! 길가의 풀님과 비교해보면, 변수의 이름을 의미랑 일치시켜서 가독성을 높이고, 함수를 하나로 뭉쳐서 구조적으로 편하게 하셨군요!!
#469
dic = {
'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'
}
def convert(x):
word=[]
for i in x.split(" "):
word.append(dic[i])
return "".join(word)
f=open("input.txt","r")
inputs=f.read().split(" ")
ans=[]
for x in inputs:
ans.append(convert(x))
print " ".join(ans)
$string = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--';
$a = array(
'.- ' => 'A','-... ' => 'B','-.-. ' => 'C','-.. ' => 'D','. ' => 'E','..-. ' => 'F',
'--. ' => 'G','.... ' => 'H','.. ' => 'I','.--- ' => 'J','-.- ' => 'K','.-.. ' => 'L',
'-- ' => 'M','-. ' => 'N','--- ' => 'O','.--. ' => 'P','--.- ' => 'Q','.-. ' => 'R',
'... ' => 'S','- ' => 'T','..- ' => 'U','...- ' => 'V','.-- ' => 'W','-..- ' => 'X',
'-.--' => 'Y','--.. ' => 'Z'
);
str_replace(" "," ", $string);
$b = strtr($string, $a);
echo strtolower($b);
public static void Main(string[] args)
{
Hashtable hs = new Hashtable();
hs.Add(".-", "A");
hs.Add("-...", "B");
hs.Add("-.-.", "C");
hs.Add("-..", "D");
hs.Add(".", "E");
hs.Add("..-.", "F");
hs.Add("--.", "G");
hs.Add("....", "H");
hs.Add("..", "I");
hs.Add(".---", "J");
hs.Add("-.-", "K");
hs.Add(".-..", "L");
hs.Add("--", "M");
hs.Add("-.", "N");
hs.Add("---", "O");
hs.Add(".--.", "P");
hs.Add("--.-", "Q");
hs.Add(".-.", "R");
hs.Add("...", "S");
hs.Add("-", "T");
hs.Add("..-", "U");
hs.Add("...-", "V");
hs.Add(".--", "W");
hs.Add("-..-", "X");
hs.Add("-.--", "Y");
hs.Add("--..", "Z");
string value = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
string[] splitxt = value.Split(' ');
foreach(string s in splitxt)
{
Console.Write(hs[s]);
}
}
static char Morse(String input)
{
String[] code = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--",
"-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." };
char[] out = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ' };
int indx = 26;
for (int i = 0; i < code.length; i++)
{
if (code[i].equals(input))
{
indx = i;
break;
}
}
return out[indx];
}
static void exce76()
{
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
String[] split = input.split(" ");
for (int i = 0; i < split.length; i++)
{
System.out.printf("%c", Morse(split[i]));
}
}
그냥 평벙하게 해봤습니다.
package test;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Scanner;
public class Morse {
public static void main(String[] args) {
HashMap<String, String> ht = new HashMap<String, String>();
ht.put(".-", "A");
ht.put("-...","B");
ht.put("-.-.","C");
ht.put("-..","D");
ht.put(".", "E");
ht.put("..-.", "F");
ht.put("--.", "G");
ht.put("....", "H");
ht.put("..", "I");
ht.put(".---", "J");
ht.put("-.-", "K");
ht.put(".-..", "L");
ht.put("--", "M");
ht.put("-.", "N");
ht.put("---", "O");
ht.put(".--.", "P");
ht.put("--.-", "Q");
ht.put(".-.", "R");
ht.put("...", "S");
ht.put("-", "T");
ht.put("..-", "U");
ht.put("...-", "V");
ht.put(".--", "W");
ht.put("-..-", "X");
ht.put("-.--", "Y");
ht.put("--..", "Z");
ht.put(null, " ");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
String[] text = input.split(" ");
for(int i=0;i<text.length;i++){
System.out.print(ht.get(text[i]));
}
}
}
def transformer(a):
if a == '.-':
a = 'A'
if a == '-...':
a = 'B'
if a == '-.-.':
a = 'C'
if a == '-..':
a = 'D'
if a == '.':
a = 'E'
if a == '..-.':
a = 'F'
if a == '--.':
a = 'G '
if a == '....':
a = 'H'
if a == '..':
a = 'I'
if a == '.---':
a = 'J'
if a == '-.-':
a = 'K'
if a == '.-..':
a = 'L'
if a == '--':
a = 'M'
if a == '-.':
a = 'N'
if a == '---':
a = 'O'
if a == '.--.':
a = 'P'
if a == '--.-':
a = 'Q'
if a == '.-.':
a = 'R'
if a == '...':
a = 'S'
if a == '-':
a = 'T'
if a == '..-':
a = 'U'
if a == '...-':
a = 'V'
if a == '.--':
a = 'W'
if a == '-..-':
a = 'X'
if a == '-.--':
a = 'Y'
if a == '--..':
a = 'Z'
return a
inputsignal = input()
wordsplitter = (" ")
wordlist = inputsignal.split(wordsplitter)
lettersplitter = (" ")
resultlist = []
for i in range(0, len(wordlist)):
wordlist[i] = wordlist[i].split(lettersplitter)
wordlist[i] = list(wordlist[i])
for ii in range(0, len(wordlist[i])):
wordlist[i][ii] = transformer(wordlist[i][ii])
resultlist.append("".join(wordlist[i]))
resultlist.append(" ")
print("".join(resultlist))
파이썬입니다.
code = {
'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'
}
def morse(string):
result = ""
for word in string.split(" "): # 단어로 구분
for char in word.split(" "): # 글자로 구분
result += code[char]
result += " "
return result
print(morse(".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"))
<?php
echo decodeMorse('.... . ... .-.. . . .--. ... . .- .-. .-.. -.--');
function decodeMorse($str)
{
$morse_code = array(
'.-'=>'A',
'-...'=>'B',
'-.-.'=>'C',
'-..'=>'D',
'.'=>'E',
'..-.'=>'F',
'--.'=>'G',
'....'=>'H',
'..'=>'I',
'.---'=>'J',
'-.-'=>'K',
'.-..'=>'L',
'--'=>'M',
'-.'=>'N',
'---'=>'O',
'.--.'=>'P',
'--.-'=>'Q',
'.-.'=>'R',
'...'=>'S',
'-'=>'T',
'..-'=>'U',
'...-'=>'V',
'.--'=>'W',
'-..-'=>'X',
'-.--'=>'Y',
'--..'=>'Z'
);
$result = '';
$str = explode(' ', $str);
foreach ($str as $str) {
if($str == '') $result .= ' ';
else $result .= $morse_code[$str];
}
return $result;
}
?>
morseDic = { '.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F', # morse부호를 저장하는 dictionary
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'}
lines = raw_input() # 라인을 입력 받음
morseList = lines.split(" ")
result = []
for morse in morseList:
if morse == "":
result.append(" ") # 공백을 표현하는 방법
continue
else:
result.append(morseDic[morse])
print "".join(result) ##list를 string으로 변환하는 방법
파이썬 2.7.11
dic = {
'.-':'a','-...':'b','-.-.':'c','-..':'d','.':'e','..-.':'f',
'--.':'g','....':'h','..':'i','.---':'j','-.-':'k','.-..':'l',
'--':'m','-.':'n','---':'o','.--.':'p','--.-':'q','.-.':'r',
'...':'s','-':'t','..-':'u','...-':'v','.--':'w','-..-':'x',
'-.--':'y','--..':'z'
}
s = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
result = ''
word_morse = s.split(' ')
for i in range(len(word_morse)):
alpabet_morse = word_morse[i].split()
for alpa in alpabet_morse:
result += dic[alpa]
result += ' '
print result
파이썬 2.7.11
dic = {
'.-':'a','-...':'b','-.-.':'c','-..':'d','.':'e','..-.':'f',
'--.':'g','....':'h','..':'i','.---':'j','-.-':'k','.-..':'l',
'--':'m','-.':'n','---':'o','.--.':'p','--.-':'q','.-.':'r',
'...':'s','-':'t','..-':'u','...-':'v','.--':'w','-..-':'x',
'-.--':'y','--..':'z'
}
s = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
result = ''
word_morse = s.split(' ')
for i in range(len(word_morse)):
alpabet_morse = word_morse[i].split()
for alpa in alpabet_morse:
result += dic[alpa]
result += ' '
print result
Mos = {'.-':'A', '-.':'N', '-...':'B', '---':'O', '-.-.':'C', '.--.':'P', '-..':'D', '--.-':'Q',
'.':'E', '.-.':'R', '..-.':'F', '...':'S', '--.':'G', '-':'T', '....':'H', '..-':'U', '..':'I', '...-':'V',
'.---':'J', '.--':'W', '-.-':'K', '-..-':'X', '.-..':'L', '-.--':'Y', '--':'M', '--..':'Z'}
msg = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
c =''
trans = []
for x in range(len(msg)):
if msg[x] == ' ' and c == '':
trans.append(' ')
elif msg[x] == ' ':
trans.append(Mos[c])
c = ''
else:
c += msg[x]
trans.append(Mos[c])
print('Translated message: ' + ''.join(trans).lower())
s=".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"
charset={".-":'A',"-...":'B',"-.-.":'C',"-..":'D',".":'E',"..-.":'F',"--.":'G',"....":'H',"..":'I',
".---":'J',"-.-":'K',".-..":'L',"--":'M',"-.":'N',"---":'O',".--.":'P',"--.-":'Q',".-.":'R',
"...":'S',"-":'T',"..-":'U',"...-":'V',".--":'W',"-..-":'X',"-.--":'Y',"--..":'Z','':' '}
for c in s.split(' '):
print charset[c],
#include <stdio.h>
#include <string.h>
#define N 200
int main(void){
int i,j;
char morse[26][2][5]={{".-",'a'},{"-...", 'b'}, {"-.-.", 'c'}, {"-..", 'd'}, {".", 'e'}, {"..-.", 'f'}, {"--.", 'g'}, {"....", 'h'}, {"..", 'i'}, {".---", 'j'}, {"-.-", 'k'}, {".-..", 'l'}, {"--", 'm'}, {"-.", 'n'}, {"---", 'o'}, {".--.", 'p'}, {"--.-", 'q'}, {".-.", 'r'}, {"...", 's'}, {"-", 't'}, {"..-", 'u'}, {"...-", 'v'}, {".--", 'w'}, {"-..-", 'x'}, {"-.--", 'y'},{"--..", 'z'}};
char code[N],play[5];
printf("모스 부호 입력:");
scanf("%[^\n]",code);
for(i=0;code[i]!='\0';i++){
for(j=0;(code[i]!='\0')&&(code[i]!=' ');i++,j++){
play[j]=code[i];
}
play[j]='\0';
for(j=0;;j++){
if(!strcmp(morse[j][0],play)){
printf("%s",morse[j][1]);
break;
}
}
if(code[i+1]==' '){
printf(" ");
i++;
}
}
}
모르스부호를 숫자로 바꿉니다. 점은 0으로 대쉬는 1로 바꿉니다. 그러면 0은 E, 1은 T 00은 I, 01은 A, 10은 N, 11은 M 이런식으로 바꿀 수 있습니다.. 단 0과 00은 구분해야 하므로 모르스부호의 자리수별로 코드표를 만듭니다. ...
이런식으로 정렬했습니다.
s = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
s = s.split(' ')
code ='ET IANM SURWDKGO HVF.L.PJBXCYZQ'.split()
d={'-':'1','.':'0'}
for w in s:
print ''.join([code[len(c)-1][eval('0b'+''.join(d[p] for p in c))] for c in w.split()]),
Ruby
DIC = %w(.- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--.
--.- .-. ... - ..- ...- .-- -..- -.-- --..).zip('a'..'z').to_h
translate = ->morse { morse.split(' ').map {|w| w.split.map(&DIC)*'' }*' ' }
Test
test_morse_str = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"
expect(translate[test_morse_str]).to eq "he sleeps early"
T = ['.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..']
while __name__ == '__main__':
inpt = input('입력: ').split(' ')
for x in range(len(inpt)):inpt[x] = inpt[x].split(' ')
for x in inpt:
for y in x:print(chr(T.index(y)+97), end = '')
print(' ', end = '')
파이썬 3.5.1입니다.
파이썬3.4입니다. 딕셔너리 키값으로 '': ' '와 알파벳이 먼저와야되는걸로 알고 있었는데, 아니였네요; 다른 풀이 보고 많이 배웠습니다.
src = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
mos={'.-':'a','-...':'b','-.-.':'c','-..':'d','.':'e','..-.':'f',
'--.':'g','....':'h','..':'i','.---':'j','-.-':'k','.-..':'l',
'--':'m','-.':'n','---':'o','.--.':'p','--.-':'q','.-.':'r',
'...':'s','-':'t','..-':'u','...-':'v','.--':'w','-..-':'x',
'-.--':'y','--..':'z'}
src_1 = src.split(' ')
for i in src_1:
for x in i.split():
print(mos.get(x), end='')
print(' ', end='')
파이썬입니다.
def do(msg):
def p(word):
ms = '''.- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. --
-. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..'''.split()
return ''.join([chr(ms.index(c) + 97) for c in word.split()])
return ' '.join([p(w) for w in i.split(' ')])
i = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"
print(do(i))
Python
morse_dict = {".-":"a", "-...":"b", "-.-.":"c", "-..":"d", ".":"e", "..-.":"f", "--.":"g",
"....":"h", "..":"i", ".---":"j", "-.-":"k", ".-..":"l", "--":"m", "-.":"n", "---":"o", ".--.":"p",
"--.-":"q", ".-.":"r", "...":"s", "-":"t", "..-":"u", "...-":"v", ".--":"w", "-..-":"x", "-.--":"y", "--..":"z", "":" " }
def morse(message):
decode_message = ""
for word in message.split(" "):
decode_message += morse_dict[word]
return decode_message
print(morse(".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"))
#파이썬3.4.2
letter = {'-.-.': 'C', '---': 'O', '-.': 'N', '....': 'H', '.--.': 'P', '--..': 'Z', '.-': 'A', '-': 'T', '.---': 'J',
'-.--': 'Y', '--.-': 'Q', '-.-': 'K', '.-.': 'R', '..-': 'U', '--.': 'G', '.-..': 'L', '-...': 'B', '.': 'E',
'...': 'S', '.--': 'W', '..': 'I', '...-': 'V', '--': 'M', '..-.': 'F', '-..': 'D', '-..-': 'X'}
def morse(s):
r = ''
s = s.split(' ')
for i in range(len(s)):
s[i] = s[i].split(' ')
for i in range(len(s)):
for ii in range(len(s[i])):
s[i][ii] = letter[s[i][ii]]
for i in s:
for ii in i:
r += ii
r += ' '
return r
print(morse(input())) # 모스부호 입력
morsedata={'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F','--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L','--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R','...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z' }
def morse(a):
result=""
for i in a.split(" "):
for k in i.split(" "):
result=result+morsedata[k]
result=result+" "
return result
print(morse(".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"))
파이썬입니다.
mos = {".-":"A", "-...":"B", "-.-.":"C", "-..":"D", ".":"E","..-.":"F","--.":"G", "....":"
H", "..":"I", ".---":"J", "-.-":"K", ".-..":"L", "--":"M", "-.":"N", "---":"O", ".--.":"P"
, "--.-":"Q", ".-.":"R", "...":"S", "-":"T", "..-":"U", "...-":"V", ".--":"W", "-..-":"X",
"-.--":"Y", "--..":"Z"}
user_input = raw_input("Enter mos signal : ")
user_input = user_input.split(" ")
output=""
for i in user_input:
words = i.split()
for mem in words:
if mem in mos:
output+=mos[mem]
output+=" "
print output
Pythong 3.5입니다.
morse_dict = {
'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z', ' ':' '
}
inp1 = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
def interpret_morse(inp):
temp = inp.split(' ')
result = ''
for x in temp:
key = morse_dict.get(x)
try:
result += key
except:
result += ' '
return result
print(interpret_morse(inp1))
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class test {
public static void main(String[] argv) {
Scanner sc = new Scanner(System.in);
String mosString = sc.nextLine();
String[] mosList = mosString.split("\\s");
Map<String, String> mosMap = new HashMap<String, String>();
String[] moDotValue = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-",
".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", ".--", "-..-", "-.--", "--.."};
for(int i = 0; i < 25; i++){
mosMap.put(moDotValue[i], String.valueOf((char)(97 + i)));
}
for(int i = 0; i< mosList.length; i++){
if(mosList[i].equals("") ){
System.out.print(" ");
}else{
System.out.print(mosMap.get(mosList[i]));
}
}
}
}
moscode = "A.-,N-.,B-...,O---,C-.-.,P.--.,D-..,Q--.-,E.,R.-.,F..-.,S...,G--.,T-,H....,U..-,I..,V...-,J.---,W.--,K-.-,X-..-,L.-..,Y-.--,M--,Z--.."
moslist = sorted(moscode.split(","))
data = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"
datalist = data.split(" ")
for i in datalist:
for k in i.split(" "):
for j in moslist:
if k == j[1:]:
print(j[0],end="")
print(end=" ")
Python 3.5.2
package 코딩도장;
import java.util.Scanner;
public class Q15 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String[] insert = in.nextLine().split("");
for(int i=0;i<insert.length;i++)
{
if(insert[i].equals("a"))
{
insert[i] = ".-";
}
else if(insert[i].equals("b"))
{
insert[i] = "-...";
}
else if(insert[i].equals("c"))
{
insert[i] = "-.-.";
}
else if(insert[i].equals("d"))
{
insert[i] = "-..";
}
else if(insert[i].equals("e"))
{
insert[i] = ".";
}
else if(insert[i].equals("f"))
{
insert[i] = "..-.";
}
else if(insert[i].equals("g"))
{
insert[i] = "--.";
}
else if(insert[i].equals("h"))
{
insert[i] = "....";
}
else if(insert[i].equals("i"))
{
insert[i] = "..";
}
else if(insert[i].equals("j"))
{
insert[i] = ".---";
}
else if(insert[i].equals("k"))
{
insert[i] = "-.-";
}
else if(insert[i].equals("l"))
{
insert[i] = ".-..";
}
else if(insert[i].equals("m"))
{
insert[i] = "--";
}
else if(insert[i].equals("n"))
{
insert[i] = "-.";
}
else if(insert[i].equals("o"))
{
insert[i] = "---";
}
else if(insert[i].equals("p"))
{
insert[i] = ".--.";
}
else if(insert[i].equals("q"))
{
insert[i] = "--.-";
}
else if(insert[i].equals("r"))
{
insert[i] = ".-.";
}
else if(insert[i].equals("s"))
{
insert[i] = "...";
}
else if(insert[i].equals("t"))
{
insert[i] = "-";
}
else if(insert[i].equals("u"))
{
insert[i] = "..-";
}
else if(insert[i].equals("v"))
{
insert[i] = "...-";
}
else if(insert[i].equals("w"))
{
insert[i] = ".--";
}
else if(insert[i].equals("x"))
{
insert[i] = "-..-";
}
else if(insert[i].equals("y"))
{
insert[i] = "-.--";
}
else if(insert[i].equals("z"))
{
insert[i] = "--..";
}
}
for(int i=0;i<insert.length;i++)
{
System.out.print(insert[i]+ " ");
}
}
}
자바로 코딩
1
HashMap<String, String> mos = new HashMap<>();
mos.put("a" , ".-" );
mos.put("b" , "-..." );
mos.put("c" , "-.-." );
mos.put("d" , "-.." );
mos.put("e" , "." );
mos.put("f" , "..-." );
mos.put("g" , "--." );
mos.put("h" , "...." );
mos.put("i" , ".." );
mos.put("j" , ".---" );
mos.put("k" , "-.-" );
mos.put("l" , ".-.." );
mos.put("m" , "--" );
mos.put("n" , "-." );
mos.put("o" , "---" );
mos.put("p" , ".--." );
mos.put("q" , "--.-" );
mos.put("r" , ".-." );
mos.put("s" , "..." );
mos.put("t" , "-" );
mos.put("u" , "..-" );
mos.put("v" , "...-" );
mos.put("w" , ".--" );
mos.put("x" , "-..-" );
mos.put("y" , "-.--" );
mos.put("z" , "--.." );
mos.put("blank" , " " );
String text = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
StringBuffer sb = new StringBuffer();
String[] txt = text.split(" ");
String[] temp;
for(int i=0; i<txt.length; i++){
temp = txt[i].split(" ");
for(int j=0; j<temp.length; j++){
System.out.println(temp[j]);
for( String key : mos.keySet() ){
if( temp[j].equals(mos.get(key)) ){
sb.append(key);
}
}
}
sb.append(" ");
}
System.out.println( sb.toString());
2
// a - z
String[] dic = { ".-" , "-..." , "-.-." , "-..." ,
"." , "..-." , "--." , "...." ,
".." , ".---" , "-.-" , ".-.." ,
"--" , "-." , "---" , ".--." ,
"--.-" , ".-." , "..." , "-" ,
"..-" , "...-" , ".--" , "-..-" ,
"-.--" , "--.."
};
String original = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
String decode = "";
for( String text : original.split(" ")){
for( String txt : text.split(" " )){
for(int i=0; i<dic.length; i++){
if( dic[i].equals(txt)){
System.out.print( (char)(i + 'a') );
}
}
}
System.out.print(" ");
}
def alphaToMos(string):
newWord = ""
dic = {'a':'.-','b':'-...','c':'-.-.','d':'-..','e':'.','f':'..-.',
'g':'--.','h':'....','i':'..','j':'.---','k':'-.-','l':'.-..',
'm':'--','n':'-.','o':'---','p':'.--.','q':'--.-','r':'.-.',
's':'...','t':'-','u':'..-','v':'...-','w':'.--','x':'-..-',
'y':'-.--','z':'--..',' ':' '}
for i in string:
if i == ' ':
newWord += dic[i.lower()]
else:
newWord += dic[i.lower()] + ' '
return newWord
def mosToAlpha(string):
newWord = ""
dic = {
'.-':'a','-...':'b','-.-.':'c','-..':'d','.':'e','..-.':'f',
'--.':'g','....':'h','..':'I','.---':'h','-.-':'k','.-..':'l',
'--':'m','-.':'n','---':'o','.--.':'p','--.-':'q','.-.':'r',
'...':'s','-':'t','..-':'u','...-':'v','.--':'w','-..-':'x',
'-.--':'y','--..':'z',' ':' '}
for i in string.split(" "):
for j in i.split():
newWord += dic[j]
newWord+= " "
return newWord
print alphaToMos("he sleeps early")
print mosToAlpha(".... . ... .-.. . . .--. ... . .- .-. .-.. -.--")
morse_list=[('A','.-'),('B','-..'),('C','-.-.'),('D','-..'),('E','.'),('F','..-.'),
('G','--.'),('H','....'),('I','..'),('J','.---'),('K','-.-'),('L','.-..'),
('M','--'),('N','-.'),('O','---'),('P','.--.'),('Q','--.-'),('R','.-.'),
('S','...'),('T','-'),('U','..-'),('V','...-'),('W','.--'),('X','-..-'),
('Y','-.--'),('Z','--..')]
def Decode_morse(m_str):
Decode_str=""
for i in m_str.split(" "):
if i=="":
Decode_str+=" "
else:
for j in range(0,len(morse_list)):
if(i==morse_list[j][1]):
Decode_str+=morse_list[j][0].lower()
print Decode_str
Decode_morse(".... . ... .-.. . . .--. ... . .- .-. .-.. -.--")
code={'.-':'a', '-...':'b', '-.-.':'c','-..':'d', '.':'e', '..-.': 'f', '--.':'g', '....':'h', '..':'i', '.---' :'j', '-.-' : 'k', '.-..': 'l', '--' : 'm', '-.': 'n', '---': 'o', '.--.' : 'p', '--.-' : 'q', '.-.': 'r', '...' : 's', '-':'t', '..-' : 'u', '...-' : 'v', '.--' : 'w', '-..-': 'x', '-.--':'y','--..':'z'}
s=input().split(" ")
string=[]
for i in s:
for j in i.split():
string.append(code[j])
string.append(" ")
for i in range(len(string)):
print(string[i],end="")
def decodeMorse(input):
TAG_MORSE = 0
TAG_SPACE = 1
TAG_WORD = 2
morse = ""
letter = ""
input += '\n'
curState = TAG_MORSE
for i in str(input):
if i == ' ' and curState == TAG_SPACE: # TAG_WORD
curState = TAG_WORD
letter += ' '
morse = ""
elif i == ' ' or i == '\n': #TAG_SPACE
curState = TAG_SPACE
if morse != "":
letter += morseMap[morse]
morse = ""
else:
curState = TAG_MORSE
morse += i
return letter
print(decodeMorse('.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'))
다른 분들 풀이를 보면, 내장 함수를 정말 잘 사용하시는것 같네요. 전 아직까지는...연습중이라.. ㅋ
python3.5입니다~ dictionary에 공백 기호를 포함해서 split('') 한번으로 처리하게끔 했습니다~
dic = {
'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z','':' '
}
mos_ex = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"
print("".join(dic[x] for x in mos_ex.split(' ')))
파이썬 코드입니다. split을 이용하여 글자마다 나누고, 공백이 ''으로 들어와서 ' '로 바꿔준후 dictionary를 이용하여 해독하였습니다.
password = input()
pairs = {'.-':"a", '-...':"b", '-.-.':"c", '-..':"d", '.':"e",
'..-.':"f", '--.':"g", '....':"h", '..':"i", '.---':"j",
'-.-':"k", '.-..':"l", '--':"m", '-.':"n", '---':"o",
'.--.':"p", '--.-':"q", '.-.':"r", '...':"s",
'-':"t", '..-':"u", '...-':"v", '.--':"w",
'-..-':"x", '-.--':"y", '--..':"z", ' ':' '}
passlist = password.split(' ')
for i in range(len(passlist)):
if passlist[i] == '':
passlist[i] = ' '
decode = ""
for i in passlist:
decode += pairs[i]
print(decode)
파이썬 초보입니다. 많은 피드백 부탁드립니다!
안녕하세요. C++로풀어 봤습니다. 암호 끝부분에 공백문자 추가해서 풀었습니다.
#include<iostream>
#include<string>
using namespace std;
void main()
{
cout<<"Hello Stranger??"<<endl;
string dec[] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--"
,"-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
string enc = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
enc += " ";
string tmp = "";
int s = 0;
for(int i =0; i<enc.length(); i++)
{
if(enc[i] == ' ')
{
tmp = enc.substr(s,i-s);
for(int i=0; i<sizeof(dec)/sizeof(dec[0]); i++)
{
if(!dec[i].compare(tmp))
cout<<(char)(i+97);
}
s = i + 1;
if(enc[i+1] ==' ')
cout<<" ";
}
}
}
#include <iostream>
#include <string>
using namespace std;
//.... . ... .-.. . . .--. ... . .- .-. .-.. -.--
int main()
{
string sArr[] = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.",
"....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.",
"--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-",
"-.--", "--.." };
string input;
getline(cin, input);
string tempStr;
for (int i = 0; i < input.length(); i++)
{
if(input[i]!=' ')
tempStr.push_back(input[i]);
if (input[i] == ' ' || input[i+1] == '\0')
{
if (tempStr.size()==0)
{
cout << " ";
tempStr.clear();
continue;
}
for (int j = 0; j < _countof(sArr); j++)
{
if (!strcmp(tempStr.c_str(), sArr[j].c_str()))
{
cout << (char)('a' + j);
tempStr.clear();
break;
}
}
}
}
cout << endl;
return 0;
}
안녕하세요 C++로 풀었습니다.
#include<iostream>
#include<string>
using namespace std;
void main()
{
cout<<"Hello Stranger??"<<endl;
string dec[] = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--"
,"-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
string enc = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
enc += " ";
string tmp = "";
int s = 0;
for(int i =0; i<enc.length(); i++)
{
if(enc[i] == ' ')
{
tmp = enc.substr(s,i-s);
for(int i=0; i<sizeof(dec)/sizeof(dec[0]); i++)
{
if(!dec[i].compare(tmp))
cout<<(char)(i+97);
}
s = i + 1;
if(enc[i+1] ==' ')
cout<<" ";
}
}
}
public class Ex16 {
public String getCharacter(String character) {
String[] characterArray = character.split(" ");
String returnCharacter = "";
for(int i = 0; i < characterArray.length; i++) {
returnCharacter += this.decode(characterArray[i]);
}
return returnCharacter;
}
public String decode(String character) {
switch(character) {
case ".-" :
return "a";
case "-..." :
return "b";
case "-.-." :
return "c";
case "-.. " :
return "d";
case "." :
return "e";
case "..-." :
return "f";
case "--." :
return "g";
case "...." :
return "h";
case ".." :
return "i";
case ".---" :
return "j";
case "-.-" :
return "k";
case ".-.." :
return "l";
case "--" :
return "m";
case "-." :
return "n";
case "---" :
return "o";
case ".--." :
return "p";
case "--.-" :
return "q";
case ".-." :
return "r";
case "..." :
return "s";
case "-" :
return "t";
case "..-" :
return "u";
case "...-" :
return "v";
case ".--" :
return "w";
case "-..-" :
return "x";
case "-.--" :
return "y";
case "--.." :
return "z";
default :
return character;
}
}
public static void main(String[] args) {
String decodingChar = "";
String code = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
String[] codeArray = code.split(" ");
Ex16 decode = new Ex16();
for(int i = 0; i < codeArray.length; i++) {
String character = decode.getCharacter(codeArray[i]);
if(i == codeArray.length - 1) {
decodingChar += character;
}else {
decodingChar += character + " ";
}
}
System.out.println(decodingChar);
}
}
morse_list = {
'.-':'a','-...':'b','-.-.':'c','-..':'d',
'.':'e','..-.':'f','--.':'g','....':'h',
'..':'i','.---':'j','-.-':'k','.-..':'l',
'--':'m','-.':'n','---':'o','.--.':'p',
'--.-':'q','.-.':'r','...':'s','-':'t',
'..-':'u','...-':'v','.--':'w','-..-':'x',
'-.--':'y','--..':'z'}
code=input("code : ")
print(' '.join([''.join([(morse_list[w] or w) for w in p.split(' ')]) for p in code.split(' ')]))
Python 3.5.2에서 작성하였습니다.
Morse_Code = {'.-':'a','-...':'b','-.-.':'c','-..':'d','.':'e','..-':'f.','--.':'g',\
'....':'h','..':'i','.---':'j','-.-':'k','.-..':'l','--':'m','-.':'n',\
'---':'o','.--.':'p','--.-':'q','.-.':'r','...':'s','-':'t','..-':'u',\
'...-':'v','.--':'w','-..-':'x','-.--':'y','--..':'z'}
code = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
print(' '.join([''.join([Morse_Code[y] for y in x.split(' ')]) for x in code.split(' ')]))
#### 2016.12.11 D-438 ####
#include <stdio.h>
#include <string.h>
char matcher(char sen[]) {
if (strcmp(sen, ".-") == 0) return 'A';
if (strcmp(sen, "-...") == 0) return 'B';
if (strcmp(sen, "-.-.") == 0) return 'C';
if (strcmp(sen, "-..") == 0) return 'D';
if (strcmp(sen, ".") == 0) return 'E';
if (strcmp(sen, "..-.") == 0) return 'F';
if (strcmp(sen, "--.") == 0) return 'G';
if (strcmp(sen, "....") == 0) return 'H';
if (strcmp(sen, "..") == 0) return 'I';
if (strcmp(sen, ".---") == 0) return 'J';
if (strcmp(sen, "-.-") == 0) return 'K';
if (strcmp(sen, ".-..") == 0) return 'L';
if (strcmp(sen, "--") == 0) return 'M';
if (strcmp(sen, "-.") == 0) return 'N';
if (strcmp(sen, "---") == 0) return 'O';
if (strcmp(sen, ".--.") == 0) return 'P';
if (strcmp(sen, "--.-") == 0) return 'Q';
if (strcmp(sen, ".-.") == 0) return 'R';
if (strcmp(sen, "...") == 0) return 'S';
if (strcmp(sen, "-") == 0) return 'T';
if (strcmp(sen, "..-") == 0) return 'U';
if (strcmp(sen, "...-") == 0) return 'V';
if (strcmp(sen, ".--") == 0) return 'W';
if (strcmp(sen, "-..-") == 0) return 'X';
if (strcmp(sen, "-.--") == 0) return 'Y';
if (strcmp(sen, "--..") == 0) return 'Z';
return '?';
}
int main() {
char tmp_str[1024];
char sen[1024];
printf("Input : ");
fgets(tmp_str, sizeof(tmp_str), stdin);
tmp_str[strlen(tmp_str)-1] = '\0';
int start = 0, end, i, curr = 0;
for (i = 0; i < strlen(tmp_str); i++) {
if (i == (strlen(tmp_str)-1)) end = i;
else if (tmp_str[i] == ' ') end = i-1;
else continue;
if (end-start > 3) { printf("Invaild input\n"); return 0; }
char tmp[5];
strncpy(tmp, tmp_str+start, end-start+1);
tmp[end-start+1] = '\0';
sen[curr++] = matcher(tmp);
if (i == (strlen(tmp_str)-1)) break;
if (tmp_str[i+1] == ' ') { sen[curr++] = ' '; i += 1; }
start = i+1;
}
for (i = 0; i < curr; i++) { if (sen[i] == '?') { printf("Invaild input\n"); return 0; } }
sen[curr] = '\0';
printf("%s\n", sen);
return 0;
}
import java.util.HashMap;
import java.util.Scanner;
public class MorseCode {
public static void main(String[] args) {
HashMap<String, String> code = new HashMap<String, String>();
code.put(".-", "a"); code.put("-...", "b"); code.put("-.-.", "c");
code.put("-..", "d"); code.put(".", "e"); code.put("..-.", "f");
code.put("--.", "g"); code.put("....", "h"); code.put("..", "i");
code.put(".---", "j"); code.put("-.-", "k"); code.put(".-..", "l");
code.put("--", "m"); code.put("-.", "n"); code.put("---", "o");
code.put(".--.", "p"); code.put("--.-", "q"); code.put(".-.", "r");
code.put("...", "s"); code.put("-", "t"); code.put("..-", "u");
code.put("...-", "v"); code.put(".--", "w"); code.put("-..-", "x");
code.put("-.--", "y"); code.put("--..", "z"); code.put(" ", "");
Scanner sc = new Scanner(System.in);
System.out.print("모스부호를 입력하세요 : ");
String str = sc.nextLine();
//띄어쓰기 별로 나누어서 단어로 만들었습니다.
String[] word = str.split(" ");
// .... . ... .-.. . . .--. ... . .- .-. .-.. -.--
String[] letter = null;
for(int i = 0; i < word.length; i++){
//단어들은 한글자 한글자 장인의 손길을 위해 나누었습니다.
letter = word[i].split(" ");
for(int idx = 0; idx < letter.length; idx++){
System.out.print(code.get(letter[idx]));
}
System.out.print(" ");
}
}
}
$decode["A"] = ".-";
$decode["B"]="-...";
$decode["C"]="-.-.";
$decode["D"]="-..";
$decode["E"]=".";
$decode["F"]="..-.";
$decode["G"]="--.";
$decode["H"]="....";
$decode["I"]="..";
$decode["J"]=".---";
$decode["K"]="-.-";
$decode["L"]=".-..";
$decode["M"]="--";
$decode["N"]="-.";
$decode["O"]="---";
$decode["P"]=".--.";
$decode["Q"]="--.-";
$decode["R"]=".-.";
$decode["S"]="...";
$decode["T"]="-";
$decode["U"]="..-";
$decode["V"]="...-";
$decode["W"]=".--";
$decode["X"]="-..-";
$decode["Y"]="-.--";
$decode["Z"]="--..";
$input = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
$words = explode(" ",$input);
foreach($words as $word){
$letters = explode(" ",$word);
foreach($letters as $letter){
$output[] = strtolower(array_search($letter,$decode));
}
$output[] = " ";
}
echo join("",$output);
def trans(da):
result=""
for i in da:
if i==".":
result+="1"
else:
result+="2"
return int(result)
def mos(data):
mo=[12,2111,2121,211,1,1121,221,1111,11,1222,212,1211,22,21,222,1221,2212,121,111,2,112,1112,122,2112,2122,2211]
alp="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
data=data.split(" ")
result=""
for i in data:
i=i.split()
for j in i:
result+=alp[mo.index(trans(j))].lower()
result+=" "
return result[:-1]
HE SLEEPS EARLY
#include <stdio.h>
#include <string.h>
char mapping(char c[]);
void main() {
char str[] = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
char temp[5];
int j=0;
for(int i=0;i<=strlen(str);i++) {
if(str[i]==' ' || str[i] == '\0') {
temp[j] = '\0';
printf("%c", mapping(temp));
j=0;
continue;
}
temp[j] = str[i];
j++;
}
}
char mapping(char c[]) {
if(!strcmp(c, ".-")) {
return 'A';
}
else if(!strcmp(c, "-..")) {
return 'B';
}
else if(!strcmp(c, "-.-.")) {
return 'C';
}
else if(!strcmp(c, "-..")) {
return 'D';
}
else if(!strcmp(c, ".")) {
return 'E';
}
else if(!strcmp(c, "..-.")) {
return 'F';
}
else if(!strcmp(c, "--.")) {
return 'G';
}
else if(!strcmp(c, "....")) {
return 'H';
}
else if(!strcmp(c, "..")) {
return 'I';
}
else if(!strcmp(c, ".---")) {
return 'J';
}
else if(!strcmp(c, "-.-")) {
return 'K';
}
else if(!strcmp(c, ".-..")) {
return 'L';
}
else if(!strcmp(c, "--")) {
return 'M';
}
else if(!strcmp(c, "-.")) {
return 'N';
}
else if(!strcmp(c, "---")) {
return 'O';
}
else if(!strcmp(c, ".--.")) {
return 'P';
}
else if(!strcmp(c, "--.-")) {
return 'Q';
}
else if(!strcmp(c, ".-.")) {
return 'R';
}
else if(!strcmp(c, "...")) {
return 'S';
}
else if(!strcmp(c, "-")) {
return 'T';
}
else if(!strcmp(c, "..-")) {
return 'U';
}
else if(!strcmp(c, "...-")) {
return 'V';
}
else if(!strcmp(c, "..--")) {
return 'W';
}
else if(!strcmp(c, "-..-")) {
return 'X';
}
else if(!strcmp(c, "-.--")) {
return 'Y';
}
else if(!strcmp(c, "--..")) {
return 'Z';
}
}
s='.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
M={ '.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'}
def morse(src):
result = []
for word in s.split(" ") :
for char in word.split(" ") :
result.append(M[char])
result.append(" ")
return ''.join(result)
print(morse('.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'))
HashMap<String, String> moss = new HashMap<String, String>();
moss.put(".-", "a");
moss.put("-...", "b");
moss.put("-.-.", "c");
moss.put("-..", "d");
moss.put(".", "e");
moss.put("..-.", "f");
moss.put("--.", "g");
moss.put("....", "h");
moss.put("..", "i");
moss.put(".---", "j");
moss.put("-.-", "k");
moss.put(".-..", "l");
moss.put("--", "m");
moss.put("-.", "n");
moss.put("---", "o");
moss.put(".--.", "p");
moss.put("--.-", "q");
moss.put(".-.", "r");
moss.put("...", "s");
moss.put("-", "t");
moss.put("..-", "u");
moss.put("...-", "v");
moss.put(".--", "w");
moss.put("-..-", "x");
moss.put("-.--", "y");
moss.put("--..", "z");
String strRcvMossCode = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
StringBuilder sbResult = new StringBuilder();
String[] strRcvChunk = strRcvMossCode.split(" ");
String sep = "";
for(int i = 0 ; i < strRcvChunk.length; i++){
String[] strRcvWordArr = strRcvChunk[i].split(" ");
String strRcvWord = "";
for(int j = 0; j < strRcvWordArr.length; j++){
if(moss.containsKey(strRcvWordArr[j])){
strRcvWord += moss.get(strRcvWordArr[j]);
}
}
sbResult.append(sep);
sbResult.append(strRcvWord);
sep = " ";
}
String strResult = sbResult.toString();
import java.util.*;
import static java.lang.System.in;
public class MorseCodeDecipher {
static Map<String, String> code = new HashMap<>();
static {
code.put("", " ");
code.put(".-", "a");
code.put("-...", "b");
code.put("-.-.", "c");
code.put("-..", "d");
code.put(".", "e");
code.put("..-.", "f");
code.put("--.", "g");
code.put("....", "h");
code.put("..", "i");
code.put(".---", "j");
code.put("-.-", "k");
code.put(".-..", "l");
code.put("..-.", "m");
code.put("-.", "n");
code.put("---", "o");
code.put(".--.", "p");
code.put("--.-", "q");
code.put(".-.", "r");
code.put("...", "s");
code.put("..-.", "t");
code.put("..-", "u");
code.put("...-", "v");
code.put(".--", "w");
code.put("-..-", "x");
code.put("-.--", "y");
code.put("--..", "z");
}
public static void main(String[] args) {
Scanner sc = new Scanner(in);
List l = Arrays.asList(sc.nextLine().split(" "));
System.out.println(l);
l.stream().forEach(i -> System.out.print(code.get(i)));
}
}
public void go(String input) {
String [] alphabet = {"a","b","c","d","e","f","g","h","i","j",
"k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
String [] mos = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--",
"-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
HashMap<String,String> a = new HashMap<String,String>();
for(int i=0 ; i<mos.length ; i++) {
a.put(mos[i], alphabet[i]);
}
String [] result = input.split(" ");
String [] result2;
for(int i=0 ; i<result.length ; i++) {
result2 = result[i].split(" ");
for(int j=0 ; j<result2.length ; j++) {
System.out.print(a.get(result2[j]));
}
System.out.print(" ");
}
mos = {
'.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D', '.': 'E', '..-.': 'F',
'--.': 'G', '....': 'H', '..': 'I', '.---': 'J', '-.-': 'K', '.-..': 'L',
'--': 'M', '-.': 'N', '---': 'O', '.--.': 'P', '--.-': 'Q', '.-.': 'R',
'...': 'S', '-': 'T', '..-': 'U', '...-': 'V', '.--': 'W', '-..-': 'X',
'-.--': 'Y','--..': 'Z'
}
sig = [x.split() for x in input("모스부호를 입력하세요.").split(' ')]
for x in sig:
for y in x:
print(mos[y], end='')
print(end=" ")
print()
mos = {
'.-':'a','-...':'b','-.-.':'c','-..':'d','.':'e','..-.':'f',
'--.':'g','....':'h','..':'i','.---':'j','-.-':'k','.-..':'l',
'--':'m','-.':'n','---':'o','.--.':'p','--.-':'q','.-.':'r',
'...':'s','-':'t','..-':'u','...-':'v','.--':'w','-..-':'x',
'-.--':'y','--..':'z', '' : ' '
}
def interpret_mos(str):
return ''.join([mos[s] for s in str.split(' ')])
print(interpret_mos('.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'))
package training;
public class MossConverter {
public static void main(String[] args) {
String str = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
String[] strArr = str.split(" "); // 단어 분리
StringBuffer sf = new StringBuffer();
for(int i=0;i<strArr.length;i++){
String[] strArr2 = strArr[i].split(" "); // 글자 분리
for(int j=0;j<strArr2.length;j++){
sf.append(convertChar(strArr2[j]));
}
sf.append(' ');
}
System.out.println("Original Text : '" + str + "'");
System.out.println("Transfer Text : '" + sf + "'");
}
public static char convertChar(String word){
char ch = 0;
if(word.equals(".-")){
ch='A';
} else if(word.equals("-...")){
ch='B';
} else if(word.equals("-.-.")){
ch='C';
} else if(word.equals("-..")){
ch='D';
} else if(word.equals(".")){
ch='E';
} else if(word.equals("..-.")){
ch='F';
} else if(word.equals("--.")){
ch='G';
} else if(word.equals("....")){
ch='H';
} else if(word.equals("..")){
ch='I';
} else if(word.equals(".---")){
ch='J';
} else if(word.equals("-.-")){
ch='K';
} else if(word.equals(".-..")){
ch='L';
} else if(word.equals("--")){
ch='M';
} else if(word.equals("-.")){
ch='N';
} else if(word.equals("---")){
ch='O';
} else if(word.equals(".--.")){
ch='P';
} else if(word.equals("--.-")){
ch='Q';
} else if(word.equals(".-.")){
ch='R';
} else if(word.equals("...")){
ch='S';
} else if(word.equals("-")){
ch='T';
} else if(word.equals("..-")){
ch='U';
} else if(word.equals("...-")){
ch='V';
} else if(word.equals(".--")){
ch='W';
} else if(word.equals("-..-")){
ch='X';
} else if(word.equals("-.--")){
ch='Y';
} else if(word.equals("--..")){
ch='Z';
}
return ch;
}
}
Python 3.4.2, Dictionary 를 사용했습니다.
moss_dic = {'.-':'A',
'-...':'B',
'-.-.':'C',
'-..':'D',
'.':'E',
'..-.':'F',
'--.':'G',
'....':'H',
'..':'I',
'.---':'J',
'-.-':'K',
'.-..':'L',
'--':'M',
'-.':'N',
'---':'O',
'.--.':'P',
'--.-':'Q',
'.-.':'R',
'...':'S',
'-':'T',
'..-':'U',
'...-':'V',
'.--':'W',
'-..-':'X',
'-.--':'Y',
'--..':'Z'}
moss = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
mos_word = moss.split(" ")
mos_letter = list(map(lambda x: mos_word[x].split(), range(len(mos_word))))
meaning = ""
for i in range(len(mos_letter)):
for j in range(len(mos_letter[i])):
meaning += moss_dic.get(mos_letter[i][j])
meaning += " "
print(meaning)
c로 풀이. 조잡한 느낌
#include <stdio.h>
#include <string.h>
int compare_morse(int morse2[5]);
int main(void)
{
int i,j,k;
int morse[50][5]={0};
FILE*fp=fopen("morse.txt","r");
for(i=0;i<50;i++)
{
for(j=0;j<5;j++)
{
morse[i][j]=fgetc(fp);
if (morse[i][j]==32) break;
if (morse[i][j]==10) break;
}
if(morse[i][j]==10) break;
}
morse[i++][j]=32;
for(j=0;j<i;j++) printf("%c",'a'+compare_morse(morse[j]));
return 0;
}
int compare_morse(int morse2[5])
{
int i,j,same;
int code[27][5]={{46,45,32},{45,46,46,46,32},{45,46,45,46,32},{45,46,46,32},{46,32},{46,46,45,46,32},{45,45,46,32},{46,46,46,46,32},
{46,46,32},{46,45,45,45,32},{45,46,45,32},{46,45,46,46,32},{45,45,32},{45,46,32},{45,45,45,32},{46,45,45,46,32},{45,45,46,45,32},{46,45,46,32},
{46,46,46,32},{45,32},{46,46,45,32},{46,46,46,45,32},{46,45,45,32},{45,46,46,45,32},{45,46,45,45,32},{45,45,46,46,32},{32}};
for(i=0;i<27;i++)
{
same=0;
for(j=0;j<5;j++) if(morse2[j]==code[i][j]) same++;
if (same==5) break;
}
if(i==26) return -65;
return i;
}
// 모스 부호 - C#
using System;
using System.Collections.Generic;
namespace Morse
{
class Program
{
static string Morsechecker(string input)
{
string check = input;
check = check.Replace(".", "");
check = check.Replace("-", "");
check = check.Replace(" ", "");
if (check != "")
return "에러입니다.";
string result = input;
result = result.Replace("-.... ", "B");
result = result.Replace("-.-. ", "C");
result = result.Replace("..-. ", "F");
result = result.Replace(".... ", "H");
result = result.Replace(".--- ", "J");
result = result.Replace(".-.. ", "L");
result = result.Replace(".--. ", "P");
result = result.Replace("--.- ", "Q");
result = result.Replace("...- ", "V");
result = result.Replace("-..- ", "X");
result = result.Replace("-.-- ", "Y");
result = result.Replace("--.. ", "Z");
result = result.Replace("... ", "S");
result = result.Replace("--. ", "G");
result = result.Replace("-.. ", "D");
result = result.Replace("--- ", "O");
result = result.Replace("-.- ", "K");
result = result.Replace(".-- ", "W");
result = result.Replace(".-. ", "R");
result = result.Replace("..- ", "U");
result = result.Replace(".- ", "A");
result = result.Replace(".. ", "I");
result = result.Replace("-. ", "N");
result = result.Replace("-- ", "M");
result = result.Replace("- ", "T");
result = result.Replace(". ", "E");
return result;
}
static void Main(string[] args)
{
Console.WriteLine("{0}", Morsechecker(".... . ... .-.. . . .--. ... . .- .-. .-.. -.-- "));//HE SLEEPS EARLY
Console.WriteLine("{0}", Morsechecker("... --- -- . --. . -. . .-. .- - .. --- -. ... .- .-. . -- --- .-. . -.-. --- -- .--. .-.. .. -.-. .- - . -.. "));
//SOME GENERATIONS ARE MORE COMPLICATED
}
}
}
public static void main(String[] args) {
System.out.print("모스부호 입력! : ");
String[] input1 =new Scanner(System.in).nextLine().split(" ");
HashMap<String , Character> map = new HashMap<String , Character>();
String [] key = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--",
"-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", " "};
char [] val = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' '};
for(int i=0;i<key.length;i++)
map.put(key[i], val[i]);
for(int i=0;i<input1.length;i++){
if(map.get(input1[i])==null)
System.out.print(" ");
else
System.out.print(map.get(input1[i]));
}
}
Python 3으로 풀었습니다.
def decode_morse(s):
table = dict(zip(' .- -... -.-. -.. . ..-. --. .... .. .--- -.- .-..'
' -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..'.split(' '),
' abcdefghijklmnopqrstuvwxyz'))
return ''.join([table[sign] for sign in s.split(' ')])
def morse(a) : # type(a) == string
morse_dict = {
'.-' : 'a',
'-...' : 'b',
'-.-.' : 'c',
'-..' : 'd',
'.' : 'e',
'..-.' : 'f',
'--.' : 'g',
'....' : 'h',
'..' : 'i',
'.---' : 'j',
'-.-' : 'k',
'.-..' : 'l',
'--' : 'm',
'-.' : 'n',
'---' : 'o',
'.--.' : 'p',
'--.-' : 'q',
'.-.' : 'r',
'...' : 's',
'-' : 't',
'..-' : 'u',
'...-' : 'v',
'.--' : 'w',
'-..-' : 'x',
'-.--' : 'y',
'--..' : 'z',
}
list1 = a.split(' ')
for i in range(0, len(list1)) :
list1[i] = list1[i].split(' ')
for n in range(0, len(list1)) :
for s in range(0, len(list1[n])) :
print(morse_dict[list1[n][s]], end="")
print(' ', end="")
파이썬입니다. 우선 공백 두 개를 기준으로 문자열을 나눈 후 다시 공백 하나를 기준으로 나누어 출력합니다.
def getWord(str1):
a = {
'.-': 'a', '-...': 'b', '-.-.': 'c', '-..': 'd', '.': 'e', '..-.': 'f',
'--.': 'g', '....': 'h', '..': 'i', '.---': 'j', '-.-': 'k', '.-..': 'l',
'--': 'm', '-.': 'n', '---': 'o', '.--.': 'p', '--.-': 'q', '.-.': 'r',
'...': 's', '-': 't', '..-': 'u', '...-': 'v', '.--': 'w', '-..-': 'x',
'-.--': 'y', '--..': 'z'
}
result = ''
print(' '.join([(''.join([a[x1] for x1 in x])) for x in [x.split(' ') for x in str1.split(' ')]]))
getWord('.... . ... .-.. . . .--. ... . .- .-. .-.. -.--')
import java.util.HashMap;
public class Example76 {
private HashMap<String, Character> map = new HashMap<>();
{
map.put(".-", 'A');
map.put("-...", 'B');
map.put("-.-.", 'C');
map.put("-..", 'D');
map.put(".", 'E');
map.put("..-.", 'F');
map.put("--.", 'G');
map.put("....", 'H');
map.put("..", 'I');
map.put(".---", 'J');
map.put("-.-", 'K');
map.put(".-..", 'L');
map.put("--", 'M');
map.put("-.", 'N');
map.put("---", 'O');
map.put(".--.", 'P');
map.put("--.-", 'Q');
map.put(".-.", 'R');
map.put("...", 'S');
map.put("-", 'T');
map.put("..-", 'U');
map.put("...-", 'V');
map.put(".--", 'W');
map.put("-..-", 'X');
map.put("-.--", 'Y');
map.put("--..", 'Z');
}
public static void main(String[] args) {
Example76 ex = new Example76();
String s = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
System.out.println(ex.getMosSign(s));
}
private String getMosSign(String s) {
StringBuilder sb = new StringBuilder();
for (String str : s.split(" ")) {
if (map.containsKey(str)) {
sb.append(map.get(str));
} else {
sb.append(" ");
}
}
return sb.toString().toLowerCase();
}
}
Map 사용 했습니다.
# python 3.6
string = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"
mos = {'.-': 'a', '-...': 'b', '-.-.': 'c', '-..': 'd', '.': 'e', '..-.': 'f',
'--.': 'g', '....': 'h', '..': 'i', '.---': 'j', '-.-': 'k', '.-..': 'l',
'--': 'm', '-.': 'n', '---': 'o', '.--.': 'p', '--.-': 'q', '.-.': 'r',
'...': 's', '-': 't', '..-': 'u', '...-': 'v', '.--': 'w', '-..-': 'x',
'-.--': 'y', '--..': 'z'}
string = [s.split(" ") for s in string.split(" ")]
trans = " ".join(["".join([mos[sign] for sign in word]) for word in string])
print(trans)
package codingdojang;
import java.util.HashMap; import java.util.Map;
public class ex76 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String, Character> re = new HashMap<String, Character>();
String mos[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--",
"-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};
char a[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
for(int i=0; i<mos.length; i++) {
re.put(mos[i], a[i]);
}
String mo = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
String dan[] = mo.split(" ");
for(int i=0; i<dan.length; i++) {
System.out.print(dan[i]);
for(String g : dan[i].split(" ")) {
for(int j=0; j<mos.length; j++) {
if(g.equals(mos[j])) {
System.out.print(re.get(mos[j]));
}
}
}
System.out.println();
}
}
}
JavaScript 입니다.
const input = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.-- ';
const decript = (input) => {
const mappingTable = {
'.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D', '.': 'E', '..-.': 'F', '--.': 'G', '....': 'H',
'..': 'I', '.---': 'J', '-.-': 'K', '.-..': 'L', '--': 'M', '-.': 'N', '---': 'O', '.--.': 'P',
'--.-': 'Q', '.-.': 'R', '...': 'S', '-': 'T', '..-': 'U', '...-': 'V', '.--': 'W', '-..-': 'X',
'-.--': 'Y', '--..': 'Z'
}
return input.split(' ').reduce( (result, current) => result += mappingTable[current] ? mappingTable[current] : ' ', '');
};
console.log(decript(input));
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Mos {
public static void main(String[] argv) {
Scanner sc = new Scanner(System.in);
String mosString = sc.nextLine();
String[] mosList = mosString.split("\\s");
Map<String, String> mosMap = new HashMap<String, String>();
String[] moDotValue = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-",
".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", ".--", "-..-", "-.--", "--.."};
for(int i = 0; i < 25; i++){
mosMap.put(moDotValue[i], String.valueOf((char)(97 + i)));
}
for(int i = 0; i< mosList.length; i++){
if(mosList[i].equals("") ){
System.out.print(" ");
}else{
System.out.print(mosMap.get(mosList[i]));
}
}
}
}
def trans(s):
change={
'.-':'A','-...':'B','-.-.':'C','-..':'D',
'.':'E','..-.':'F','--.':'G','....':'H',
'..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P',
'--.-':'Q','.-.':'R','...':'S','-':'T',
'..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'}
tmp=[x.split() for x in s.split(' ')]
for i in range(len(tmp)):
for j in range(len(tmp[i])):
tmp[i][j]=change[tmp[i][j]]
tmp[i]=''.join(tmp[i])
tmp=' '.join(tmp)
return(tmp)
line=input()
print(trans(line))
dic = { '.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F', '--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L', '--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R', '...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X', '-.--':'Y','--..':'Z' }
s = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--' r = []
for word in s.split(' ') : for s in word.split(' ') : r.append(dic[s]) r.append(' ')
print(''.join(r))
dic = {'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z','':' '}
def sentence(sen,dic):
alph = list(dic[x] for x in sen)
print("".join(alph))
x_list = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--".split(" ")
sentence(x_list,dic)
파이썬 3.6
def translator(code):
alphabet = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
codepass = ['.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..']
return alphabet[codepass.index(code)].lower()
def morse(codeset):
code_char = []
code_word = []
sentence = []
code_word = codeset.split(' ')
for word in code_word:
code_char = word.split(' ')
for code in code_char:
sentence.append(translator(code))
sentence.append(' ')
print(''.join(sentence))
if __name__ == "__main__":
s = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
morse(s)
he sleeps early
파이썬으로 작성했습니다
mos = { '.-':'A', '-...' : 'B', '-.-.': 'C', '-..':'D', '.':'E',
'..-.':'F', '--.':'G', '....':'H', '..':'I', '.---':'J',
'-.-':'K', '.-..':'L', '--':'M', '-.':'N', '---':'O',
'.--.':'P', '--.-':'Q', '.-.':'R', '...':'S', '-':'T',
'..-':'U', '...-':'V', '.--':'W', '-..-':'X', '-.--':'Y',
'--..':'Z' }
a = input('모스부호 입력: ')
mylist = a.split(' ')
printstr = ''
for li in mylist:
if li=='':
printstr+=' '
else:
printstr+=mos[li]
print(printstr.lower())
# 파이썬
dic = {
'.-':'A', '-...':'B', '-.-.':'C', '-..':'D', '.':'E', '..-.':'F',
'--.':'G', '....':'H', '..':'I', '.---':'J', '-.-':'K', '.-..':'L',
'--':'M', '-.':'N', '---':'O', '.--.':'P', '--.-':'Q', '.-.':'R',
'...':'S', '-':'T', '..-':'U', '...-':'V', '.--':'W', '-..-':'X',
'-.--':'Y', '--..':'Z'
}
def morse(s1):
l1 = s1.split(" ")
r = ""
for m in l1:
l2 = m.split()
for n in l2:
r += dic[n]
r += " "
return r
print(morse(".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"))
morsecode = {'.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D', '.': 'E', '..-.': 'F', '--.': 'G', '....': 'H', '..': 'I',
'.---': 'J', '-.-': 'K', '.-..': 'L', '--': 'M', '-.': 'N', '---': 'O', '.--.': 'P', '--.-': 'Q', '.-.': 'R',
'...': 'S', '-': 'T', '..-': 'U', '...-': 'V', '.--': 'W', '-..-': 'X', '-.--': 'Y', '--..': 'Z'}
def morse(a):
b = ''
for i in a.split(' '):
b += morsecode.get(i, "No alphabet")
return b
b = input().split(' ')
for i in b:
print(morse(i))
morse_code_dict={'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E',
'..-.':'F','--.':'G','....':'H','..':'I','.---':'J',
'-.-':'K','.-..':'L','--':'M','-.':'N','---':'O',
'.--.':'P','--.-':'Q','.-.':'R','...':'S',
'-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'}
for_change=input("모스코드를 입력하세요:")
for_change_list=for_change.split(' ')
new_for_change_list=[]
for string in for_change_list:
if string== '':
new_for_change_list.append(' ')
continue
new_for_change_list.append(string)
ans=''
for string in new_for_change_list:
if string==' ':
ans+=' '
else:
ans+=morse_code_dict[string]
print(ans)
def morse(code):
table = {
'.-':'a','-...':'b','-.-.':'c','-..':'d','.':'e','..-.':'f','--.':'g','....':'h','..':'i','.---':'j','-.-':'k','.-..':'l','--':'m',
'-.':'n','---':'o','.--.':'p','--.-':'q','.-.':'r','...':'s','-':'t','..-':'u','...-':'v','.--':'w','-..-':'x','-.--':'y','--..':'z'}
decoding = ''
alpha = ''
for i, char in enumerate(code):
if char == ' ':
if code[i + 1] == ' ':
decoding = decoding + table[alpha]
decoding = decoding + ' '
elif code[i - 1] == ' ':
pass
else: decoding = decoding + table[alpha]
alpha = ''
else: alpha = alpha + char
decoding = decoding + table[alpha]
return decoding
import re
dict = {}
for i, name in enumerate(['.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---', '-.-', '.-..', '--'
,'-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..']):
dict[name] = chr(i+65)
dict['4'] = chr(32)
sentence = input()
sentence = re.sub(' ', ' 4 ', sentence)
sentence = sentence.split()
convert = []
for i in sentence:
convert.append(dict[i])
print("".join(convert))
Swift입니다.
import Foundation
let code = [".-":"A", "-...":"B", "-.-.":"C", "-..":"D", ".":"E", "..-.":"F",
"--.":"G","....":"H","..":"I",".---":"J", "-.-":"K", ".-..":"L", "--":"M",
"-.":"N","---":"O",".--.":"P","--.-":"Q",".-.":"R","...":"S","-":"T","..-":"U",
"...-":"V",".--":"W","-..-":"X","-.--":"Y","--..":"Z"]
func translate(_ input: String) {
let words = input.components(separatedBy: " ")
for word in words {
let chars = word.split(separator: " ")
for char in chars {
print(code[String(char)]!, terminator: "")
}
print(" ", terminator: "")
}
print("")
}
translate(".... . ... .-.. . . .--. ... . .- .-. .-.. -.--")
def mos():
cc = list(input('Input: ').split(' '))
print(cc)
key = []
for i in range(len(cc)):
en = cc[i].split(' ')
for x in range(len(en)):
key.append(MOS.get(en[x]))
key.append(" ")
key[len(key)-1] = ''
print(key)
print(''.join(key))
object Main extends App {
val mos = Map(
".-" -> 'A',"_..." -> 'B',"-.-." -> 'C',
"-.." -> 'D',"." -> 'E',"..-." -> 'F',
"--." -> 'G',"...." -> 'H',".." -> 'I',
".---" -> 'J',"-.-" -> 'K',".-.." -> 'L',
"--" -> 'M',"-." -> 'N',"---" -> 'O',
".--." -> 'P',"--.-" -> 'Q',".-." -> 'R',
"..." -> 'S',"-" -> 'T',"..-" -> 'U',
"...-" -> 'V',".--" -> 'W',"-..-" -> 'X',
"-.--" -> 'Y',"--.." -> 'Z'
)
val str = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"
println(str.split(" ").map(_.split(" ").map(x => mos(x)).mkString("")).mkString(" "))
}
C++도 아니고 C#도 아닌 C로 짜려니까 힘드네요.. 문자열 변수형의 소중함을 느낍니다.
#include <stdio.h>
char Trans_morse(char inp[]);
int main() {
char source[500] = {".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"};
char cut_per_letter[5] = {0};
int cut_index = 0;
char Endfor = 0;
//scanf("%s", source);
//scanf사용하니까 공백문자 만났을떄 입력을 종료해버리더군요..
//그냥 배열에 값 넣어버리고 끝냈습니다.ㅠㅠ
for(int i = 0; Endfor != 1; i++) { //모스부호의 끝에서 for문 종료
if(source[i] != ' ' && source[i] != '\0') {
cut_per_letter[cut_index] = source[i];
cut_index +=1;
}//모스문자 하나를 받는 배열cut_per_letter에 모스코드 하나씩 넣기
else if (source[i-1] == ' ' && source[i] == ' ') {
printf(" ");
} //공백 앞에 공백이 있으면, 공백 출력
else if(source[i] == '\0') {
printf("%c", Trans_morse(cut_per_letter));
Endfor = 1;
}
else { //source[i] == ' '
printf("%c", Trans_morse(cut_per_letter));
for(int j = 0; j <= 4; j++){
cut_per_letter[j] = 0; //cut_per_letter배열 초기화
}
cut_index = 0;
}
}
return 0;
}
char Trans_morse(char inp[]) { //문자배열 하나를 받아서 morse배열과 비교.
char alpha[27] = {'a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y',
'z', '\0' };
char morse[26][5] = { ".-\0\0", "-...", "-.-.", "-..\0", ".\0\0\0",
"..-.", "--.\0", "....", "..\0\0", ".---",
"-.-\0", ".-..", "--\0\0", "-.\0\0", "---\0",
".--.", "--.-", ".-.\0", "...\0", "-\0\0\0",
"..-\0", "...-", ".--\0", "-..-", "-.--",
"--.."};
char IsBool = 1;
for(int i = 0; i <= 25; i++) {
for(int j = 0; j <= 4; j++) {
if(inp[j] == morse[i][j])
IsBool = IsBool && 1;
else
IsBool = IsBool && 0;
} //받은 배열과 같은 문자 찾기
if(IsBool == 1)
return alpha[i];
else
IsBool = 1;
}
}
#include<iostream>
#include"stdafx.h"
char decode_mos(string str)
{
if (str == ".-")return 'A';
else if(str == "-...")return 'B';
else if (str == "-.-.")return 'C';
else if (str == "-..")return 'D';
else if (str == ".")return 'E';
else if (str == "..-.")return 'F';
else if (str == "--.")return 'G';
else if (str == "....")return 'H';
else if (str == ".---")return 'I';
else if (str == ".---")return 'J';
else if (str == "-.-")return 'K';
else if (str == ".-..")return 'L';
else if (str == "--")return 'M';
else if (str == "-.")return 'N';
else if (str == "---")return 'O';
else if (str == ".--.")return 'P';
else if (str == "--.-")return 'Q';
else if (str == ".-.")return 'R';
else if (str == "...")return 'S';
else if (str == "-")return 'T';
else if (str == "...-")return 'U';
else if (str == "...-")return 'V';
else if (str == ".--")return 'W';
else if (str == "-..-")return 'X';
else if (str == "-.--")return 'Y';
else if (str == "--..")return 'Z';
}
int main()
{
string Mos(".... . ... .-.. . . .--. ... . .- .-. .-.. -.--");
string decode;
string temp;
int branch = 0;
char alphabet;
cout << Mos << endl;
for (string::size_type i = 0; i <= Mos.size(); i++)
{
if (Mos[i] == ' '&&Mos[i + 1] == ' ')
{
alphabet = decode_mos(temp);
decode += alphabet;
temp.clear();
decode += " ";
i += 2;
}
if (Mos[i] == ' '||i==Mos.size())
{
alphabet = decode_mos(temp);
decode += alphabet;
temp.clear();
}
else
{
temp += Mos[i];
}
}
cout << decode << endl;
}
public class Morsecodedecode {
public static void main(String[] args) {
String mos[] = { ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." };
String input = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
String[] word = input.split(" ");
for (int i = 0; i < word.length; i++) {
String[] alpha = word[i].split(" ");
for (int j = 0; j < alpha.length; j++)
for (int k = 0; k < mos.length; k++)
System.out.print(mos[k].equals(alpha[j]) ? (char) (k + 97) : "");
System.out.print(" ");
}
}
}
#include <stdio.h>
int main() {
char st[26][5] = {{".-"},{"-..."},{"-.-."},{"-.."},{"."},{"..-."},{"--."},{"...."},{".."},{".---"},
{"-.-"},{".-.."},{"--"},{"-."},{"---"},{".--."},{"--.-"},{".-."},{"..."},{"-"},
{"..-"},{"...-"},{".--"},{"-..-"},{"-.--"},{"--.."}};
char temp[] = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
int index = -1, length = sizeof(temp) * sizeof(char), index2 = 0, a, j = -1;
for(int i=0;i<length; i = index + 1){
while (temp[++index] != ' ' && temp[index] != '\0') {}
for(index2 = -1; ++index2 < 25; j = i - 1){
a = -1;
while (st[index2][++a] == temp[++j]) {}
if (temp[j-1] == '\0' || (a == (index-i) && st[index2][a] == '\0'))
break;
}
printf("%c", index2+'a');
if (temp[index + 1] == ' ') {
printf(" ");
i = ++index;
}
}
}
Python
mos = {
'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'
}
test = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"
ans = ""
for words in test.split(' '):
tmp_ans = ""
for chars in words.split(' '):
tmp_ans += mos[chars]
ans += tmp_ans + " "
print(ans[:-1])
import java.util.HashMap;
public class MosSignal {
HashMap<String, String> MosTable = new HashMap<String, String>();
String[] mosList = {".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."};
String[] alphaList = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
public MosSignal() { // constructor
for (int i=0 ; i < this.mosList.length ; i++) {
this.MosTable.put(this.mosList[i], this.alphaList[i]);
}
}
public String interprete(String mosSignal) {
String[] mosWordSplit = mosSignal.split(" ");
String sentence= "";
for (String eachMosWord : mosWordSplit) {
String[] mosAlphaSplit = eachMosWord.split(" ");
for (String eachMos : mosAlphaSplit) {
sentence += this.MosTable.get(eachMos);
}
sentence += " ";
}
return sentence.substring(0, sentence.length()-1).toLowerCase();
}
public static void main(String[] args) {
MosSignal ms = new MosSignal();
String mos = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
String result = ms.interprete(mos);
System.out.println("'" + result + "'");
}
}
스페이스와 스페이스 두개로 구분하는게 좀 어렵네요 딕셔너리를 이용해서 모스 부호로 알파벳을 찾도록 하고 스트링의 split을 이용해서 문장을 단어로 단어를 스펠링으로 쪼개서 매핑하는 방식입니다.
morse={
'.-':'A',
'-...':'B',
'-.-.':'C',
'-..':'D',
'.':'E',
'..-.':'F',
'--.':'G',
'....':'H',
'..':'I',
'.---':'J',
'-.-':'K',
'.-..':'L',
'--':'M',
'-.':'N',
'---':'O',
'.--.':'P',
'--.-':'Q',
'.-.':'R',
'...':'S',
'-':'T',
'..-':'U',
'...-':'V',
'.--':'W',
'-..-':'X',
'-.--':'Y',
'--..':'Z'
}
#message = input("input message please : ")
message = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"
result = ""
for word in message.split(" "):
for char in word.split(" "):
result += morse[char]
result += " "
print(result)
파이썬 한줄에 끝내기~
data = '''.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'''
mos = {
'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'
}
print(''.join([''.join([mos[char] for char in word.split()] + [' ']) for word in data.split(' '* 2)]).strip())
파이썬
data = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"
dic = {
'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'
}
data1 = data.replace(" ", " ^ ")
data1_list = data1.split(" ")
result = ""
for m in data1_list:
if(m == '^'):
result += " "
else:
result += dic[m]
print(result)
def morse_conv(s):
s = s.split(' ')
moscode = {'.-': 'A','-.': 'N','-...': 'B','---': 'O','-.-.': 'C','.--.': 'P','-..': 'D','--.-': 'Q','.' : 'E','.-.': 'R','..-.': 'F','...': 'S','--.': 'G','-': 'T','....': 'H','..-': 'U','..': 'I','...-': 'V','.---': 'J','.--': 'W','-.-': 'K','-..-': 'X','.-..': 'L','-.--': 'Y','--': 'M','--..': 'Z','':' '}
print(''.join(moscode[i] for i in s))
morse_conv('.... . ... .-.. . . .--. ... . .- .-. .-.. -.--')
def mtoa(morse_code):
dic = {
'.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D', '.': 'E', '..-.': 'F',
'--.': 'G', '....': 'H', '..': 'I', '.---': 'J', '-.-': 'K', '.-..': 'L',
'--': 'M', '-.': 'N', '---': 'O', '.--.': 'P', '--.-': 'Q', '.-.': 'R',
'...': 'S', '-': 'T', '..-': 'U', '...-': 'V', '.--': 'W', '-..-': 'X',
'-.--': 'Y', '--..': 'Z',
'/':' '
}
return ''.join([dic[morse_char] for morse_char in morse_code.replace(' ', ' / ').split()])
print(mtoa('.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'))
lists = {
'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'
}
def func(src):
result = []
for i in src.split(" "):
for j in i.split(" "):
result.append(lists[j])
result.append(" ")
return "".join(result)
print(func('.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'))
morse_dic = {}
morse_file = open("morse_code.txt", 'r')
for i in morse_file.readlines():
morse_dic[i.split()[0]] = i.split()[1]
enter = input("모스 부호를 입력하시오 ")
enter_word = enter.split(" ")
translation_word = ''
for word in enter_word:
for morse in word.split():
translation_word += morse_dic[morse]
translation_word += ' '
print(translation_word)
namespace codingdojang__
{
class Program
{
static void Main(string[] args)
{
Hashtable morse = new Hashtable();
morse.Add(".-", "a");
morse.Add("-...", "b");
morse.Add("-.-.", "c");
morse.Add("-..", "d");
morse.Add(".", "e");
morse.Add("..-.", "f");
morse.Add("--.", "g");
morse.Add("....", "h");
morse.Add("..", "i");
morse.Add(".---", "j");
morse.Add("-.-", "k");
morse.Add(".-..", "l");
morse.Add("--", "m");
morse.Add("-.", "n");
morse.Add("---", "o");
morse.Add(".--.", "p");
morse.Add("--.-", "q");
morse.Add(".-.", "r");
morse.Add("...", "s");
morse.Add("-", "t");
morse.Add("..-", "u");
morse.Add("...-", "v");
morse.Add(".--", "w");
morse.Add("-..-", "x");
morse.Add("-.--", "y");
morse.Add("--..", "z");
morse.Add("|", " ");
string morse_ex = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
morse_ex = morse_ex.Replace(" "," | ");
string[] morse_ex_split = morse_ex.Split(' ');
foreach (var i in morse_ex_split)
{
Console.Write(morse[i]);
}
}
}
}
morses = ['.-','-...','-.-.','-..','.','..-.','--.','....','..','.---','-.-','.-..','--','-.',
'---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..']
def morse(code):
for x in code.split(' '):
for x in ''.join(x).split():
print(chr(morses.index(x)+65),end = '')
print(' ',end = '')
def mos(string):
tr={'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F','--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L','--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R','...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X','-.--':'Y','--..':'Z'}
for i in string.split(" "):
if i == '':
print(' ',end='')
else:
print(tr[i],end='')
mos(".... . ... .-.. . . .--. ... . .- .-. .-.. -.--")
python
mos = {'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F','--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L','--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R','...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X','-.--':'Y','--..':'Z'}
src = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
sentence = ""
for w in src.split(' '):
for w2 in w.split(' '):
sentence += mos[w2]
sentence += " "
print(sentence)
mos = {
'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'
}
s = input()
result = []
for word in s.split(" "):
for char in word.split(" "):
result.append(mos[char])
result.append(" ")
print("".join(result))
dic_mos = {'.-':'A', '-...':'B', '-.-.':'C', '-..':'D', '.':'E', '..-.':'F', '--.':'G', '....':'H',
'..':'I', '.---':'J', '-.-':'K', '.-..':'L', '--':'M', '-.':'N', '---':'O', '.--.':'P',
'--.-':'Q', '.-.':'R', '...':'S', '-':'T', '..-':'U', '...-':'V', '.--':'W', '-..-':'X',
'-.--':'Y', '--..':'Z'}
str_input = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
# str_input = '-- .. -. ... ..- -. .--. .-. --- --. .-. .- --'
str_result=''
str_current=''
for i in range(len(str_input)):
if str_input[i]==' ' and str_input[i+1]!=' ' and str_input[i-1]!=' ':
str_result = str_result+ dic_mos[str_current]
str_current = ''
elif str_input[i]==' 'and str_input[i+1]==' ':
str_result = str_result+ dic_mos[str_current] + ' '
str_current=''
elif str_input[i]==' 'and str_input[i-1]==' ':
continue
else:
str_current += str_input[i]
str_result += dic_mos[str_current]
print(str_result)
while True:
morse=input("input morse code: ")
morsecode=['.-','-...','-.-.','-..','.',
'..-.','--.','....','..','.---',
'-.-','.-..','--',
'-.','---','.--.','--.-','.-.',
'...','-','..-','...-','.--',
'-..-','-.--','--..']
alphabet=list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
morsesplit=morse.split(" ")
for i in morsesplit:
if i in morsecode:
morsesplit[morsesplit.index(i)]=alphabet[morsecode.index(i)]
else:
morsesplit[morsesplit.index(i)]=" "
result=""
for i in morsesplit:
result+=i
print(result)
dic = dic={'':' ','.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F','--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L','--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R','...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X','-.--':'Y','--..':'Z'}
morse = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"
sentence = ''
i = 0
for words in morse.split(" "):
word = words.split()
for sub_word in word:
sentence += dic[sub_word]
if i < len(morse.split(" ")) - 1:
sentence += ' '
i += 1
sentence
map함수와 lambda를 이용하면 한줄로 표현가능합니다.
dic = {
'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z', '':' '
}
def Morse(s):
return "".join(list(map(lambda a : dic[a], s.split(" "))))
s = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
print(Morse(s))
def mos(S,ANS):
if S[0]==' ':
ANS+=S[0]
return mos(S[1:],ANS)
elif ' ' not in S:
ANS+=dic[S]+'.';ANS=ANS.lower()
return ANS[0].upper()+ANS[1:]
for i in range(len(S)):
if S[i]==' ':
ANS+=dic[S[:i]]
return mos(S[i+1:],ANS)
dic = {
'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'
}
print(mos(input(),''))
딕쇼나리의 키와 값들은 박응용 운영자님의 코드에서 참조를 하였읍니다. 나머지는 평범하였고, 다만 결과가 모두 대문자로 나와서 처음 문자만 대문자로하고 나머지는 모조리 소문자로 하여 출력하여보았읍니다.^^
파이썬3.7 사용. 덕분에 딕셔너리 문법 복습했네요. 감사합니다.
#'부호' : '문자' 형식. 스페이스를 처리하기 위해 마지막에 '':' ' 추가
Rules={'.-': 'A', '-...':'B', '-.-.':'C', '-..':'D', '.':'E', '..-.':'F', '--.':'G', '....':'H', '..':'I', '.---':'J', '-.-':'K', '.-..':'L', '--':'M', '-.':'N', '---':'O', '.--.':'P', '--.-':'Q', '.-.':'R', '...':'S', '-':'T','..-':'U','...-':'V','.--':'W', '-..-':'X', '-.--':'Y', '--..':'Z','':' '}
inputstr='.... . ... .-.. . . .--. ... . .- .-. .-.. -.--' #입력문자열
Mos_list=inputstr.split(' ')
Msg=''
for code in Mos_list:
Msg+=Rules[code]
print(Msg)
연습삼아서 모스부호에서 문자열, 문자열에서 모스부호로 변환하는 함수를 각각 만들어봤습니다.
#'부호' : '문자'형식. 스페이스를 처리하기 위해 마지막에 '':' ' 추가
Rules={'.-': 'A', '-...':'B', '-.-.':'C', '-..':'D', '.':'E', '..-.':'F', '--.':'G', '....':'H', '..':'I', '.---':'J', '-.-':'K', '.-..':'L', '--':'M', '-.':'N', '---':'O', '.--.':'P', '--.-':'Q', '.-.':'R', '...':'S', '-':'T','..-':'U','...-':'V','.--':'W', '-..-':'X', '-.--':'Y', '--..':'Z','':' '}
def MosToMsg(Code): #모스코드를 문자로
Mos_list=Code.split(' ')
Msg=''
for i in Mos_list:
try:
Msg+=Rules[i]
except: #정의되지 않은 코드는 오류처리
Msg='오류발생. 잘못된 코드가 있습니다.'
return Msg
def MsgToMos(Msg): #문자를 모스코드로
Msg=Msg.upper() #모두 대문자로 전환
Code=''
for char1 in Msg:
if char1==' ': #Rules에 있는 스페이스에 대응하는 값은 잘못되었으므로 수정. 다른 문자 뒤에는 공백이 한칸씩 있으므로 하나만 더 추가시키면 공백 2개가 된다
Code+=' '
else:
tmp=0
for c, letter in Rules.items(): #Rules에서 key값으로 일치하는 코드 찾기
if letter==char1:
Code+=c
Code+=' '
tmp=1
break #찾으면 루프종료
if tmp==0: #루프를 다 돌고 Rules를 전부 보았지만 대응되는 코드를 못찾으면 에러처리
Code='오류발생. 문자와 일치하는 코드가 없습니다.'
break
return Code
if __name__=='__main__':
Msg='he sleeps early' #메세지 입력
Code=MsgToMos(Msg) #모스부호로 변환
print(Code) #보스부호 출력
print(MosToMsg(Code)) #메시지로 재변환후 출력. 모두 대문자로 출력된다.
data = {
'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'
}
def morse(n):
result = []
for i in n.split(' '):
for j in i.split(' '):
result.append(data[j])
result.append(' ')
return ''.join(result)
print(morse('.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'))
#include <stdio.h>
int main(void)
{
char quest[50] = {".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"};
char nowc;
int blank = 0;
int foc = 0;
while(blank != 3)
{
if(blank == 2)
{
printf(" ");
}
//printf("\n%d",foc);
nowc = quest[foc];
if(nowc == '.')
{
foc++;
nowc = quest[foc];
if(nowc == '.')
{
foc++;
nowc = quest[foc];
if(nowc == '.')
{
foc++;
nowc = quest[foc];
if(nowc == '.')
{
printf("h");
blank = 0;
}
else if(nowc == '-')
{
printf("v");
blank = 0;
}
else
{
printf("s");
blank = 1;
}
}
else if(nowc == '-')
{
foc++;
nowc = quest[foc];
if(nowc == '.')
{
printf("f");
blank = 0;
}
else
{
printf("u");
blank = 1;
}
}
else
{
printf("i");
blank = 1;
}
}
else if(nowc == '-')
{
foc++;
nowc = quest[foc];
if(nowc == '.')
{
foc++;
nowc = quest[foc];
if(nowc == '.')
{
printf("l");
blank = 0;
}
else
{
printf("r");
blank = 1;
}
}
else if(nowc == '-')
{
foc++;
nowc = quest[foc];
if(nowc == '.')
{
printf("p");
blank = 0;
}
else if(nowc == '-')
{
printf("j");
blank = 0;
}
else
{
printf("w");
blank = 1;
}
}
else
{
printf("a");
blank = 1;
}
}
else
{
printf("e");
blank = 1;
}
}
else if(nowc == '-')
{
foc++;
nowc = quest[foc];
if(nowc == '.')
{
foc++;
nowc = quest[foc];
if(nowc == '.')
{
foc++;
nowc = quest[foc];
if(nowc == '.')
{
printf("b");
blank = 0;
}
else if(nowc == '-')
{
printf("x");
blank = 0;
}
else
{
printf("d");
blank = 1;
}
}
else if(nowc == '-')
{
foc++;
nowc = quest[foc];
if(nowc == '.')
{
printf("c");
blank = 0;
}
else if(nowc == '-')
{
printf("y");
blank = 0;
}
else
{
printf("k");
blank = 1;
}
}
else
{
printf("n");
blank = 1;
}
}
else if(nowc == '-')
{
foc++;
nowc = quest[foc];
if(nowc == '.')
{
foc++;
nowc = quest[foc];
if(nowc == '.')
{
printf("z");
blank = 0;
}
else if(nowc == '-')
{
printf("q");
blank = 0;
}
else
{
printf("g");
blank = 1;
}
}
else if(nowc == '-')
{
printf("g");
blank = 0;
}
else
{
printf("m");
blank = 1;
}
}
else
{
printf("t");
blank = 1;
}
}
else
{
blank++;
}
foc++;
nowc = quest[foc];
}
}
java
import java.util.*;
public class q6 {
public static void main(String [] args){
HashMap<String, String> map = new HashMap<>();
String[] mos = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--",
"-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", " "};
String[] Alpabat = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", " "};
for(int i =0; i < mos.length; i ++){
map.put(mos[i], Alpabat[i]);
}
Scanner sc = new Scanner(System.in);
String[] str = sc.nextLine().split(" ");
for (String s : str) {
if(map.get(s)==null){
System.out.print(" ");
}else{
System.out.print(map.get(s));
}
}
}
}
Python 3.7
a = input().split(' ')
dic = {'.-':'A', '-...':'B', '-.-.':'C', '-..':'D', '.':'E', '..-.':'F', '--.':'G', '....':'H', '..':'I', '.---':'J', '-.-':'K', '.-..':'L', '--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R', '...':'S', '-':'T', '..-':'U', '...-':'V', '.--':'W', '-..-':'X', '-.--':'Y', '--..':'Z', '':' '}
b = [dic[i] for i in a]
print(''.join(b))
n=input("모스부호: ").split(' ')
a=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
b=[".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."]
result=""
for i in n:
if i in b:
result=result+a[b.index(i)]
elif i=='':
result=result+' '
print(result)
data = input("문자를 입력하세요 : ")
char = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'," "]
moss = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."," "]
output = ""
for i in range(0,len(data)):
for j in range(0,len(char)):
if data[i] == char[j]:
output += moss[j]
output += " "
print(output)
mos = {'.-': 'a', '-...':'b', '-.-.':'c', '-..':'d', '.':'e', '..-.':'f', '--.':'g',
'....':'h', '..':'i', '.---':'j', '-.-':'k', '.-..':'l', '--':'m', '-.':'n', '---':'o',
'.--.':'p', '--.-':'q', '.-.':'r', '...':'s', '-':'t', '..-':'u', '...-':'v', '.--':'w',
'-..-':'x', '-.--':'y', '--..':'z', '':' '}
def mosTrans(str):
lstStr = str.split(' ')
for i in range(len(lstStr)):
lstStr[i] = mos.get(lstStr[i])
return ''.join(lstStr)
print(mosTrans('.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'))
dic = {'A':'.-', 'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.', 'F':'..-.',
'G':'--.', 'H':'....', 'I':'..', 'J':'.---', 'K':'-.-', 'L':'.-..',
'M':'--', 'N':'-.', 'O':'---', 'P':".--.",'R':'.-.', 'S':'...', 'T':'-', 'U':'..-',
'V':'...-', 'W':'.--', 'X':'-..-', 'Y':'-.--', 'Y':'-.--', 'Z':'--..',
" ": " "}
string = "HE SLEEPS EARLY"
result = ""
for i in range(len(string)):
result += str(dic.get(string[i])) + " "
print(result)
public class 모스부호해독 {
public static void main(String[] args) {
MossCode(".... . ... .-.. . . .--. ... . .- .-. .-.. -.--");
}
public static void MossCode(String moss) {
String[] Moss = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....",
"..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.",
"...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.."};
String[] MossSpell = {"A", "B", "C", "D", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "v",
"W", "X", "Y", "Z"};
StringBuffer line = new StringBuffer();
String[] word = moss.split(" ");
for(int i=0; i<word.length; i++) {
String[] spell = word[i].split(" ");
for(int k =0; k<spell.length; k++) {
for(int l=0; l<Moss.length; l++) {
if(spell[k].equals(Moss[l])) {
line.append(MossSpell[l]);
}
}
}
line.append(" ");
}
System.out.println(line);
}
}
파이썬3입니다.
dic_morse = {
'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z', '':' '
}
def morse(a):
x = a.split(' ')
for i in x: print(dic_morse[i], end='')
morse( '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--') # HE SLEEPS EARLY
dic={'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'}
m=input("모스부호를 입력하십시오: ").split(" ") #.- .-. . ..- -- .- -.. ?
elst=[]
for s in m:
if s in dic:
s=dic.get(s)
elif s=='':
s=" "
else:
s=str(s)
elst.append(s)
print("".join(elst)) #ARE U MAD?
Nlist,N = input().split(' '), ''
Ndic = {'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F','--.':'G',
'....':'H','..':'I','.---':'J','-.-':'K','.-..':'L','--':'M','-.':'N',
'---':'O','.--.':'P','--.-':'Q','.-.':'R','...':'S','-':'T','..-':'U',
'...-':'V','.--':'W','-..-':'X','-.--':'Y','--..':'Z','':' '}
for i in range(len(Nlist)):
N += Ndic[Nlist[i]]
print(N)
def morse():
code = { '.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z' }
word = input('')
wordlist = word.split(" ")
decoded = []
decoded_final = 0
for i in range(len(wordlist)):
aa = wordlist[i]
if aa == '':
decoded.append(' ')
else:
decoded.append(code.get(aa))
while None in decoded:
decoded.remove(None)
decoded_word = ''.join(decoded)
return decoded_word
morse()
.... . .-.. .-.. --- .-- --- .-. .-.. -..
'HELLO WORLD'
Python
sign = {'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F','--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L','--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R','...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X','-.--':'Y','--..':'Z'}
text = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"
char = text.split(' ')
for i in char:
if i == '':
print(' ', end="")
else :
print(sign[i], end="")
python 3.8
a=['.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---', '-.-', '.-..', '--' ,'-.','---','.--.','--.-','.-.','...','-','..-','...-','.--','-..-','-.--','--..']
b='.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'.split(' ')
print(('').join(list(chr(97+a.index(i)) for i in b)))
영화 기생충 보고 흥미가 생겨서 급 만들어 봤습니다. 재밌네요 ㅎㅎ 좋은 과제 감사합니다.
morse={".-":"A","-.":"N","-...":"B","---":"O","-.-.":"C",".--.":"P",
"-..":"D","--.-":"Q",".":"E",".-.":"R","..-.":"F","...":"S",
"--.":"G","-":"T","....":"H","..-":"U","..":"I","...-":"V",
".---":"J",".--":"W","-.-":"K","-..-":"X",".-..":"L","-.--":"Y",
"--":"M","--..":"Z"}
morse['']=' '
output=''
message=input('모스 부호를 입력하시오')
message_trans=message.split(' ')
for i in message_trans:
output+=morse[i]
print(output)
dic = {
'.-':'a','-...':'b','-.-.':'c','-..':'d','.':'e','..-.':'f',
'--.':'g','....':'h','..':'i','.---':'j','-.-':'k','.-..':'l',
'--':'m','-.':'n','---':'o','.--.':'p','--.-':'q','.-.':'r',
'...':'s','-':'t','..-':'u','...-':'v','.--':'w','-..-':'x',
'-.--':'y','--..':'z','':' '
}
m = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
morse = m.split(' ')
s = ''
for m in morse:
s += dic[m]
print(s)
#파이썬
mos='.- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..'.split(' ')
mos_in='.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'.split(' ')
result=[]
for i in range (len(mos_in)):
j=0
while (j<26):
if mos_in[i]==mos[j]:
result.append(chr(j+65))
break
elif mos_in[i]=='':
result.append(' ')
break
j+=1
print (''.join(result))
dic = {'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'}
inputt = list(str(input()).split(' '))
print(inputt)
hack = []
for i in inputt:
if i == '':
hack.append(' ')
else:
hack.append(dic[i])
hack
alphabet={'':' ','.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F','--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L','--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R','...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X','-.--':'Y','--..':'Z'}
line=input("type morse: ").split(' ')
for i in line:
print(alphabet[i], end='')
프린트함수에 end를 이용하면 가로 줄로도 나올 수 있는 걸 이제야 알았네요..
import java.util.*;
public class Test {
public static void main(String args[]) {
StringBuffer b = new StringBuffer();
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String a = input.toUpperCase();
for(int i = 0; i < a.length(); i++) {
switch(a.charAt(i)) {
case 'A':
b.append(".- ");
break;
case 'B':
b.append("-... ");
break;
case 'C':
b.append("-.-. ");
break;
case 'D':
b.append("-.. ");
break;
case 'E':
b.append(". ");
break;
case 'F':
b.append("..-. ");
break;
case 'G':
b.append("--. ");
break;
case 'H':
b.append(".... ");
break;
case 'I':
b.append(".. ");
break;
case 'J':
b.append(".--- ");
break;
case 'K':
b.append("-.- ");
break;
case 'L':
b.append(".-.. ");
break;
case 'M':
b.append("-- ");
break;
case 'N':
b.append("-. ");
break;
case 'O':
b.append("--- ");
break;
case 'P':
b.append(".--. ");
break;
case 'Q':
b.append("--.- ");
break;
case 'R':
b.append(".-. ");
break;
case 'S':
b.append("... ");
break;
case 'T':
b.append("- ");
break;
case 'U':
b.append("..- ");
break;
case 'V':
b.append("...- ");
break;
case 'W':
b.append(".-- ");
break;
case 'X':
b.append("-..- ");
break;
case 'Y':
b.append("-.-- ");
break;
case 'Z':
b.append("--.. ");
break;
case ' ':
b.append(" ");
break;
}
}
System.out.println(b);
}
}
public class test12 {
public static void main(String[] args) {
String input = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
input = input.replace(" ", " x ");
StringBuilder result = new StringBuilder();
for(String x : input.split(" ")) {
if(x.equals("x")){
result.append(" ");
}else {
result.append(moss_kaisyaku(x));
}
}
System.out.println(result);
}
public static String moss_kaisyaku(String input) {
switch(input) {
case ".-" : {
return "A";
}
case "-..." : {
return "B";
}
case "-.-." : {
return "C";
}
case "-.." : {
return "D";
}
case "." : {
return "E";
}
case "..-." : {
return "F";
}
case "--." : {
return "G";
}
case "...." : {
return "H";
}
case ".." : {
return "I";
}
case ".---" : {
return "J";
}
case "-.-" : {
return "K";
}
case ".-.." : {
return "L";
}
case "--" : {
return "M";
}
case "-." : {
return "N";
}
case "---" : {
return "O";
}
case ".--." : {
return "P";
}
case "--.-" : {
return "Q";
}
case ".-." : {
return "R";
}
case "..." : {
return "S";
}
case "-" : {
return "T";
}
case "..-" : {
return "U";
}
case "...-" : {
return "V";
}
case ".--" : {
return "W";
}
case "-..-" : {
return "X";
}
case "-.--" : {
return "Y";
}
case "--.." : {
return "Z";
}
default: {
return "이게 머꼬";
}
}
}
}
code=input().split(' ')
chart= {'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'}
decoded=''
for x in code:
decodedletter=' '
for y in chart:
if x==y:
decodedletter=chart[y]
break
decoded+=decodedletter
print(decoded)
#소문자로 쓰려면 print(decoded.lower()) 하시면 됩니다
def decoding(strings):
dictionary={'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F','--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L','--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R','...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X','-.--':'Y','--..':'Z'}
no_1=strings.split(' ')
for_answer=[]
for i in no_1:
answers=i.split(' ')
for_answer.append(answers)
real_answer=[]
for i in for_answer:
for j in i:
real_answer.append(dictionary[j])
real_answer.append(' ')
print("".join(real_answer))
decoding('.... . ... .-.. . . .--. ... . .- .-. .-.. -.--')
mos = {
'A': '.-', 'N': '-.',
'B': '-...', 'O': '---',
'C': '-.-.', 'P': '.--.',
'D': '-..', 'Q': '--.-',
'E': '.', 'R': '.-.',
'F': '..-.', 'S': '...',
'G': '--.', 'T': '-',
'H': '....', 'U': '..-',
'I': '..', 'V': '...-',
'J': '.---', 'W': '.--',
'K': '-.-', 'X': '-..-',
'L': '.-..', 'Y': '-.--',
'M': '--', 'Z': '--..',
' ': ''
}
line = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
# dict의 key, value 바꾸기
new_mos = {v:k for k,v in mos.items()}
result = ''
for i in line.split(' '):
if i in new_mos.keys():
result += new_mos.get(i)
print(result)
a = "he sleeps early"
q = ' '.join(a)
w = q.replace(" "," ")
# 딕셔너리
mos = {'a':".-",'b':"-...",'c':"-.-.",'d':"-..",'e':'.','f':"..-.",'g':'--.','h':'....','i':'..','j':'.---',
'k':'-.-','l':'.-..','m':'--','n':'-.','o':'---','p':'.--.','q':'--.-','r':'.-.','s':'...','t':'-','u':'..-',
'v':'...-','w':'.--','x':'-..-','y':'-.--','z':'--..',' ':' '}
i=0
r=[]
while i < len(w):
r.append(mos[w[i]])
i+=1
print(r)
def morse(text):
table = {}
table['A'] = '.-'
table['B'] = '-...'
table['C'] = '-.-.'
table['D'] = '-..'
table['E'] = '.'
table['F'] = '..-.'
table['G'] = '--.'
table['H'] = '....'
table['I'] = '..'
table['J'] = '.---'
table['K'] = '-.-'
table['L'] = '.-..'
table['M'] = '--'
table['N'] = '-.'
table['O'] = '---'
table['P'] = '.--.'
table['Q'] = '--.-'
table['R'] = '.-.'
table['S'] = '...'
table['T'] = '-'
table['U'] = '..-'
table['V'] = '...-'
table['W'] = '.--'
table['X'] = '-..-'
table['Y'] = '-.--'
table['Z'] = '--..'
table[' '] = ' '
result = []
for aa in text.upper():
result.append(table[aa]+' ')
return print(''.join(result))
morse('he sleeps early')
const mosSecret=['.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---', '-.-', '.-..', '--','-.', '---', '.--.', '--.-', '.-.', '...', '-', '..-', '...-', '.--', '-..-', '-.--', '--..',''];
const alphabet=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm','n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',' '];
const ary=prompt('모스부호 띄어쓰기로 구분하여 입력','').split(' ');
const result = ary.map((el)=>alphabet[mosSecret.indexOf(el)]).join('');
console.log(result);
mos = {'.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D', '.': 'E', '..-.': 'F',
'--.': 'G', '....': 'H', '..': 'I', '.---': 'J', '-.-': 'K', '.-..': 'L',
'--': 'M', '-.': 'N', '---': 'O', '.--.': 'P', '--.-': 'Q', '.-.': 'R',
'...': 'S', '-': 'T', '..-': 'U', '...-': 'V', '.--': 'W', '-..-': 'X',
'-.--': 'Y', '--..': 'Z'
}
sample = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"
result1 = sample.split(" ")
result2 = []
for i in range(len(result1)):
result2.append(result1[i].split(" "))
for j in range(len(result2)):
if j != 0:
print(" ", end="")
for k in range(len(result2[j])):
print(mos.get("{}".format(result2[j][k])), end="")
매번 느끼는거지만 정말 짧으면 한없이 짧아지는게 코딩인거같슴다.
def convert(word):
word_l = word.split(' ')
alph = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
code = '.- -... -.-. -.. . ..-. --. .... .. .--- -.- .-.. -- -. --- .--. --.- .-. ... - ..- ...- .-- -..- -.-- --..'.split('\t')
output = ''
for w in word_l:
try:
i = code.index(w)
output += alph[i]
except:
output += ' '
return output
print(convert('.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'))
import java.util.Arrays;
import java.util.Scanner;
//단어자르기
public class Morse {
public static void main(String[] args) {
System.out.println("모스 부호를 입력해 주세요.");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String[] mosArr = input.split(" ");
//{he, sleeps, early}
for (int i = 0; i < mosArr.length; i++) {
String[] mosArr2 = mosArr[i].split(" ");
//{h, e}
for (int j = 0; j < mosArr2.length; j++) {
switch (mosArr2[j]) {
case ".-" :
System.out.print('A'); break;
case "-...":
System.out.print('B'); break;
case "-.-.":
System.out.print('C'); break;
case "-..":
System.out.print('D'); break;
case ".":
System.out.print('E'); break;
case "..-.":
System.out.print('F'); break;
case "--.":
System.out.print('G'); break;
case "....":
System.out.print('H'); break;
case "..":
System.out.print('I'); break;
case ".---":
System.out.print('J'); break;
case "-.-":
System.out.print('K'); break;
case ".-..":
System.out.print('L'); break;
case "--":
System.out.print('M'); break;
case "-.":
System.out.print('N'); break;
case "---":
System.out.print('O'); break;
case ".--.":
System.out.print('P'); break;
case "--.-":
System.out.print('Q'); break;
case ".-.":
System.out.print('R'); break;
case "...":
System.out.print('S'); break;
case "-":
System.out.print('T'); break;
case "..-":
System.out.print('U'); break;
case "...-":
System.out.print('V'); break;
case ".--":
System.out.print('W'); break;
case "-..-":
System.out.print('X'); break;
case "-.--":
System.out.print('Y'); break;
case "--..":
System.out.print('Z'); break;
default:
System.out.print("오류"); break;
}
}
System.out.print(" ");
}
}
}
String[][] alpha = {
{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","z"},
{".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.",
"...","-","..-","...-",".--","-..-","-.--","--.."}
};
Scanner sc = new Scanner(System.in);
System.out.println("모스부호를 입력해주세요.: ");
String str = sc.nextLine();
System.out.println(str);
//String str = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
String[] strArr= str.split(" ");
//System.out.println(Arrays.toString(strArr));
for(int i = 0; i < strArr.length; i++) {
String[] strArr2 = strArr[i].split(" ");
//System.out.println(Arrays.toString(strArr2)); // 단어별 분리
for(int k =0; k < strArr2.length; k++) {
for(int j =0; j<alpha[1].length; j++) {
if(strArr2[k].equals(alpha[1][j])) {
System.out.print(alpha[0][j]);
}
}
}
System.out.print(" ");
}
Mos = {'.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D', '.': 'E',
'..-.': 'F', '--.': 'G', '....': 'H', '..': 'I', '.---': 'J',
'-.-': 'K', '.-..': 'L', '--': 'M', '-.': 'N', '---': 'O', '.--.': 'P',
'--.-': 'Q','.-.':'R','...':'S','-':'T','..-':'U','...-':'V','.--':'W',
'-..-':'X','-.--':'Y','--..':'Z'}
mos = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
word = mos.split(' ')
decode = ''
for text in word :
t = text.split()
for i in t:
decode += Mos[i]
decode += ' '
print(decode)
python 3.9.5입니다. 소스 코드의 길이를 줄이기 위해 dict 대신 list를 사용하고, 모스 부호를 글자로 바꾸는 것은 먼저 index로 접근한 뒤 chr 함수를 이용했습니다. 소스 코드입니다.
morse_list = ['.-','-...','-.-.','-..','.','..-.',
'--.','....','..','.---','-.-','.-..',
'--','-.','---','.--.','--.-','.-.',
'...','-','..-','...-','.--','-..-',
'-.--','--..']
morse = input('모스 부호를 입력하세요: ')
morse_words = morse.split(' ')
morse_letters = [word.split(' ') for word in morse_words]
result = ''
for words in morse_letters:
for letters in words:
try:
convert = chr(morse_list.index(letters) + 97)
except ValueError:
print('올바르지 않은 값입니다.')
convert = '?'
result += convert
result += ' '
print(f'해독 결과는 <{result[:-1]}>입니다.')
실행 결과입니다.
모스 부호를 입력하세요: .... . ... .-.. . . .--. ... . .- .-. .-.. -.--
해독 결과는 <he sleeps early>입니다.
#codingdojing_morse
m_dic = {
'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'
}
code = input('morse: ')
decode = ''
for word in code.split(' '):
for c in word.split():
decode += m_dic[c]
decode += ' '
print(decode)
package justStudying;
public class test1_20210822 {
public static String sol(String input) {
String ans = "";
String words[] = input.split(" ");
String mos[];
for(int i=0; i<words.length; i++) {
mos = words[i].split(" ");
for(int j=0; j<mos.length; j++) {
switch(mos[j]) {
case ".-":
ans += "A";
break;
case "-...":
ans += "B";
break;
case "-.-.":
ans += "C";
break;
case "-..":
ans += "D";
break;
case ".":
ans += "E";
break;
case "..-.":
ans += "F";
break;
case "--.":
ans += "G";
break;
case "....":
ans += "H";
break;
case "..":
ans += "I";
break;
case ".---":
ans += "J";
break;
case "-.-":
ans += "K";
break;
case ".-..":
ans += "L";
break;
case "--":
ans += "M";
break;
case "-.":
ans += "N";
break;
case "---":
ans += "O";
break;
case ".--.":
ans += "P";
break;
case "--.-":
ans += "Q";
break;
case ".-.":
ans += "R";
break;
case "...":
ans += "S";
break;
case "-":
ans += "T";
break;
case "..-":
ans += "U";
break;
case "...-":
ans += "V";
break;
case ".--":
ans += "W";
break;
case "-..-":
ans += "X";
break;
case "-.--":
ans += "Y";
break;
case "--..":
ans += "Z";
break;
default:
break;
}
}
ans += " ";
}
return ans;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String input = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--";
System.out.println(sol(input));
}
}
dic = {
'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z',"": " "}
#mos = input("")
mos = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"
di = mos.split(" ")
for j in di :
print(dic[j], end="")
a = 'he sleeps early'
b = ''
def morse_inverter(self):
global b
if self == 'a':
b = b + '.- '
elif self == 'b':
b = b + '-... '
elif self == 'c':
b = b + '-.-. '
elif self == 'd':
b = b + '-.. '
elif self == 'e':
b = b + '. '
elif self == 'f':
b = b + '..-. '
elif self == 'g':
b = b + '-... '
elif self == 'h':
b = b + '.... '
elif self == 'i':
b = b + '.. '
elif self == 'j':
b = b + '.--- '
elif self == 'k':
b = b + '-.- '
elif self == 'l':
b = b + '.-.. '
elif self == 'm':
b = b + '-- '
elif self == 'n':
b = b + '-. '
elif self == 'o':
b = b + '--- '
elif self == 'p':
b = b + '.--. '
elif self == 'q':
b = b + '--.- '
elif self == 'r':
b = b + '.-. '
elif self == 's':
b = b + '... '
elif self == 't':
b = b + '- '
elif self == 'u':
b = b + '..- '
elif self == 'v':
b = b + '...- '
elif self == 'w':
b = b + '.-- '
elif self == 'x':
b = b + '-..- '
elif self == 'y':
b = b + '-.-- '
elif self == 'z':
b = b + '--.. '
for row in a:
morse_inverter(row)
print(b)
a = {'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z','':' '}
def morse_code(morse):
for i in morse.split(' '):
print(a[i],end='')
if __name__ == '__main__':
morse = ".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"
morse_code(morse)
a = str(input("해독할 모스코드를 입력 하시오")).split(" ")
def Convert (a) :
for i in range(len(a)):
if a[i]==".-":
a[i]='A'
elif a[i]=="-...":
a[i]='B'
elif a[i]=="-.-.":
a[i]='C'
elif a[i]=="-..":
a[i]='D'
elif a[i]==".":
a[i]='E'
elif a[i]=="..-.":
a[i]='F'
elif a[i]=="--.":
a[i]='G'
elif a[i]=="....":
a[i]='H'
elif a[i]=="..":
a[i]='I'
elif a[i]==".---":
a[i]='J'
elif a[i]=="-.-":
a[i]='K'
elif a[i]==".-..":
a[i]='L'
elif a[i]=="--":
a[i]='M'
elif a[i]=="-.":
a[i]='N'
elif a[i]=="---":
a[i]='O'
elif a[i]==".--.":
a[i]='P'
elif a[i]=="--.-":
a[i]='Q'
elif a[i]==".-.":
a[i]='R'
elif a[i]=="...":
a[i]='S'
elif a[i]=="-":
a[i]='T'
elif a[i]=="..-":
a[i]='U'
elif a[i]=="...-":
a[i]='V'
elif a[i]==".--":
a[i]='W'
elif a[i]=="-..-":
a[i]='X'
elif a[i]=="-.--":
a[i]='Y'
elif a[i]=="--..":
a[i]='Z'
elif a[i]=="":
a[i]=" "
return print("".join(a))
Convert(a)
그냥 조건절로 노가다 해봤습니다
dic = {
'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'
}
sen = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
sen_mor=[]
for i in sen.split(' '):
for j in i.split(' '):
sen_mor.append(dic[j])
sen_mor.append(' ')
''.join(sen_mor).lower().strip()
code='.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
table={ '.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z','':' '}
code_list=code.split(" ") #띄어쓰기는 리스트에서 ''로 표현됨. 위에 표에 '':' '를 넣어 띄어쓰기 표현.
decod=[table[i] for i in code_list]
print(''.join(decod))
안녕하세요 코린이에요 ㅎㅎ... 제 코드 다른 분들에 비하면 진짜 애기수준이긴 한데 지적이나 개선점 말씀해주시면 감사하겠습니당!
dic = { '.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F', '--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L', '--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R', '...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X', '-.--':'Y','--..':'Z' }
def morseToAlpha(morse): a = dic[morse] return(a.lower())
sentenceMorse = input()
sentence = sentenceMorse.split(" ")
for i in range(len(sentence)): sentence[i] = sentence[i].split(' ')
for i in range(len(sentence)): for j in range(len(sentence[i])): if sentence[i][j] in list(dic.keys()): print(morseToAlpha(sentence[i][j]),end='') print(" ", end = '')
험난한 뉴비의 코딩........
dic = {
'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z'
}
pwd='.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
word= pwd.split((" "))
reword = [str(x).split() for x in word]
result=[]
for j in reword:
i=0
while i in range(len(j)):
result.append(dic.get(j[i]))
i+=1
result.append(" ")
result = "".join(str(s) for s in result)
print(result)
자바로 풀었습니다.
import java.util.Scanner;
import java.util.HashMap;
public class calculator {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// 모스부호 맵 생성
HashMap<String, String> mos = new HashMap<>();
mos.put(".-", "a");
mos.put("-...", "b");
mos.put("-.-.", "c");
mos.put("-..", "d");
mos.put(".", "e");
mos.put("..-.", "f");
mos.put("--.", "g");
mos.put("....", "h");
mos.put("..", "i");
mos.put(".---", "j");
mos.put("-.-", "k");
mos.put(".-..", "l");
mos.put("--", "m");
mos.put("-.", "n");
mos.put("---", "o");
mos.put(".--.", "p");
mos.put("--.-", "q");
mos.put(".-.", "r");
mos.put("...", "s");
mos.put("-", "t");
mos.put("..-", "u");
mos.put("...-", "v");
mos.put(".--", "w");
mos.put("-..-", "x");
mos.put("-.--", "y");
mos.put("--..", "z");
// 입력
System.out.print("모스코드를 입력:");
String mosCode = scan.nextLine();
// 공백*2 기준 split
String[] splitedCode = mosCode.split(" ");
// 단어별로 해석
String interpretedCode = "";
for(int i=0; i<splitedCode.length; i++) {
String[] splitedWord = splitedCode[i].split(" ");
for(int j=0; j<splitedWord.length; j++) {
String interpreted = mos.get(splitedWord[j]);
// 첫 글자이면 대문자로 전환
if(i==0&j==0) {
interpreted = interpreted.toUpperCase();
}
interpretedCode += interpreted;
}
interpretedCode += " ";
}
// 결과 출력
System.out.printf("Interpreted Code: %s\n", interpretedCode);
}
}
dic = {
'.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E','..-.':'F',
'--.':'G','....':'H','..':'I','.---':'J','-.-':'K','.-..':'L',
'--':'M','-.':'N','---':'O','.--.':'P','--.-':'Q','.-.':'R',
'...':'S','-':'T','..-':'U','...-':'V','.--':'W','-..-':'X',
'-.--':'Y','--..':'Z','':' '
}
mos= '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
for i in mos.split(' '):
print(dic[i], end = '')
def Morse_Code(codes, rules):
recode = [[rules[j] for j in i.split(' ')] for i in codes.split(" ")]
for i in recode:
print("".join(i), end = ' ')
rules = {'.-' : 'A', '-...' : 'B', '-.-.' : 'C', '-..' : 'D', '.' : 'E', '..-.' : 'F', '--.' : 'G', '....' : 'H', '..' : 'I' , '.---' : 'J', '-.-' : 'K', '.-..' : 'L', '--' : 'M', '-.' : 'N', '---' : 'O', '.--.' : 'P', '--.-' : 'Q', '.-.' : 'R', '...' : 'S', '-' : 'T', '..-' : 'U', '...-' : 'V', '.--' : 'W', '-..-' : 'X', '-.--' : 'Y', '--..' : 'Z'}
codes = input('모스코드를 입력해주세요 : ')
Morse_Code(codes, rules)
Python. 모스부호표를 딕셔너리로 만드는 더 좋은 방법이 있지 않을까..생각이 듭니다.
morse = {'.-':'a', '-...':'b', '-.-.':'c', '-..':'d', '.':'e', '..-.':'f','--.':'g','....':'h', '..':'i', '.---':'j', '-.-':'k', '.-..':'l', '--':'m', '-.':'n', '---':'o', '.--.':'p', '--.-':'q', '.-.':'r', '...':'s', '-':'t', '..-':'u', '...-':'v', '.--':'w', '-..-':'x', '-.--':'y', '--..':'z', 'space':' '} #모스부호 표를 딕셔너리로 저장(단, 공백은 임의의 문자를 지정하여 설정)
def morse_decode(code):
result='' #변환된 결과를 나타낼 변수를 생성
decoding_1 = code.replace(' ', ' space ') #입력된 모스부호에서 공백 2칸을 공백 1칸으로 해석하기 위한 키값으로 교체
decoding_2 = decoding_1.split(' ') #입력된 모스부호를 공백 1칸을 기준으로 나누어 리스트화
for word in decoding_2:
result += morse[word] #딕셔너리 morse에서 각 모스부호에 해당하는 밸류를 결과에 순서대로 추가
return result
test = '.... . ... .-.. . . .--. ... . .- .-. .-.. -.--'
print(morse_decode(test))
결과 : he sleeps early
dic={'':' ','.-':'A','-...':'B','-.-.':'C','-..':'D','.':'E',
'..-.':'F','--.':'G','....':'H','..':'I','.---':'J',
'-.-':'K','.-..':'L','--':'M','-.':'N','---':'O',
'.--.':'P','--.-':'Q','.-.':'R','...':'S','-':'T',
'..-':'U','...-':'V','.--':'W','-..-':'X','-.--':'Y','--..':'Z'}
morse=".... . ... .-.. . . .--. ... . .- .-. .-.. -.--"
word = ''
w = ''
for char in morse:
if char==' ':
if len(w)>0:
word += dic[w]
w=''
else:
word += ' '
else:
w +=char
word += dic[w]
print(word)