作为我对学习Python的兴趣的一部分,我在遇到一个表明:
的练习时停了下来。考虑表达式(1 + x + x ^ 2)^ n并编写一个程序 计算修改后的Pascal三角形(称为三项式) 三角形)用于其扩展系数。你能想出来吗? 一个简单的规则(并证明它有效!),这将使你能够 记下这个三角形的系数?
所以,我试图编写一个从用户输入中打印出trinomial triangle的代码。这是我到目前为止的代码:
class ViewController: UIViewController {
var people: [Person] = []
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let context = appDelegate.persistentContainer.viewContext
let fetchRequest: NSFetchRequest<Person> = Person.fetchRequest()
people = try? context.fetch(fetchRequest)
}
}
返回
import math
rows = 0 #We count how many rows we print
#We define a function that will calculate the triangle.
def calc(n, r):
if r == 0 or r == n:
return 1
return int(math.pow(1 + r + math.pow(r, 2), n))
#We define a function that append the values in an array.
def triangle(rows):
result = [] #We need an array to collect our results.
for count in range(rows): #For each count in the inputted rows
row = [] #We need a row element to collect the rows.
for element in range(count + 1):
#We add the function calculation to the row array.
row.append(calc(count, element))
#We add the row(s) to the result array.
result.append(row)
return result
number = int(input("How many rows do you want printed? "))
#We can now print the results:
for row in triangle(number):
rows += 1 #We add one count to the amount of rows
print("Row %d: %s" % (rows, row)) #Print everything
据我了解,预期结果应为:
How many rows do you want printed? 5
Row 1: [1]
Row 2: [1, 1]
Row 3: [1, 9, 1]
Row 4: [1, 27, 343, 1]
Row 5: [1, 81, 2401, 28561, 1]
我不知道如何从这里开始。任何建议指出我正确的方向将不胜感激。
答案 0 :(得分:1)
在Pascal三角形的通常二项式版本中,我们可以通过在其上方添加两个条目来计算连续的每个值。在三项式版本中,我们添加了三个条目。证明这一点并不难,所以我会让你弄明白。 ;)
这是在Python中实现这一目标的一种方法。
row = [1]
for i in range(8):
print(row)
row = [sum(t) for t in zip([0,0]+row, [0]+row+[0], row+[0,0])]
<强>输出强>
[1]
[1, 1, 1]
[1, 2, 3, 2, 1]
[1, 3, 6, 7, 6, 3, 1]
[1, 4, 10, 16, 19, 16, 10, 4, 1]
[1, 5, 15, 30, 45, 51, 45, 30, 15, 5, 1]
[1, 6, 21, 50, 90, 126, 141, 126, 90, 50, 21, 6, 1]
[1, 7, 28, 77, 161, 266, 357, 393, 357, 266, 161, 77, 28, 7, 1]
答案 1 :(得分:-1)
为了使我想显示的线显示为例如收入2,我只向我显示了三角形的第二条线1 1 1