How can I write the for loop in Python as I write it in C:
for(i=0;i<10;)
{
if(i%2==0)
i=i+3;
else
i++;
printf("%d\n",i);
}
Can anyone tell me about this? I searched a lot but couldn't find it. I wrote it like this in Python:
for i in range(0,10):
if (i%2==0):
i+=3
else:
i+=1
print i
Output:
3
2
5
4
7
6
9
8
11
10
Expected output:
3
4
7
8
11
Can anyone also explain the reason of this output?
To write the same loop in Python:
i = 0
while i < 10:
if i % 2 == 0:
i += 3
else:
i += 1
print i
Which gives:
3
4
7
8
11
Note that, per the tutorial:
The for statement in Python differs a bit from what you may be used to
in C or Pascal. Rather than always iterating over an arithmetic
progression of numbers (like in Pascal), or giving the user the
ability to define both the iteration step and halting condition (as
C), Python’s for statement iterates over the items of any sequence (a
list or a string), in the order that they appear in the sequence.
In a Python for loop, any changes to the loop variable (i, in this case) that occur during the loop are ignored when the loop repeats, and the next value from the object being iterated over is used. In this case, the object is a list of numbers:
>>> range(10) # note that a 0 start is the default
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Some languages call this a for each loop. See also the language reference for more details.
range(0, 10) function returns list of values from 0 to 9:
range(0, 10) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Then for body is executed for each element in this list.
If You have 0, the 0 % 2 == 0 so it prints 0 + 3 etc.
In C You changed i value so You jumped to other value in set. Using python's for You will get through all elements. You should use
i = 0
while i < 10:
if (i % 2 == 0):
i += 3
else:
i += 1
print i
To have same results as in C
try this
for i in range(10):
if i%2 == 0:
i = i+3
else:
i = i + 1
print i
it gives the same output u asked for...hope this helps
Related
I encountered something I don't understand. I created a simple example in order to explain it. I have the following list:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
I iterate through the list, printing the value at the current index, and remove the value if it is even. This results in the next value getting skipped because they all move up one index (filling the gap created by the removal).
for i in numbers:
print(i)
if i % 2 == 0:
numbers.remove(i)
This results in the following output, which is as expected:
1
2
4
6
8
10
When iterating through the list backwards, this problem will be avoided, since all the lower indexes won't be affected by the removal of a higher index.
for i in numbers[::-1]:
print(i)
if i % 2 == 0:
numbers.remove(i)
Which results in (as expected):
10
9
8
7
6
5
4
3
2
1
Now we've arrived at the part I don't understand. As far as I know the default stepsize is 1, so adding [::1] shouldn't make any difference right? Well, it does...
for i in numbers[::1]:
print(i)
if i % 2 == 0:
numbers.remove(i)
Which results in:
1
2
3
4
5
6
7
8
9
10
As yous see all the numbers are getting printed, while I expected some to be skipped due to the shifting explained earlier.
Can someone explain why this is?
So, the answer is already there in the comments, just a proper explanation here:
Basically, when you say:
for i in numbers:
print(i)
if i % 2 == 0:
numbers.remove(i)
You are iterating through the list numbers
But when you write:
for i in numbers[::1]:
print(i)
if i % 2 == 0:
numbers.remove(i)
It can be seen as an equivalent to:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]# <-------------
num2 = numbers.copy() #or numbers[::1] <-------------- |
# i.e. python automatically creates a copy of the | |
# list numbers to iterate through | |
# since it seems like you are iterating through a | |
# slice of the original list | |
# | |
for i in numbers[::1]: # iterates through------------- |
print(i) # |
if i % 2 == 0: # |
numbers.remove(i) # this removes elements from --
The difference? The copy created is only stored until iteration is done. Hence even when the elements are removed, since the current list is the same, no number is skipped.
I am trying to reverse arrays in groups. I have wasted more than half an hour finding the problem but not able to figure out how is index is out of range.
Here is my code:
def rev(A,S,N):
start=S
end=N
while start<end:
A[start],A[end]=A[end],A[start] #error here
start+=1
end-=1
return A
def reverseInGroups(A,N,K):
#Your code here
rev(A,0,K)
rev(A,K,N) #error here
return A
Here is the error I am getting
Sample Input 1 : N=5 K=3 A= [1,2,3,4,5]
Sample Output 1 : 3 2 1 5 4
Sample Output 2 N= 8 K=3 A=[1,2,3,4,5,6,7,8]
Sample Output 2 : 3 2 1 6 5 4 8 7
For more information please visit this link
How about
def rev(a,start,end, middle):
assert 0 <= start <= middle <= end < len(a)
a[start:middle] = reversed(a[start:middle])
a[middle:end] = reversed(a[middle:end])
return a
There is no need to use / iterate positions at all - this avoids your error because slicing can handle oversized slices: [1,2,3,4][2:99] works w/o error.
def rev(data, start, end):
"""Reverses the range start:end (end exclusive) of the given list.
No safeguards whatsoever so only use with correct data. Out of bounds
is irrelevant due to slices used to reverse."""
data[start:end] = data[start:end][::-1] # you need end+1 if you want inclusive
return data
def reverseInGroups(A,N,K):
rev(A,0,K)
rev(A,K,N)
return A
l = list(range(11))
print ( reverseInGroups(l , 8, 3)) # why N (the bigger number) first?
to get
[2, 1, 0, 7, 6, 5, 4, 3, 8, 9, 10]
#0 1 2 3 4 5 6 7 8 9 10 # 0-3(exclusive) and 3-8(exclusive) reversed
To revere all K sized groups do
def reverseInGroups(A,K):
pos_at = 0
while pos_at < len(A):
rev(A, pos_at, pos_at+K)
pos_at += K
return A
I’m new to python and would like to do a simple function. I’d like to read the input array and if the value is more than 4 digits, to then split it then print the first value then the second value.
I’m having issues splitting the number and getting rid of 0’s inbetween; so for example 1006, would become 1, 6.
Input array:
a = [ 1002, 2, 3, 7 ,9, 15, 5992]
Desired output in console:
1, 2
2
3
7
9
15
59,92
You can abstract the splitting into a function and then use a list comprehension to map that function over the list. The following can be tweaked (it matches more of what you had before one of your edits). It can be tweaked of course:
def split_num(n):
s = str(n)
if len(s) < 4:
return 0, n
else:
a,b = s[:2], s[2:]
if a[1] == '0': a = a[0]
return int(a), int(b)
nums = [1002, 2, 3, 7 ,9, 15, 5992]
result = [split_num(n) for n in nums]
for a,b in result:
print(a,b)
Output:
1 2
0 2
0 3
0 7
0 9
0 15
59 92
If you just want a list of the non-zero digits in the original list, you can use this:
a = [ 1002, 2, 3, 7 ,9, 15, 5992]
strings = [str(el) for el in a]
str_digits = [char for el in strings for char in el if char != '0']
and if you want the digits as ints, you can do:
int_digits = [int(el) for el in str_digits]
or go straight to
int_digits = [int(char) for el in strings for char in el if char != '0']
I'm not sure what the logic is behind your desired output is, though, so if this isn't helpful I'm sorry.
I'm sorry if the title is confusing. Here's a better explanation:
So basically what I need to do is iterate through every number in list and print the biggest number west (list[0:i]) and the biggest number east. If the biggest number is smaller than i, we print i. So for list [1, 3, 2, 4, 3] the output should be:
1 4
3 4
3 4
4 4
4 3
I thought my code was correct but it doesn't work for the last number in list, is anyone able to help?
'a' is the list in my code
a = [1, 3, 2, 4, 3]
for i in a:
west = a[0:i]
east = a[i:int(len(a))]
if max(west) > i:
print(max(west))
else:
print(i)
if max(east) > i:
print(max(east))
else:
print(i)
Try:
for i in range(len(a)):
print(max(a[:i+1]))
print(max(a[i:]))
You are not iterating over the indices in your original code; and thus the partition does not make sense.
The only mistake in your code is the for i in a loop, which loops throgh i = 1,3,2,4,3 and not i=0,1,2,3,4
The following piece of code works
a=[1,3,2,4,3]
for i in range(len(a)) :
print max(i,max(a[:i+1]))
print max(i,max(a[i:]))
this may work... not fully tested but it looks correct
a = [1, 3, 2, 4, 3]
for i in a[:-1]:
west = a[0:i]
east = a[i:int(len(a))]
if max(west) > i:
print(max(west))
else:
print(i)
if max(east) > i:
print(max(east))
else:
print(i)
num = a[-1]
west = a[0:-1]
if max(west) > num:
print(max(west))
else:
print(str(a[-1]))
print(str(a[-1]))
Output: 1 4 3 4 4 4 4 3
This question already has answers here:
Scope of python variable in for loop
(10 answers)
Closed 9 years ago.
I am trying to do something as simple as changing the varible in which I am iterating over (i) but I am getting different behaviours in both Python and C.
In Python,
for i in range(10):
print i,
if i == 2:
i = 4;
I get 0 1 2 3 4 5 6 7 8 9, but the equivalent in C:
int i;
for (i = 0; i < 10; i++) {
printf("%d", i);
if (i == 2)
i = 4;
}
I get 01256789 (note that numbers 3 and 4 don't appear, as expected).
What's happening here?
Python has a few nice things happening in the background of for loops.
For example:
for i in range(10):
will constantly set i to be the next element in the range 0-10 no matter what.
If you want to do the equivalent in python you would do:
i = 0
while i < 10:
print(i)
if i == 2:
i = 4
else: # these line are
i += 1 # the correct way
i += 1 # note that this is wrong if you want 1,2,4,5,6,7,8,9
If you are trying to convert it to C then you have to remember that the i++ in the for loop will always add to the i.
The function range() creates a list.
For example, range(10) will create the following list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].
When you say for i in range(10), first off all the list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] will be generated, and then i will be assigned all the values from that list, in order.
It doesn't matter if you change the value of i because on the next iteration it will be assigned the next element from the list.
It C/C++ on the other hand, at the end of each iteration the value of i is incremented and then compared to the maximum allowed value (in this case 9) and if it is greater, then the loop ends.
When you call range(10) you create an iteratable list [0,1,2,3,4,5,6,7,8,9].
And the for loop just pick up one number after the other from the list at each turn, whether or not you haved changed the value of i.
Python gives you the elements in range(10), one after another. C repeatedly increments a variable.
Both of them don't really care what else you do with the variable inside the loop, but since the two language constructs do slightly different things, the outcome is different in some cases.
You can not do this by using range function.
you have to do it by using while loop only because for loop uses range function and in range function variable will get incremented by its internal method no matter what you specify in the loop it will get incremented by range list only.
for i in range(10):
... print i
... if i == 2:
... i = 4
... else:
... i += 1
...
0
1
2
3
4
5
6
7
8
9
An interesting example is here....
for i in range(10):
... print i
... i = i + 10
... print i
...
this will print...
0
10
1
11
2
12
3
13
4
14
5
15
6
16
7
17
8
18
9
19
It's because when you use the range() function in python. Your variable i will be go through the value in range. For example,
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
However, the C language that you have written is just using the normally condition to change the value of i. There is no function involved.