将字符串乘以数字!

34

前一阵子关于将字符串相乘存在一个挑战。它向我们展示了如何不仅可以将数字相乘,而且还可以将字符串相乘。但是,我们仍然无法正确地将数字乘以字符串。已经尝试过这样做,但这显然是错误的。我们需要解决这个问题!

你的任务:

编写一个将两个输入(一个字符串和一个整数)相乘的函数或程序。要将字符串乘以整数(适当),请将字符串拆分为字符,将每个字符重复等于整数的次数,然后将字符重新粘在一起。如果整数为负数,则在第一步中使用其绝对值,然后反转字符串。如果输入为0,则不输出任何东西(乘以0等于零)。

输入:

一个仅由可打印的ASCII字符和换行符以及一个整数(可能为负数)组成的字符串。

输出:

字符串乘以整数。

例子:

Hello World!, 3 --> HHHeeellllllooo WWWooorrrlllddd!!!

foo, 12 --> ffffffffffffoooooooooooooooooooooooo

String, -3 --> gggnnniiirrrtttSSS

This is a fun challenge, 0 -->

Hello

World!, 2 --> HHeelllloo

WWoorrlldd!!

得分:

这是代码高尔夫球,最低字节数获胜!

4

我们是否可以假设字符串是仅可打印的ASCII加上换行符?

我们可以输出字符串列表吗?

视网膜局部解决方案。仅适用于整数的正值。如果有人愿意,我可能不会花时间完成它。tio.run/##K0otycxL/P8/…–

@ mbomb007,是的,很抱歉花了这么长时间。

@totallyhuman,不,您可能不会。

Answers:

31

果冻,6 5 4字节

²Ɠxm

怎么运行的

²Ɠxm Main link. Argument: n (integer)

² Yield n².

Ɠ Read and eval one line of input. This yields a string s.

x Repeat the characters of s in-place, each one n² times.

m Takes each |n|-th character of the result, starting with the first if n > 0,

the last if n < 0.

1

好吧,现在我真的很感动。我希望以微缩形式解释这个特殊的奇迹。

当然。一旦我做了一个测试套件并完成了打高尔夫球。

4

好的,如果您可以将其缩小,我将放弃尝试提出一个将使您> 10个字节的问题。

13

好,就是这样。我正在学习果冻。我也想做魔术。

2

我们都知道,关于果冻链的讨论最终会变成一团糟...

9

JavaScript(ES6),63个字节

以currying语法接受输入(s)(n)。

s=>n=>[...s].reduce((s,c)=>n<0?c.repeat(-n)+s:s+c.repeat(n),'')

测试用例

letf=s=>n=>[...s].reduce((s,c)=>n<0?c.repeat(-n)+s:s+c.repeat(n),'')console.log(f(`HelloWorld!`)(3))console.log(f(`foo`)(12))console.log(f(`String`)(-3))console.log(f(`Thisis a fun challenge`)(0))console.log(f(`HelloWorld!`)(2))

运行代码段隐藏结果

3

+1 reduce!

9

Python 3,44字节

f=lambdas,n:sands[0]*n+f(s[1:],n)+s[0]*-n

基本情况似乎忽略了最后一个字符。

不太确定为什么要这么做...谢谢!

1

41个字节。但是如果函数调用f(n,*s)被认为有效,则为idk

9

Python 2中,59个 57 50 46字节

-2个字节感谢Anders Kaseorg。-4个字节感谢Dennis。

lambdas,n:''.join(i*n**2foriins)[::nor1]

6

05AB1E,10个字节

S²Ä×J²0‹iR

S # Split the string into characters

²Ä× # Repeat each character abs(integer) times

J # Join into a string

²0‹i # If the integer is less than 0...

R # Reverse the string

TFW,您花了30分钟的时间来尝试向@Riley证明²0‹i并非最佳途径,并提出了0种选择。

@MagicOctopusUrn我以前使用过类似的东西²0‹i,我始终认为必须有更好的东西。

我想我现在已经尝试寻找大约10倍的替代方法...浪费了我一生的3个小时。Ä.D)øJ¹0‹iR是我最好的选择,我不会复制您,我认为您的状态已经优化。

如果您愿意的话,Emigna è 在这里使用过,尽管我找不到在这种情况下应用它的方法。如果那样的话,最多可以保存1个字节。

SÂΛ@²Ä×J,Î如果要更改顺序,可使用推送0并输入。节省1个字节!(还替换了if,因此它不需要关闭)

5

MATL,9个字节

y|Y"w0<?P

输入是:数字,然后是字符串。

带有换行符的字符串使用char输入10,如下所示:['first line' 10 'second line']。

说明

考虑输入-3和'String'。

y % Implicitly take two inputs. Duplicate from below

% STACK: -3, 'String', -3

| % Absolute value

% STACK: -3, 'String', 3

Y" % Run-length decoding

% STACK: -3, 'SSStttrrriiinnnggg'

w % Swap

% STACK: 'SSStttrrriiinnnggg', -3

0< % Less than 0?

% STACK: 'SSStttrrriiinnnggg', 1

? % If so

P % Flip

% STACK: 'gggnnniiirrrtttSSS'

% End (implicit). Display (implicit)

5

Haskell,41 36字节

f n|n<0=reverse.f(-n)|1<3=(

用法示例:f (-3) "abc"yields "cccbbbaaa"。

编辑: -5字节感谢xnor!

1

还有(

@xnor谢谢!很高兴知道。

5

V,29,23,18,17字节

æ_ñÀuñÓ./&ò

ÀäëÍî

十六进制转储:

00000000: e65f f1c0 75f1 d32e 2f26 f20a c0e4 ebcd ._..u.../&......

00000010: ee .

感谢@ nmjcman101保存了6个字节,这鼓励我再保存5个字节!

最初的修订版本非常糟糕,但是现在我真的为这个答案感到骄傲,因为它可以很好地处理负数。(V几乎没有数字支持,也没有负数支持)

说明:

æ_ " Reverse the input

ñ ñ " In a macro:

À " Run the arg input. If it's positive it'll give a count. If it's negative

" running the '-' will cause V to go up a line which will fail since we're

" on the first line, which will break out of this macro

u " (if arg is positive) Undo the last command (un-reverse the line)

Ó./&ò " Put every character on it's own line

此时,缓冲区如下所示:

H

e

l

l

o

w

o

r

l

d

!

重要的是不要尾随换行符,并且光标应位于其上。

À " Run arg again. If it's negative, we will move up a line, and then give the

" absolute value of the count. If it's positive (or 0) it'll just give the

" count directly (staying on the last line)

ä " Duplicate... (count times)

ë " This column.

Íî " Remove all newlines.

ya的一些字节在线尝试! 我一直很讨厌“负数意味着别的东西!” 边缘情况也是如此。在这种情况下,您0在V 中的特殊情况非常有用。

对不起,负数特殊。但是,许多答案设法将其纳入主要答案。尽管对这个V印象深刻。

@ nmjcman101哦,哇,这很明显,我不知道我是怎么想的。谢谢!

@狮phon哦,我知道。挑战很好,我只是不喜欢自己的语言,因为我对自己本该擅长的语言太不好了。:P

5

R,83 78 76字节

function(s,i)cat('if'(i<0,rev,`(`)(rep(el(strsplit(s,'')),e=abs(i))),sep='')

匿名函数。

弗雷德里克(Frederic)保存了3个字节,朱塞佩(Giuseppe)保存了2 4。

说明:

el(strsplit(s,'')) # split string into list characters

rep( ,e=abs(i))) # repeat each character abs(i) times

'if'(i<0,rev, ){...} # if i>0, reverse character list

`(` # otherwise leave it alone: `(` is the identity function

cat( ,sep='') # print the result

测试:

> f('Hello World!', 3 )

HHHeeellllllooo WWWooorrrlllddd!!!

> f('foo', 12)

ffffffffffffoooooooooooooooooooooooo

> f('String', -3)

gggnnniiirrrtttSSS

> f('This is a fun challenge', 0)

> f('Hello

+ World!', 2)

HHeelllloo

WWoorrlldd!!

2

做得好 !你可以节省写作几个字节rep(foo,,,3)或rep(foo,e=3)(同lenght);-)

@Frédéric你击败了我,我要说同样的话!

1

是的,没问题!基本上,我想摆脱大括号,所以我需要摆脱a=。因此,通过条件返回函数,我将aif 的值用作反向函数if i<0的参数(这就是为什么我需要反引号)。但是我还需要为i>=0案件应用身份功能,因此我使用了(足够接近的身份。(实际上是一个功能。R很奇怪。

1

顺便说一句,Paren的R文档说(在语义上等价于该身份function(x)x

4

05AB1E,10个字节

0‹FR}ʒ¹Ä×?

说明

0‹F # input_1 < 0 times do:

R # reverse input_2

} # end loop

ʒ # filter

¹Ä× # repeat current char abs(input_1) times

? # print without newline

4

PHP> = 7.1,65字节

for([,$s,$n]=$argv;$i

1

在整数上下文中,$n<0具有与相同的值,$n<0?:0但短3个字节:-)

4

([(({})())]<>)<>{({}())<>({}<>)<>>)<>}{}<>{}<>({})<>)>())>[()]})([][()])}{}{}<>>){{}{({}<>)<>}(<>)}{}

只是在这里给DJMcMayhem一些竞争。;)

说明

这是DJMcMayhem的解释的修改版本

#Compute the sign and negative absolute value

([(({}))]<>)<>{({}())<>({}<>)<>>)<>}{}<>{}<>

#Keep track of the sign

({}<

#For each char in the input string:

([][()])

{

{}

#Push n copies to the alternate stack

({)<>)>())>[()]})

#Endwhile

([][()])

}{}{}<>

#Push the sign back on

>)

#If so...

{{}

#Reverse the whole stack

{({}<>)<>}

#And toggle over, ending the loop

(<>)

}

#Pop the counter off

{}

4

J,19 15 13字节

(#~|)A.~0-@>]

说明

0-@>] NB. first or last index depending on sign of right arg

A.~ NB. get first or last Anagram of left arg

(#~|) NB. copy left arg, absolute-value-of-right-arg times

2

(#~|)A.~0-@>]13字节

很好@miles!

没问题。您也不需要计算用于调用动词的括号。

1

同样是13个字节:#~ ::(|.@#~|)

3

Dyalog APL,15个字节

{⌽⍣(⍵<0)⊢⍺/⍨|⍵}

字符串作为左参数,数字作为右参数。

怎么样?

⍺/⍨ -重复字符串

|⍵ -绝对次数

⌽⍣ -如果相反

(⍵<0) -数字低于0

嗯,如果TIO这样工作会很好吗?

@Gryphon,然后是字节...

是的,我刚刚意识到这一点,并且正在输入我的评论告诉您。

3

MATLAB,37个字节

@(s,n)flip(repelem(s,abs(n)),(n<0)+1)

这使用输入s:字符串和n:数字来定义和匿名函数。

示例运行:

>> @(s,n)flip(repelem(s,abs(n)),(n<0)+1)

ans =

@(s,n)flip(repelem(s,abs(n)),(n<0)+1)

>> f = ans;

>> f('String', 3)

ans =

SSStttrrriiinnnggg

>> f('String', -3)

ans =

gggnnniiirrrtttSSS

>> f('String', 0)

ans =

Empty matrix: 1-by-0

选择要翻转的尺寸要比我写的+1更好。我总是忘记repelem存在。

@StewieGriffin好吧,您也可以将其包含在您的答案中:-)(+ 1)。我想,有没有repelem现在在八度,对

3

(({}))){({}()({}<>)<>>)<>}{}([{}]<>)([][()]){{}({)<>)>[()])>()})([][()])}{}{}<>>)([({})](<>)){({}())<>}{}{(())<>{}}{}<>{}{{}{({}<>)<>}(<>)}{}

这可能是最糟糕的语言了,但是已经做到了。感谢@Wheatwizard提供了Haskell解释器,该解释器允许混合输入格式。如果没有它,则长度将增加约150个字节。

说明:

#Keep track of the first input (n)

(({})<

#Push abs(n) (thanks WheatWizard!)

(([({})]<>)){({}()({}<>)<>>)<>}{}([{}]<>)

#For each char in the input string:

([][()])

{

{}

#Push n copies to the alternate stack

({)<>)>[()])>()})

#Endwhile

([][()])

}{}{}<>

#Push the original n back on

>)

#Push n >= 0

([({})](<>)){({}())<>}{}{(())<>{}}{}<>{}

#If so...

{{}

#Reverse the whole stack

{({}<>)<>}

#And toggle over, ending the loop

(<>)

}

#Pop the counter off

{}

您可以使用我的52个字节的abs保存2个字节,也可以使用我给您的50个字节的-abs并递增而不是递减以保存6个字节。

3

s->n->{for(inti=s.length*(n<0?n:-n),r=n<0?0:~i;i++<0;)System.out.print(s[(i+r)/n]);}

-2个字节,感谢@Xanderhall

-2个字节,感谢@Nevay

无效的想法(更长的时间):将字符串反向,使用流,

1

使用s[(n<0?-l-~i:i)/n]

@Xanderhall谢谢!我一直在寻找那个眼睛,我的眼睛一直流血。我知道这是可能的,我只是在实施它时弄乱了一切。

1

@ user902383是的,这是强制性的。如果它们是可选的,那么很多事情将是不可读的。另外,我的功能不是“单个语句”,而是包含多个语句的for循环。

1

您可以通过增加icondition 来保存1个字节s->n->{for(int l=s.length*(n<0?-n:n),i=0;i++n->{for(int i=s.length*(n<0?n:-n),r=n<0?0:~i;i++<0;)System.out.print(s[(i+r)/n]);})进行迭代,可以保存另一个字节。

2

八度,49字节

@(s,n){t=repmat(s,abs(n),1)(:)',flip(t)}{2-(n>0)}

我明天将提供解释。

2

红宝石,59 +1 = 60字节

使用-n标志。

n=eval$_

a=$<.read>

a.reverse!ifn<0a.chars{|i|$><

1

eval$_短于$_.to_i1个字节。String#chars也可以以相同的方式接受阻止String#each_char。最后,在处理每个字符之前,请反转输入,以便可以直接打印(将标志切换为-n)。所有这些结合起来成为55 + 1 = 56字节。

2

木炭,16字节

Fθ¿‹η0F±Iη←ιFIηι

在线尝试!链接是详细版本的代码。说明:

Fθ For each character in the input string

¿‹η0 If the input number is less than zero

F±Iη Repeat the negation of the input number times

←ι Print the character leftwards (i.e. reversed)

FIη Otherwise repeat the input number times

ι Print the character

2

Japt,12个字节

®pVaìr!+sVg

说明

字符串U和整数的隐式输入V。

®pVaÃ

将(®)的每个字母U(隐含)映射到自身重复(p)abs(V)(Va)次。

¬r

将字符串转换为chars(¬)数组,并r用(... )减少它。

!+sVg

"!+".slice(sign(V))-通过+→ a + b或!+→ 减小b + a。

感谢@Arnauld提出的向后减少的想法!

我觉得£gY*Vg)pVa应该缩短解决方案的时间,但由于假期我的大脑已经关闭,所以我不太清楚。不过,您也许可以做一些事情。

2

<(s,x){<x?x>0n+=i:n=i+n/>n}

f("Hello World", -2) // returns ddllrrooWW oolllleeHH

说明(无高尔夫球):

let f => (s, x) {

let n = ""

for i : s

for j : 0->x

if x > 0 n += i

else n = i + n

ret n

}

2

C89字节

main(int c,char**v){for(;*v[1];v[1]++)for(c=atoi(v[2]+(*v[2]=='-'));c--;)putchar(*v[1]);}

我看到了本·佩林(Ben Perlin)的版本,想知道您是否还能再简短一点,并拥有完整的程序?当然,atoi()和putchar()不贵以字节为单位?看来我是对的!

2

Pyth,13 11字节

*sm*.aQdz._

-2个字节,感谢@jacoblaw

说明

*sm*.aQdz._

m z # map onto the input string (lambda var: d)

*.aQd # repeat the char d as often as the absolute value of the input number

s # sum the list of strings into a single string

* ._Q # Multiply with the sign of the implicit input value: reverse for negative Q

旧方法,13个字节

_W

您可以使用此反向逻辑保存两个字节

2

Python 3,68个字节

h=lambdas,n:h(s[::-1],-n)ifn<0elses[0]*n+h(s[1:],n)ifselses*n

您好,欢迎光临本站!不幸的是,此答​​案目前无效,因为它不支持负数。挑战说:If the integer is negative, we use its absolute value in the first step, and then reverse the string.

感谢您修复它!顺便说一句,您可以通过删除括号后的空格来减少两个字节)

编辑,感谢您的贡献

n<0 else=>n<0else

1

QBIC,32字节

g=sgn(c)[_l;||[:*g|?_sA,b*g,1|';

说明

Takes inputs A$ ('Hello'), and c (-3) from the cmd line

g=sgn(c) Save the sign of c -1

[_l;|| FOR each char in A$

[:*g| FOR the number of repetitions wanted (ie: -3 * -1)

Note that : reads a number from the cmd line, and c is the first

available variable to save it in after a and b got used as FOR counters.

Also note that a negative value times the sign becomes positive.

?_s PRINT a substring

A of A$

,b*g startng at char n, where n is the first FOR loop counter times the sign

That means that when c is negative, so is this. A negative starting index

on Substring instructs QBIC to take from the right.

,1| taking 1 char.

'; This bit injects a literal ; in the output QBasic, to suppress newlines om PRINT

1

Mathematica,89个字节

(T=Table;t=""<>T[s[[i]]~T~Abs@#2,{i,Length[s=Characters@#]}];If[#2>0,t,StringReverse@t])&

输入

[“ Hello World!”,3]

1

1-v{R.[v.R]v}R[v>R]v&@

嗯,还不错。

将输入作为整数和字符数组。

或者:

l1->[M]1-v&,{R.[v.R]v}R[v>R]v&@

将输入作为整数和字符串

1

C,109位元组

char *f(int n, char *s){char *o=calloc(n,strlen(s)+1),*t=o;while(*s){for(int i=n;i--;)*t++=*s;s++;}return o;}

从一个接受一个int和一个字符串并产生一个字符串的函数声明开始(似乎暗示内存没有被预先分配,必须创建),似乎直截了当的方法比我尝试过的任何切刀都短。

char *f(int n, char *s){

char *o=calloc(n, strlen(s)+1),

*t=o;

while (*s) {

for(int i=n; i--; )

*t++=*s;

s++;

}

return o;

}

这似乎不适用于负数n。

字符串乘以数字python_将字符串乘以数字!相关推荐

  1. 怎样组合数字python_利用python实现数字组合

    需求:假设让用户输入两次数字,第一次为12,第二次为34,实现的组合为13,14,23,24: 即第一次输入的每一个数字与第2次输入的每一个数字进行俩俩组合. num1 = input('请输入0-9 ...

  2. 字符串转二进制 python_将字符串转换为二进制

    我需要一些帮助把字符串转换成二进制.我必须使用我自己的代码,而不是内置函数(除了我可以使用'ord'将字符转换成十进制).在 我遇到的问题是它似乎只将第一个字符转换为二进制,而不是字符串的所有字符.例 ...

  3. python3 PIL模块 写入中文_英文_字符串 在图片中居中对齐【字符串包括中英文数字等】

    前言: 大家好我是最渣的黑客(宋哈哈),今天在写一个小脚本,让文字写到图片中,一个两个标题就可以手工用adobe 的 photoshop 就能解决,但是很多,就显得那么无力,当然也可以用 ps 的 数 ...

  4. 具有大写字母和数字的随机字符串生成

    我想生成一个大小为N的字符串. 它应该由数字和大写英文字母组成,例如: 6U1S75 4Z4UKK U911K4 我如何以pythonic方式实现这一目标? #1楼 如果您需要一个随机字符串而不是伪随 ...

  5. python123自定义幂函数_《python语言程序设计》_第三章(数字函数、字符串和对象)...

    3.2_常见的Python函数 (1) abs()函数 求绝对值 (2) max(x1,x2,x3,....)求最大值 (3) min(x1,x2,x3,....)求最小值 (4) pow 返回a的b ...

  6. python使用正则表达式删除字符串中的其它字符只保留数字和字母

    python使用正则表达式删除字符串中的其它字符只保留数字和字母 #python使用正则表达式删除字符串中的其它字符只保留数字和字母 # Python code to demonstrate # to ...

  7. python的四种内置数字类型_浅析Python数字类型和字符串类型的内置方法

    一.数字类型内置方法 1.1 整型的内置方法 作用 描述年龄.号码.id号 定义方式 x = 10 x = int('10') x = int(10.1) x = int('10.1') # 报错 内 ...

  8. 算法---给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合

    题目 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合.答案可以按 任意顺序 返回.给出数字到字母的映射如下(与电话按键相同).注意 1 不对应任何字母.示例 1:输入:digits ...

  9. android字符串获取数字索引,从字符串中提取特定数据(Extract specific data from a string)...

    从字符串中提取特定数据(Extract specific data from a string) 我有一个带有描述的长字符串. 我想从字符串中提取一些信息. 但我无法弄明白该怎么做. 这是字符串: C ...

最新文章

  1. Bitcoin.com推出BCH新图表,加大对BCH的支持
  2. POJ1195Mobile phones
  3. 解决 spring-cloud-starter-zipkin 启动错误
  4. Entityframework批量删除
  5. Kafka 优化参数 unclean.leader.election.enable
  6. HiveQL学习笔记(四):Hive窗口函数
  7. appenders_Log4j Appenders教程
  8. SVM支撑向量机原理
  9. selenium webdriver实战宝典 pdf_Selenium+webdriver爬虫技术实战之沃运维报表提取
  10. 正射影像、倾斜摄影测量相关软件汇总
  11. 计算机控制系统的框图,计算机控制系统原理框图.doc
  12. sklearn——一元线性回归
  13. android接口和type c对比,USB Type-C究竟比3.5mm音频接口好在哪里?
  14. 前端canvas图片压缩原理解析
  15. Git 常用回滚撤销命令总结
  16. img文件制作linux启动u盘,制作Linux的U盘启动盘
  17. 计算机电子贺卡制作圣诞节,圣诞电子贺卡制作方法
  18. 扩展点系列之ApplicationContextAwareProcessor普通类获取Spring Bean - 第433篇
  19. 如何对待新事物_以积极态度看待不断出现的新事物
  20. Self2Self With Dropout: Learning Self-Supervised Denoising From Single Image【使用单张图像进行自监督学习去噪】

热门文章

  1. IC-CAD IC 设计流程及 EDA 工具
  2. Python正则表达式中的转义问题\\\\\\\\\????(焯!什么鬼)
  3. mysql互为主从注意事项_MySQL互为主从复制常见问题
  4. 【人体骨骼点】gt构建
  5. js 中的 Event Loop 以及 宏任务 与 微任务
  6. The Unarchiver 4.1.0版本在苹果电脑系统10.15.6上解压xcode.xip有问题
  7. 命令行参数输入特殊字符
  8. C语言经典100题——求一个二维数组的鞍点
  9. 公务员面试紧张说错话要怎么补救?
  10. 【2021-09-22 修订】【梳理】计算机网络:自顶向下方法 附录一 物理层与通信基础