提问人:Rakesh Nandi 提问时间:6/24/2023 最后编辑:PhilRakesh Nandi 更新时间:6/25/2023 访问量:60
将 python 函数转换为 r 函数
Convert a python function to a r function
问:
我在 python 中定义了一个带有输入的函数
nodes=['A7', 'A9', 'A6', 'A1', 'A3', 'A4', 'A5', 'A8', 'A2']
graph={'A7': ['A8', 'A9', 'A6', 'A5'],
'A9': ['A8', 'A5', 'A4', 'A7'],
'A6': ['A7', 'A3', 'A5', 'A8', 'A2'],
'A1': ['A3', 'A4', 'A2'],
'A3': ['A6', 'A1', 'A4', 'A5'],
'A4': ['A9', 'A3', 'A1', 'A5'],
'A5': ['A7', 'A9', 'A6', 'A3', 'A4'],
'A8': ['A7', 'A9', 'A6', 'A2'],
'A2': ['A8', 'A6', 'A1']}
start = 'A9'
end = ['A1']
max_depth=5
def get_all_best_routes(graph,start,end,max_depth):
past_path = []
# maintain a queue of paths
queue = []
# push the first path into the queue
queue.append([start])
while queue:
# get the first path from the queue
path = queue.pop(0)
# get the last node from the path
node = path[-1]
# path found
# print "*"
# enumerate all adjacent nodes, construct a new path and push it into the queue
for adjacent in graph.get(node, []):
new_path = list(path)
## end the current loop if we already reach the point
if adjacent in end:
new_path.append(adjacent)
past_path.append(new_path)
continue
if adjacent in new_path:
continue
new_path.append(adjacent)
if len(new_path) >= max_depth and new_path[-1] not in end:
break
# print new_path
queue.append(new_path)
past_path.append(new_path)
best_paths = []
for l in past_path:
if l[-1] in end:
best_paths.append(l)
return best_paths
代码的步骤已经在 python 代码的取消注释行中进行了描述。 我正在尝试用 r 代码编写这个 python 函数,输入如下
# Define the nodes and graph
node <- list("A9", "A8", "A4", "A5", "A7", "A2", "A6", "A1", "A3")
graph <- list()
graph[["A9"]] <- list("A8", "A4", "A5", "A7")
graph[["A8"]] <- list("A2", "A6", "A7", "A9")
graph[["A4"]] <- list("A5", "A9", "A1", "A3")
graph[["A5"]] <- list("A3", "A6", "A7", "A9", "A4")
graph[["A7"]] <- list("A6", "A8", "A9", "A5")
graph[["A2"]] <- list("A8", "A1", "A6")
graph[["A6"]] <- list("A2", "A8", "A3", "A5", "A7")
graph[["A1"]] <- list("A2", "A3", "A4")
graph[["A3"]] <- list("A4", "A6", "A1", "A5")
max_depth <- 5
start <- "A9"
end <- c("A1")
我试过了
get_all_best_routes <- function(graph, start, end, max_depth) {
past_path <- list()
queue <- list()
queue[[1]] <- list(start)
while (length(queue) > 0) {
path <- queue[[1]]
queue <- queue[-1]
node <- tail(path, 1)
for (adjacent in graph[names(graph) %in% node]) {
new_path <- list(path)
if (adjacent %in% end) {
new_path <- c(new_path, adjacent)
past_path <- c(past_path, list(new_path))
next
}
if (adjacent %in% new_path) {
next
}
new_path <- c(new_path, adjacent)
if (length(new_path) >= max_depth && !(new_path[length(new_path)] %in% end)) {
break
}
queue <- c(queue, new_path)
past_path <- c(past_path, new_path)
}
}
best_paths <- list()
for (l in past_path) {
if (l[length(l)] %in% end) {
best_paths <- c(best_paths, l)
}
}
return(best_paths)
}
有了这个,我发现了类似
Error in if (adjacent %in% end) { : the condition has length \> 1
我需要您的帮助进行此调试,非常感谢您的帮助。
答: 暂无答案
评论
debug()
if()
[[1]] [1] "A8" [[2]] [1] "A4" [[3]] [1] "A5" [[4]] [1] "A7"