break for loop in Python [duplicate] - c++

This question already has answers here:
How to change index of a for loop?
(5 answers)
Closed 4 months ago.
is it possible to break a for loop in Python, without break command?
I'm asking this question in order to compare it with C++ for loop, in which actually checks a condition each time.
i.e. it's possible to break a for loop in C++ like below:
for(int i=0; i<100; i++)
i = 1000; // equal to break;
is it possible to do the same in Python?
for i in range(0,100):
i = 10000 // not working

Python's for is really a "for each" and is used with iterables, not loop conditions.
Instead, use a while statement, which checks the loop condition on each pass:
i = 0
while i < 1000:
i = 1000
Or use an if statement paired with a break statement to exit the loop:
for i in range(1000):
if i == 10:
break

Use a while loop for that purpose:
i = 0
while i < 100:
i = 1000

No, for doesn't work like that in Python. for iterates over a list (in this case) or other container or iterable. for i in range(0, 100) doesn't mean "increment i until i is greater than or equal to 100", it means "set i to successive items from a list of these 100 items until the list is exhausted."
If i is 50, then the next item of the list is still 51, regardless of what you may set i to.
break is better anyway.

This won't work (as you've noticed). The reason is that, in principle, you are iterating the elements of a list of ascending numbers (whether that is really true depends on if you're using python 2 or 3). You can use the 'break' keyword to break out of a loop at any time, although using it in excess might make it hard to follow your code.

You might have to settle for the break statement:
http://docs.python.org/tutorial/controlflow.html
for i in range(0,100):
print i
if i == 10:
break

Related

Duplicate values in Julia with Function

I need writing a function which takes as input
a = [12,39,48,36]
and produces as output
b=[4,4,4,13,13,13,16,16,16,12,12,12]
where the idea is to repeat one element three times or two times (this should be variable) and divided by 2 or 3.
I tried doing this:
c=[12,39,48,36]
a=size(c)
for i in a
repeat(c[i]/3,3)
end
You need to vectorize the division operator with a dot ..
Additionally I understand that you want results to be Int - you can vectorizing casting to Int too:
repeat(Int.(a./3), inner=3)
Przemyslaw's answer, repeat(Int.(a./3), inner=3), is excellent and is how you should write your code for conciseness and clarity. Let me in this answer analyze your attempted solution and offer a revised solution which preserves your intent. (I find that this is often useful for educational purposes).
Your code is:
c = [12,39,48,36]
a = size(c)
for i in a
repeat(c[i]/3, 3)
end
The immediate fix is:
c = [12,39,48,36]
output = Int[]
for x in c
append!(output, fill(x/3, 3))
end
Here are the changes I made:
You need an array to actually store the output. The repeat function, which you use in your loop, would produce a result, but this result would be thrown away! Instead, we define an initially empty output = Int[] and then append! each repeated block.
Your for loop specification is iterating over a size tuple (4,), which generates just a single number 4. (Probably, you misunderstand the purpose of the size function: it is primarily useful for multidimensional arrays.) To fix it, you could do a = 1:length(c) instead of a = size(c). But you don't actually need the index i, you only require the elements x of c directly, so we can simplify the loop to just for x in c.
Finally, repeat is designed for arrays. It does not work for a single scalar (this is probably the error you are seeing); you can use the more appropriate fill(scalar, n) to get [scalar, ..., scalar].

Is there a #between? for numbers in Crystal?

I was wondering if I simply cannot find a between method for numbers in Crystal.
In Ruby, there's the Comparable#between? method which can (among others) compare two numeric values (my specific case).
Background: I want to achieve a not-between solution without using
variable < 2 || variable > 5
I tried 5.between(2,5) and 5.between?(2,5) but all I got was a compilation error:
Error in line 1: undefined method 'between?' for Int32
I ended up with extending the number structure:
struct Number
def between?(a, b)
self <=> a >= 0 && self <=> b <= 0
end
end
Question 2: Is my solution above a feasible one? If not, suggestions are welcomed.
In crystal you can write 2 <= variable <= 5, which is easier to read and gives you greater control over inclusivity/exclusivity at each end of the range.
From a deleted answer but I still like it:
You can use a similar method Range#includes? (or #covers).

misunderstanding about Range in python 2.7

I've been doing some exercises, and having one question for you guys.
following to the picture I added.
for number =2 the range we get in the second line is from 2 until 2.
so, why dont i get some error message? How does it work?
How does the program know to skip it and return True?
Code:
def main(number):
for i in range(2,int(number**0.5)+1):
if number % i == 0:
return False
return True
print main(2)
Thanks!!
Some people think that Python attaches some special syntax between for and range, but range is an object that supports iteration.
This means that it has an __iter__ function that returns an iterator, and this supports the iterator protocol. This is a protocol that allows us to enumerate items out of that object. Like we can also enumerate over a list, tuple, set, etc.
for on the other hand simply uses this protocol such that for each iteration, it aims to fetch the next element out of the iterator. In case there is a next element, it assigns that element to the variable(s) on the left side. In case the iterator is exhausted (has no elements anymore), it stops.
In case you construct a range(start,stop) object where stop <= start. That range object is considered to be empty: it simply does not enumerate any items. for does not know what it is enumerating, but since the iterator over the range(..) element simply says that there are no elements anymore for stops.
You might indeed argue that it would be better if range(..) raises an error in case the stop is less than or equal to start. But usually it is wanted behavior that no error is risen, and the loop simply does not execute.
You can compare for i in range(0,n) to a construct in the Java/C++ language family:
for(int i = 0; i < n; i++) {
//...
}
In this case if n is less than or equal to zero, the loop will not be executed either. The range(..) object somewhat a generator for such type of loops.
A extra note is that range actually is more sophisticated than described here in this answer, since you can also add a step, and you can countdown. But this has no impact on the semantics of this answer.
You can make the code more elegant, by using a generator in an all statement. Like:
def main(number):
return all(number % i for i in range(2,int(number**0.5)+1))
Furthermore we can boost performance a bit, by only checking odd divisors (and 2):
def main(number):
sq = int(number ** 0.5) + 1
return (number & 1) and all(number % i for i in range(3, n, 2))

for loop in c++, any difference between these two style? [duplicate]

This question already has answers here:
which is better "for(int i = 0; i != 5; ++i)" or "for(int i = 0; i <= 5; i++)"? [duplicate]
(7 answers)
Closed 7 years ago.
Style one: for (int i=0;i<10000;++i){...}
Style two: for (int i=0;i!=10000;++i){...}
Let's say what happens in the {} will not affect the value of i, what is the difference between these two style? since I have checked with the compiler they all get the same results.
Given this particular question, there is no difference. However, in general, the first style is preferred because it is slightly safer.
Think about what happens if i becomes something like 10,001? In the first style, the loop will terminate. Whereas in the second style, you get an infinite loop.
If you stick to the first style, you'll also be able to increase i by anything that isn't a factor of 10000 and still guarantee termination of the loop.
No difference in this case. The commonly used '<' sigh is just for safty purpose. In case you work with float instead of int or the value of i is modified inside the loop so that it may skip the value against which it is checked.
As default choice, prefer '<' over '!=' unless '!=' is really required like in pointers comparison.
if you also manipulate i inside the loop, there are chances that i may not equal 10000 in second style at any point of time and it might become infinite loop.
Where as in first style even if i's value is incremented inside loop for any condition, the loop will certainly terminate at some point of time.
Edit: Even if i's value will not be modified inside the loop, and if you assume these are just two ways of doing the same thing, As a programmer you must choose the first style as it has meaning, readability and slightly safer for obvious reasons.

For loop based on condition check

I am looking for the best approach to write the following code.
if (condition == true)
for (i = 0; i < 200; i++)
{
/// 600 lines of code
}
else
for (i = 200; i > 0; i--)
{
/// same 600 lines of code as in above condition check
}
As of now, I have the same code copied inside both loops. However is there a way to do a check and then have the code appear only once? The only thing that depends upon the condition check is the way the loop will work. I have to go forward or backward in the loop as per the condition check and don't want to have the same 600 lines of code pasted twice. I am writing this in C.
Instead of having two loops with slightly different loop variables, you could just alter the loop variable depending on the condition so it effectively either counts from 0 up to 200 or from 200 down to 0.
for (iteration = 0; iteration < max; iteration++)
{
index = (condition == true) ? iteration : max-iteration;
// 600 lines of code, using index
}
You might want to add a comment to that, so others (and you, later) know what this is supposed to do.
However, even then you should probably try to refactor those 600 lines of code to a separate method -- or rather several separate methods, each handling one aspect of those 600 lines. As a rule of thumb: i) Whenever you have repeated code, no matter whether its 600 lines or just 10 lines, try to make it a method, and ii) whenever you have a really long block of code, even if it's not repeated many times, try to split it up into several methods. This will make the code more self-descriptive and much easier to maintain.
This might not always be easy, e.g. if those 600 lines access and modify many variables declared outside of the loop, but then again, this in itself might be another flaw in design...