Menu
CoddyTech

Final: port a queue model

Lesson 48 of 48 in Coddy's PHP for Python Developers course.

challenge icon

Challenge

Easy

Input is [initial,operations]. Port the source reference program supplied in this task. WorkQueue(initial array) stores string items. push(string):void appends; pop():?string removes and returns the oldest or null when empty; size():int counts remaining. Operations are [push,text] or [pop]. Driver prints popped values separated by commas, using EMPTY for null, then |size. Input items contain ASCII letters only.

The supplied main script reads one JSON value from standard input, checks the named public APIs, and prints the result. Implement the module declarations without printing; do not replace the launcher or read input from a module. Input satisfies the stated types and bounds.

Edit WorkQueue.php. main.php is the locked entry file. Dependencies use require_once __DIR__ with a relative filename.

Python reference program

from collections import deque
class WorkQueue:
    def __init__(self, initial): self.items = deque(initial)
    def push(self, item): self.items.append(item)
    def pop(self): return self.items.popleft() if self.items else None
    def size(self): return len(self.items)
q = WorkQueue(["a", "b"])
out = [q.pop()]
q.push("c")
out.append(q.pop())
print(",".join(out) + "|" + str(q.size()))

Try it yourself

<?php
declare(strict_types=1);
require_once __DIR__."/WorkQueue.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
function queueReport(array $i):string{$q=new WorkQueue($i[0]);$out=[];foreach($i[1] as $op){if($op[0]==="push")$q->push($op[1]);else $out[]=$q->pop()??"EMPTY";}return implode(",",$out)."|".$q->size();}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
$a=new WorkQueue(["a"]);$b=new WorkQueue([]);ensure($a->pop()==="a" && $a->pop()===null && $b->size()===0,"queue independence");$a->push("z");ensure($a->size()===1 && $a->pop()==="z","queue API");
echo queueReport($input),"\n";

All lessons in PHP for Python Developers

Practice on your own: Online PHP compiler