Home > Mobile >  Rewrite Java code to Python(function) but it does not work
Rewrite Java code to Python(function) but it does not work

Time:10-25

I want to rewrite a Java function in Python but it doesn't really work the way I want it to. This is how the Java code looks like:

public String matchText(String[] splitText, String[] clozeText, int emptySpaces){
    String result="";
    for(int i=0;i<splitText.length;i  ){
        if (splitText[i].equals(clozeText[0])){
            if(splitText[i emptySpaces].equals(clozeText[emptySpaces 1])){
                for (int x=i;i<=i emptySpaces;x  ){
                    result  = splitText[x];
                }
            }
        }
    }
    return result;
}

And this is my attempt:

def matchText(splitText, clozeText, emptySpaces):
    result = ""
    for i in range(len(splitText)):
        if splitText[i] == clozeText[0]:
            if splitText[i   emptySpaces] == clozeText[emptySpaces   1]:
                for x in emptySpaces:
                    result  = splitText[x]
    return result

CodePudding user response:

The inner for loop should be

for x in range(i, i   emptySpaces   1):
    result  = splitText[x]

This is the correct implementation:

from typing import List

def matchText(splitText: List[str], clozeText: List[str], emptySpaces: int) -> str:
    result = ""
    for i in range(len(splitText)):
        if splitText[i] == clozeText[0]:
            if splitText[i   emptySpaces] == clozeText[emptySpaces   1]:
                for x in range(i, i   emptySpaces   1):
                    result  = splitText[x]
    return result

You can't do for x in emptySpaces because emptySpaces is an integer! You can't iterate integers. That's why your approach is not working in Python.

Note that I also added types to arguments and returned result (this is optional, but it helps you understand how the function works).

  • Related