所以我正在制作Pascal的三角形,我无法弄清楚为什么这段代码不起作用。它打印出类似这样的东西
[]
[1]
[1, 2]
[1, 3, 3]
[1, 4, 6, 4]
[1, 5, 10, 10, 5]
[1, 6, 15, 20, 15, 6]
[1, 7, 21, 35, 35, 21, 7]
[1, 8, 28, 56, 70, 56, 28, 8]
[1, 9, 36, 84, 126, 126, 84, 36, 9]
这几乎是正确的,但似乎值似乎是行数太高,所以1,2,如果你计算2作为第一行而1作为第0行,2是1值太高,因为它在第一行,它应该是1,1。下一行应该是1,2,1,第一个值是正确的但下一个值是1值太高而后一个值是2个值太高。
我尝试过像append(a-i)这样的东西,但似乎不起作用,你怎么能正确打印呢?
def triangle(rows):
for rownum in range (rows):
newValue=1
PrintingList = list()
for iteration in range (rownum):
newValue = newValue * ( rownum-iteration ) * 1 / ( iteration + 1 )
PrintingList.append(int(newValue))
print(PrintingList)
print()
提前致谢。
答案 0 :(得分:10)
我会将PrintingList = list()
更改为PrintingList = [newValue]
。
triangle(10)
然后会给您以下内容:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
这是一个有效的Pascal三角形。
答案 1 :(得分:2)
我的代码下面有一些打印语句,可以帮助显示它是如何工作的。我在IPython笔记本中运行它。我的输出如下:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
除了输出看起来应该如此之外,计算方法实际上遵循Pascal三角形的原始定义,其中每一行都是从上面的那一行构建的。 (有些方法使用组合/因子,这可能会给出正确答案,但不要遵循帕斯卡尔三角形的原始精神。)
以下是代码:
def MakeTriangle(numberOfRows):
"""the print statements are not required. They are just to help see how it works."""
triangle=[[1]] #base case (i.e., 0th row)
print 'triangle[-1] is ', triangle[-1]
for _x in range(numberOfRows - 1): #_x isn't used
zipperd = zip([0] + triangle[-1], triangle[-1] + [0])
print "zipperd: ", zipperd
newRow = map(sum, zipperd)
triangle.append(list(newRow))
print 'triangle[-1] is ', triangle[-1] #to help see how tri is built
print "\n\n"
return triangle
for row in MakeTriangle(5):
print('{0:^50}'.format(row))
要开始了解其工作原理,请注意上述函数zip
和map
的以下简单案例:
x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
print zipped #output is [(1, 4), (2, 5), (3, 6)]
print map(sum, zipped) #output is [5, 7, 9]
使用MakeTriangle函数中的print语句,您将获得此输出以帮助您进一步了解代码的工作原理:
triangle[-1] is [1]
zipperd: [(0, 1), (1, 0)]
triangle[-1] is [1, 1]
zipperd: [(0, 1), (1, 1), (1, 0)]
triangle[-1] is [1, 2, 1]
zipperd: [(0, 1), (1, 2), (2, 1), (1, 0)]
triangle[-1] is [1, 3, 3, 1]
zipperd: [(0, 1), (1, 3), (3, 3), (3, 1), (1, 0)]
triangle[-1] is [1, 4, 6, 4, 1]
在查看此输出时阅读下面的文档,它将开始有意义:
如果它仍然没有意义,请将这些打印语句粘贴在MakeTriangle的for
循环中:
print "[0] + triangle[-1] is ", [0] + triangle[-1]
print "triangle[-1] + [0] is ", triangle[-1] + [0]
请注意,使用http://docs.python.org/2/library/string.html#format-examples中的示例完成对齐(居中)打印。
答案 2 :(得分:1)
我收到错误但你应该尝试这样的事情:
row1 = whatever
pascal = [[row/(colum*(row-colum) for row in range(0, colum)] for row in range(1, row1)]]
答案 3 :(得分:0)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");