Confused as to why one for loop works but one doesn't? Aren't they doing the same thing? Like shouldn't x = y?
x = 3
for i in range(8):
if i > x:
print i, ">", x
i = x
print x
y = 3
for i in range(8):
if y < i:
print y, "<", i
y = i
print y
Both are not same in first you have assignment (every time 3 to i) i = x, while in second you assign counter's i value to y as y = i.
shouldn't x = y?
No, after first loop x remains 3 whereas after second loop y becomes 7.
No.
In the first loop you are not reassigning the value of x. So x is unchanged in the loop.
In the second loop, you are updating y every time y is less than i
Related
I'm curious what x means when you look at this:
import random
for x in range(10):
print random.randint(1,101)
x itself has no special meaning, it simply (as a part of the for loop) provides a way to repeat
print random.randint(1,101)
10 times, regardless of the variable name (i.e., x could be, say, n).
In each iteration the value of x keeps increasing, but we don't use it. On the other hand, e.g.,
for x in range(3):
print(x)
would give
0
1
2
For x in range(3) simply means,
for each value of x in range(3), range(3) = 0,1,2
As it is range(3), the loop is looped three times and at each time, value of x becomes 0, then 1 and then 2
Here, x is just a variable name used to store the integer value of the current position in the range of loop and it iterates through out the range of a loop.
Like in for x in range(10):
x iterates 10 times and for instance in your for loop above, during the first iteration of the loop x = 1, then x=2 for the next iteration then, x= 3 and so on...
It is not neccessary to take x as a variable only you can take any variable name like i,a etc...
X is a variable name, so could be any name allowed by python for variable names. As a variable , it’s value will be different every time the loop circle ends, in this particular loop range(10) the value of x will start in 0 and next 1 , and next 2, until reach value of 10
so If you want to print a random int:
for x in range(10):
print(random.randint(x))
also, if it is python3.X, print(x) not print x, second is python2.X
I am coming from a short intro in C, and I was confused by the 'x' as well. For those coming from C,C++,C# etc.:
The 'x in range(10)' is the same thing as doing this in C:
for (x = 0; x < 10; x++)
f(x) represents the function of a triangular waveform. In which you input the value x and it returns you the associated y value. However my function returns x every time instead of y. For example f(1) should give 2/pi instead of 1.
def f(x):
y=x
if x in arange(-math.pi,-math.pi/2):
y=(-2/math.pi)*x-2
elif x in arange(-math.pi/2,math.pi/2):
y=(2/math.pi)*x
elif x in arange(math.pi/2,math.pi):
y=(-2/math.pi)*x+2
return y
numpy.arange returns an array of non-consecutive numbers. in operation against it will return True only if the left-hand operand belong to those numbers.
You'd better to use <= / < pair to avoid such problem. In addition to be correct, it also save cost of creating arrays.
def f(x):
y = x
if -math.pi <= x < -math.pi/2:
y = (-2/math.pi)*x-2
elif -math.pi/2 <= x < math.pi/2:
y = (2/math.pi)*x
elif math.pi/2 <= x < math.pi:
y = (-2/math.pi)*x+2
return y
The 'in' keyword only checks if the searched element lies in the list. Here, your list contains only values in the step of 1. Perhaps the value of x is not an integral step. Hence, the corrected function would be:
def f(x):
y=x
if x>-math.pi and x<-math.pi/2:
y=(-2/math.pi)*x-2
elif x>-math.pi/2 and x<math.pi/2:
y=(2/math.pi)*x
elif x>math.pi/2 and x<math.pi:
y=(-2/math.pi)*x+2
return y
I am trying to create a function in Python. This function should be able to create a list of whole numbers less than or equal to the number provided. I've created an empty list, a variable called y and a while loop. In this while loop, as long as y <= x, the results of the subsequent equations are appended to the empty list, and y increments by 1. However, when I call this function, I get a list with only one element. How can I fix this?
def fff(x):
numbers = []
y = 2
while(y <= x):
x = x - (x - y)
numbers.append(x)
y += 1
return numbers
>>> fff(10)
[2]
That function already exists, more or less.
Python 2
def fff(x):
return range(1,x+1)
Python 3
def fff(x):
return list(range(1,x+1))
If you look at this line x = x - (x - y) and think of your inputs, you will see the problem. if x initially equals 10, then x - (x - y) equals 2, and y will equal 3, therefore breaking out of your loop.
If you are trying to mimic the range function then this is how you would do it:
def fff(x):
numbers = []
y = 1
while(y <= x):
numbers.append(y)
y += 1
return numbers
I have a list comprising a number of X,Y values
aList = [[1, 2],[3, 4],[5, 6],[7, 8]]
i.e. X = 1, Y = 2
I need to extract each X and Y value on a row separately, assign those values to an X and Y variable respectively, and then act on the X and Y values.
This should then loop to the next row where the same process would occur again. I'll use print instead of the excessive code that needs to occur after this loop.
i.e. loop starts, X is assigned 1, Y is assigned 2, X and Y are used as inputs in formula, loop ends (and repeat for the remaining values in this list)
aListLen = len(aList)
aListRows = len(aList)
aListCols = len(aList[0])
The following code only extracts values 1 by one in the list
for row in range(aListRows):
for column in range(aListCols):
X = aList[row][column]
print X
adding a Y variable as follows results in an error
for row in range(aListRows):
for column in range(aListCols):
X = a[row][column]
Y = a[row][column+1]
print X
print Y
Looking at it now, I'm not sure the following if/elif loop would work as the X and Y values need to go in a formula together.
I could add an if/elif statement under the 2nd loop, but I'd still need to have a way of forcing the 2nd loop to repeat. (Which brings us back to the original problem anyway)
for row in range(aListRows):
for column in range(aListCols):
if column == 0:
X = aList[row][column]
elif column == 1:
Y = aList[row][column]
How can I force the loop to restart once the X value has been provided?
I assume the loop would then repeat, this time providing the value for Y.
Is there a better way of doing this?
Should point out this is Python 2.7 (so I cannot use anything exclusive to Python 3)
You're looping over the indices of the inner list and adding 1 to them. This will cause an IndexError when column contains the value of aListCols, since len(a[row]) == column+1
I think you are looking for this:
In [17]: aList = [[1, 2],[3, 4],[5, 6],[7, 8]]
In [18]: for X,Y in aList:
....: print "X value is %s, Y value is %s" %(X, Y)
....:
X value is 1, Y value is 2
X value is 3, Y value is 4
X value is 5, Y value is 6
X value is 7, Y value is 8
To assign the variables instead of printing them you could do:
for X,Y in aList:
tempX = X
tempY = Y
At the first iteration tempX will have a value of 1, tempY will have a value of 2. At the second iteration tempX will be 3, tempY will be 4...
You could, instead of a loop, use a recursive function.
Basically, that is a function that calls itself. For example:
def myfunction():
(something happens that wants you to start the function over)
myfunction()
Hence, it will call the function again, forcing the code to go back to the top.
I use a lot of N dimensional arrays and it gets a pain to have to write such indented code and I know some codes can be replaced with list comprehensions and inline statements. For example:
for x in (0,1,2,3):
for y in (0,1,2,3):
if x < y:
print (x, y, x*y)
can be replaced with:
print [(x, y, x * y) for x in (0,1,2,3) for y in (0,1,2,3) if x < y]
But how could I change the action instead of print to do something else like:
total = x+y
So what I want to do is something like:
[(total+=x+y) for x in (0,1,2,3) for y in (0,1,2,3) if x < y]
However this doesn't work
Is there a smart way to do this rather than:
for x in (0,1,2,3):
for y in (0,1,2,3):
if x < y:
total+=x+y
sum works here:
total = sum(x+y for x in (0,1,2,3) for y in (0,1,2,3) if x < y)
As an alternative to writing loops N levels deep, you could use itertools.product():
In [1]: import itertools as it
In [2]: for x, y in it.product((0,1,2,3),(0,1,2,3)):
...: if x < y:
...: print x, y, x*y
0 1 0
0 2 0
0 3 0
1 2 2
1 3 3
2 3 6
This extends naturally to N dimensions.
Use numpy. This lets you use arrays that add up like vectors:
x = numpy.arange(3)
y = numpy.arange(3)
total = x + y
With the modified question, add a call to sum as well
total = numpy.sum(x+y)
Reduce function directly reduces collective items to single item. You can read more about them here, but this should work for you:
total=reduce(lambda x,y:x+y,range(4))
or
total=reduce(lambda x,y:x+y,(0,1,2,3))
Another possibility is:
for x,y in ((x,y) for x in (0,1,2,3) for y in (0,1,2,3) if x < y):
print (x, y, x * y)
In this way you can iterate over anything you'd use in a list comprehension without actually creating the comprehended list (if you get my meaning ;) If comprehended list is big, maybe so big it saturates or even doesn't fit in memory, that's quite handy..