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

如何修改Python代码将倒序哈希三角形改为正序输出

实现递增哈希三角形的代码修改方案

给定的line函数

def line(num=int, word=str):
   if word == "":
       print("*" * num)
   else:
       print(word[0] * num)

现有代码

def line(num=int, word=str):
    if word == "":
        print("*" * num)
    else:
        print(word[0] * num)

def triangle(size):
    # You should call function line here with proper parameters
    
    while size > 0:
        
        line(size, "#")
        size -= 1

当前输出

######
#####
#### 
###  
##   
# 

期望输出

#
##
###
####
#####
######

修改方案

问题核心是循环方向错误:当前代码从size递减到1,导致输出从最长到最短。要实现递增效果,需从1开始循环到指定的size。

修改后的triangle函数(while循环版)

def triangle(size):
    current = 1
    while current <= size:
        line(current, "#")
        current += 1

更简洁的for循环版

def triangle(size):
    for current in range(1, size + 1):
        line(current, "#")

修改后,每次调用line时传入的num参数从1逐步递增到size,即可输出符合预期的递增哈希三角形。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 11:26:12