Breaking Bad - ize cualquier cadena (compresión) [duplicar]

Aug 17 2020

La serie de televisión "Breaking Bad" reemplazó las letras Br y Ba con una representación de tabla periódica, impresión [Br35]eaking [Ba56]d.

Cree un programa que tome una entrada de cadena, haga un reemplazo e imprima una salida. El reemplazo subsidiará cualquier subcadena que coincida con un símbolo de elemento con la notación demostrada en [Br35]eaking [Ba56]d. Es decir, agregue el número atómico al símbolo del elemento y encierre entre corchetes.

Todos los elementos comienzan con una letra mayúscula y constan de una o dos letras. El elemento más alto a considerar es Og118. De wikipedia:

1 H, 2 He, 3 Li, 4 Be, 5 B, 6 C, 7 N, 8 O, 9 F, 10 Ne, 11 Na, 12 Mg, 13 Al, 14 Si, 15 P, 16 S, 17 Cl , 18 Ar, 19 K, 20 Ca, 21 Sc, 22 Ti, 23 V, 24 Cr, 25 Mn, 26 Fe, 27 Co, 28 Ni, 29 Cu, 30 Zn, 31 Ga, 32 Ge, 33 As, 34 Se, 35 Br, 36 Kr, 37 Rb, 38 Sr, 39 Y, 40 Zr, 41 Nb, 42 Mo, 43 Tc, 44 Ru, 45 Rh, 46 Pd, 47 Ag, 48 Cd, 49 In, 50 Sn, 51 Sb, 52 Te, 53 I, 54 Xe, 55 Cs, 56 Ba, 57 La, 58 Ce, 59 Pr, 60 Nd, 61 Pm, 62 Sm, 63 Eu, 64 Gd, 65 Tb, 66 Dy, 67 Ho , 68 Er, 69 Tm, 70 Yb, 71 Lu, 72 Hf, 73 Ta, 74 W, 75 Re, 76 Os, 77 Ir, 78 Pt, 79 Au, 80 Hg, 81 Tl, 82 Pb, 83 Bi, 84 Po, 85 At, 86 Rn, 87 Fr, 88 Ra, 89 Ac, 90 Th, 91 Pa, 92 U, 93 Np, 94 Pu, 95 Am, 96 Cm, 97 Bk, 98 Cf, 99 Es, 100 Fm, 101 Md, 102 No, 103 Lr, 104 Rf, 105 Db, 106 Sg, 107 Bh, 108 Hs, 109 Mt, 110 Ds, 111 Rg, 112 Cn, 113 Nh, 114 Fl, 115 Mc, 116 Lv, 117 Ts , 118 Og

Reglas adicionales:

  • Como este desafío se trata tanto de la compresión como del código de golf, debe proporcionar usted mismo la lista de elementos. No debe utilizar ninguna compilación en tablas periódicas proporcionadas por nuestro idioma.
  • Trabajo sensible a mayúsculas y minúsculas. Eso significa que "Breaking Bad" tiene 2 reemplazos, "Breaking Bad" tiene uno. La entrada puede ser arbitraria y no siempre seguirá la gramática inglesa. fOoBar se convertirá en f [O8] o [Ba56] r.
  • Busca codiciosos, [Él] tiene prioridad sobre [H].

El código más corto en bytes gana.

Respuestas

6 Arnauld Aug 17 2020 at 22:57

JavaScript (ES6), 327 bytes

s=>s.replace(RegExp([...a="HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg".match(/.[a-z]?/g)].sort(s=>-!!s[1]).join`|`,'g'),s=>`[${s+-~a.indexOf(s)}]`)

¡Pruébelo en línea!

¿Cómo?

La cadena de datos consta de todos los símbolos de elementos concatenados, de menor a mayor número atómico.

"HHeLiBeBCNOFNeNaMg...LvTsOg"

Lo dividimos en una lista a[]de 118 entradas con la siguiente expresión regular:

 +------> any character (always a capital letter)
 |   +--> optionally followed by a letter in lower case
 | __|_
 |/    \
/.[a-z]?/g

Creamos una copia de a[], colocamos todos los elementos de un solo carácter al final de la lista y los unimos con tuberías:

[...a].sort(s => -!!s[1]).join('|')

Lo que da:

"Og|Ts|Lv|Mc|Fl|Nh|...|He|H|B|C|N|O|F|P|S|K|V|Y|I|W|U"

Convertimos esta cadena en una expresión regular y la aplicamos a la cadena de entrada. Cada subcadena coincidente sse reemplaza con el patrón:

`[${s + -~a.indexOf(s)}]`
4 Noodle9 Aug 17 2020 at 23:20

Python 3.8 , 454 \$\cdots\$409385 octetos

Se salvó la friolera de 38 40 45 69 bytes (y se solucionó un error) gracias a ovs !!!

eval("lambda s:_]and_<b][-1]".replace('_',"[(s:=re.sub(f'(?<!\[){b}',f'[{b}{e}]',s))for e,b in p if b[1:]"))
import re
p=[*enumerate(re.split("(?=[A-Z])","HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg"))][1:]

¡Pruébelo en línea!

Primero pasa por los químicos de dos letras y luego los de una sola letra.

4 Neil Aug 18 2020 at 03:17

Carbón , 217 bytes

F⪪”}∨"²Q/QH▷⊕Ff←SγG¤º&ρωVφ∨]›¶⁻Nr*Sψ⦄π⁶&U⊞jεJκκH‹ι7◧"↷⌊Rι¦◧◧‽3▷↨↑´^@➙⊙×π+sQ⌈⊙▷TQ|ⅉB{_Π"⪪η(⁵AxQWW/⁻∨8▶u…κ¹*ITλ_⟧‽Hj.⊞;r⬤|›∧7ψjêÞζp⸿⊖¿⊖Q℅↷Hb↨“↔=bY⁵⌈↷¬δ⎚⪫:D₂↓;≦?⁺[‴.t4r±,s^)↗τ”²⊞υΦι›κ ≔⪪⮌S¹θW∧θ⭆⊕№υ⭆²§⮌θκ⊟θ¿№υι«[ιI⊕⌕υι]»ι

¡Pruébelo en línea! El enlace corresponde a la versión detallada del código. Explicación:

F⪪”...”²⊞υΦι›κ 

Divida una lista de nombres de elementos en pares de letras y elimine los espacios.

≔⪪⮌S¹θ

Invierta la entrada y divídala en caracteres.

W∧θ⭆⊕№υ⭆²§⮌θκ⊟θ

Mientras todavía hay entrada, elimine los últimos 2 caracteres si hay un elemento coincidente; de ​​lo contrario, elimine el último carácter.

¿№υι«

Si hay una coincidencia en la matriz, entonces ...

[ιI⊕⌕υι]

... imprime la coincidencia y su número atómico dentro de []s.

»ι

De lo contrario, imprima el carácter actual.

1 KevinCruijssen Aug 20 2020 at 18:56

05AB1E , 183 181 bytes

.œʒ.•2вy>ÖΘZθÒ7ßΩ¨ÑÝ
(Îiþ∍ćf=ÆΛ}’.мιoiFδC¸Γ=¢`Ÿíнp»ΛÑzðÿ®ÄÄ‘Â@Âη+(Óûò‘8нKKK#â<Ù#<“râµ5£”м}ÓæuüåÈZµ-ΔÈ;VzeY¯õnK§ÁÚ¡[θƶη„Gp©6›mðÿāε1ΛÎíγJò~܉cT¢Œƶʒ˜•2ô™ðм©såüαP}Σ€g{ygš}θ®DεN>«…[ÿ]}‡J

Bastante lento para entradas largas.

Pruébelo en línea o verifique algunos casos de prueba más cortos .

Explicación:

.œ               # Get all partitions of the (implicit) input-string
  ʒ              # Filter these list of parts by:
   .•2вy...ƶʒ˜•  #  Push compressed string "h helibeb c n o f nenamgalsip s clark casctiv crmnfeconicuzngageassebrkrrbsry zrnbmotcrurhpdagcdinsnsbtei xecsbalaceprndpmsmeugdtbdyhoertmybluhftaw reosirptauhgtlpbbipoatrnfrraacthpau nppuamcmbkcfesfmmdnolrrfdbsgbhhsmtdsrgcnnhflmclvtsog"
     2ô          #  Split it into parts of size 2: ["h ","he","li","be","b "...]
       ™         #  Titlecase each string: ["H ","He","Li","Be","B ",...]
        ðм       #  Remove all spaces from each string: ["H","He","Li","Be","B",...]
          ©      #  Store this list in variable `®` (without popping)
           s     #  Swap so the current partition is at the top of the stack
            å    #  Check for each inner part whether it's in the element-list
                 #  (1 if truthy; 0 if falsey)
             ü   #  For each overlapping pair:
              α  #   Get the absolute difference
               P #  Get the product of those to check if all are truthy (1)
                 #  (partitions in the form of [0,1,0,1,...] or [1,0,1,0,...] are left)
  }Σ             # After the filter: sort any remaining partition by:
    €            #  Map each part in the list to:
     g           #   Pop and push its length
      {          #  Sort this list of lengths
       y         #  Push the current partition again
        g        #  Pop and push its length to get the amount of parts in this partition
         š       #  And prepend it at the front of the other lengths
   }θ            # After the sort by: only leave the last partition,
                 # which will have the most parts, as well as the longest individual parts
     ®           # Push the list of elements from variable `®` again
      D          # Duplicate it
       ε         # Map the copy to:
        N>       #  Push the 0-based map index, and increase it by 1
          «      #  Append it to the element-string
           …[ÿ]  #  Push string "[ÿ]", where the `ÿ` is automatically filled with the
                 #  element name and number
       }‡        # After the map: transliterate all elements to the formatted elements in
                 # the partition
         J       # And join it back together to a single string
                 # (after which it is output implicitly as result)

Ver este consejo 05AB1E mío (sección Cómo comprimir cadenas que no forman parte del diccionario? ) Para entender por qué .•2вy>ÖΘZθÒ7ßΩ¨ÑÝ\n(Îiþ∍ćf=ÆΛ}’.мιoiFδC¸Γ=¢`Ÿíнp»ΛÑzðÿ®ÄÄ‘Â@Âη+(Óûò‘8нKKK#â<Ù#<“râµ5£”м}ÓæuüåÈZµ-ΔÈ;VzeY¯õnK§ÁÚ¡[θƶη„Gp©6›mðÿāε1ΛÎíγJò~܉cT¢Œƶʒ˜•es "h helibeb c n o f nenamgalsip s clark casctiv crmnfeconicuzngageassebrkrrbsry zrnbmotcrurhpdagcdinsnsbtei xecsbalaceprndpmsmeugdtbdyhoertmybluhftaw reosirptauhgtlpbbipoatrnfrraacthpau nppuamcmbkcfesfmmdnolrrfdbsgbhhsmtdsrgcnnhflmclvtsog".

Xcali Aug 21 2020 at 02:20

Perl 5 -p , 313 bytes

map$k{$_}=++$j,HHeLiBeBCNOFNeNaMgAlSiPSClArKCaScTiVCrMnFeCoNiCuZnGaGeAsSeBrKrRbSrYZrNbMoTcRuRhPdAgCdInSnSbTeIXeCsBaLaCePrNdPmSmEuGdTbDyHoErTmYbLuHfTaWReOsIrPtAuHgTlPbBiPoAtRnFrRaAcThPaUNpPuAmCmBkCfEsFmMdNoLrRfDbSgBhHsMtDsRgCnNhFlMcLvTsOg=~/.[a-z]?/g;for$a(sort{$b=~y///c-length$a}keys%k){s/(?<!\[)$a/[$a$k{$a}]/g}

¡Pruébelo en línea!