Scrivi un programma che trova la lettera associata più frequente in una stringa


20

Il programma deve generare la lettera più associata. Ad esempio, se al tuo programma è stata assegnata la seguente stringa:

"Sally's friend Bobby searched for seashells."

deve emettere Lperché si "ll"verifica due volte, il che è più frequente dell'altra coppia "bb".

Regole:

  • Se più di una lettera ha il 1 ° posto per le occorrenze, quindi emettile tutte in ordine alfabetico (ad es., "Sally's friends Jimmy and Bobby rummaged for seashells."Dovresti produrre sia LAND che M[o "LM"per favore] perché entrambe si verificano più frequentemente rispetto ad altre coppie.)
  • Le lettere che sono triplicate, quadruplicate, ecc. Contano come una coppia (ad es. "lll"In "willless"è contata come una sola coppia di L.)
  • Le coppie di lettere devono essere composte da una sola parola (ad esempio, "Sally's sociable friends Sammy and Bobby searched for fabulous seashells."devono essere prodotte Le non Sperché nonostante "ss"abbiano più occorrenze di "ll", sono separate da spazi).
  • Conta solo lettere dell'alfabeto inglese
  • Il caso non ha importanza (ad es. "Ss"È uguale a "SS"o "ss"e tutti vengono conteggiati come una coppia di S.)

Puoi leggere il tuo contributo ovunque tu voglia. Il codice più corto vince.


2
Possiamo supporre che solo le lettere si verifichino in coppia o che l'input possa contenere doppi spazi o doppio 'ecc.?
Martin Ender,

1
Possiamo presumere che almeno una lettera compaia due volte?
Martin Ender,

@ MartinBüttner Sì, puoi supporre che si verifichi almeno una coppia di lettere. Tuttavia, anche altri personaggi possono apparire in coppia. Conta solo lettere.
Ayane,

Anche se c'è solo una coppia, posso ancora stamparlo in un elenco come ['l']?
Maltysen,

@Maltysen Sì, puoi farlo.
Ayane,

Risposte:


6

Pyth, 26 25 24 16 15 byte

.M/sfthTrrz08ZG

Provalo online: dimostrazione

Spiegazione:

.M/sfthTrrz08ZG   implicit: z = input string
         rz0      convert z to lower-char
        r   8     run-length-encoding (into tuples [count, char])
    f             filter for tuples T, which satisfy:
     thT            T[0]-1 != 0 (count > 1)
   s              join to a string
.M            G   find the elements Z of "abcd...z", which produce the highest value:
  /...........Z       count of Z in ...

1
eC-> ssalva un byte.
Isaacg,

Conosci qualche buona risorsa che potrei usare per imparare Pyth?
Decadimento beta

@BetaDecay Puoi trovare un tutorial su Pyth su pyth.readthedocs.org Non copre tutte le funzionalità e i trucchi, ma è un buon inizio. E se hai qualche domanda, basta chiedere nella chat .
Jakube,

7

Bash + GNU coreutils, 133

grep -Eo '([A-Z])\1+'<<<"${1^^}"|cut -c1|sort|uniq -c|sort -rn|while read n l
do((a-n&&a-0))&&exit||echo $l&&a=$n
done|sort|tr -d \\n

Casi test:

$ for t in "Sally's friend Bobby searched for seashells." \
> "Sally's friends Jimmy and Bobby rummaged for seashells." \
> "willless" \
> "Sally's sociable friends Sammy and Bobby searched for fabulous seashells." \
> "11ss11aa"
> do
> ./mostpaired.sh "$t"
> echo
> done
L
LM
LS
L
AS
$ 

Conta solo lettere? (testcase: 11ss11aa-> SA)
edc65

@ edc65 Lì l'ho risolto ;-). In realtà, 11ss11aa-> AS :)
Digital Trauma,

Penso che tu sort -rdebba esserlo sort -rnse hai 10 o più lettere abbinate.
Toby Speight,

@TobySpeight. Sì. Fisso.
Digital Trauma,

può renderlo più breve con AWK invece di while: awk '! n {n = $ 1}; n == $ 1' | grep -o. $
Nik O'Lai

5

CJam, 29 27 byte

leue`{2a>},s_el-$e`$z~\)-,>

Grazie a @Optimizer per giocare a golf con 2 byte!

Provalo online nell'interprete CJam .

Come funziona

leu    e# Read a line from STDIN and covert to uppercase.
e`     e# Perform run-length encoding.
       e# Example: "AABBBC!!" -> [[2 'A] [3 'B] [1 'C] [2 '!]]
{2a>}, e# Filter out all pairs that are less of equal to [2].
s      e# Stringify.
       e# Example: [[2 'A] [3 'B] [2 '!]] -> "2A3B2!"
_el    e# Push a copy of the string and convert to lowercase.
       e# Example: "2A3B2!" -> "2a3b2!"
-      e# Remove all character from the second string from the first.
       e# Example: "2A3B2!" "2a3b2!" - -> "AB"
$e`$   e# Sort, perform run-length encoding and sort again.
       e# Example: "ABACABDBC" -> "AAABBBCCD"
       e#                      -> [[3 'A] [3 'B] [2 'C] [1 'D]]
                               -> [[1 'D] [2 'C] [3 'A] [3 'B]]
z~     e# Zip and dump.
       e# Example: [[1 'D] [2 'C] [3 'A] [3 'B]] -> [1 2 3 3] ['D 'C 'A 'B]
\)     e# Pop out the last element from the first array.
       e# Example: [1 2 3 3] -> [1 2 3] 3
-      e# Remove all occurrences of the popped element from the array.
       e# Example: [1 2 3] 3 -> [1 2]
,      e# Compute the length of the remainder.
>      e# Skip that many elements from the character array.

z~\)-,>dovrebbe funzionare per quanto posso vedere.
Ottimizzatore

@Optimizer: più breve e molto più intuitivo. Grazie!
Dennis,

4

Pyth - 23 22 21 20 byte

Utilizza la sostituzione regexp per sostituire tutti o due o più dell'alfabeto con un valore temporaneo e utilizza l' .Masimale per ottenere tutti i casi con il maggior numero di occorrenze. Grazie a @Jakube per aver sottolineato la ridondanza dell'ordinamento e del salvataggio di un byte.

.M/:rz0+Z"{2,}"KC0KG

Prende input da stdin e output simili ['l', 'm']a stdout.

.M        G         Values which yield maximal amount over lowercase alphabet
 /                  Count
  :                 Regexp substitution
   rz0              Lowercased input
   +Z               String concatenate current loop var         
    "{2,}"          Regexp 2 or more of previous group
   KCZ              Inline assign null byte to K and use value
  K                 Count K which is null byte

Provalo online qui .


4

C, 155

Qualcosa di diverso, nessuna regexps.

m=1,i=1,n[91];
main(c,a)char**a;
{
  char*t=a[1];
  for(;c=*t++;)(c&=95)>64&&c<91&&(c-(*t&95)?i=1:(c=(n[c]+=i),i=0,m=m<c?c:m));
  for(c=0;++c<91;)n[c]-m||putchar(c);
}

3

Python 2, 132 143 byte

def f(x):import re;x=re.findall(r'(.)\1+',x.upper());s={l:x.count(l)for l in x};print "".join(sorted([l for l in s if s[l]==max(s.values())]))

Esempio di esecuzione:

f("Sally's friends Jimmy and Bobby rummaged for seashells.")
LM

1
Probabilmente non soddisfa "Le lettere che sono triplicate, quadruplicate, ecc. Contano come una coppia"
Ginden,

Hai ragione! ho provato a ripararlo. grazie per
averlo

2

CJam, 37 byte

leue`{~_el-\(e&},1f=$e`$_W=0=f-{,1=},

Provalo online

Senza il supporto delle espressioni regolari, temo che sarà difficile competere con Pyth. Questo è il migliore che mi è venuto in mente al primo passaggio.

Spiegazione:

l     Get input.
eu    Convert it to upper case, since case does not matter.
e`    Run length encoding, to split into groups of same characters.
{     Start of block for filtering.
  ~     Unpack the length/letter pair.
  _     Copy the letter.
  el    Change copy to lower case.
  -     Subtract to compare. If result is non-zero, this is a letter.
  \     Swap count to top.
  (     Decrement to get truthy value for count > 1.
  e&    Logical and: It's a letter, and count is > 1.
},    End of filter.
1f=   Don't need the counts anymore, filter out the letters only from the RLE pairs.
$     Sort them, so that multiples of the same letter are sequential.
e`    RLE again, to count how many multiples of each letter we had.
$     And sort again, to get the count/letter pairs in order of incrementing count.
_     Copy list.
W=0=  Pick out count of last element, which is the highest count.
f-    Remove count from pairs that have the highest count. This leaves them
      as one member lists with letter only, while others still have count/letter.
{     Start block for filter.
  ,1=   Check for list length one.
},    End filter.

2

Q (66)

Leggibile relativamente all'avvio:

{where g=max g:.Q.A#count each group y where not differ y:upper x}

2

R, 105 byte

cat(substr(names(b<-table(regmatches(s<-toupper(readline()),gregexpr("([A-Z])\\1+",s))))[b==max(b)],1,1))

Questo legge una riga di testo da STDIN e stampa un elenco delimitato da spazi delle più comuni lettere accoppiate a STDOUT.

Ungolfed + spiegazione:

# Read a string from STDIN, convert to uppercase
s <- toupper(readline())

# Get each match of the regex /([A-Z])\1+/
matches <- regmatches(s, gregexpr("([A-Z])\\1+", s))

# Compute the frequency of each match
freq <- table(matches)

# Get the matches with the highest frequency
highest <- names(freq)[freq == max(freq)]

# Each element of highest is the literal pair, so take the first character
first <- substr(highest, 1, 1)

# Print to STDOUT
cat(first)

Esempi:

> (code)
Sally's friends Jimmy and Bobby rummaged for seashells.
L M

> (code)
Sally's friend Bobby searched for seashells.
L

> (code)
Sally's sociable friends Sammy and Bobby searched for fabulous seashells.
L

> (code)
11ss11nn
N S

Puoi provarlo online !


Probabilmente puoi sbarazzarti del touppercaso se ignori il caso e usi perl nel tuo gregexpr. ad es.cat(substr(names(b<-table(regmatches(s<-readline(),gregexpr("(\\w)\\1+",s,T,T))))[b==max(b)],1,1))
MickyT

@MickyT: ci avevo pensato, ma sembra che l'OP voglia che l'output sia maiuscolo, quindi dovrebbe usarlo toupperper assicurarsi comunque.
Alex A.

È una vergogna, quando l'ho letto la domanda mi mancava.
MickyT

Ho provato il violino, ma sembra funzionare per sempre senza outpuy in Firefox. Testcase: 11ss11nn?
edc65,

@ edc65 È un problema con R-Fiddle; niente funziona affatto. Ho contattato il loro amministratore per segnalare il problema. Risolto il problema con il mio regex e ora il test funziona come previsto, ma mi è costato 2 byte. Grazie per aver segnalato queste cose, lo apprezzo!
Alex A.

2

Ruby, 60 anni

f=->s{(?a..?z).group_by{|l|s.scan(/#{l*2}+/i).size}.max[1]}

p f["Sally's friends Jimmy and Bobby rummaged for seashells."]

group_bycrea una struttura hash (dizionario) in cui le chiavi sono l'output del blocco e i valori sono elenchi di lettere che risultano in ciascuna chiave. In questo caso, le chiavi sono conteggi di 2+ esecuzioni di una lettera, senza distinzione tra maiuscole e minuscole. maxconfronta le [key,value]tuple lessicograficamente, quindi trova solo la chiave massima. Quindi [1]restituisce la parte dell'elenco di valori della tupla.


2

Python 2, 185 159 153

i=input().lower()
d=sorted({l:len(i.split(l+l))for l in map(chr,range(97,123))}.items(),None,lambda x:x[1],1)
print sorted(c for c,k in d if k==d[0][1])

Accetta l'input come stringa tra virgolette.


2

C # 160 byte

Dov'è sl'input:

char? d(string s){s=s.ToUpper();return s.Select((x,i)=>new{y=x,z=i==0?(char?)null:s[i-1]}).Where(x=>x.y==x.z).GroupBy(x=>x.z).OrderBy(x=>x.Count()).Last().Key;}

1

rs, 146 byte

[^A-Za-z]/
*(.)\1+/\1\1
*(.)(?!\1)/
$/#
+*(.)#(?!.*?\1)/#\1
+*(.)(.*)#(.*)\1/\2#\3\1\1
#/
*(.)(\1*)/\1(_)^^((^^\1\2))
([^_])(_+)(?!_)(?=.*\2_)/
_/

Provalo! Per favore! Mi ci è voluto un'eternità per creare i pulsanti anche con la casella di output in quella pagina ...

Bene, questo era abbastanza ... pazzo. La logica qui è piuttosto strana; Pubblicherò una spiegazione solo se qualcuno lo chiede. (Naturalmente, ho anche detto che per una risposta INTERCAL la cui spiegazione è stata richiesta ... che non ho mai spiegato ...;)


Mi piace l'interprete, ma potresti voler mettere la casella di controllo del debug sulla stessa riga dei pulsanti o qualcosa del genere. Sembra un po 'strano fino in fondo. Comunque fico! +1
Maltysen,


@Maltysen Lo prenderò in considerazione. Grazie!
kirbyfan64sos,

@ edc65 Accidenti ... qual è stato il messaggio di errore completo? Sembra che potrebbe essere un bug di PyPy.js. O semplicemente il fatto che non l'ho mai provato su Firefox ...
kirbyfan64sos il

1

JavaScript 156 153

var x=prompt(),f={},a=0,o
x.toUpperCase().replace(/([A-Z])\1+/g,function(m,s){m=f[s]=-~f[s]
if(a==m)o.push(s)
if(a<m)a=m,o=[s]})
alert(o.sort().join(""))


f[s]?f[s]+1:1->-~f[s]
edc65,

Fallisce con le non lettere:Count only letters from the English alphabet
edc65

Grazie @ edc65. Ho aggiunto il collegamento e il controllo AZ.
Wolfhammer,

1
Il tuo codice esatto, ottimizzato ed ES6: f=x=>{x.toUpperCase(f={},a=0,o).replace(/([A-Z])\1+/g,(m,s)=>a<(m=f[s]=-~f[s])?(a=m,o=[s]):a>m?0:o.push(s));alert(o.sort().join'')}(gli ultimi 2 '' sono davvero backtick, e # 96
edc65,

1

Bash + textutils (grep, sed), 111 caratteri

fold -1<<<$s|uniq -iD|sort -f|uniq -ic|sort -rn|grep -i [A-Z]|sed -n '1h;G;s/\(\s*\S\+\s\)\(.\)\n\1./\2/p'|sort

Bash + awk (invece di sed), 97 caratteri

fold -1<<<$s|uniq -iD|sort -f|uniq -ic|sort -rn|grep -i [A-Z]|awk '!n{n=$1};n==$1{print $2}'|sort

per testarlo, prima assegna s

s="Sally's friends Jimmy ää and Bobby rummaged ää for seashells."

0

R, 98 byte

Molto simile alla soluzione di Alex, ma utilizza una sostituzione anziché una corrispondenza per determinare le lettere consecutive. La scansione viene utilizzata per ottenere l'input e anche per dividere il risultato di sostituzione sugli spazi.

cat(names(a<-table(scan(,'',t=gsub('([A-z]?)(\\1?)[^A-z]*','\\U\\2 ',scan(,''),T,T))))[a==max(a)])

Un paio di test

> cat(names(a<-table(scan(,'',t=gsub('([A-z]?)(\\1?)[^A-z]*','\\U\\2 ',scan(,''),T,T))))[a==max(a)])
1: 11 was a race horse, 22 was one too. 11 won one race and 22 one won too.
19: 
Read 18 items
Read 2 items
O
> cat(names(a<-table(scan(,'',t=gsub('([A-z]?)(\\1?)[^A-z]*','\\U\\2 ',scan(,''),T,T))))[a==max(a)])
1: Sally's friends Jimmy and Bobby rummaged for seashells.
9: 
Read 8 items
Read 5 items
L M
> cat(names(a<-table(scan(,'',t=gsub('([A-z]?)(\\1?)[^A-z]*','\\U\\2 ',scan(,''),T,T))))[a==max(a)])
1: 11ss11nn
2: 
Read 1 item
Read 2 items
N S
> 
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.