You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python菱形图案函数需返回结果而非打印,求修改方案

Fixing Your Diamond Function to Return the Pattern Instead of Printing

No problem at all! The main issue with your current code is that it uses print() to output each line directly. To return the pattern instead, we just need to collect all the lines into a list (or build a single string) and then return that collection joined with newline characters.

Here's the revised code that does exactly that:

def diamond(num):
    # Initialize a list to hold each line of the diamond
    lines = []
    a = 1
    b = int((num - 1) / 2)
    c = num - 2
    d = 1

    # Upper half of the diamond (excluding middle line for odd num)
    for i in range(0, int((num - 1) / 2)):
        lines.append(" " * b + a * "*")
        a += 2
        b -= 1

    # Middle line(s) - handle odd and even cases
    if num % 2 == 1:
        lines.append("*" * num)
    else:
        lines.append("*" * (num - 1))
        lines.append("*" * (num - 1))

    # Lower half of the diamond
    c = num - 3 if num % 2 == 0 else num - 2
    d = 1
    for i in range(0, int((num - 1) / 2)):
        lines.append(" " * d + c * "*")
        c -= 2
        d += 1

    # Join all lines with newlines and return the final string
    return '\n'.join(lines)

How it works:

  • We use a list lines to store each line of the diamond instead of printing immediately. This is more efficient than string concatenation in loops.
  • Everywhere you had print(...), we now do lines.append(...) to add the line to our list.
  • Finally, we join all the lines with '\n' (newline characters) to create a single string that represents the entire diamond, then return that string.

Example usage:

If you want to see the output, you can call the function and print the result:

print(diamond(5))

This will output:

*
 ***
*****
 ***
  *

And for an even number like diamond(4):

**
 **
  *

内容的提问来源于stack exchange,提问作者juyong Lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:16:46