Home Updating only the first occurrence of an object in a queue with python without break
Reply: 2

Updating only the first occurrence of an object in a queue with python without break

KMAN Published in 2018-02-13 22:09:53Z

I created a function in python that will change the priority for the first occurrence of an object, but im having trouble fixing it so that it would only work for the first occurrence without the use of break. In my code below I have used break and it works as intended but I would like to not use it.

    def update_priority(self, object, priority):

for i in range(len(self._queue)):
    if object == self._queue[i].get_item():
        # checking object already has that priority
        if priority == self._queue[i].get_priority():
            # dont change if it has the priority
        # if the object does not have that priority set to new
synchronizer Reply to 2018-02-13 22:29:48Z

It sounds like you also want to learn how to reduce the length of the code. A rule of thumb is to concentrate on making your code clear and concise first, so you can try to identify ways to simplify the structure. For example, you can restructure and remove redundant branches. Many of your cases are just passes. Also, yes, college classes say that break statements aren't great. For clarity, you might want to use a conditional variable to end the loop. In this case, you don't really need to do that, but an alternative is to wrap the code in a function and bypass the rest of a loop simply by returning, You already use a function, so you can just return from the function if all you do is update the one item's priority (and exit). Perhaps you want to return a status code indicating that an item was found or not. (True or False).

def update_priority(self, object, priority):
    # check all items in the queue (you do not require the index.)
    # the entry is stored in "entry"
    for entry in self._queue:
        # if you find the object and its priority needs an update
        if object == entry.get_item() and priority != entry.get_priority():
            # set the priority
            # return true for success, you found the object and updated it
            return True
    """ If you arrive at this line, the object didn't exist or 
        it didn't need an update (if you need to distinguish between "object not found" and 
       "object found but didn't update," use an extra flag or nest the != entry.get_priority as you did before"""
    return False
mgracer Reply to 2018-02-13 22:18:38Z

Your solution is correct you do not need to change it so it doesnt use break. There is no other way to end a loop unless its a while loop and the condition is false or you reach the end of range in a for loop.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.390282 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO