Is this Python code equivalent of Java code? - java

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])

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!

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

Related

Cut out different elements from a string and put them into a list

Here's updated code. For those following along the question edits contains the original question.
if (0 != searchString.length()) {
for (int index = input.indexOf(searchString, 0);
index != -1;
index = input.indexOf(searchString, eagerMatching ? index + 1 : index + searchString.length())) {
occurences++;
System.out.println(occurences);
indexIN=input.indexOf(ListStringIN, occurences - 1) + ListStringIN.length();
System.out.println(indexIN);
System.out.println(ListStringIN.length());
indexOUT=input.indexOf(ListStringOUT, occurences - 1);
System.out.println(indexOUT);
Lresult.add(input.substring(indexIN, indexOUT));
System.out.println();
}
}
As you can see, I gave me out the index numbers
My code works well with only one Element
But when I write something like this: %%%%ONE++++ %%%%TWO++++
There's this exception:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 16, end 7, length 23
at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3410)
at java.base/java.lang.String.substring(String.java:1883)
at com.DMMS.Main.identify(Main.java:81)
And I found out that the indexIN changes in the Start of the second String but not the indexOUT
I couldn't find out why
When you look at your code you can notice: in the first loop that counts the number of occurrences, your code "knows" that it has to use that version of indexOf() that relies on offsets within the search strings.
In other words: you know that you have to search after previous "hits" when walking through your string.
But your second loop, the one that has to extract the actual things, there you are using indexOf() without that extra offset parameter. Therefore you keep "copying out" the same part repeatedly.
Thus: "simply" apply the same logic from loop 1 for loop 2!
Beyond that:
you don't need two loops for that. Counting occurrences and "copying out" the matching code ... can be done in one loop
and honestly: rewrite that first loop. This code is almost incomprehensible for human beings. A reader would have to sit down and read this 10, 20 times, and then run it in a debugger to understand what it is doing
I dit it!
Heres the code:
.........................
static String ListStringIN = "%%%%";
static String ListStringOUT = "++++";
........................
else if (input.contains(ListStringIN) && input.contains(ListStringOUT)) {
System.out.println("Identifiziere Liste...");
String searchString = ListStringIN;
int occurences = 0;
boolean eagerMatching = false;
if (0 != searchString.length()) {
for (int index = input.indexOf(searchString, 0); index != -1; index = input
.indexOf(searchString, eagerMatching ? index + 1 : index + searchString.length())) {
occurences++;
System.out.println(occurences);
indexIN=input.indexOf(ListStringIN, occurences - 1) + ListStringIN.length();
System.out.println(indexIN);
//indexOUT=input.indexOf(ListStringOUT, occurences);
//indexOUT=input.indexOf(ListStringOUT, occurences - 1);
indexOUT = input.indexOf(ListStringOUT, eagerMatching ? index + 1 : index + ListStringOUT.length());
System.out.println(indexOUT);
Lresult.add(input.substring(indexIN, indexOUT));
System.out.println();
}
}
//for (int i = 0; i <occurences; i ++) {
// Lresult.add(input.substring(input.indexOf(ListStringIN, 0) + ListStringIN.length(), input.indexOf(ListStringOUT)));
//}
result = Lresult.toString();
return result;
}
I hope this is useful for other people
#GhostCat Thanks for your advices!

Add Two Binary Numbers Recursively, w/o Bitwise Operations; Java Homework

I think I've gotten mostly to a solution for a homework problem.
This is for a 201 CS class. Right now I just want to get the logic right. At present, it doesn't operate as intended, but it's close.
We don't want to use .toBinary, bitwise, or anything else. We also haven't been taught stringBuilder, so I'd like to avoid using it.
There's a System.out.println(); within the method which provides the correct answer if you read the console from bottom to top.
public static void main(String[] args) {
System.out.println(addBin(1100111011,1101110011));
}
public static String addBin(int num1,int num2){
String result = "";
if(num1 > 0 || num2 > 0){
int part1 = num1%10, part2 = num2%10;
int rem1 = num1/10, rem2 = num2/10;
result += Integer.toString((part1 + part2)%2);
//System.out.println(result);
int carry = (part1 + part2) /2;
addBin(rem1 + carry, rem2);
return result;
}
return result;
}
So, this example adds 1100111011 and 1101110011 with the output
0
1
1
1
0
1
0
1
0
1
1
0
when the correct answer is 11010101110.
I'm having trouble understanding how to properly "pop" the "result" part properly. Could you please help me understand this process, possibly within the context of this problem?
Thanks!
As you can see from your output, you are getting the correct result in the reverse order but you are not appending any of your older result to the ones that are being currently computed.
Inside your if condition, you are calling the addBin() function but you are not using the result that it gives anywhere. Just change that line to the following:
result = addBin(rem1 + carry, rem2)+result;
That should effective append all your results in front of the current answer so that you do not get the result in backwards direction. Hope this helps.

I don't really understand the do { } while structure

I'm trying to learn Java, I studied Pascal in high school and it has the repeat until..; instruction.
I want to solve an exercise where I'm supposed to keep entering numbers until the penultimate + antepenultimate numbers equal the last number I entered.(a[i-2]+a[i-1] = a[i]); I'm doing it without arrays but that doesn't really matter.
In Pascal it would be easy because repeat until is more easier to use
For ex it would be
repeat
...
until ((a[i-2]+a[i-1] = a[i]) and (n=3));
n is the number of values I entered
I can't figure out how to introduce it in Java, so far I did this but it doesn't work if I enter 2 2 4. It should stop but it keeps asking for numbers
int pen = 0, ant = 0, s = 0, n = 1;
int ult = input.nextInt();
s = s + ult;
do {
do {
ant = pen;
pen = ult;
ult = input.nextInt();
n++;
s = s + ult;
} while (ant + pen != ult);
System.out.println(n);
} while ((n == 3) || (n < 4));
ult is the last number I enter, s is the sum of the numbers entered.
Could anyone tell me how to set the conditions so it will stop if I enter the values 2 2 4?
A Do-While loop runs the code in the loop first. It evaluates the logic last, and then if it's true it repeats the code inside the loop, and so on until the logic is false.
The way to solve tricky problems like this is to get out a sheet of paper and record what each variable does. Step through each line like a debugger and record what's being stored in each variable as the program progresses.
It's the best way to do it. You'll find that you'll gain a deeper understanding of how your programs are working.
Java isn't any more magic than Pascal, the issue might be you've had a long break from programming :). Anyway, its been a while since I wrote anything in Java, but the issue I could spot in your code is just that n equals three after you've entered three ints, and so the outer loop continues.
int pen = 0, ant = 0, ult = 0, n = 0;
do {
ant = pen;
pen = ult;
ult = input.nextInt();
} while (++n < 3 || ant + pen != ult );
assert n >= 3;
assert ant + pen == ult;
Note that ever since Pascal everything has been zero indexed instead of one indexed.
Pascal uses the form:
repeat
doStuff();
until (boleanValue);
Java is basically the same, except for one important point:
do
doStuff();
while (~boleanValue);
The important difference is that "~" before booleanValue. The Pascal repeat ... until keeps running until the boolean evaluates to true. In Java the do ... while keeps running until the boolean evaluates to false. When converting from Pascal to Java you need to switch the boolean to work the other way.
The primary difference between while loop and a do-while loop is that while loop does eager condition check where as do-while loop does lazy condition check
while: Expression is evaluated at the top of the loop
syntax:
while (expression) {
statement(s)
}
(taken from http://www.w3resource.com/c-programming/c-while-loop.php)
Example:
public class WhileDemo{
public static void main(String args[]) {
boolean isSunday = false;
while(isSunday) {
System.out.println("Yayy.. Its Sunday!!");
}
}
}
Output: (nothing is printed on console)
Reason: Since isSunday is false, the body of loop is not executed
do-while: Expression is evaluated at the bottom of the loop. Therefore, the statements within the do block are always executed at least once.
syntax:
do {
statement(s)
} while (expression);
(taken from http://www.w3resource.com/c-programming/c-do-while-loop.php)
Example:
public class DoWhileDemo{
public static void main(String args[]) {
boolean isSunday = false;
do {
System.out.println("Yayy.. Its Sunday!!");
} while(isSunday);
}
}
Output: Yayy.. Its Sunday!!
Reason: The body of do is executed first, there by printing Yayy.. Its Sunday!! and then the condition while(isSunday); evaluates to false since isSunday is false and the loop terminates
You're only missing one thing from your problem. Your explanation of the Pascal code is almost correct, but wouldn't work without some modification.
In Java, use short-circuit logical operators to do the check.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
Not tested:
int n = 0;
int a[] = new a[3];
do {
n++;
a[0] = a[1];
a[1] = a[2];
a[2] = input.nextInt();
} while ((n < 3) || (a[0]+a[1] != a[2]));
System.out.println(a[2]);

c++ to java conversion, a few questions

I am converting a some C++ to java and have a small bit that I am unsure about
first question is what is tested for in the line
if (ampconst[i][0] || ampconst[i][1])
this in an example to the data in the array.
static short ampconst[NUT_SERIES][2] = {
{0,0},
{0,0},
{46,-24}
};
and my second question is that the ampsecul array is far shorter than NUT_SERIES
so I am getting array out of bounds exceptions, the array terminates like so
static long ampsecul[][5] = {
{0 ,-171996 ,-1742 ,92025 ,89},
{1 ,2062 ,2 ,-895 ,5},
{8 ,-13187 ,-16 ,5736 ,-31},
{9 ,1426 ,-34 ,54 ,-1},
{10 ,-517 ,12 ,224 ,-6},
{11 ,217 ,-5 ,-95 ,3},
{12 ,129 ,1 ,-70 ,0},
{15 ,17 ,-1 ,0 ,0},
{17 ,-16 ,1 ,7 ,0},
{30 ,-2274 ,-2 ,977 ,-5},
{31 ,712 ,1 ,-7 ,0},
{32 ,-386 ,-4 ,200 ,0},
{33 ,-301 ,0 ,129 ,-1},
{37 ,63 ,1 ,-33 ,0},
{38 ,-58 ,-1 ,32 ,0},
/* termination */ { -1, }
};
so how could this be handled in java and what would the values be at these lines
when the array is out of bounds or how would C++ handle this.
ampsin = ampsecul[isecul][1] + ampsecul[isecul][2] * T10;
ampcos = ampsecul[isecul][3] + ampsecul[isecul][4] * T10;
thanks in advance for any advice.
This is the whole for loop too see the code in context.
for (i = isecul = 0; i < NUT_SERIES ; ++i) {
double arg = 0., ampsin, ampcos;
short j;
if (ampconst[i][0] || ampconst[i][1]) {
/* take non-secular terms from simple array */
ampsin = ampconst[i][0];
ampcos = ampconst[i][1];
} else {
/* secular terms from different array */
ampsin = ampsecul[isecul][1] + ampsecul[isecul][2] * T10;
ampcos = ampsecul[isecul][3] + ampsecul[isecul][4] * T10;
++isecul;
}
for (j = 0; j < 5; ++j)
arg += delcache[j][NUT_MAXMUL + multarg[i][j]];
if (fabs(ampsin) >= prec)
lastdpsi += ampsin * sin(arg);
if (fabs(ampcos) >= prec)
lastdeps += ampcos * cos(arg);
}
if (ampconst[i][0] || ampconst[i][1])
tests whether the first/second column in ampconst[i] contain non-zero (it is an early-out optimization: if both the constants are 0 then the calculation can be skipped)
Edit I just found (google!) that this is a nutation calculation that has been adopted in quite a few places, but seems to be originally from a libastro.
hg clone https://bitbucket.org/brandon/pyephem
As far as the isecul index is concerned: apparently isecul should never grow to >= 15 (note that i is the loop variable, not isecul, isecul is incremented conditionally).
However, seeing the 'terminator' (-1) value, I'd really expect a check some like
if (ampsecul[isecul][0] == -1)
isecul = 0; // ? just guessing :)
or
if (ampsecul[isecul][0] == -1)
break;
Also, I get the impression that the first column of ampsecul is a range-based division, so somehow, there would be a binarysearch for the matching slot into ampsecul, not direct indexing (i.e. isecul=4 would select index 2 (2..8) not 4)
Are you sure you are getting the source code correctly? I looks very much like there are some custom indexers (operators[](...)) that you misssed out on? This would probably be about the same class/function that contains the terminator check like shown above.
Edit from the linked source I get the impression that the code is very much intended as is, and hence isecul should simply not be growing >= 15
That first if statement is testing the array entries for zero/non-zero. In C/C++ a boolean is simply an int that is used in a special way such that zero is false and non-zero is true.
As for your second array question I haven't grocked it yet. But understand that C/C++ does no array bounds checking (other than what may accidentally occur if you touch an undefined storage page), so unless there's an egregious error in the C++ code there must be something that limits references to the valid bounds of the array.

Is there a way to pre increment by more than 1 in Java?

In Java you can do a post increment of an integer i by more that one in this manner:
j + i += 2.
I would like to do the same thing with a pre increment.
e.g j + (2 += i) //This will not work
Just put the increment statement in parentheses. For example, the following will output pre: 2:
int i = 0;
System.out.println(
((i+=2) == 0)
? "post: " + i : "pre: " + i);
However, writing code like this borders on obfuscation. Splitting up the statement into multiple lines will significantly improve readability.
Not sure if there is a confusion in terminology going on, but += is not a post or pre-increment operator! Java follows the C/C++ definition of post-increment/pre-increment and they are well defined in the standard as unary operators. += is a shortcut for a binary operator. It evaluates to this:
lvalue1 += 5 ;
// is really (almost)
lvalue1 = lvalue1 + 5;
The assembler for the instruction doesn't look exactly like the binary version but at the level your using Java you do not see that.
The post-increment/pre-increment are unary operators that function kind of like this:
i++ ; // is something like _temp = i; i = i + 1; return temp;
++i; // is something like i = i + 1; return i;
This is just an example of how it works, the byte code doesn't translate too multiple statements for the post-increment case.
In your example, you could say a post-increment occurs but really, its just an increment. which is why I believe you have made the (incorrect) leap that it might be possible to have a pre-increment version of the same operation. But such a thing does not exist in C, C++, or Java.
Something like:
int increment = 42;
int oldI = i;
i += increment;
result = myMethod(oldI);
// Rest of code follows.
But why would you want to do this?
The += is pre increment. If you want post increment simply create wrapper with postInc method which will do this. If you really need this it would be more readable than parenthesis.

Categories

Resources