复制和开关盒


34

目标是,以字符串作为输入,复制每个拉丁字母并“切换”其大小写(即大写变为小写,反之亦然)。

输入和输出示例:

Input      Output
bad        bBaAdD
Nice       NniIcCeE
T e S t    Tt eE Ss tT
s E t      sS Ee tT
1!1!1st!   1!1!1sStT!
n00b       nN00bB     
(e.g.)     (eE.gG.)
H3l|@!     Hh3lL|@!

输入由可打印的ASCII符号组成。

您不应该重复非拉丁字母,数字,特殊字符。


17
这是一个非常不错的,简单但不平凡的挑战。
— Mego

Answers:


10

果冻,5个字节

żŒsQ€

在线尝试!

怎么运行的

żŒsQ€  Main link. Argument: s (string)

 Œs    Yield s with swapped case.
ż      Zip s with the result.
   Q€  Unique each; deduplicate each pair of characters.

17

Python,56 54字节

lambda s:''.join(c+c.swapcase()*c.isalpha()for c in s)

在Ideone上进行测试。


ang!出去打我4个字节...
— R. Kap

这如何维护非字母字符?我认为它们会显示为空字符串。
— Atlasologist '16

@atlasologist正如您在Ideone上看到的那样,他们没有。*具有比更高的优先级+,因此它只影响cwith交换大小写。
— 丹尼斯

哦,好吧,我没想到那样。真好
— 气象学家'16

16

的JavaScript ES6,70 68 66 64字节

感谢@Kevin Lau节省了2个字节-不是Kenny

@CᴏɴᴏʀO'Bʀɪᴇɴ节省了2个字节

s=>s.replace(/[A-Z]/gi,l=>l+l[`to${l<"a"?"Low":"Upp"}erCase`]())

说明

这使用了一个很hacky:

l[`to${l<"a"?"Low":"Upp"}erCase`]()

松散的是:

l[`to${
   l < "a" ?
   "Low" : 
   "Upp"
}erCase`]()

基本上l < "a"检查字母的代码点是否小于的代码点a(因此为大写字母)。如果是的话,它将变成to + Low + erCase哪个l['toLowerCase']()并使字符变为小写。`引号允许字符串格式化,因此从本质上讲,您可以想到:

`to${l < "a" ?"Low" : "Upp"}erCase`

as:"to" + (l<"a" ? "Low" : "Upp") + "erCase"生成要调用的函数(使字符串大写或小写)。我们将其放在方括号中[ ... ],这样我们就可以访问以字符串形式给出的属性。这将返回适当的函数,然后我们将其调用。


3
/[A-Z]/gi是较短的正则表达式:3
— 价值墨水

@ KevinLau-notKenny哦,不错,谢谢!
— Downgoat

1
to${l<"a"?"Lower":"Upper"}Case到to${l<"a"?"Low":"Upp"}erCase
— 科纳·奥布莱恩

@CᴏɴᴏʀO'Bʀɪᴇɴ哦,很好,谢谢!
— Downgoat

4
l[`to${l<"a"?"Low":"Upp"}erCase`]()我认为我们对邪恶有了新的定义。
— gcampbell '16

10

Ruby,37 33(30 + -p标志)个字节

swapcase营救!有点。@Lynn中的-4个字节。

gsub(/[a-z]/i){$&+$&.swapcase}

gsub(/[a-z]/i){$&+$&.swapcase}加上p标志是31个字节。
— 林恩

1
@Lynn我认为共识是默认脚本所需的编辑差异,因此p标志也(space)-p称为3个字节。
— 价值墨水

8

C,63 60字节

f(char*s){for(;*s;s++)isalpha(putchar(*s))&&putchar(32^*s);}

使用事实'a' XOR 32 == 'A',等等。

多亏了FryAmTheEggman,节省了三个字节。


您可以s++在最后一个putchar(&&putchar(32^*s++))中移动来保存一个字节
— Giacomo Garabello,2016年

我想你可以替换&&使用*,不是吗?
— aloisdg说恢复莫妮卡

1
如果我考虑一下&&短路行为是如何工作的,我很确定这两种方法都不起作用。
— 林恩

f(char*s){isalpha(putchar(*s))&&putchar(32^*s);*s&&f(1+s);}递归的?
— l4m2

1
f(char*s){*s&&f(1+s,isalpha(putchar(*s))&&putchar(32^*s));}递归的?
— l4m2

6

CJam,11个字节

l_el_eu.+.|

在这里测试。

说明

l      e# Read input.
_el    e# Duplicate, convert to lower case.
_eu    e# Duplicate, convert to upper case.
.+     e# Concatenate the two characters in matching positions from those two
       e# strings. E.g. "ab!" "AB!" would give ["aA" "bB" "!!"].
       e# For each character from the original string and the corresponding 
.|     e# string from this list, take the set union (which eliminates duplicates
       e# and keeps the order the values appear in from left to right, so that
       e# the original case of each letter comes first).

5

Pyth,7个字节

sm{+dr2

测试套件。

sm{+dr2    input: Q
sm{+dr2dQ  implicit arguments

        Q  input
 m         for each character as d:
     r2d       swapcase
   +d          prepend d
  {            deduplicate
s          join as string

哈哈,那真的很快:D
— nicael '16


5

Haskell,73个字节

l=['a'..'z']
u=['A'..]
(>>= \c->c:maybe""pure(lookup c$zip l u++zip u l))

5

切达,118104字节

(s)->s.chars.map((i)->{if String.letters has i.lower{if i<"a"{i+i.lower}else{i+i.upper}}else{i}}).join()

第一个真正的切达干酪答案!!!这比我想象的要少得多。

与非竞争版本1.0.0-beta.9一起使用。


如您所知,我不是将切达干酪设计成高尔夫球状的:/

取消高尔夫:

(str) -> str.chars.map(
    (i) -> {
        if String.letters has i {
            if i < "a" { // Check char code, meaning it's upper case if true
                i+i.lower
            }
            else {
                i+i.upper
            }
        } else {
            i
        }
    }
).join()

用法:

var doThing = <code here>;
doThing("input...");

更新: 16年7月14日,我完成了三元运算,将其减少到84个字节

切达(Cheddar),84个字节

(s)->s.chars.map((i)->String.letters has i.lower?i<"a"?i+i.lower:i+i.upper:i).join()

从v1.0.0-beta.14版本开始工作


4
好极了!我们已经等了很久了!
— DJMcMayhem

更改一两个方法名称后,同样有效的Sidef
— cat

@cat o_o相似之处令人不安
— Downgoat

那么,他们俩都被Perl,Perl 6中,红宝石,巨蟒等的影响,所以这并不奇怪:P
— 猫

1
@cat哦,不,不,不,不,切达不受 python的影响
— Downgoat

4

视网膜,28 27 21字节

这些是制表符,而不是空格。

.
$&  $&
T`lL    p`Ll_`  .

在线尝试

谢谢大家的建议。


SE占用了这些空间。
— 科纳·奥布莱恩

[A-Za-z]->i`[A-Z]
— Downgoat

马丁和我在聊天中,我们想到
— FryAmTheEggman

@FryAmTheEggman啊,我忘了_。我将使用选项卡,以便我可以一次测试所有测试用例。
— mbomb007 '16

1
但是,测试套件并不一定必须精打细算:P只需留下一个注释,说“第一行使其可以在每一行上分别运行”就足够了。在这里,可以节省制表符的疯狂。
— FryAmTheEggman'7

4

C,87 80

将字符串作为输入传递f(),并将输出写入STDOUT。该字符串未修改。

f(char*v){for(;*v;++v)putchar(*v),isalpha(*v)?putchar(*v-32+64*!islower(*v)):0;}

您可以提供一种在线尝试的方法吗?
— aloisdg说恢复莫妮卡

@aloisdg尝试ideone.com
— 猫

4

sed,30个字节

29字节代码+ 1字节参数 -r

s/([a-z])|([A-Z])/&\u\1\l\2/g

用法:

echo -e 'bad\nNice\nT e S t\ns E t\n1!1!1st!\nn00b\n(e.g.)\nH3l|@!' |\
sed -r 's/([a-z])|([A-Z])/&\u\1\l\2/g'

4

J,31 29字节

[:;]<@~."1@,.tolower,.toupper

说明

[:;]<@~."1@,.tolower,.toupper  Input: s
                      toupper  Convert s to all uppercase
             tolower           Convert s to all lowercase
                    ,.         Join them as columns in a 2d array
   ]                           Identity function, get s
           ,.                  Prepend s as a column to the 2d array
      ~."1@                    Take the unique chars on each row
    <@                         Box them
[:;                            Unbox the list of boxes and join their contents and return

4

Haskell中,121,101,85, 82

import Data.Char
g n|isLower n=toUpper n|1<2=toLower n
(>>= \x->x:[g x|isAlpha x])

3
通过用警卫代替if-then-else,您可以节省15个字节左右。并且isLower比具有的构造要短elem5个字节。
— arjanen '16

1
>>=是concatMap(或concat.map)参数已翻转:f n = n >>= (\x->if isAlpha x then[x,r x]else[x])。你可以去pointfree并省略函数名和替换的定义f有(>>= \x->if isAlpha x then[x,r x]else[x])。
— nimi

1
otherwise您可以使用任何计算结果为的表达式代替True,例如1<2。您可以将if .. then .. else列表理解替换为\x->[x]++[g x|isAlpha x]。哦,有一个错误:第二toUpper中g必须是toLower。
— nimi

1
哦,还有一个:[x]++是x:。
— nimi

4

Perl,36个字节(35 + -n标志)

s/[a-z]/$&.(ord$&<97?lc$&:uc$&)/ige

(-p需要标签)

(由于@Dom Hasting,-2个字节)

简短说明:
ord返回一个char的数值。ord(any lower case) >= 97和ord(any upper case) <= 90)。

运行:

perl -pe 's/[a-z]/$&.(ord$&<97?lc$&:uc$&)/ige'

您仍然需要使用,/i否则您的正则表达式将在字母之间匹配多个代码点。
— Oleg V. Volkov

@ OlegV.Volkov哦,对了,谢谢,答案已编辑。
— 达达

使用您的方法,再将其减小一个字节:在线尝试!
— Xcali

4

Ruby,31 + 1 = 32 30 + 1 = 31个字节

带有-p标志,运行

gsub(/(?<=(.))/){$1.swapcase!}

利用这样的事实,swapcase!它将返回nil除ASCII字母之外的任何东西,当从gsub块中返回时,它将转换为空字符串。@Jordan通过捕获后面的字符来节省了一个字节。


匹配//然后再使用$`[-1]很聪明。
— 约旦

1
我设法用lookbehind:删除了六个字节gsub(/(?<=(.))/){$1.swapcase!}。不过,基本概念相同,请随时使用。
— 约旦

凉!对我来说,这似乎短了一个字节。
— histocrat

嗯,是的,一个字节。我想我那里还有一些额外的代码来测试我不小心计算在内的代码。
— 约旦

无需使用的自我修改版本.swapcase!。(我的意思是,删除该!。)
— manatwork '16

4

R,191 187 168 156 98 99个字节

由于Giuseppe和MickyT的改进,有99个字节。

paste0(x<-unlist(strsplit(readline(),"")),gsub("[^A-Za-z]","",chartr("a-zA-Z","A-Za-z",x)),collapse="")

98字节 -也许在明年的某个时候,我们可以再找一个高尔夫,哈哈哈。
— 朱塞佩

1
我讨厌成为坏的新手,但在带有空格的测试用例上却失败了。 readline()可以使用,但是会花费一个字节
— MickyT '18

@MickyT谢谢,现在修复。
— rturnbull

@MickyT scan将使用用引号引起来的输入(通常是其他语言的命令行参数的情况)
— Giuseppe

@Giuseppe对不起,我没有意识到。我只是认为它会自动在空格上拆分,除非您指定了非空格字符。抱歉,rturnbull
— MickyT'Apr 3'18

3

05AB1E,7个字节

码:

vyyš«Ù?

说明:

v       # For each in input.
 yyš    # Push y and y swapcased.
    «Ù  # Concatentate and uniquify.
      ? # Print without a newline.

使用CP-1252编码。在线尝试!


也许您可以提供指向翻译的链接?
— nicael

2
@nicael它是链接的...就在github上。
— mbomb007 '16

因此,没有在线口译员吗?:(
— nicael

@nicael然后下载并运行。不必有在线口译员,只需一个口译员即可。
— mbomb007 '16

1
@nicael是的,尚无在线翻译器:(。脱机版本应可使用。–
— Adnan



3

实际上是8个字节

`;Öo╔`MΣ

在线尝试!

说明:

`;Öo╔`MΣ
`;Öo╔`M   for each character in input:
 ;          duplicate the character
  Ö         swap case
   o        append to original character
    ╔       remove duplicated characters
       Σ  concatenate

3

MATL,11个 9字节

tYov"@uv!

在线尝试

说明

        % Implicitly grab input as string
t       % Duplicate the input
Yo      % Swap case of all characters
v       % Vertically concatenate the original and swap-cased versions
"       % For each column (letter in the original)
  @u    % Compute the unique values (without sorting)
  v!    % Vertically concatenate with the existing output and transpose
        % Implicit end of for loop and implicit display

3

Perl, 28 22 21 bytes (20 + -p flag)

s/[a-z]/$&.$&^$"/ige

I imagine you can save a byte by using $" instead of ' ', but I haven't tested.
— msh210

@msh210, nice! How could I forget to check perlvar for default strings? Thanks!
— Oleg V. Volkov

3

Stax, 7 6 bytes

Thanks to @recursive for a byte saved!

┤§ÆP♦■

Run and debug it at staxlang.xyz! (link is to unpacked version)

Unpacked (7 bytes):

c:~\{um

Explanation:

c:~\{um
c          Copy the top element of the stack (the input, in this case).
 :~        Switch case of each letter in the copy.
   \       Zip. This produces an array of two-character strings.
    { m    Map a block over this array of two-character strings.
     u       Get all unique elements.
           Implicit concatenate and print.

Thanks for giving stax a try. One easy improvement you can make is to use u instead of :g. It will get all the unique elements in an array, which is exactly what you want in this case. Other than that, this looks well golfed.
— recursive

@recursive Thanks! Forgot about that one :/ Will edit in soon.
— Khuldraeseth na'Barya

Doesn't work for 123. You may need to change the format for all inputs (i.e. quote them). The link is also broken. You need to replace m=11 with m=2. There is a PPCG post generating button on staxlang.xyz so you may want to use that one.
— Weijun Zhou

@WeijunZhou Thanks, fixed!
— Khuldraeseth na'Barya

2

Python, 59 bytes

lambda s:''.join((x,x+x.swapcase())[x.isalpha()]for x in s)

Edited to fix repeating non-alphabetic characters



2

PHP 4.1, 57 bytes

This code assumes access through a web server (Apache, for example), using the default configuration.

You can pass the string by sending the key S by any means (POST, GET, COOKIE, SESSION...).

<?for($i=0;$c=$S[$i++];)echo$c,ctype_alpha($c)?$c^' ':'';


2

Common Lisp (Lispworks), 262 bytes

(defun f(s)(let((b""))(dotimes(i(length s))(if(lower-case-p(elt s i))(progn #1=(setf b(concatenate 'string b(string #2=(elt s i))))(setf b(concatenate 'string b(string(char-upcase #2#)))))(progn #1#(setf b(concatenate 'string b(string(char-downcase #2#)))))))b))

ungolfed:

(defun f (s)
  (let ((b ""))
    (dotimes (i (length s))
      (if (lower-case-p (elt s i))
          (progn
           #1=(setf b (concatenate 'string b (string #2=(elt s i))))
           (setf b (concatenate 'string b (string (char-upcase #2#)))))
        (progn
          #1#
          (setf b (concatenate 'string b (string (char-downcase #2#)))))))
    b))

Usage:

CL-USER 1 > (f "abc")
"aAbBcC"

CL-USER 2 > (f "bad")
"bBaAdD"
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.