Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# command interface
from abc import ABC, abstractmethod



class CommandInterface:
"""generic command interface"""
def __init__(self,editor):
self.editor = editor

@abstractmethod
def execute(self):
pass
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#Implementing TextEditor and button operations via command pattern
from abc import ABC,abstractmethod
from commandInterface import CommandInterface

class BoldCommand(CommandInterface):
"""Bold command implemented via interface"""

def execute(self):
return self.editor.boldText()


class ItalicCommand(CommandInterface):
"""Italic command"""

def execute(self):
return self.editor.italicText()

Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
from concreteCommand import BoldCommand,ItalicCommand


class TextEditor:
"""Text editor class to process text"""

def __init__(self,text):
self.text = text

def boldText(self):
print(f"the {self.text} has been bolded!")

def italicText(self):
print(f"the {self.text} has been italicized!")

def underlineText(self):
print(f"the {self.text} has been underlined!")


class Button:
"""Generic button class"""
def __init__(self):
self.command = None

def setCommand(self, command):
self.command = command

def click(self):
if self.command:
self.command.execute()
else:
print("Invalid command")



def main():

editor = TextEditor("Hello world")
button = Button()


button.setCommand(BoldCommand(editor))
button.click()

button.setCommand(ItalicCommand(editor))
button.click()


if __name__ == "__main__":
main()



Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#Book class

class Book:

def __init__(self,title: str) -> None:
self.title = title

def getTitle(self):
return self.title



Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
class Book:
def __init__(self, title):
self.title = title

def __str__(self):
return f"Book{{title='{self.title}'}}"

def __lt__(self, other):
return self.title < other.title


class BookCollectionV2:
def __init__(self):
self.books = []

def add_book(self, book):
self.books.append(book)

def get_books(self):
return self.books

def create_iterator(self):
return self.BookIterator(self.books)

class BookIterator:
def __init__(self, books):
self.books = books
self.position = 0

def has_next(self):
return self.position < len(self.books)

def next(self):
if not self.has_next():
raise StopIteration
book = self.books[self.position]
self.position += 1
return book


# Client Code
if __name__ == "__main__":
book_collection = BookCollectionV2()
book_collection.add_book(Book("C++ Book"))
book_collection.add_book(Book("Java Book"))
book_collection.add_book(Book("Python Book"))

iterator = book_collection.create_iterator()

while iterator.has_next():
book = iterator.next()
print(book)
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
from __future__ import annotations
from collections.abc import Iterable, Iterator
from typing import Any


"""
To create an iterator in Python, there are two abstract classes from the built-
in `collections` module - Iterable,Iterator. We need to implement the
`__iter__()` method in the iterated object (collection), and the `__next__ ()`
method in the iterator.
"""


class AlphabeticalOrderIterator(Iterator):
"""
Concrete Iterators implement various traversal algorithms. These classes
store the current traversal position at all times.
"""

"""
`_position` attribute stores the current traversal position. An iterator may
have a lot of other fields for storing iteration state, especially when it
is supposed to work with a particular kind of collection.
"""
_position: int = None
"""
This attribute indicates the traversal direction.
"""
_reverse: bool = False

def __init__(self, collection: WordsCollection, reverse: bool = False) -> None:
self._collection = collection
self._reverse = reverse
self._position = -1 if reverse else 0


def __next__(self) -> Any:
"""
The __next__() method must return the next item in the sequence. On
reaching the end, and in subsequent calls, it must raise StopIteration.
"""
try:
value = self._collection[self._position]
self._position += -1 if self._reverse else 1
except IndexError:
raise StopIteration()

return value


class WordsCollection(Iterable):
"""
Concrete Collections provide one or several methods for retrieving fresh
iterator instances, compatible with the collection class.
"""

def __init__(self, collection: list[Any] | None = None) -> None:
self._collection = collection or []


def __getitem__(self, index: int) -> Any:
return self._collection[index]

def __iter__(self) -> AlphabeticalOrderIterator:
"""
The __iter__() method returns the iterator object itself, by default we
return the iterator in ascending order.
"""
return AlphabeticalOrderIterator(self)

def get_reverse_iterator(self) -> AlphabeticalOrderIterator:
return AlphabeticalOrderIterator(self, True)

def add_item(self, item: Any) -> None:
self._collection.append(item)


if __name__ == "__main__":
# The client code may or may not know about the Concrete Iterator or
# Collection classes, depending on the level of indirection you want to keep
# in your program.
collection = WordsCollection()
collection.add_item("First")
collection.add_item("Second")
collection.add_item("Third")

print("Straight traversal:")
print("\n".join(collection))
print("")

print("Reverse traversal:")
print("\n".join(collection.get_reverse_iterator()), end="")
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
#Designing a Book collection (library) which can be maintained in many ways
#list, set, tree etc. Provide an interface using Iterator to iterate over all the elements in the Collection
#hiding its internal implementation


Loading