I have post the similar question before,but this time the problem is different,I got stuck with the following code..can anyone help with it?thanks in advance
I have fixed mu code as suggested,thanks
from numpy import *
#vs,fs,rs are all m*n matrixs,got initial values in,i.e vs[0],fs[0],rs[0] are known
#want use this foor loop to update them
vs=zeros((10,3))
vs[0]=([1,2,3])
fs=zeros((10,3))
fs[0]=([2,3,4])
vs=zeros((10,3))
vs[0]=([3,4,5])
for i in range(5):
#start looping..
vs[i+1]=vs[i]+fs[i]
fs[i+1]=(rs[i]-re[i])
rs[i+1]=rs[i]+vs[i]
print vs,fs,rs
then this code gives vs,fs,rs in different i,but not update each rows of rs,fs,vs and return me a single array of rs,fs,vs (fully updated). whats the problem here?..what should I add?thanks
Put your inizialization outside the loop! Right now, you're resetting the arrays to all zeros each time through the loop, over and over, which is absurd. You also appear to have a typo -- you set vs twice and rs never -- so I've tried to guess what you meant.
from numpy import *
#vs,fs,rs are all m*n matrixs,got initial values in,i.e vs[0],fs[0],rs[0] are known
#want use this foor loop to update them
vs=zeros((10,3))
vs[0]=([1,2,3])
fs=zeros((10,3))
fs[0]=([2,3,4])
rs=zeros((10,3))
rs[0]=([3,4,5])
for i in range(5):
#start looping..
vs[i+1]=vs[i]+fs[i]
fs[i+1]=rs[i]-re[i]
rs[i+1]=rs[i]+vs[i]
print vs,fs,rs
You do not start looping where the comment indicates it, but at the for i in range(5): line. Everything in the indented block (the "body of the for-loop") is done repeatedly for each i. So setting vs and fs to zero is done repeatedly, each time deleting what was calculated before. These initializations should be done before the for.
Also vs is initialized twice while rs isn't initialized at all, probably that's a typo and it should look like this:
vs=zeros((10,3))
vs[0]=([1,2,3])
fs=zeros((10,3))
fs[0]=([2,3,4])
rs=zeros((10,3))
rs[0]=([3,4,5])
for i in range(5):
#start looping..
...
I don't know exactly what you want to print. If you want to print every matrix every time it is updated, then you're fine. But if you want to print the matrices after all the updates have been completed, then you should bring that print statement out of the for loop.
This and what Alex and sth have said should fix your code fully
Related
When solving a question of Project Euler I ran into the following logical error related to when n is updated.
while(n<1000):
#update n
#do something with n
#do stuff
vs
while(n<1000):
#do something with n
#do stuff
#update n
In the first instance, I ended up performing an operation with n even though the condition of n<1000 is violated.
Does this logical error have a name? How common is this bug?
I tried to look for it, I did find things about pre-incrementing and post-incrementing a variable. Although that is close to the error, it isn't exactly what is happening here. I found a reference to this in a SO answer about for loop vs while loop in the part describing how for loops are more concise and direct when compared to while loops. Essentially with while loops we end up running code after a variable update which could be buried somewhere in the code.
This is not always a bug: it depends on the algorithm. In some cases, you know that the original value of n is legal (so you can enter the loop), but you want to update and use the new value in your processing. You need to match your code to your algorithm. Your second code block is the canonical for-equivalent, and is more common.
This falls under the general heading of "off by 1 error".
I am creating a probabilistic learning task. It has a learning phase which is what I am preparing at the moment using the builder interface with custom code in PsychoPy. The learning phase has at least 60 trials in a loop called practice.
Apart from the correct answer which is used to give feedback to participants, there are three conditions by which it can be decided whether the learning phase can be finished. Once the criteria are reached, the training phase will be terminated.
I need to append three variables and keep count of the scores.
I have created 3 variables (resembling the resp.corr variable) calculated specifically for the three conditions. The code is placed in the ‘end routine’ section because in the earlier sections resp was not yet defined.
End routine
if (resp.keys == letterA):
resp1 = 1
else:
resp1 = 0
if (resp.keys == letterC):
resp2 = 1
else:
resp2 = 0
if (resp.keys == letterE):
resp3 = 1
else:
resp3 = 0
This is working fine. I added variables resp1, resp2 and resp3 to the excel output. I checked and they are all calculated correctly.
So i know that I need to append these variables in a list and I used the following code:
End Routine
resplist1.append(resp1)
resplist2.append(resp2)
resplist3.append(resp3)
I also saved these lists in the excel output to check if they are calculated correctly. I used the following code:
End Routine
practice.addData('resplist1', resplist1)
practice.addData('resplist2', resplist2)
practice.addData('resplist3', resplist3)
Unfortunately, replist1, replist2 and replist3 fail to append the list. Instead the values of resp1, resp2 and resp3 are printed in []. Picture at the bottom:
imageimage.png1635×655 34.1 KB
I also checked whether it was possible to calculate the sum of replist1, replist2 and replist3 and as you can guess it did not work. The calculated values were exactly the same as resp1, resp2 and resp3.
I am not sure why the list is not being appended correctly and I will appreciate all help! I have been stuck on this task for way too long now and I am desperate to have it finished.
https://i.stack.imgur.com/aXW60.png
You don't show how you initialise your lists resplist1 etc. My guess is that you are doing so in the "Begin routine" tab. That would continually reset them so that they never contain more than one value.
If so, shift their initialisation to the "Begin experiment" tab so you don't lose the newly appended values on every trial.
When you have a list that actually contains multiple elements, the easiest way to do calculations upon it is to convert it to a numpy (imported as np) array, which allows vectorised operations, e.g:
sum_1 = np.array(resplist1).sum()
display expression: prints out the value of an expression each time it gets changed. This is useful for monitoring the value of variables that get changed in loops. So, suppose the following is the code:
for i in range(100):
for j in range(100):
a=f(i,j)
I know something is wrong with the execution of a=f(i,j) for certain values of i and j. Then, how to use the display command from pdb module to find out the values of i and j when it does not work? I suppose when you use display command, it will display the value of i and j automatically, right? Do I need to combine the c command and b command from pdb module also? Many thanks for your time and attention.
display sets a "watch", so that each time execution stops (whether by completing a next, a step, or an until, or breaking on a continue ), if the value has changed, it will print a message showing the old value and the new value.
Since you know something is wrong with your f function, your easiest solution is to put a break on that function, and set display of the inputs inside that scope. Since you have shown us nothing about f, I don't know what the input variables will be called at that level, but it's likely that it won't be "i" and "j", so set the display appropriately.
I find display most useful for when I'm stepping through code that involves loops, using n or s or c. It keeps track of variables for me, and saves me from having to print the variables I'm interested in. If you know your problem is in f, you'll have to step through the code there yourself, and check all the variables at all the interesting statements. If you find yourself checking a variable repeatedly, that's where you use display.
I have a while loop below the commented out portions are from a previous test.
My hope was that the while loop would execute the methods from top to bottom and as the methods finish the methods below would start.
My hope felt valid as when the code was not in a while loop that was what was happening. Or maybe it just seemed that way?
My point is the code is executing in such a way that my assumption above seems wrong.
can any one please explain this to me?
counter = (len(cities)-1)
count = 0
while count != counter:
setCity(cities[count])
getApiData()
#populateVars()
#storeInDatabase()
#goToNextPage()
count +=1
storeData.createCSV(OTS.CSVname)
storeData.purgeDatabase()
Just iterate over the array without an index:
for city in cities:
setCity(city)
getApiData()
It seems that the code is indeed being run sequentially, unless there's some concurrency behind the scenes that you don't know about or aren't mentioning.
Regarding your code as it is, I think you're mistakenly subtracting 1 from len(cities); and anyhow, you should just iterate directly over the cities using a for loop.
for city in cities:
setCity(city)
getApiData()
# populateVars()
# storeInDatabase()
# goToNextPage()
storeData.createCSV(OTS.CSVname)
storeData.purgeDatabase()
I will update this answer if there are any changes/clarifications.
The following code hangs,
while np.any((np.log10((O3 / HB)) < 0.61 / (np.log10(N2 / HA) - 0.05) + 1.3).any()):
plt.plot(np.array(np.log10(N2 / HA)), np.array(np.log10(O3 / HB)), '.g')
plt.plot(np.array(np.log10(N2 / HA)), np.array(np.log10(O3 / HB)), '.r')
The plot works without the "while" condition. In the above form it hangs.
Do I need a "break"?
thanks
The code probably freezes because you are making a new plot object every time the loop iterates, eventually you'll run out of memory. The program usually spits out a warning after 20 or so plots made.
You can clear the axis each time as an alternative, or
When to use cla(), clf() or close() for clearing a plot in matplotlib?
or you could use the .set_xdata, set_ydata commands to simply update the data. Or you could reuse the same axes if you want to overlay the data.
Discussion of Issue
The code freezes because you are using a while loop with a condition whose variables do not change within the loop. Therefore, if the condition evaluates to True the first time through the loop, it will evaluate to True indefinitely, (i.e. the code 'hangs'). Typically (unless you want the loop to run forever) one or more variables within a while loop will change within the loop. A very simple example is,
while index < 10:
plt.plot(x_data[index], y_data[index])
index += 1 # Here the index changes.
Note: For these purposes it is more common to use for index in range(10): or better yet for xd, yd in zip(x_data, y_data): plt.plot(xd, yd) rather than a while loop because then you don't need to have the index += 1 line, and it is clearer at the beginning of the loop what is going on. I merely provided this as a clear example use of while.
Even if the conditional variables do change within the loop (i.e. if you're only providing a snippet of your while loop), it is possible that the conditional statement always evaluates to True. In this case, again, you will never exit the while loop and your code will 'hang'.
Potential Solutions
There are several ways you could fix your problem depending on what you are trying to do:
If you just want to plot your data once, use if instead of while.
If you are only showing us a snippet of your loop and the variables in the conditional statement do change within the loop, I would recommend:
A) starting by placing a print(np.any((np.log10((O3 / HB)) < 0.61 / (np.log10(N2 / HA) - 0.05) + 1.3).any())) at the top of your loop and run your code. I presume this will dump True to your console.
B) You could then start to break this statement apart using more print statements such as print('N2: %f' % N2) to understand why your statement is never evaluating to False and therefore you are never exiting the loop.