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~
3 Answers 3
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])
2 Comments
sum(c == "0" for c in new_town[::2])I don't know too much Java, but I believe this is a more direct translation of your code into python:
def countDeafRats(town):
count = 0
new_town = town.replace(' ','')
#format for range: start, end (exclusive), increment
for i in range(0, len(new_town), 2):
if new_town[i] == '0':
count += 1
return count
I agree with @Ajax1234 's answer, but I thought you might like an example that looks closer to your code, with the use of a for loop that demonstrates use of an increment of 2. Hope this helps!
Comments
Okay I will recommend that you must follow the answer provided by @Ajax1234 but since you mentioned that you are fairly new(probably not familiar much about regex) to python so I would suggest for the current instance you should stick to your code which you are trying to convert to. It is fairly correct just you need to make some amendments to your code(although very small related to indentation). Your amended code would look something like:
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
#print count_deaf_rats("~O~O~O~OP~O~OO~")
This yields the same result as your corresponding java code. Also since while loops are not considered much handy(but at some instances much useful also) in python therefore I will insist to use for loop as:
#Same as above
for increment in range(0,len(newTown),2):
if newTown[increment] == 'O':
count +=1
return count
Read more about range function here
defshould be indented to the rightfor i in range(0, newTown, 2):whileloop here in Python, but by glancing at it, it looks equivalent.increment += 2should not be inside the if-block