![](/img/trans.png)
[英]Why the insert method of list does not work correctly in my recursion?
[英]Why does my recursion work in Swift but not Python?
我是 Swift 母语人士,我很难理解为什么我的算法在翻译成 Python 时不起作用。
在 Python 中运行时,它永远不会将 x 或 y 值重置为零。 例如,输入 4 应该给出 (2, 0),但在 python 版本中它返回 (2, 1)。
在 Swift 中:
func position(from index: Int, gridSize: Int = 32) -> (x: Int, y: Int) {
if index < 0 {
return (-1, -1)
}
if gridSize < 1 {
return (0, 0)
}
let localIndex = Int((Float(index) / Float(gridSize * gridSize)) * 4)
let qx = localIndex % 2
let qy = localIndex / 2
let halfGrid = gridSize / 2
var x = qx * halfGrid
var y = qy * halfGrid
let nextIndex = Int(index - localIndex * halfGrid * halfGrid)
let (nextX, nextY) = position(from: nextIndex, gridSize: gridSize / 2)
x += nextX
y += nextY
return (x, y)
}
在 Python 中:
def posFromIndex(index, grid):
if index < 0:
return -1, -1
if grid < 1:
return 0, 0
localIndex = int((index / float(grid * grid)) * 4)
qx = localIndex % 2
qy = localIndex / 2
hg = grid / 2
x = qx * hg
y = qy * hg
nextIndex = int(index - localIndex * hg * hg)
nextX, nextY = posFromIndex(nextIndex, grid / 2)
x += nextX
y += nextY
print(x, y)
return int(x), int(y)
The reason is that these kinds of integer divisions gridSize / 2
in Swift return intergers, but in Python grid / 2
returns a float, even though grid
is an integer.
如果在 Python 中使用类似的 integer 除法,则需要使用//
运算符。
如果您更正该错误(并为grid
参数添加默认值,您将正确获得 output (2, 0)
的输入4
:
def posFromIndex(index, grid = 32):
if index < 0:
return -1, -1
if grid < 1:
return 0, 0
localIndex = int(index / (grid * grid) * 4)
qx = localIndex % 2
qy = localIndex // 2
hg = grid // 2
x = qx * hg
y = qy * hg
nextIndex = index - localIndex * hg * hg
nextX, nextY = posFromIndex(nextIndex, grid // 2)
x += nextX
y += nextY
return x, y
print(posFromIndex(4))
Output:
(2, 0)
请注意,您还可以通过从中删除一堆不必要的转换来简化 function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.