所以我需要创建一个函数,只使用一个返回值,将数字的平方加起来直到n。
我试过了:
import QtQuick 2.0
import QtLocation 5.5
Map {
id: map
plugin: Plugin {name: "osm"}
zoomLevel: (maximumZoomLevel - minimumZoomLevel)/2
center {
// The Qt Company in Oslo
latitude: 59.9485
longitude: 10.7686
}
MapQuickItem {
id:marker
sourceItem: Image{
id: image
source: "marker2.png"
}
coordinate: map.center
anchorPoint.x: image.width / 2
anchorPoint.y: image.height / 2
}
MouseArea {
anchors.fill: parent
onPressed: {
marker.coordinate = map.toCoordinate(Qt.point(mouse.x,mouse.y))
}
}
}
出现错误: from functools import reduce
def soma_quadrados(n):
return sum(list(reduce(lambda x: x**2, list(range(1,n+1)))))
我也试过
lambda () takes 1 positional argument but 2 were given
出现错误: return sum(list(reduce(lambda x: x**2, n)))
我该怎么办? 提前致谢
答案 0 :(得分:3)
reduce()
传递两个参数:到目前为止累积的结果和下一个值。您的lambda
不接受结果参数(第一个)。
如果要生成所有正方形的总和,请将sum()
与生成器表达式一起使用:
sum(i ** 2 for i in range(1, n + 1))
或使用map()
将整数映射到它们的正方形来代替生成器表达式:
sum(map(lambda i: i ** 2, range(1, n + 1)))
如果您必须使用reduce()
,请将其加总:
reduce(lambda r, i: r + i ** 2, range(1, n + 1), 0)