我想创建一个函数,打印以下序列的n行
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
...
这是我目前为止写的:
def numTriangle(n):
#n = number of rows
integers = range(0,n-1)
val = 1
places = 1
for num in integers:
print val
val = val + 1
我已经意识到我需要创建一个循环,它打印值,然后添加1,但也创建一个比前一个大1的新变量,并打印原始值+ 1和新变量,等等。如何为每行创建一个新变量,或者该函数是否有其他替代方案,例如为每行打印索引的附加部分?
我不想帮你做功课,但至少你对你的计划有一个基本的描述。这是一个非常简单的版本。
def pyramid(n):
k = 1
for i in range(n):
print ' '.join(map(str, range(k, k+i+1)))
k += i + 1
这是一个更详细的版本。
def pyramid(n):
k = 1
for i in range(1, n +1):
first_number = k
next_row_first_number = k + i
numbers = range(first_number, next_row_first_number)
numbers_as_strings = map(str, numbers)
line = ' '.join(numbers_as_strings)
print line
k = next_row_first_number
和多个循环!
def pyramid(n):
k = 1
for i in range(1, n +1):
first_number = k
next_row_first_number = k + i
numbers = range(first_number, next_row_first_number)
line = ""
for num in numbers:
line = line + str(num) + ' '
print line
k = next_row_first_number
输出:
n = 6; y= 1;
for i in range(0,n):
for j in range (0,i):
print y,
y = y+1;
print "n"
注意缩进,缩进定义了范围