0

What is the best way to provide a string representation of everyone in the queue. A person with a value 0 or less will have infinite number of turns. When a person is removed from the queue, they are re-added to the queue if they still have turns left. My queue stays empty. The goal is to follow FIFO rules when it comes to queue.

class Queue:
    
# implementation of a Queue
    def __init__(self):
    #    empty queue.
        self.queue = []

    def enqueue(self, value):
        # Add an item to the queue - run code queue is empty
        self.queue.insert(0, value)

    def dequeue(self):
       
        # Remove the next item from the queue. 
       
        value = self.queue[0]
        del self.queue[0]
        return value

    def is_empty(self):
        # check to see if queue is empty
        return len(self.queue) == 0
    
    def __len__(self):
        
        return len(self.queue)

    def __str__(self):
       
        result = "["
        for item in self.queue:
            result += str(item) + ", "
            result += ", "
        result += "]"
        return result


class Taking_Turns_Queue:
   
    
    class Person:
    #    define name and turns

        def __init__(self, name, turns):
           
            self.name = name
            self.turns = turns

        def __str__(self):
            # display a person
            if self.turns <= 0:
                result = "({}:Forever)".format(self.name)
            else:
                # Add zero and 1 below. THe orginal code had zero.
                result = "({}:{})".format(self.name, self.turns)
            return result

    def __init__(self):
        """ 
        Start with an empty queue
        """
        self.people = Queue()

    def add_person(self, name, turns):
        """
        Add new people to the queue with a name and number of turns
        """
        person = Taking_Turns_Queue.Person(name, turns)
        self.people.enqueue(person)

    def get_next_person(self):
        
        if self.people.is_empty():
            print("No one in the queue.")
        else:
            person = self.people.dequeue()
            if person.turns > 1:  
                person.turns -= 1 
                self.people.enqueue(person)
            print(person.name)

    def __len__(self):
        """
        Support the len() function
        """
        return len(self.people)

    def __str__(self):
        """
        Provide a string representation of everyone in the queue
        """
        return str(self.people)

# Test Cases

# Test 1
# Scenario: Create a queue with the following people and turns: Bob (2), Tim (5), Sue (3) and
#           run until the queue is empty
# Exepcted Result: Bob, Tim, Sue, Bob, Tim, Sue, Tim, Sue, Tim, Tim
print("Test 1")
players = Taking_Turns_Queue()
players.add_person("Bob", 2)
players.add_person("Tim", 5)
players.add_person("Sue", 3)
print(players)   
while len(players) > 0:
    players.get_next_person()
# Defect(s) Found: 

print("=================")

# Test 2
# Scenario: Create a queue with the following people and turns: Bob (2), Tim (5), Sue (3)
#           After running 5 times, add George with 3 turns.  Run until the queue is empty.
# Exepcted Result: Bob, Tim, Sue, Bob, Tim, Sue, Tim, George, Sue, Tim, George, Tim, George
print("Test 2")
players = Taking_Turns_Queue()
players.add_person("Bob", 2)
players.add_person("Tim", 5)
players.add_person("Sue", 3)
for i in range(5):
    players.get_next_person()
print(players)
players.add_person("George", 3)
print(players)
while len(players) > 0:
    players.get_next_person()
# Defect(s) Found: 

print("=================")

# Test 3
# Scenario: Create a queue with the following people and turns: Bob (2), Tim (Forever), Sue (3)
#           Run 10 times.
# Exepcted Result: Bob, Tim, Sue, Bob, Tim, Sue, Tim, Sue, Tim, Tim
print("Test 3")
players = Taking_Turns_Queue()
players.add_person("Bob", 2)
players.add_person("Tim", 0)
players.add_person("Sue", 3)
print(players)
for i in range(10):
    players.get_next_person()
print(players)    
# Defect(s) Found: 

print("=================")

# Test 4
# Scenario: Try to get the next person from an empty queue
# Exepcted Result: Error message should be displayed
print("Test 4")
players = Taking_Turns_Queue()
players.get_next_person()
# Defect(s) Found:
    
BRN
  • 1
  • 1
  • What is the issue you are having? – Kaia Feb 09 '23 at 17:21
  • 1
    @Kaia: "My queue stays empty." – JonSG Feb 09 '23 at 17:25
  • I'm trying to figure out to make the queue add and remove name with numbers. The queue often stays the same or empty. – BRN Feb 09 '23 at 17:29
  • 1
    Double check your indexing. You're inserting Bob, then Tim, then Sue all at index 0, so your queue is `[(Sue:3), (Tim:5), (Bob:2)]` going into `Test 1`, but you're dequeuing index 0 and then inserting back into index 0. There may be other things going on, but make sure you actually have a FIFO before debugging anything else. Test your FIFO with a simpler structure before moving up. – picobit Feb 09 '23 at 17:40
  • You insert *on-the-left* and remove *from-the-left*. That is first in last out behaviour. You might want to use a collections.deque, it is designed for inserts and removals at either end. – wwii Feb 09 '23 at 19:33
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Feb 09 '23 at 19:45
  • The code written below gave a better understanding of FILO. – BRN Feb 09 '23 at 20:01

1 Answers1

0

Your FIFO isn't a FIFO. Start with something like this before complicating things with people and turn counts.

class FIFO:
    def __init__(self):
        self.buffer = []
    def add(self,item):
        self.buffer.insert(0,item)
    def get(self):
        return self.buffer.pop()
    def __str__(self):
        if len(self.buffer) == 0:
            return "[]"
        out = "[" + ''.join([f'{item},' for item in self.buffer])
        return out[:-1]+"]"

mybuf = FIFO()
mybuf.add("one")
mybuf.add("two")
mybuf.add("three")
assert mybuf.buffer == ["three", "two", "one"]

_item = mybuf.get()
mybuf.add(_item)
assert mybuf.buffer ==  ["one", "three", "two"]

print("All tests passed.")

# All tests passed.

Once that's working, then you can take baby steps toward your goal.

class FIFO:
    def __init__(self):
        self.buffer = []
    def add(self,item):
        if item["Turns"] > 0:
            self.buffer.insert(0,item)
    def get(self):
        person = self.buffer.pop()
        person["Turns"] -= 1
        return person
    def __str__(self):
        if len(self.buffer) == 0:
            return "[]"
        out = "[" + ''.join([f'{item},' for item in self.buffer])
        return out[:-1]+"]"
    def items(self):
        return len(self.buffer)

# Test 1
# Expected result: Bob Tim Sue Bob Tim Sue Tim Sue Tim Tim
mybuf = FIFO()
mybuf.add({"Name":"Bob","Turns":2})
mybuf.add({"Name":"Tim","Turns":5})
mybuf.add({"Name":"Sue","Turns":3})

debug = False # Set this to true for more information
output = []
while mybuf.items() > 0:
    person = mybuf.get()
    if debug:
        print(f"Got: {person['Name']}, Remaining turns: {person['Turns']}")
    output.append(person["Name"])
    mybuf.add(person)
    if debug:
        print(f"Buffer is: {mybuf}\n")

print(' '.join(output))
# Bob Tim Sue Bob Tim Sue Tim Sue Tim Tim
picobit
  • 527
  • 5
  • 15