java - 我如何在 Java 中实现这个 Python 片段?

标签 java python function

我有这段在网上找到的 Python 代码,想知道如何将它翻译成 Java。我的问题不是算法,而是如何处理函数的参数。

代码如下:

def ternarySearch(f, left, right, absolutePrecision):
    #left and right are the current bounds; the maximum is between them
    if (right - left) < absolutePrecision:
        return (left + right)/2
 
    leftThird = (2*left + right)/3
    rightThird = (left + 2*right)/3
 
    if f(leftThird) < f(rightThird):
        return ternarySearch(f, leftThird, right, absolutePrecision)

    return ternarySearch(f, left, rightThird, absolutePrecision)

我想知道函数定义是什么样的。例如,返回 y=x^2+3 的函数看起来像:

public static int y(int x){
 return x*x+3;
}

但是

 return ternarySearch(f, leftThird, right, absolutePrecision)

对我不起作用,我想知道该怎么做。

更新:

所以例如我有 y=3*x+2 它会像这样吗?

interface MyFunctor {
 int myFunction(int x);
}

class MyFunctorImpl implements MyFunctor {
  int myFunction(int  x) {
      return 3*x+2
  }
}

像这样吗?

最佳答案

在 Java 中,没有高阶函数。也就是说,您不能将一个函数作为参数传递给另一个函数。您可以做的是使用命令模式;定义一个支持所需方法的接口(interface),然后传递实现该方法的接口(interface)实例。

例如:

int ternarySearch(MyFunctor f, int left, int right, float absolutePrecision) {
  #left and right are the current bounds; the maximum is between them
  if (right - left) < absolutePrecision:
    return (left + right)/2

  leftThird = (2*left + right)/3
  rightThird = (left + 2*right)/3

  if (f.myFunction(leftThird) < f.myFunction(rightThird)) {
    return ternarySearch(f, leftThird, right, absolutePrecision)
  }
  return ternarySearch(f, left, rightThird, absolutePrecision)
}

interface MyFunctor {
  int myFunction(int arg);
}

class MyFunctorImpl implements MyFunctor {
  int myFunction(int arg) {
     // implementation
  }
}

然后您可以使用 MyFunctorImpl 的实例作为第一个参数来调用 ternarySearch

关于java - 我如何在 Java 中实现这个 Python 片段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2874487/

相关文章:

python - 在 Python 中处理 XML 真的很简单吗?

python - 如何找到pandas中多列的非零中位数/平均值?

python - 创建在协程完成时产生协程结果的生成器

javascript - 打印数字 - setTimeout JavaScript

java - 包 org.hamcrest 不存在

java - map 清除与空

java - 如何通过单击抽屉导航上的 ImageView 来获取用户个人资料图片,从图库中选择图像

php - session_start 不起作用 :(

python - 函数注释在 python 中给出错误?

java - Java-selenium 上的 StaleElementReferenceException 错误