作为练习,我使用python中的递归实现了map函数,如下所示:
#map function that applies the function f on every element of list l and returns the new list
def map(l,f):
if l == []:
return []
else:
return [f(l[0])] + map(l[1:],f)
Run Code Online (Sandbox Code Playgroud)
我知道python不支持尾递归优化这一事实,但我如何以尾递归方式编写相同的函数?
请帮助谢谢
以下代码不返回None,而是一些神秘的" main _.link_list对象":
class link_list(object):
"""a link list class"""
def __init__(self, list):
super(link_list, self).__init__()
pdb.set_trace()
if list==[]:
return None
else:
self.value = list[0]
self.next = link_list(list[1:len(list)])
Run Code Online (Sandbox Code Playgroud)
测试代码打印'False':
l=link_list([1,2,3])
print l.next.next.next==None
Run Code Online (Sandbox Code Playgroud)
为什么?
我正在学习尾递归,在解决这个问题之前,我想对代码片段是否尾递归进行是/否的回答。
int fib_in(int n, int current, int prev) {
if (n == 1 || n == 2) { // n = 1 or 2 both gives fib number 1
return current;
}
return fib_in(n - 1, current + prev, current); // recursive call, current gets updated and new prev is the current, so were going backwards if that makes sense
}
int fib(int n) {
return fib_in(n, 1, 1); // 1 and 1 is the 2 first fib numbers so …Run Code Online (Sandbox Code Playgroud) 我用两种不同的方式计算斐波那那排.为什么fib1的执行时间比fib2长得多?
public class RecursionTest {
@Test
public void fib1() {
long t = System.currentTimeMillis();
long fib = fib1(47);
System.out.println(fib + " Completed fib1 in:" + (System.currentTimeMillis() - t));
t = System.currentTimeMillis();
fib = fib2(47);
System.out.println(fib + " Completed fib2 in:" + (System.currentTimeMillis() - t));
}
long fib1(int n) {
if (n == 0 || n == 1) {
return n;
} else {
return fib1(n - 1) + fib1(n - 2);
}
}
long fib2(int n) {
return n == …Run Code Online (Sandbox Code Playgroud) 代码:(我尝试翻译成 Java。它是一种我不知道的不同语言):
selection_sort(int a, int b){
if(a == b+1){
//do nothing
}else{
i = minIndex(arr, a, b); //minIndex finds minimum value of 2 index's an array
if(i != a)
swap(arr, i, a);
selection_sort(a+1, b);
}
}
Run Code Online (Sandbox Code Playgroud)
作业问题要求消除此代码中的尾递归。这是否意味着用迭代循环替换最后一次递归调用?或者添加额外的递归调用?
我认为问题可能源于我不知道常规递归和尾递归算法之间的区别。如果我错了,请纠正我,但我的理解是尾递归用于通过减少递归调用的次数来提高效率,除非调用是代码中的最后一条指令。关键在于,较少的递归调用意味着较少的递归堆栈存储在内存中。
编辑:代码中交换调用中的错误已修复。
我想创建一个添加参数的函数.应该调用这个函数
functionAdd(2)(3)(4)...(n);
Run Code Online (Sandbox Code Playgroud)
结果2 + 3 + 4 ... + n我正在尝试这个
function myfunction(num){
var summ =+ num;
if(num !== undefined){
return myfunction(summ);
}
};
Run Code Online (Sandbox Code Playgroud)
但它不起作用,ovwerflow的错误.而且我不明白我应该从这个功能中找到什么;