difference between loop iterations in python and Java or C - java

I am learning python and seeing the difference in this loop conditions declarations I just have a question that how exactly the for loop in python is different from same algorithm for loopin C or Java, I know the difference in syntax but is there difference in the machine execution, and which is faster
for example
for i in range(0,10):
if i in range(3,7):
print i
and in java
for(int i=0,i<10;i++){
if i>=3 && i<7
system.out.println(i);
Here I just want to know about the difference in actual iterations over 'i' not the printing statements or the output of the code.
Also comment on the if condition used to check whether 'i' is in between 3 and 7. in python if I had used the similar statement if i>=3 and i <7: what difference would have it made.
I am using python2.7

If you're using python 2.x, then the range call creates a full-fledged list in memory, holding all the numbers in the range. This would be like populating a LinkedList with the numbers in Java, and iterating over it.
If you want to avoid the list, there's xrange. It returns an iterable object that does not create the temporary list, and is equivalent to the Java code you posted.
Note that the in condition is not equivalent to a manual bounds check. Python will iterate through the range in O(n) looking for the item.
In python 3.x, xrange is no more, and range returns an iterable.

Related

Why Java data structure (like array) doesn't seem to support vectorized operation?

Given an array T of integers, if we want to multiply each item by 2, in Java we will do it via a for-loop (Known as scalar operation). With python 's numpy array, we can just multiply array by 2 (Known as vectorized operation).
My question is: Is there a way in Java that allows us to perform that multiply operation in a vectorized way?
And if Java doesn't support that, is there a reason why?
Update: I'm not asking for sugar syntax. It is about CPU instruction vectorization like SIMD What is "vectorization"?
Thank you.

Collections sort method vs iteration

I was working on a playing cards shuffle problem and found two solutions for it.
The target is to shuffle all 52 playing cards stored in a array as Card objects. Card class has id and name associated to it.
Now, one way is to iterate using for loop and then with the help of a temp card object holder and a random number generator, we can swap two objects. This continues until we reach half of the cards.
Another way is to implement comparable overriding compareto method with a random generator number, so we get a random response each time we call the method.
Which way is better you think?
You should not do it by sorting with a comparator that returns random results, because then those random results can be inconsistent with one another (e.g., saying that a<b<c<a), and this can actually result in the distribution of orderings you get being far from uniform. See e.g. this demonstration by Mike Bostock. Also, it takes longer, not that that should matter for shuffling 52 objects.
The standard way to do it does involve a loop, but your description sounds peculiar and I suspect what you have in mind may also not produce the ideal results. (If the question is updated to make it clearer what the "iterate using for loop" approach is meant to be, I will update this.)
(There is a way to get good shuffling by sorting: pair each element up with a random number -- e.g., a random floating-point number in the range 0..1 -- and then sort using that number as key. But this is slower than Fisher-Yates and requires extra memory. In lower-level languages it generally also takes more code; in higher-level languages it can be terser; I'd guess that for Java it ends up being about equal.)
[EDITED to add:] As Louis Wasserman very wisely says in comments, when your language's standard library has a ready-made function to do a thing, you should generally use it. Unless you're doing this for, e.g., a homework assignment that requires you to find and implement an algorithm to solve the problem.
First of all, the comparator you've described wont work. More on this here. TLDR: comparsions must be reproducible, so if your comparator says that a is less then b next time when comparing b to a it should return "greater", not a random value. The same for Comparable.
If I were you, I'd rather use Collections#shuffle method, which "randomly permutes the specified list using a default source of randomness. All permutations occur with approximately equal likelihood". It's always better to rely on someone's code, then write your own, especially if it is in a standard library.

Multiplying arrays in Java without a for loop

Suppose I have two equally long arrays of numbers. I want to create a third array such that:
c[0] = a[0] * b[0]
c[1] = a[1] * b[1]
...
If I were in Matlab, I could write a loop that performed the multiplication like this:
for i=1:length(a)
c(i) = a(i) * b(i);
end
but I know that it's good to avoid for loops, and there's a way to do that, which is:
c = a .* b;
This makes sense to me, and having timed it (tic toc) several times on two 8192-length arrays of random numbers, the .* method consistently finishes about 3x faster than the for loop.
So now I want to multiply the arrays in Java. So I write a for loop and say:
for (int i=0; i<a.length; i++) {
c[i] = a[i] * b[i];
}
My question is: is there a better way of doing this that avoids the for loop? And if there is, does it make a difference? In my mind, it runs faster without the for loop because it's multiplying the numbers in parallel instead of in series, but I have no idea what's going on under the hood (like if the compiler is unrolling the loop on its own).
There are (at least) two reasons why .* is faster than an explicit loop in Matlab. By explicit I mean a loop written in Matlab code, as opposed to internal loops that Matlab functions might be using. The reasons are:
.* is vectorized. This means that, although it very likely does the computations internally with a loop, that loop has been coded in some faster language than Matlab itself.
.* is multithreaded, and so it benefits from multiple cores running in parallel.
So in Matlab, whenever there is a built-in vectorized function, you should use it. Although the speed of Matlab's explicit loops has improved in recent years (thanks to JIT compiling for example), they are still slower than their vectorized versions.
Java follows a more conventional approach, in which explicit loops are the norm. They are not slow, and generally there are not vectorized functions that can replace them. So I'd say an explicit loop is the way to go in Java.
Although YOU are not writing a loop in Matlab, underneath, it's most likely that there is some kind of loop, and even maybe more than one (we'd have to check the source code). There is nothing magic in Matlab. It's just a "simplified" language, where underneath there are more complex code generated.
Your Java loop is the correct way.

Should I use java collection sort() or implement my own?

I have an array that I need to sort the values in increasing order. The possible value inside the array are is between 1-9, there will be a lot of repeating value. (fyi: I'm working on a sudoku solver and trying to solve the puzzle starting with the box with least possibilities using backtracking)
The first idea that comes to my mine is to use Shell Sort.
I did some look up and I found out that the java collection uses "modified mergesort"(in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist).
So I wish to know if the differences in performance will be noticeable if I implement my own sorting algorithm.
If you only have 9 possible values, you probably want counting sort - the basic idea is:
Create an array of counts of size 9.
Iterate through the array and increment the corresponding index in the count array for each element.
Go through the count array and recreate the original array.
The running time of this would be O(n + 9) = O(n), where-as the running time of the standard API sort will be O(n log n).
So yes, this will most likely be faster than the standard comparison-based sort that the Java API uses, but only a benchmark will tell you for sure (and it could depend on the size of your data).
In general, I'd suggest that you first try using the standard API sort, and see if it's fast enough - it's literally just 1 line of code (except if you have to define a comparison function), compared to quite a few more for creating your own sorting function, and quite a bit of effort has gone into making sure it's as fast as possible, while keeping it generic.
If that's not fast enough, try to find and implement a sort that works well with your data. For example:
Insertion sort works well on data that's already almost sorted (although the running time is pretty terrible if the data is far from sorted).
Distribution sorts are worth considering if you have numeric data.
As noted in the comment, Arrays.parallelSort (from Java 8) is also an option worth considering, since it multi-threads the work (which sort doesn't do, and is certainly quite a bit of effort to do yourself ... efficiently).

Iterating over Permutations of an Array

I'm working on some java code for some research I'm working on, and need to have a way to iterate over all permutations of an ArrayList. I've looked over some previous questions asked here, but most were not quite what I want to do, and the ones that were close had answers dealing with strings and example code written in Perl, or in the case of the one implementation that seemed like it would work ... do not actually work.
Ideally I'm looking for tips/code snippets to help me write a function permute(list, i) that as i goes from 0 to list.size()! gives me every permutation of my ArrayList.
There is a way of counting from 0 to (n! - 1) that will list off all permutations of a list of n elements. The idea is to rewrite the numbers as you go using the factorial number system and interpreting the number as an encoded way of determining which permutation to use. If you're curious about this, I have a C++ implementation of this algorithm. I also once gave a talk about this, in case you'd like some visuals on the topic.
Hope this helps!
If iterating over all permutations is enough for you, see this answer: Stepping through all permutations one swap at a time .
For a given n the iterator produces all permutations of numbers 0 to (n-1).
You can simply wrap it into another iterator that converts the permutation of numbers into a permutation of your array elements. (Note that you cannot just replace int[] within the iterator with an arbitrary array/list. The algorithm needs to work with numbers.)

Categories