Endless loop wont work - python

I'm having difficulty realizing why is this part of code
for stanje in pomocna:
for znak in abcd:
novi = tablicaPrijelaza.get((stanje, znak))
dohvatljiva_stanja.append(novi)
dohvatljiva_stanja = list(set(dohvatljiva_stanja))
dohvatljiva_stanja = sorted(dohvatljiva_stanja)
pomocna = dohvatljiva_stanja
not done x times with this implementation of a for that does x iterrations
Yet it seems that it does an endless loop.
One iterration is fine and does what it is supposed to, but after first iterration it goes nowhere
Traceback says it is stuck in second append.

Proper implementation is something more like this which works:
for stanje in dohvatljiva_stanja:
for znak in abcd:
novi=tablicaPrijelaza.get((stanje,znak))
if novi:
pomocna.append(novi)
dohvatljiva_stanja.extend(pomocna)
dohvatljiva_stanja=list(set(dohvatljiva_stanja))
dohvatljiva_stanja=sorted(dohvatljiva_stanja)
del pomocna[0:len(pomocna)]

Related

How do I run a conditional statement "only once" and every time it changes?

I might be asking a simple question. I have a python program that runs every minute. But I would like a block of code to only run once the condition changes? My code looks like this:
# def shortIndicator():
a = int(indicate_5min.value5)
b = int(indicate_10min.value10)
c = int(indicate_15min.value15)
if a + b + c == 3:
print("Trade posible!")
else:
print("Trade NOT posible!")
# This lets the processor work more than it should.
"""run_once = 0 # This lets the processor work more than it should.
while 1:
if run_once == 0:
shortIndicator()
run_once = 1"""
I've run it without using a function. But then I get an output every minute. I've tried to run it as a function, when I enable the commented code it sort of runs, but also the processing usage is more. If there perhaps a smarter way of doing this?
It's really not clear what you mean, but if you only want to print a notification when the result changes, add another variable to rembember the previous result.
def shortIndicator():
return indicate_5min.value5 and indicate_10min.value10 and indicate_15min.value15
previous = None
while True:
indicator = shortIndicator()
if previous is None or indicator != previous:
if indicator:
print("Trade possible!")
else:
print("Trade NOT possible!")
previous = indicator
# take a break so as not to query too often
time.sleep(60)
Initializing provious to None creates a third state which is only true the first time the while loop executes; by definition, the result cannot be identical to the previous result because there isn't really a previous result the first time.
Perhaps also notice the boolean shorthand inside the function, which is simpler and more idiomatic than converting each value to an int and checking their sum.
I'm guessing the time.sleep is what you were looking for to reduce the load of running this code repeatedly, though that part of the question remains really unclear.
Finally, check the spelling of possible.
If I understand it correctly, you can save previous output to a file, then read it at the beginning of program and print output only if previous output was different.

How to check if the line of code displays error

I am trying to do something with lists. I would like to learn this.
So let's say I have this
_list = [1,2,3]
I want to check values of elements inside the list while iterating,
for x in range(len(_list)):
if _list[x] == _list[x+1]:
print(_list[x])
But the problem here is it throws an error while checking _list[-1] how do i solve this?
I tried -
if _list[x] != _list[-1]
assert _list[3]
These doesnt seem convenient,
I am thinking of trying try and except block but is any other option is available?
Make your loop go till len(_list) -1:
for x in range(len(_list) - 1):
if _list[x] == _list[x+1]:
print(_list[x])

Python: Minimizing function via loop

My code is really simple:
import numpy
def f(x):
return x**2 +1
f_min=10
for x in numpy.arange(-1,10,0.1):
if f(x)<f_min :
f_min=f(x)
x_min=x
else:
print (x_min)
It gives me the correct result (x-->0) but not only once but alot of times. Why is that and how can I keep it from doing so?
Because you told it to. :-)
Your if statement reads:
if I have a new minimum, record the value and position;
otherwise, print the existing minimum.
Any time you don't find a new minimum, you print. Since this function has its minimum early in your range, you get a lot of output.
If you want the global minimum printed only once, then do it only once: move it outside of the loop.
for x in numpy.arange(-1,10,0.1):
if f(x)<f_min :
f_min=f(x)
x_min=x
print (x_min)
To fix this, move the print statement out of the for loop:
import numpy
def f(x):
return x**2 +1
f_min=10
for x in numpy.arange(-1,10,0.1):
if f(x)<f_min :
f_min=f(x)
x_min=x
print (x_min)
Why do this? Well, before, when you had the print statement in the for loop, each time the for loop went through, whenever the if statement was not true, it printed, so you got a bunch of printed things. Now, when you move it out of the for loop, it can only be printed once, and the program works as you expect.

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:

Python. Project Euler Q35. Got a solution but I don't understand why other method doesn't work.

def rot_dig(x):
y=''
output=[x]
listing=list(x)
for i in range(1,len(x)):
listing.append(listing[0])
del(listing[0])
for i in listing:
y=y+i
output.append(y)
y=''
return output
import math
def prime_is(x,prime):
for m in prime:
if m&lt=math.sqrt(x):
if x%m==0:
return False
else:
return True
prime=[2]
for x in range(3,1000000):
if prime_is(x,prime):
prime.append(x)
primestr=[]
for x in prime:
primestr.append(str(x))
sums=0
for x in primestr:
count=0
for y in rot_dig(x):
if y in primestr:
count+=1
if count==len(x):
sums+=1
else:
for y in rot_dig(x):
if y in primestr:
primestr.remove(y)
print sums
When run with the bold code the solutions miss the final rotation. So if it looks at say 1193, it includes 1193, 3119, 9311 but not 1931. I have spent a while trying to work out why but I don't get it.
I have since edited the code to make it much quicker and solved the problem I had by simply removing the block of code, but I can't understand why it happens since surely that block of code will only be executed on non circular primes.
It's probably because your outer loop is for x in primestr: and the marked code removes items from primestr. You don't want to change primestr while looping over it that way. You could use a loop like while i < len(primestr) instead.
Some other improvements would be to compute sqrt outside the loop; to use a list comprehension instead of a loop to create primestr; and especially to use string slicing in rot_dig, it's way more complicated than it needs to be.

Categories