Plotting something halfway through a for loop - python - python

I'm running a model of a spring in python using a for loop over 50 iterations and want to plot it after 25 iterations, and again after 50 iterations.
Here's an excerpt of the code I've been using so far (I can post the whole thing if that would be helpful).
ts = np.array([0])
xs = f(ts)
for i in range(50):
tn = ts[i]+0.1
xn = f(tn)
ts = np.append(ts,tn)
xs = np.append(xs,xn)
while i == 24:
plt.plot(ts,xs)
plt.savefig('Weight plotted after 2.5 seconds.png')
while i == 49:
plt.plot(ts,xs)
plt.savefig('Spring plotted after 5 seconds.png')
I'm not getting any errors but it's just not returning anything. I'm pretty new to python and coding in general so any input that anyone might have would be much appreciated!

You need to replace your while statements with if statements.
while will repeat the indented code as long as the condition i == 24 is satisfied. Once your loop reaches i == 24, the program will repeatedly save your figure until you terminate the program because i does not change within the while loop.
if will execute the indented code once if the condition is satisfied--which is what you want.

Related

List_Name.clear causes crash in python

I'm trying to create a snake algorithm that beats the game on its own, I've gone for the Hamiltonian cycle method with the capability of creating shortcuts, I was trying to create the cycle by using a pathfinding algorithm and compute the longest path where the head of the snake is the start, the tail the end and the 2 blocks in between are walls, the pathfinding library in python uses a matrix to represent the map of pixels, so to generate my matrix I use this block of code:
from pathfinding.core.grid import Grid
from pathfinding.finder.a_star import AStarFinder
from pathfinding.core.diagonal_movement import DiagonalMovement
matrix=[]
row=[]
yi=0
xi=0
while yi<800:
if row != []:
matrix.append(row)
yi += 20
row.clear() #This causes crash
while xi<1400:
row.append(1)
if xi == 40 or xi == 60:
if yi == 20:
row.append(0)
xi += 20
grid = Grid(matrix=matrix)
start = grid.node(4, 1)
end = grid.node(1, 1)
finder = AStarFinder(diagonal_movement=DiagonalMovement.always)
path, runs = finder.find_path(start, end, grid)
print('operations:', runs, 'path length:', len(path))
print(grid.grid_str(path=path, start=start, end=end))
But whenever I run it, it crashes,
I've narrowed it down to the line
row.clear()
but I have no clue why it does this, if I remove it no walls are created, other methods of emptying the list like :row=[] or
while i<len(row):
row.remove(i)
row += 1
give me the same result, I get no error message, nothing prints it just crashes, its even more clear on the entire code because the window displaying the game of snake doesn't display anything and the windows crash window appears, I'm using Windows 10, python 3.8.2
I'm quite new to programming so please excuse my inefficient code, I do it for fun and performance brings me little pleasure, any help is greatly appreciated
I hope I didn't miss anything obvious making you waste time but as long as my code is fixed I'm a happy chappy.
Thanks
Turns out I'm really stupid and forgot to add xi = 0 so it could start the indented loop again instead of just looping into infinity

Why is a line in my if statement running every time? (python)

I am working on a project were the user inputs a number and a list, and whatever item in the list is closest to the number, is printed out. I have come across a problem were the line in my if() statement in my while loop is running every time? I have a feeling it has something to do with indenting if() statements in python 3 but I am not certain. Anybody know why this is happening?
import math
MatchingI = math.inf
while i < len(compareList):
if (abs(int(mainNum) - int(compareList[i])) < MatchingI):
MatchingI = int(compareList[i])
i += 1
I think that you need to assign abs(int(mainNum) - int(compareList[i])) to MatchingI, instead of assigning int(compareList[i]) to MatchingI.
import math
MatchingI = math.inf
while i < len(compareList):
if (abs(int(mainNum) - int(compareList[i])) < MatchingI):
MatchingI = abs(int(mainNum) - int(compareList[i]))
answer = compareList[i]
i += 1
print(answer)
Isn't this what you are looking for?

How to add a new value to a list everytime a 'while' loop occurs?

My problem is very basic, I'd say. I'm just starting to learn Python, but I can't do one little thing that is driving me mad.
I have a 'while' loop, and I want to add the value of a variable (that changes every loop too, as you can see in the code, the variable is the 'minutos_decorridos') to a list, everytime the loop occurs.
Here's my code
minutos_decorridos = 0
lista_entradas = []
lista_saidas = []
while minutos_decorridos <= 15:
minutos_decorridos=minutos_decorridos+1
lista_entradas.append(minutos_decorridos)
lista_saidas.append(minutos_decorridos)
print(lista_entradas)
print(lista_saidas)
The results are:
[16]
[16]
But my expected result is
[1,2,3,4,5,...,15,16]
[1,2,3,4,5,...,15,16]
Because I want it to add the value of the variable to the list every time the loop occurs. Note that the variable is increasing by 1 every loop too, that's why I'm expecting 1,2,3,4...15,16.
Only the code that is indented will be executed in each iteration. You can simply move your append statements into the while loop, like so:
minutos_decorridos = 0
lista_entradas = []
lista_saidas = []
while minutos_decorridos <= 15:
minutos_decorridos=minutos_decorridos+1
lista_entradas.append(minutos_decorridos)
lista_saidas.append(minutos_decorridos)
print(lista_entradas)
print(lista_saidas)
Not sure, if you have done, other languages. But other languages like 'C++' uses curly braces to identify what goes inside the loop.
While (i<15)
{
statement;
}
However, in python, it is only indentation, that makes the statements inside a loop or condition.

while loop within if statement condition

I'm really struggling to finish the last part of my code.
Here's some background. This code looks for an object that's in front of it via an ultrasonic sensor, and if there is, it logs that onto an internet database via http_get, if there isn't an object, it just keeps looking every 2s.
I have everything waxed, except for if someone leaves an object there for a long time. Have a look at the code and it will make sense. (This is just a portion of the code).
while True:
#Setting the pins and taking the reading.
#In a while loop so that it continually does it.
trig=machine.Pin(5,machine.Pin.OUT)
trig.low()
time.sleep_ms(2)
trig.high()
time.sleep_ms(10)
trig.low()
echo=machine.Pin(4,machine.Pin.IN)
while echo.value() == 0:
pass
t1 = time.ticks_us()
while echo.value() == 1:
pass
t2 = time.ticks_us()
cm = (t2 - t1) / 58.0
print(cm) #cm is the output that I use to determine if the object is there or not.
if cm >= 15: #This means there is nothing there.
time.sleep(1)
elif cm <= 15: #Because the distance is less than 15cm, something is there, and it logs it.
http_get('URL')
time.sleep(5)
So now, as you can see, if someone leaves the object there for less than 5 seconds, that will only log once (the count of the object is crucial). The caveat is, if someone forgets the object there, or leaves it there for 10s, it will log twice, which we can't have. So, I kind of need something like this, but syntactically correct.
def checking():
if cm >= 15:
time.sleep(1)
elif cm <= 15:
http_get('URL')
time.sleep(5)
while: cm <= 15:
keep sensing but not logging.
then, if the distance changes to back to more than 15cm,
return back to the top. (because the object would be gone).
I hope this is clear enough for you guys.
Let me know if there needs to be any clarification somewhere.
Use a flag to check that the distance went to more than 15 or not
flag_reset = 0
while True:
(your_code)
if cm >15:
time.sleep(1)
flag_reset = 0
elif cm <=15 and flag_reset == 0:
do_something()
flag_reset = 1

Bubble sort error with nested (high scores) list - python

For my software major work I have to create a program. In summary, the high scores list needs to be sorted before it can be written to file. To do this, I am using a bubble sort and I can't use the inbuilt sort function. The text file that the data is being read from is stored in a nested list. The text file looks like this:
NameOne
10
NameTwo
15
NameThree
9
This is the bubble sort code I have but does not work:
b_not_sorted = True
while b_not_sorted:
counter = 0
b_not_sorted = False
for counter in range(len(highest_scores) - 1):
if highest_scores[counter] < highest_scores[counter + 1]:
b_not_sorted = True
highest_scores[counter], highest_scores[counter+1] = highest_scores[counter+1], highest_scores[counter]
counter = counter + 1
I need the scores to be sorted from highest to lowest. Any help would be greatly appreciated and you will be credited appropriately in my program credits :). Thanks.
Here's a hint:
Check how many times your outer while loop is running. It should be running more than once, correct? What will always happen that causes the loop to exit, no matter what?
Try going through the code line by line and seeing what happens at every point.
The statement b_not_sorted = False at the end of the outer loop results in the outer loop exiting after executing only once. You need to move that statement to another part of your code. Try changing the name of b_not_sorted to I_still_need_to_go_through_the_list in your head:
Obviously in the first line:
while I_still_need_to_go_through_the_list:
it should be True, since you haven't gone over the list at all. You don't know if it's in order or not.
and after the line:
if highest_scores[counter] < highest_scores[counter + 1]:
Of course then we still need to make another pass, since we just made a change to the list and need to make sure no further changes are needed.
But what if no changes are made? I_still_need_to_go_through_the_list should be False then. Hmmm. If we put I_still_need_to_go_through_the_list = False right before the for loop, then it will be False unless we make changes to the list, which is exactly what we want.
You're doing b_not_sorted = False right after the first iteration, but it shouldn't be there! The algorithm just stops before it finishes the sorting.
You should instead do b_not_sorted = True only if highest_scores[counter] < highest_scores[counter + 1]
Also, the swapping code can look much nicer in Python. Instead of using temp_var just do this:
highest_scores[counter], highest_scores[counter+1] = highest_scores[counter+1], highest_scores[counter]
Python style guide suggests that you shoudn't write == True or == False in if statements. Do it like this:
while b_not_sorted:

Categories