在 Mathematica 中创建可变长度的空格字符串

发布于 2024-11-08 20:32:59 字数 157 浏览 0 评论 0原文

以下 Mathematica 函数 f 创建一个长度为 n 的空白字符串。

f[n_]:=Fold[StringJoin,"",Array[" "&,n]]

必须有无数种替代方案来创建此功能。

你会怎么做呢?

The following Mathematica function f creates a string of whitespace of length n.

f[n_]:=Fold[StringJoin,"",Array[" "&,n]]

There must be a zillion alternatives to create this function.

How would you have done it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

穿越时光隧道 2024-11-15 20:32:59
f[n_] := StringJoin @ ConstantArray[" ", n]

编辑:由于@与@@一样惯用,并且速度更快(感谢Mr.Wizard进行基准测试)并且更短,因此我更新了解决方案。

f[n_] := StringJoin @ ConstantArray[" ", n]

Edit: since @ is as idiomatic as @@ and a bit faster (thanks to Mr.Wizard for benchmarking) and shorter i updated the solution.

败给现实 2024-11-15 20:32:59
f[n_] := FromCharacterCode[ConstantArray[32, {n}]]

顺便说一句:您应该知道 faq 中不赞成这种类型的问题:

我不应该在这里问什么样的问题?

你应该只问实用的,
根据实际情况回答问题
您面临的问题。健谈,
开放式问题减少了
我们网站的实用性并推动其他
头版上的问题。到
防止你的问题被
已标记并可能已删除,请避免
提出主观问题……

<前><代码>1。每个答案都同样有效:“你最喜欢什么______?”

如果问题已结束,请不要感到惊讶。

f[n_] := FromCharacterCode[ConstantArray[32, {n}]]

By the way: you should be aware that this type of question is frowned upon in the faq:

What kind of questions should I not ask here?

You should only ask practical,
answerable questions based on actual
problems that you face. Chatty,
open-ended questions diminish the
usefulness of our site and push other
questions off the front page. To
prevent your question from being
flagged and possibly removed, avoid
asking subjective questions where …

1. every answer is equally valid: “What’s your favorite ______?”

Don't be surprised if the question is closed.

寄离 2024-11-15 20:32:59
f[n_] := StringJoin[Table[" ", {n}]]
f[n_] := StringJoin[Table[" ", {n}]]
盛装女皇 2024-11-15 20:32:59

SpacerInvisible 对于创建空白也很有用,只是指定空格大小的方式有所不同。

Spacer and Invisible are also be useful for creating whitespace, with differences in how you specify the size of the space.

情感失落者 2024-11-15 20:32:59
f = ConstantArray[" ", #] <> "" &;

这大约是 Thies Heidecke 函数的两倍,但远不及 Sjoerd 函数快。


对于较大的n,较长的初始字符串会很有帮助。这比 Sjoerd 的 n > 方法更快。 10000 :

f2ss = " "~ConstantArray~499 <> "";
f2[n_ /; n < 500] := StringTake[f2ss, n]
f2[n_ /; n < 5000] := StringTake[ConstantArray["          ", ⌈n/10⌉] <> "", n]
f2[n_] := StringTake[ConstantArray[f2@400, ⌈n/400⌉] <> "", n]
f = ConstantArray[" ", #] <> "" &;

This is about twice as fast as Thies Heidecke's function, but not nearly as fast as Sjoerd's.


For large n a longer initial string is helpful. This is faster than Sjoerd's method for n > 10000:

f2ss = " "~ConstantArray~499 <> "";
f2[n_ /; n < 500] := StringTake[f2ss, n]
f2[n_ /; n < 5000] := StringTake[ConstantArray["          ", ⌈n/10⌉] <> "", n]
f2[n_] := StringTake[ConstantArray[f2@400, ⌈n/400⌉] <> "", n]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文