Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

converting recursive function from python to scala

I'm trying to convert this recursive function from python code to scala. In python:

    def func(x,y,z):
        if x >= y:
            return 0.0
        if y>= 12:
            return 1.0/6**z
        
        probability = 0.0
        
        for val in [1,2,3,4]:
            probability += func(x,y+val,z+1)        
        for val in [5,6]:
            probability += func(x+val,y,z+1)

        return probability

    print(func(1,7,0))

In scala, my the code became

object Prob extends App {

  println(func(1, 7, 0))

  def func(y: Int, x: Int, z: Int): Double = { 
    if (x>= y) {
      return 0.0;
    }   
    if (y>= 12) {
      return scala.math.pow(1.0/6,z);
    }
      
    var probability : Double = 0.0;
      
    for (i <- 1 to 4) {
        probability += func(x,y+i,z+1);
    }
    for (i <- 5 to 6) {
        probability += func(x+i,y,z+1);
    }
    return probability;
  }
}

Unfortunately, while the python code returns the correct value of 0.6, the scala code returns 0.0.

Where's the error in the scala code?

question from:https://stackoverflow.com/questions/65858844/converting-recursive-function-from-python-to-scala

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You swapped the order of parameters:

def func(hunter,goose,num):
def func(goose: Int, hunter: Int, num: Int): Double = { 

Since you call func(1, 7, 0), in scala you immediately hit the hunter >= goose case, which returns 0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...