r - 缺少 x 没有默认值。在 R 中的函数内调用函数
问题描述
我正在使用从 YouTube 找到的视频编写代码来解决数独难题,该视频通过 Python 编写了相同的算法。这段代码需要三个函数
- 找一个空方格。
- 在空方格中插入一个数字。
- 测试这个数字是否有效以解决难题。
这是对求解器使用回溯算法。
一起调用函数时遇到问题,出现错误:
Error in free_squ(x) : argument "x" is missing, with no default
In addition: Warning message:
In if (empty_sq == FALSE) { :
the condition has length > 1 and only the first element will be used
Called from: free_squ(x)
这很令人困惑,因为我只有在运行此代码时才会得到它。所以我可以编写其他函数来调用各个函数来分析插入到上层函数中的参数:
function1(argument){
function2(argument){
function3(argument){
***DO STUFF***}}}
为什么对于以下代码,主函数中的函数无法识别参数?
sudoku_solve <- function(x){
empty_sq <- free_squ(x) # Define a new object to give coordinates of empty square
if(empty_sq == FALSE){ # If no empty square can be found
return(x) # Return the matrix
} else{
empty_sq <- empty_sq # Pointless line kept for clarity
}
for(i in c(1:9)){ # Integers to insert into the found empty square
if(valid(x, i, empty_sq) == TRUE){ # can the intiger be placed in this square?
x[empty_sq[1], empty_sq[2]] = i # if i valid, insert into empty square
}
if(sudoku_solve()){ # are all i's valid?
return(TRUE) # All i's valid
} else{
x[empty_sq[1], empty_sq[2]] = 0 # reset the initial try and try again with another
}
}
return(FALSE)
}
我已将数独拼图命名为“拼图”,并通过以下方式调用该函数:
sudoku_solve(puzzle)
解决方案
我认为在以下语句中,您没有将任何值传递给函数,并且 x 也没有默认值。
if(sudoku_solve()){ # are all i's valid?
return(TRUE) # All i's valid
}
因此,虽然参数最初是传递的,但在循环之后再次调用该函数时,它会在没有参数的情况下调用。所以你在 sudoku_solve() 中传递给 free_sq(x),它给出了一个错误。
empty_sq <- free_squ(x)
确保将值传递给 sudoku_solve 或在 sudoku_solve 或 free_squ 类/函数中设置 x wither 的默认值。
推荐阅读
- python - 我可以在 Flask 应用程序中使用 python3 类吗?
- python - 我的验证和训练损失不断增加,我是否过度简化了我的网络?
- c - 无法在 C 中打印多行字符串
- r - 从列表中获取计数数据后创建二进制矩阵文件
- python - 与 pygame.sprite.spritecollide() 的敌人碰撞
- mysql - Laravel 从一张表中选择价格最低的独特产品
- powershell - 重命名文件以使用 Powershell 匹配第二个文件夹中的文件
- wordpress - Word Press(终极会员)如何重新排列登录和注册页面中的按钮顺序
- css - 如何增加表格宽度
- pointers - pre ANSI-C“0 指针”应该如何用 ANSI C 编写?