递归行星号Python程序

时间:2015-04-23 13:22:03

标签: python

程序应在屏幕上用第一行打印星号 包含一个星号,第二行包含2个星号,直到第n个 包含n个星号的行。

这是我到目前为止所拥有的,但有更简单的方法吗?我想使用if / else,但无法使其发挥作用。

def show_asterisks(n):
    if (n > 0):
        show_asterisks(n-1)
    num = n
    str = ''
    while (num > 0):
        str += '*'
        num -= 1
        print(str)

有更好的方法吗?谢谢你的帮助!

3 个答案:

答案 0 :(得分:1)

不需要递归,但是如果你想......

此解决方案基于以下事实:Python序列(包括字符串)可以乘以正整数。

assert [1, 2] * 2 == [1, 2, 1, 2]
assert "qwe" * 3 == "qweqweqwe"

解决方案很简单:

def print_asterisks(n):
    if (n > 1):
        print_asterisks(n-1)
    print "*" * n

答案 1 :(得分:1)

由于您希望星号线增加

作为行号=打印的星号数

def a(i, n):
    if i > n:  # check if we reached the end  and prevent infinite recursion
        return

    print(i*'*')
    a(i+1, n)  # call the function recursively with an incremented line number   


a(1,3) # (start linenumber, end linenumber)

给出

*
**
***

答案 2 :(得分:0)

python中最简单的方法是使用循环和字符串乘法运算符

def show_asterisks(n):
    if n>1: # >0 is redundant!
        show_asterisks(n-1)
    print('*' * n) 

递归是类似的

Mapper.CreateMap<MySourceType, MyDestinationType>();
相关问题