Exit with a status code

Exit with a status code

Easysys Module Programs · 3 of 20

Write a Python program that exits with code 1 on failure and show the code the caller sees.

Output
['check.py', 'x'] -> 0 ok
['check.py'] -> 1 missing argument

Approach

  1. sys.exit(1); the parent reads returncode.

Solution

Python
import subprocessimport sys with open("check.py", "w") as f:    f.write("import sys\nif len(sys.argv) < 2:\n    print('missing argument', file=sys.stderr)\n    sys.exit(1)\nprint('ok')\n")for args in [["check.py", "x"], ["check.py"]]:    r = subprocess.run([sys.executable, *args], capture_output=True, text=True)    print(args, "->", r.returncode, (r.stdout or r.stderr).strip())
Output
['check.py', 'x'] -> 0 ok
['check.py'] -> 1 missing argument

Learn the concept

New to this topic? Read the lesson, then come back.

More sys module programs

← All 20 sys Module Programs

Read command-line arguments

Read command-line arguments

Easysys Module Programs · 1 of 20

Write a Python program that prints its command-line arguments.

Output
show_args.py ['login', '--browser', 'firefox']

Approach

  1. Write a helper script and run it with arguments via subprocess.

Solution

Python
import subprocessimport sys with open("show_args.py", "w") as f:    f.write("import sys\nprint(sys.argv[0], sys.argv[1:])\n")print(subprocess.run([sys.executable, "show_args.py", "login", "--browser", "firefox"],                     capture_output=True, text=True).stdout.strip())
Output
show_args.py ['login', '--browser', 'firefox']

Line by line

Line 5

sys.argv[0] is the script name; the rest are the arguments, as strings.

Learn the concept

New to this topic? Read the lesson, then come back.

More sys module programs

← All 20 sys Module Programs

Palindrome check with deque

Palindrome check with deque

EasyCollections Programs · 20 of 20

Write a Python program to check palindromes by removing characters from both ends of a deque.

Output
[('Level', True), ('python', False), ('racecar', True)]

Approach

  1. Compare popleft() with pop() until the middle.

Solution

Python
from collections import deque def is_palindrome(word):    d = deque(word.lower())    while len(d) > 1:        if d.popleft() != d.pop():            return False    return True print([(w, is_palindrome(w)) for w in ["Level", "python", "racecar"]])
Output
[('Level', True), ('python', False), ('racecar', True)]

Learn the concept

New to this topic? Read the lesson, then come back.

More collections programs

← All 20 Collections Programs

Python Collections Programs with Solutions

Python Practice › Collections Programs

Python Collections Programs with Solutions

20 programs18 easy2 medium0 hard

20 programs for the collections module: Counter for counting, defaultdict for grouping, deque for queues and sliding windows, namedtuple for records, OrderedDict for an LRU cache and ChainMap for layered settings.

Before you start

Read the Collections lesson first if the topic is new to you.

All programs

Invert a dictionary with duplicates

Invert a dictionary with duplicates

EasyCollections Programs · 19 of 20

Write a Python program to invert a grade dictionary into grade -> students.

Output
{'A': ['asha', 'meena'], 'B': ['ravi'], 'C': ['john']}

Approach

  1. defaultdict(list).

Solution

Python
from collections import defaultdict grades = {"asha": "A", "ravi": "B", "meena": "A", "john": "C"}by_grade = defaultdict(list)for student, grade in grades.items():    by_grade[grade].append(student)print(dict(sorted(by_grade.items())))
Output
{'A': ['asha', 'meena'], 'B': ['ravi'], 'C': ['john']}

Learn the concept

New to this topic? Read the lesson, then come back.

More collections programs

← All 20 Collections Programs

Top three scorers

Top three scorers

EasyCollections Programs · 18 of 20

Write a Python program to total player runs from match records and show the top 3.

Output
[('Virat', 143), ('Rohit', 115), ('Gill', 90)]

Approach

  1. Add runs into a Counter.

Solution

Python
from collections import Counter innings = [("Virat", 82), ("Rohit", 45), ("Virat", 61), ("Gill", 90), ("Rohit", 70), ("Rahul", 30)]totals = Counter()for player, runs in innings:    totals[player] += runsprint(totals.most_common(3))
Output
[('Virat', 143), ('Rohit', 115), ('Gill', 90)]

Learn the concept

New to this topic? Read the lesson, then come back.

More collections programs

← All 20 Collections Programs

Expand a Counter

Expand a Counter

EasyCollections Programs · 17 of 20

Write a Python program to list every item of a Counter as many times as its count.

Output
['a', 'a', 'b', 'b', 'b', 'c']

Approach

  1. elements().

Solution

Python
from collections import Counterprint(sorted(Counter(a=2, b=3, c=1).elements()))
Output
['a', 'a', 'b', 'b', 'b', 'c']

Learn the concept

New to this topic? Read the lesson, then come back.

More collections programs

← All 20 Collections Programs

Layered settings with ChainMap

Layered settings with ChainMap

EasyCollections Programs · 16 of 20

Write a Python program that looks up settings in command-line, environment and default layers.

Output
firefox 2 True

Approach

  1. ChainMap(cli, env, defaults) searches left to right.

Solution

Python
from collections import ChainMap defaults = {"browser": "chromium", "retries": 0, "headless": True}env = {"retries": 2}cli = {"browser": "firefox"}settings = ChainMap(cli, env, defaults)print(settings["browser"], settings["retries"], settings["headless"])
Output
firefox 2 True

Learn the concept

New to this topic? Read the lesson, then come back.

More collections programs

← All 20 Collections Programs

namedtuple helpers

namedtuple helpers

EasyCollections Programs · 14 of 20

Write a Python program using _asdict, _replace and _make.

Output
Point(x=3, y=4) {'x': 3, 'y': 4} Point(x=10, y=4)

Approach

  1. These helpers convert and copy named tuples.

Solution

Python
from collections import namedtuple Point = namedtuple("Point", "x y")p = Point._make([3, 4])print(p, p._asdict(), p._replace(x=10))
Output
Point(x=3, y=4) {'x': 3, 'y': 4} Point(x=10, y=4)

Learn the concept

New to this topic? Read the lesson, then come back.

More collections programs

← All 20 Collections Programs

LRU cache with OrderedDict

LRU cache with OrderedDict

MediumCollections Programs · 15 of 20

Write a small least-recently-used cache that holds 2 items.

Output
['a', 'c']

Approach

  1. move_to_end on access; popitem(last=False) evicts the oldest.

Solution

Python
from collections import OrderedDict class LRUCache:    def __init__(self, capacity):        self.capacity = capacity        self.data = OrderedDict()     def get(self, key):        if key not in self.data:            return None        self.data.move_to_end(key)        return self.data[key]     def put(self, key, value):        self.data[key] = value        self.data.move_to_end(key)        if len(self.data) > self.capacity:            self.data.popitem(last=False) cache = LRUCache(2)cache.put("a", 1)cache.put("b", 2)cache.get("a")cache.put("c", 3)print(list(cache.data))
Output
['a', 'c']

Line by line

Lines 22-24

Reading “a” makes it recently used, so adding “c” evicts “b”.

Learn the concept

New to this topic? Read the lesson, then come back.

More collections programs

← All 20 Collections Programs