查找递归首字母缩写


10

介绍

一个递归的缩写,是一个包含或引用本身,例如首字母缩写: Fish可能是递归的缩写Fish is shiny hero,通知怎么也包含缩写本身。另一个例子是Hi-> Hi igloo。甚至ppcg paints->ppcg paints cool galaxies pouring acid into night time stars

因此,基本上,如果每个单词的第一个字母拼写出第一个单词或多个单词,那么句子就是递归首字母缩写词。


挑战

编写一个程序,该程序接受由1个或多个单词组成的字符串,并用空格字符分隔,然后输出一个递归首字母缩写词;如果不可能,则输出一个空字符串。例如,不可能为字符串创建递归首字母缩写词,ppcg elephant因为您首先要使用pfrom,ppcg然后将其添加到首字母缩写词,然后使用efrom elephant。但是现在我们有了矛盾,因为首字母缩写词目前拼写为“ pe ..”,与“ pp ..”冲突。例如,也是如此hi。您可以使用hfrom hi,但是句子现在结束了,没有更多字母可以拼出hi,我们只剩下h不匹配的字母hi。(字符串需要的单词数量大于或等于首字母缩写词中的字母数量)

输入和输出不区分大小写


限制条件

  • 输入到程序中的任何内容都将是有效的英语单词。但是,您还必须确保输出有效的英语单词(可以使用数据库,也可以只为26个字母存储一个单词)
  • 适用标准漏洞和默认IO规则

测试用例

hi igloo -> hi
ppcg paints -> (impossible)
ppcg paints cool giraffes -> ppcg
ppcg paints cool galaxies pouring acid into night time stars -> ppcgpaints
ppcg paints cool galaxies pouring acid into night time -> ppcg
ppcg questions professional pool challengers greatly -> (impossible)
I -> I

计分

这是,因此以字节为单位的最小源代码获胜


1
Q,q [kyoo]名词,复数Q或Qs,q或qs。英文字母的第17个字母,辅音。以字母Q或q表示的任何语音,例如快速,无罪释放或伊拉克。有Q的形状的东西
l4m2

3
我也不认为ppcg是字典中的单词
l4m2 18-10-26

1
好的,这些测试用例之一并没有达到我的预期。只是为了确保我们两个人都不会犯错ppcg paints cool galaxies pouring acid into night time,当将其缩写为“ ppcgpaint”时,ppcg即使输出只是部分匹配,输出也应该是?
卡米尔·德拉卡里

1
由于当前所有的解决方案都采用第一个选项(“首字母缩写”),而“查找句子”选项则更为复杂(因此,与第一个选项相比没有任何竞争性–首先,您需要一些单词列表),我建议将其从这一挑战中删除,并提出自己的问题。
圣保罗Ebermann

2
@PaŭloEbermann好吧,我删除了它
FireCubez

Answers:


5

Japt,13个字节

¸
mά
VøUÎ ©V

在线尝试!



1
这在ppcg paints cool galaxies pouring acid into night time stars测试用例上失败了
Kamil Drakari,

是适用于该测试用例的版本,但它不是高尔夫球用的
Kamil Drakari 18-10-26

我以前的13个字节的解决方案是正确的Dx \
路易斯·费利佩·德·耶稣·穆诺兹

当前版本仅检查首字母缩写词是否包含第一个单词,这会导致一些新问题
Kamil Drakari '18 October

5

05AB1E,16个字节

ð¡©ηʒJ®€нJηså}θJ

在线尝试!


1
为什么更改为ð¡而不是#上次编辑?我没有考虑一些特殊的测试用例?
凯文·克鲁伊森

@KevinCruijssen:因为#单个单词输入输出输入而不是空字符串会失败。
Emigna '18 -10-26

是的,就是这样。我记得以前曾问过类似的问题。我仍然认为#应该与ð¡.. 一样。是否有一个用例,您可以想到要在空格上分割字符串的地方,但是如果它不包含空格,则应该保留该字符串(而不是字符串)包裹在列表中)?其他人在阅读这篇文章;仅供参考:#在不带空格的字符串上使用(在空格上分隔)将按原样生成字符串(即"test" -> "test")。ð¡在没有空格的字符串上使用(在空格上分隔)会导致字符串包装在列表中(即"test" -> ["test"])。
凯文·克鲁伊森

@KevinCruijssen:我认为这主要是因为它#也被用作quit if true(它的主要功能)。如果#返回false,则可能不希望将检查的值包装在堆栈中的列表中。
Emigna '18 -10-26

1
@KamilDrakari:虽然现在可以工作。
Emigna '18 -10-26

2

Haskell,51 48字节

编辑:-3字节感谢@xnor。

(\w->[r|p<-scanl1(++)w,map(!!0)w==p,r<-p]).words

查找首字母缩写词。

在线尝试!

\w->            .words -- let 'w' be the input list split into words
   p<-scanl1(++)w      -- loop 'p' through the list starting with the first word
                       --  and appending the next words one by one, e.g.
                       --  "Fish","is","shiny","hero" -> "Fish","Fishis","Fishisshiny","Fishisshinyhero"
     ,map(!!0)w==p     -- if the word made out of the first characters of the
                       --  words of 'w' equal 'p'
  [r|   r<-p]          -- return the letters of 'p' - if the check before
                       --  never evaluates to True then no letters, i.e. the
                       --  the empty string is returned

由于您未使用x,因此合成(\w-> ...).words会更短。
xnor18年

2

Perl 6的50个42 58 49字节

-9字节归功于nwellnhof

{~first {m:g/<<./.join~~/^$^a/},[R,] [\~] .words}

在线尝试!

第一选择。我正在利用这样一个事实,即ord唯一返回字符串的第一个字母的序数值,而chrs接收一个ords列表并返回一个字符串。或来自Moonheart回答的正则表达式较短:(。作为参考,以前的答案是.words>>.ord.chrs不是[~] m:g/<<./

说明:

{~first {m:g/<<./.join~~/^$^a/},[R,] [\~] .words}
{                                               } # Anonymous code block
  first  # Find the first 
                                [R,] [\~] .words  # Of the reverse of the triangular joined words
         {                    }  # That matches:
          m:g/   /   # Match all from the original string
              <<.    # Single letters after a word boundary
                  .join    # Joined
                       ~~/^$^a/   # And starts with the given word
 ~  # And stringify Nil to an empty string

您现在不需要输出“不可能”
FireCubez

@Jo King我可以做正则表达式,但是对于我一生来说,我似乎无法与所有运算符一起思考。我忘记了x运算符的存在,例如:P
moonheart08 '18

1

视网膜0.8.2,60字节

^
$'¶
\G(\w)\w* ?
$1
+`^(.+)(\w.*¶\1 )
$1 $2
!`^(.+)(?=¶\1 )

在线尝试!查找递归首字母缩写词(如果有)。说明:

^
$'¶

复制输入。

\G(\w)\w* ?
$1

将第一行中的单词减少到其首字母。

+`^(.+)(\w.*¶\1 )
$1 $2

如果可能,请插入空格以匹配原始单词。

!`^(.+)(?=¶\1 )

如果它是第二行的前缀,则输出第一行。


对于ppcg涂料,输出无效,它不应输出任何内容,因为pp仅拼写了第一个单词的一部分,而不是所有单词
FireCubez

@FireCubez抱歉,我正在研究该问题的旧版本。
尼尔,

1

Perl 6、56字节

$!=[~] m:g{<<.};say $! if m:g{<<\w+}.map({$_ eq $!}).any

在线尝试!

以前的正则表达式令我困惑,无法使用。突然我完全理解它们。我怎么了:P

完成选择1。


可悲的是,我仍处于正则表达式简直是疯狂的阶段。不幸的是,这没有通过ppcgpaints测试,否则我会建议类似$!∈.words的if条件
Jo King


1

Rust,155岁,在线尝试!

选择:问题1:查找首字母缩写词

type S=String;fn f(t:&str)->S{let l=t.to_lowercase();let w=l.split(' ').fold(S::new(),|a,b|a+&b[..1])+" ";if (l+" ").contains(w.as_str()){w}else{S::new()}}

放开手,只需要一点:

fn f(t: &str) -> String {
    let l = t.to_lowercase();
    let w = l.split(' ').fold(String::new(), |a, b| a + &b[0..1]) + " ";
    if (l + " ").contains(w.as_str()) {
        w
    } else {
        String::new()
    }
}

或者,如果我们假设输入全部为小写,则只需130:

type S=String;fn f(l:S)->S{let w=l.split(' ').fold(S::new(),|a,b|a+&b[..1])+" ";if (l+" ").contains(&w.as_str()){w}else{S::new()}}

该程序可以选择2个选项中的哪个?
FireCubez

@FireCubez更新。
Hannes Karppila

1

果冻,9字节

Ḳµ;\fZḢWƊ

如果可能,请执行全程序打印递归缩写。

在线尝试!

怎么样?

Ḳµ;\fZḢWƊ - Main Link: list of characters
Ḳ         - split at space (let's call this v)
 µ        - start a new monadic chain (i.e. f(v)):
   \      - cumulative reduce v with:
  ;       -   concatenation -> [v(1), v(1);v(2), v(1);v(2);v(3); ...]
        Ɗ - last three links as a monad (i.e. f(v)):
     Z    -   transpose -> [[v(1)[1], v(2)[1], ...],[v(1)[1],v(2)[2],...],...]
      Ḣ   -   head -> [v(1)[1], v(2)[1], ...] ... i.e. 'the potential abbreviation'
       W  -   wrap in a list -> ['the potential abbreviation']
    f     - filter discard those from the left list that are not in the right list
          - implicit print -- a list of length 0 prints nothing
          -                   while a list of a single item prints that item

“打印第一个字”是什么意思?它需要找到首字母缩写词(如果存在)吗?
FireCubez

对于“ ppcg涂料无法将酸倒入天空的凉爽星系”失败,应打印“ ppcg涂料”或“ ppcgpaints”
FireCubez

哦,我错过了相邻的单词要求:(
Jonathan Allan'Oct

修复它以满足此要求。
乔纳森·艾伦

1

JavaScript [ES6],74个字节

s=>s.split` `.map(w=>(b+='('+w,e+=')?',t+=w[0]),b=e=t='')&&t.match(b+e)[0]

创建一个正则表达式进行匹配。请参见代码示例。

所有测试用例:

let f=

s=>s.split` `.map(w=>(b+='('+w,e+=')?',t+=w[0]),b=e=t='')&&t.match(b+e)[0]

console.log(f('hi igloo'))
// 'hi'.match('(hi(igloo)?)?')[0] == 'hi'

console.log(f('ppcg paints'))
// 'pp'.match('(ppcg(paints)?)?')[0] == ''

console.log(f('ppcg paints cool giraffes'))
// 'ppcg'.match('(ppcg(paints(cool(giraffes)?)?)?)?')[0] == 'ppcg'

console.log(f('ppcg paints cool galaxies pouring acid into night time stars'))
// 'ppcgpaints'.match('(ppcg(paints(cool(galaxies(pouring(acid(into(night(time(stars)?)?)?)?)?)?)?)?)?)?')[0] == 'ppcgpaints'

console.log(f('ppcg paints cool galaxies pouring acid into night time'))
// 'ppcgpaint'.match('(ppcg(paints(cool(galaxies(pouring(acid(into(night(time)?)?)?)?)?)?)?)?)?')[0] == 'ppcg'

console.log(f('ppcg questions professional pool challengers greatly'))
// 'pqppcg'.match('(ppcg(questions(professional(pool(challengers(greatly)?)?)?)?)?)?')[0] == ''

console.log(f('I'))
// 'I'.match('(I)?')[0] == 'I'

console.log(f('increase i'))
// 'ii'.match('(increase(i)?)?')[0] == ''

console.log(f('i increase'))
// 'ii'.match('(i(increase)?)?')[0] == 'i'


失败increase i
平方米,

@ l4m2,现已修复。
瑞克·希区柯克

0

Python 2,106个字节

第一种选择-查找递归首字母缩写词。
返回列表中的结果。

I=input().split()
print[' '.join(I[:i])for i in range(1,-~len(I))if[j[0]for j in I]==list(''.join(I[:i]))]

在线尝试!

Python 2,120字节

第一种选择-查找递归首字母缩写词。

def F(I,a=[],r=''):
 for j in I.split():
  a+=j,
  if list(''.join(a))==[i[0]for i in I.split()]:r=' '.join(a)
 return r

在线尝试!


您不需要按照@JoKing的要求输出“ IMPOSSIBLE”,这可能会减少字节数
FireCubez

像“我”这样的单个字母不起作用,它应该输出该单个字母
FireCubez

@FireCubez已修复
Dead Possum,

0

Javascript,71个字节

方法1

l=s=>{p=s.split(' ');k=p.reduce((r,x)=>r+x[0],'');return k==p[0]?k:''}

取消高尔夫:

l=s=>{
    p = s.split(' ');
    k = p.reduce((r,x)=>r+x[0],'');
    return k==p[0] ? k : '';
}
  • 按空格分割字符串。
  • 通过从每个单词中获取第一个字符来创建新字符串。
  • 将其与第一个单词进行比较。



0

Scala,76个字节

简单案例的解决方案(不带空格的缩写)

def^(s:String)={val l=s.split(" ");if(l(0)==l.map(_(0)).mkString)l(0)else""} 

Scala,144字节 100字节(请参阅注释中仅ASCII的解决方案)

def^(s:String)={val l=s.split(" ");l.scanLeft(List[String]())(_:::List(_)).find(_.mkString==l.map(_(0)).mkString).map(_.mkString).getOrElse("")}

在REPL中测试

scala> def^(s:String)={val l=s.split(" ");if(l(0)==l.map(_(0)).mkString)l(0)else""}
$up: (s: String)String

scala> ^("hi igloo")
res12: String = hi

scala> ^("ppcg paints cool giraffes")
res13: String = ppcg

scala> ^("ppcg paints Xcool giraffes")
res14: String = ""

scala> ^("ppcg paints cool galaxies pouring acid into night time stars")
res15: String = ""

scala>

scala> def^(s:String)={val l=s.split(" ");l.scanLeft(List[String]())(_:::List(_)).find(_.mkString==l.map(_(0)).mkString).map(_.mkString).getOrElse("")}
$up: (s: String)String

scala> ^("hi igloo")
res16: String = hi

scala> ^("ppcg paints cool giraffes")
res17: String = ppcg

scala> ^("ppcg paints Xcool giraffes")
res18: String = ""

scala> ^("ppcg paints cool galaxies pouring acid into night time stars")
res19: String = ppcgpaints


可以:::代替++吗?另外,List[String]-> Seq[Any]
分,仅使用ASCII


仅@ASCII,太酷了!该解决方案胜过Python。:)
Y Wit博士

介意添加代码吗?IMO,看到字节数却看不到解决方案有点奇怪
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.