Recalling a function iteratively - python

I have a question about recalling my function within a loop.
Below is my code:
List_new = myfunction()
for items in List_new:
if(my condition is TRUE):
Execute some commands
if(my condition is FALSE):
recall myfunction()
My problem is that I am loading "List_new" using myfunction(). How can I change "List_new" iteratively when my condition is False. I want to reload the function especially when the condition is FALSE. This means I keep calling the function until it is false and then execute the final output from myfunction().
Thank you in advance for your help.

I am going to assume the list generated by myfunction() is a constant size.
You can use a while loop:
List_new = myfunction()
index=0
while index < len(List_new):
items = List_new[index]
if(my condition is TRUE):
#Execute some commands
i+=1
if(my condition is FALSE):
List_new = myfunction()
Keep in mind that this solution will have an infinite loop if myfunction() continuously generates false values. If you can guarantee that all values will eventually be True then it should always terminate.

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.

If statement called, ignore after even if condition has been met

I have a simple if statement in my code
if len(bootstrap_node_list_recieved_no_dups) >= min_node_to_complete_boot_strap:
print "recieved required nodes"
Basically I want to know if have enough nodes, I only want this to occur once, as the code will still carry on and be run repeatedly so currently this if statement is run every time as I would expect.
Is there a way to code it so the if statement is run, but after it completes once it is never run again?
The >= is required as the input is not a constant.
I hope this is clear, as it's a bit hard to describe.
Update,
i have tried to implement the suggestions but am getting the error
UnboundLocalError: local variable 'flag' referenced before assignment
full code below:
flag = False
def number_of_duplicates_in_list():
number_recieved = len(bootstrap_node_list_recieved)
bootstrap_node_list_recieved_before = len(bootstrap_node_list_recieved_no_dups)
" this method works in O(n^2) time and is thus very slow on large lists"
for i in bootstrap_node_list_recieved:
if i not in bootstrap_node_list_recieved_no_dups:
bootstrap_node_list_recieved_no_dups.append(i)
assert len(bootstrap_node_list_recieved_no_dups) >= bootstrap_node_list_recieved_before
if len(bootstrap_node_list_recieved_no_dups) >= min_node_to_complete_boot_strap and flag is False:
print "recieved required nodes"
flag = True
You could have some flagging variable that is changed when the if statement is first triggered. The below code is a minimal example which will only print the 'Triggered' statement once, even though all numbers above 3 would trigger the statement if the flag was not also being checked.
flag = False
for x in xrange(10):
if x > 3 and flag is False:
print 'Triggered'
flag = True
# Do something else
If you want to do this inside a function, you need to move the flag initialisation into the function as well. Note that re-running the function will reset the flag:
def test_func():
flag = False
for x in xrange(10):
if x > 3 and flag is False:
print 'Triggered'
flag = True
# Do something else
test_func()
To be able to run the function multiple times but only trigger the if statement and change the flag once, you need to link the flag to the function calls. A simple method of doing this is to pass and return the flag on each call:
flag = False
def test_func(flag):
for x in xrange(10):
if x > 3 and flag is False:
print 'Triggered'
flag = True
# Do something else
return flag
flag = test_func(flag)
flag = test_func(flag)
Here, the flag is define outside of the function and passed to each function when called. If not triggered, it passes through without change. If triggered, it is changed and its state passed back outside the function.
Other approaches could be defining a global variable or building a class with the flag as an object variable and accessing it via self.
Define flag to be global within number_of_duplicates_in_list. Otherwise, you can only read it.

or condition in while loop python

Does or condition work in a while loop in python? I can't seem to make it work. This is the sample of how my code works.
newslot = 3
moved = False
while newslot > 0 or moved != True:
enabled = query something on the database where slot = newslot
if enabled:
print 'do something here'
moved = True
else:
newslot-=1
print 'slot disabled'
So when the newslot gets to value of zero it still proceeds to go inside the while loop.
I seem to be missing something here.
or is working as should be expected. A while loop will continue until its condition is false. If its condition is two separate conditions connected with an or, it will only be false when the two conditions are both false.
Your loop will continue repeating until moved is false and newslot is <= 0. I'm guessing you actually want to use and in this case, as you want the loop to stop once either condition is met.

Python: While Loop Check Throughout Loop if True

I have a very simple problem: I have made a while loop, and in the middle of it, set the initial condition to false. This, however, does not stop the loop and runs entirely through, (somewhat obviously,) until it attempts to unsuccessfully go through again. Here is a simplified construction of what I have.
while(a):
print("hi")
a = False
print("bye")
This returns:
hi
bye
Again I would like to only return hi; I want the loop to continually check if its satisfied.
Any help greatly appreciated.
Use:
return, or break
while a:
print('hi')
a = False
if not a:
break
print('bye')
In a function or loop, when something is returned, the function or loop terminates. You could also return True, or break which is a specific way to 'break' out of a loop.
Since the condition is true to start with (by design), the body of the loop will execute at least once. The fact you do something in the body of the loop to make the loop condition false doesn't stop the current iteration. It just means there won't be a next iteration after this one is done.
So if you want to get out in the middle of the current iteration, then you need to use break, return, or something more sophisticated like #inspectorG4dget's suggestion.
while(a):
print("hi")
a = False
if a:
print("bye")
OR
while(a):
for s in ["hi", "bye"]:
if a:
print(s)
if someCondition:
a = False

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