Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Created February 18, 2026 11:26
Show Gist options
  • Select an option

  • Save sunmeat/267c714c928cfb84c511fbb87ce89489 to your computer and use it in GitHub Desktop.

Select an option

Save sunmeat/267c714c928cfb84c511fbb87ce89489 to your computer and use it in GitHub Desktop.
узагальнення в пайтон
from collections.abc import Iterable
from typing import Self
# узагальнений клас-стек (LIFO)
class Stack[T]:
def __init__(self) -> None:
self._items: list[T] = []
def push(self, item: T) -> None:
self._items.append(item)
def pop(self) -> T | None:
return self._items.pop() if self._items else None
def peek(self) -> T | None:
return self._items[-1] if self._items else None
def is_empty(self) -> bool:
return len(self._items) == 0
def size(self) -> int:
return len(self._items)
# зручний метод для ланцюжкового виклику
def clear(self) -> Self:
self._items.clear()
return self
#################################################################
numbers = Stack[int]()
numbers.push(10)
numbers.push(20)
numbers.push(30)
print(numbers.pop()) # 30
print(numbers.peek()) # 20
words = Stack[str]()
words.push("привіт")
words.push("світ")
print(words.pop())
class User:
def __init__(self, name: str):
self.name = name
def __repr__(self) -> str:
return f"User({self.name!r})"
users = Stack[User]()
users.push(User("Олексій"))
users.push(User("Марія"))
print(users.peek())
# стек зі змішаними типами
mixed = Stack[object]() # або просто Stack без [T]
mixed.push(42)
mixed.push("текст")
mixed.push(User("тест"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment