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~
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.
Comments