Is this Python code equivalent of Java code?

Helquin

I'm fairly new to Python so please bear with me.

This is the Java code:

public static int countDeafRats(final String town) {
    String t = town.replaceAll(" ","");
    int count = 0;
    for (int i = 0 ; i < t.length() ; i+=2) 
        if (t.charAt(i) == 'O') count++;
    return count;
}

This is my attempt to translate it to Python:

def count_deaf_rats(town):
    count = 0
    increment = 0
    newTown = town.replace(" ", "")
    while increment <= len(newTown):
        if newTown[increment]=='O':
            count +=1
            increment +=2
    return count

I didn't use for loop in Python since I don't how to increment by 2, so as the title says, would this be an acceptable translation?

Edit, sample input: ~O~O~O~OP~O~OO~

Ajax1234

It appears that you are trying to find the number of zeroes in the string that occur at indices incremented by 2. You can use regex and list comprehensions in Python:

import re

new_town = re.sub("\s+", '', town)

count = sum(i == "0" for i in new_town[::2])

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Equivalent Scala code for Java code

From Dev

Is this Haskell code equivalent to this Python code?

From Dev

Is this Haskell code equivalent to this Python code?

From Dev

Haskell equivalent of this Python code

From Dev

What is the Java equivalent of this Scala code?

From Dev

Python equivalent of password encryption from RSA key Java code

From Dev

Python equivalent for given MATLAB code

From Dev

What is the equivalent of this snippet of Java code in C#?

From Dev

What is this Java code equivalent in C# ? (setRequestEntity)

From Dev

What is this Java code equivalent in C# ? (setRequestEntity)

From Dev

C++ equivalent to python code: 'function(*list)'

From Dev

C++ equivalent to python code: 'function(*list)'

From Dev

R equivalent python code gives different output

From Dev

What's the equivalent of this Ruby code in Python?

From Dev

Javascript/NodeJS equivalent code for the Java code Cipher.doFinal(byte[])?

From Dev

Equivalent java code statement for C code statement used in recursion

From Dev

What is the code equivalent to this css code?

From Dev

Python to Java code conversion

From Dev

Code works in Java but not Python?

From Dev

Code works in Java but not Python?

From Dev

Are these lines of JavaScript code equivalent?

From Dev

C# Equivalent to this code

From Dev

Matlab equivalent code for file

From Dev

%timeit equivalent in code

From Dev

Equivalent code in IronPython

From Dev

C# Equivalent to this code

From Dev

Matlab equivalent code for file

From Dev

sed equivalent code for AIX

From Dev

Equivalent code without the library