Predefined text replacements in C ++ and Python

As a hobby project, I wanted to implement a Morse code encoder and decoder in C ++ and Python (both). I was wondering what data structure should I use for this. This question is related not only to this particular project, but in general, when you need to make predefined text replacements, what is the best and fastest way to do this?

I would avoid re-inventing any data structure if possible (and I think it is). Please note that this is a purely educational exercise, and I always wondered what would be the best way to do this. I can save the code and the corresponding character in the dictionary, maybe then iterate over the text and make replacements. Is this the best way to do this, or can I do better?

+3
source share
7 answers

There is no simple optimal structure - for any given fixed mapping there can be diabolical bit-torsion optimizers for this exact mapping, which are better or worse on different architectures and different inputs. The map / dictionary should be pretty good all the time, and the code is pretty simple.

My official advice is to stick with this. Search efficiency is very unlikely for such code, since most likely you can easily encode / decode faster than you can input / output.

, : → , /. , , ++ . , char , A, :

std::string encode['Z'-'A'];
encode['A' - 'A'] = ".-";
encode['B' - 'A'] = "-...";
// etc.
encode['Z' - 'A'] = "--..";

, , (true ASCII, EBCDIC), :

std::string encode[26] = {".-", "-...", /* etc */ "--.."};

, c:

morse = encode[c - 'A'];

Python ASCII ( ), ord.

-, , ( char), , ..

+1
from collections import defaultdict

morsecode = [('a','._'), ('b','_...'), ('c','_._.')]
codedict = defaultdict(lambda:' ')
for k,v in morsecode:
    codedict[k] = v

tomorse = lambda x: ' '.join([codedict[chr] for chr in x])

print tomorse('bab cab')

:

_... ._ _...   _._. ._ _...
+3

Python , , ( , ), . - :

MORSE = {'A': '.-', ...}

def morsify(data):
    return [MORSE[c] for c in data if c in MORSE]

, ..

(, , , -, .)

+2

str.translate:

m = {ord('S'): '---', ord('O'): '...'}
print( O S'.translate(m))

:

--- ... ---
+2

Python - . ++ std:: map, . , , std:: for_each .

+2

first click on google .

Depending on the amount of text, 'foo'.replace (' f ',' ..-. '). replace ('o', '---') will work.

If you don't translate thousands of lines of text, you probably won't notice much of a difference in any method you use, although you can easily use the timeit module to test each other method.

+1
source

Python (expects a string):

def m(t):
 m=0xBFAFA7AEA1A0B0B8BCBE121A021D11120C41888A642082668040876584434267868D626021618163898B8C
 r=[]
 for c in t.upper():
  val=int((m/(256**(90-ord(c))))%256)
  r.append("".join([str((val>>y)&1) for y in range(val/32-1,-1,-1)]))
 return " ".join(r)
0
source

Source: https://habr.com/ru/post/1764893/


All Articles