【发布时间】:2016-02-16 20:59:18
【问题描述】:
我的问题是关于 Udacity 作业中的一些代码。以下代码不返回任何值。我假设我没有从我的“标准化”函数中正确调用“标量”函数。 norm = self.scalar(scale) 行返回无类型。谁能给我指点一下?
代码:
import math
from decimal import Decimal, getcontext
getcontext().prec = 10
class Vector(object):
def __init__(self, coordinates):
try:
if not coordinates:
raise ValueError
self.coordinates = tuple([Decimal(x) for x in coordinates])
self.dimension = len(self.coordinates)
except ValueError:
raise ValueError('The coordinates must be nonempty')
except TypeError:
raise TypeError('The coordinates must be an iterable')
def __eq__(self, v):
return self.coordinates == v.coordinates
def scalar(self, c):
new_coordinates = [Decimal(c)*x for x in self.coordinates]
#new_coordinates = []
#n = len(self.coordinates)
#for i in range(n):
# new_coordinates.append(self.coordinates[i] * c)
#print(Vector(new_coordinates))
def magnitude(self):
new_sq = [x**2 for x in self.coordinates]
new_mag = math.sqrt(sum(new_sq))
return (new_mag)
def normalized(self):
magnitude = self.magnitude()
scale = 1/magnitude
print(scale)
norm = self.scalar(scale)
#print(type(norm))
print(norm)
return (norm)
my_vector = Vector([1,2])
Vector.normalized(my_vector)
【问题讨论】:
-
嗯,标量方法中有return语句吗?
-
这是合法的进口方式吗?这可能不是您的问题的根源,但不应该是:
import math在一行上,from decimal import Decimal, getcontext在另一行上? -
@Igor 我认为这是一个复制粘贴问题,它可能应该是
import math; from decimal import ..其中;是换行符 -
@NickHumrich 这是因为 Blckknght 试图修复导致代码的顶部和底部部分没有被格式化的格式问题。由于作者没有以两个空格结束他们的代码行,这意味着它们之间插入了一个空格而不是换行符。
-
@GarethPW 我修正了格式
标签: python python-3.x nonetype