所以,我在麻省理工学院开放式课程计算机科学与编程导论中解决了这个问题:
Problem #2
Implement the compute_deriv function. This function computes the derivative
of a polynomial function. It takes in a tuple of numbers poly and returns
the derivative, which is also a polynomial represented by a tuple.
def compute_deriv(poly):
"""
Computes and returns the derivative of a polynomial function. If the
derivative is 0, returns (0.0,).
Example:
>>> poly = (-13.39, 0.0, 17.5, 3.0, 1.0) # x4 + 3.0x3 + 17.5x2 - 13.39
>>> print compute_deriv(poly) # 4.0x3 + 9.0x2 + 35.0x
(0.0, 35.0, 9.0, 4.0)
poly: tuple of numbers, length > 0
returns: tuple of numbers
"""
# TO DO ...
这是我的程序(它有效):
def compute_deriv(poly):
derivatives=()
for i in poly:
if list(poly).index(i)==0: #my version is 2.5.4, so I cannot use
continue #tuple.index(i) and since I didn't
else: #find another way, I converted the
deriv=i*list(poly).index(i) #tuple to a list
derivatives=derivatives+(deriv,)
return derivatives
polyx=(-13.39, 0.0, 17.5, 3.0, 1.0)
print compute_deriv(polyx)
polyxx=(1.3, 7.0, 4.0, 2.5, 0.0, -8.0)
print compute_deriv(polyxx)
首先,我希望程序让我输入多项式而不是在其中写入:
...
polyx=tuple(raw_input("Enter your polynomial tuple here:"))
print compute_deriv(polyx)
但这不起作用:
Enter your tuple here:-13.39, 0.0, 17.5, 3.0, 1.0
('1', '33', '...', '33', '99999', ',,,,,,', ' ', '00000000', '...',
'00000000', ',,,,,,', ' ', '1', '77777777777777', '...',
'5555555555555555', ',,,,,,', ' ', '33', '...', '00000000', ',,,,,,',
' ', '1', '...', '00000000')
为什么呢? 另一个问题是第二个元组(-8x ^ 5 + 2.5x ^ 3 + 4x ^ 2 + 7x + 1.3) - 当它的成员分别是(1.3,7.0,4.0,2.5,0.0,-8.0)时,它按预期返回 - (7.0,8.0,7.5,0.0,-40.0),但如果第一个成员为0.0(如在-8x ^ 5 + 2.5x ^ 3 + 4x ^ 2 + 7x中),则会发生变化 - (7.0, 8.0,7.5,-40.0)。第二个0.0被省略了,这是一个问题,因为它意味着当它为4时-40.0的功率为3。再次,为什么?
感谢您的时间!
答案 0 :(得分:2)
raw_input
会将您的输入转换为字符串。因此,输入-13.39, 0.0, 17.5, 3.0, 1.0
将产生一个字符串。
然后将其转换为元组。默认情况下,当给定一个字符串时,tuple
将拆分字符串中的每个字符并形成一个包含所有字符的元组。例如:
tuple("Hello World")
输出:('H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd')
这就是你得到这些结果的原因。可能的解决方案:输入以逗号','
分隔的元组,然后将其拆分:
polyx = tuple(raw_input("Enter your polynomial tuple here: ").split(","))
示例:
Enter your polynomial tuple here: -13.39,0.0,17.5,3.0,1.0
输出:(u'-13.39', u'0.0', u'17.5', u'3.0', u'1.0')
请注意,此元组将包含字符串,而不是浮点数。你需要转换它们:
polyx = tuple(float(x) for x in raw_input("Enter your polynomial tuple here: ").split(","))
示例:
Enter your polynomial tuple here: -13.39, 0.0, 17.5, 3.0, 1.0
输出:(-13.39, 0.0, 17.5, 3.0, 1.0)
答案 1 :(得分:-1)
这不是导致你麻烦的元组行为,而是raw_input()
的行为。
>>> polyx=tuple(raw_input("Enter your polynomial tuple here:"))
Enter your polynomial tuple here:-13.39, 0.0, 17.5, 3.0, 1.0
>>> polyx
('-', '1', '3', '.', '3', '9', ',', ' ', '0', '.', '0', ',', ' ', '1', '7', '.', '5', ',', ' ', '3', '.', '0', ',', ' ', '1', '.', '0')
您可以使用input()
代替:
>>> polyx=tuple(input("Enter your polynomial tuple here:"))
Enter your polynomial tuple here:-13.39, 0.0, 17.5, 3.0, 1.0
>>> polyx
(-13.39, 0.0, 17.5, 3.0, 1.0)
但这被认为是不安全的(也许不在这里,但总的来说)。另一种选择是自己解析输入行。