如果用C语言写:
void q_sort(int numbers[], int left, int right) { int pivot, l_hold, r_hold; l_hold = left; r_hold = right; pivot = numbers[left]; while (left < right) { while ((numbers[right] >= pivot) && (left < right)) right--; if (left != right) { numbers[left] = numbers[right]; left++; } while ((numbers[left] <= pivot) && (left < right)) left++; if (left != right) { numbers[right] = numbers[left]; right--; } } numbers[left] = pivot; pivot = left; left = l_hold; right = r_hold; if (left < pivot) q_sort(numbers, left, pivot-1); if (right > pivot) q_sort(numbers, pivot+1, right); }
def qsort(lis): if len(lis) == 0: return [] else: low = [] hig = [] for x in lis[1:]: if x < lis[0]: low.append(x) else: hig.append(x) low = qsort(low) hig = qsort(hig) return low+lis[:1]+hig
def qsort(L): if not L: return [] return qsort([x for x in L[1:] if x< L[0]]) + L[0:1] + qsort([x for x in L[1:] if x>=L[0]])
def factorial(x): if x == 0: return 1 else: return x * factorial(x - 1)
f = lambda x: x and x * f(x - 1) or 1
(以下代码来自啄木鸟社区,如果有版权问题,请告诉我,我马上删除)
public class Calculator { static public double Foo(char op, double x, double y) { switch(op) case '+': return x+y; break; case '-': return x-y; break; case '*': return x*y; break; case '/': return x/y; break; default: throw new Exception("????") } }
public interface Ioper { double getResult(double x, double y); }
然后在开始interface这些
public class OperatorAdd interface Ioper { public double getResult(double x, double y) { return x+y; } } public class OperatorSub interface Ioper { public double getResult(double x, double y) { return x-y; } } public class OperatorMul interface Ioper { public double getResult(double x, double y) { return x*y; } } public class OperatorDiv interface Ioper { public double getResult(double x, double y) { return x/y; } }
public class TheMainClass { public static void Main() { Ioper cul = new OperatorAdd();//看你如何初始化了,来个工厂? double resu = cul.getResult(3,4); System.out.println(resu); } }
def foo(op,x,y): print eval("%d%s%d"%(x,op,y))就这两行...为什么会这样?因为python支持FP(函数式编程),在函数式编程中,函数变成了一等公民。