如何扭转彼此嵌套的循环?

发布于 2025-02-03 07:17:57 字数 307 浏览 5 评论 0原文

存在一个字符串s =“ abcd”,

如何通过字符串迭代其索引产生以下输出:

3
32
321
3210

我编写了以下代码:

for i in reversed(range(len(s))):
    for j in range(i, -1, -1):
        print(j, end='')
    print()

它给了我输出:

3210
210
10
0

如何实现所需的输出?

There exists a string s = "abcd"

How do I iterate through the string such that it produces the following output for its index:

3
32
321
3210

I have written the following code:

for i in reversed(range(len(s))):
    for j in range(i, -1, -1):
        print(j, end='')
    print()

It gives me the output:

3210
210
10
0

How do I achieve the desired output?

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

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

发布评论

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

评论(1

故人爱我别走 2025-02-10 07:17:57

考虑解决逆问题:

0
01
012
0123

该解决方案似乎很容易,而产生结果的唯一更改是从len(s)-1 -1中减去。

s = "abcd"
for i in range(len(s)):
    for j in range(i+1):
        print(len(s)-j-1, end='')
    print()

Think about solving the inverse problem:

0
01
012
0123

That solution seems pretty easy, and the only change to produce your result is subtracting from len(s)-1.

s = "abcd"
for i in range(len(s)):
    for j in range(i+1):
        print(len(s)-j-1, end='')
    print()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文