├── src ├── lecture │ ├── __init__.py │ ├── examples │ │ ├── __init__.py │ │ ├── ex24_gui │ │ │ ├── __init__.py │ │ │ ├── domain │ │ │ │ ├── __init__.py │ │ │ │ ├── validators.py │ │ │ │ └── entities.py │ │ │ ├── tests │ │ │ │ ├── __init__.py │ │ │ │ └── tests.py │ │ │ ├── ui │ │ │ │ └── __init__.py │ │ │ ├── controllers │ │ │ │ └── __init__.py │ │ │ ├── repository │ │ │ │ ├── __init__.py │ │ │ │ └── teststudent.txt │ │ │ ├── teststudent.txt │ │ │ ├── students.txt │ │ │ └── appCoord.py │ │ ├── ex09_modules │ │ │ ├── __init__.py │ │ │ ├── rational │ │ │ │ ├── __init__.py │ │ │ │ ├── rational_list.py │ │ │ │ └── rational_dict.py │ │ │ └── operations.py │ │ ├── ex10_modular_calc │ │ │ ├── __init__.py │ │ │ ├── ui │ │ │ │ ├── __init__.py │ │ │ │ └── console.py │ │ │ ├── domain │ │ │ │ ├── __init__.py │ │ │ │ ├── rational.py │ │ │ │ └── calculator.py │ │ │ └── rational_calc.py │ │ ├── ex16_rationalCalculator │ │ │ ├── __init__.py │ │ │ ├── calculator.py │ │ │ └── ui.py │ │ ├── ex05_ParameterPassing.py │ │ ├── ex11_existingDataTypes.py │ │ ├── ex06_SideEffects.py │ │ ├── ex01_BasicSyntax.py │ │ ├── ex33_lambdas.py │ │ ├── ex03_ProgramFlow.py │ │ ├── ex15_instanceVsClassAttributes.py │ │ ├── ex02_BasicCompoundTypes.py │ │ ├── ex31_stableSort.py │ │ ├── ex34_backtracking.py │ │ ├── ex12_pythonClassParticularities.py │ │ ├── ex08_Exceptions.py │ │ ├── ex18_TestDrivenDevelopment1.py │ │ ├── ex36_longestIncreasingSubsequence.py │ │ ├── ex16_BlackBoxWhiteBox.py │ │ ├── ex22_pickleFiles.py │ │ ├── ex39_eggDroppingPuzzle.py │ │ ├── ex04_VariableScope.py │ │ ├── ex38_01knapsack.py │ │ ├── ex21_textFiles.py │ │ ├── ex13_rationalNumberBasic.py │ │ ├── ex35_coins.py │ │ └── ex30_iterators.py │ ├── livecoding │ │ ├── __init__.py │ │ ├── lecture_04 │ │ │ ├── __init__.py │ │ │ ├── ui.py │ │ │ └── game.py │ │ ├── lecture_05 │ │ │ ├── __init__.py │ │ │ └── ui.py │ │ ├── lecture_06_08 │ │ │ ├── __init__.py │ │ │ ├── repo │ │ │ │ ├── __init__.py │ │ │ │ └── test_repo.py │ │ │ ├── ui │ │ │ │ ├── __init__.py │ │ │ │ └── ui.py │ │ │ ├── domain │ │ │ │ ├── __init__.py │ │ │ │ ├── IdObject.py │ │ │ │ ├── Stock.py │ │ │ │ ├── testingredient.py │ │ │ │ ├── Product.py │ │ │ │ ├── Ingredient.py │ │ │ │ └── Recipe.py │ │ │ ├── services │ │ │ │ ├── __init__.py │ │ │ │ ├── productService.py │ │ │ │ └── ingredientService.py │ │ │ ├── ingredients.bin │ │ │ └── ingredients.txt │ │ ├── lecture_01.py │ │ ├── lecture_11.py │ │ └── lecture_12.py │ └── .DS_Store ├── seminar │ ├── __init__.py │ ├── group_911 │ │ ├── __init__.py │ │ ├── seminar_05 │ │ │ ├── __init__.py │ │ │ ├── functions.py │ │ │ └── ui.py │ │ ├── seminar_06_09 │ │ │ ├── __init__.py │ │ │ ├── domain │ │ │ │ ├── __init__.py │ │ │ │ ├── client_validators.py │ │ │ │ ├── rental_validators.py │ │ │ │ ├── client.py │ │ │ │ ├── exceptions.py │ │ │ │ ├── rental.py │ │ │ │ └── car_validators.py │ │ │ ├── repository │ │ │ │ ├── repository_exception.py │ │ │ │ ├── client_repo.py │ │ │ │ └── rental_repo.py │ │ │ └── services │ │ │ │ ├── client_service.py │ │ │ │ └── rental_service.py │ │ ├── seminar_09 │ │ │ ├── __init__.py │ │ │ ├── domain │ │ │ │ ├── __init__.py │ │ │ │ ├── CarRentalException.py │ │ │ │ ├── ValidatorException.py │ │ │ │ ├── Client.py │ │ │ │ └── Rental.py │ │ │ ├── service │ │ │ │ ├── __init__.py │ │ │ │ ├── CarRentalException.py │ │ │ │ ├── CarService.py │ │ │ │ ├── UndoService.py │ │ │ │ └── RentalService.py │ │ │ ├── repository │ │ │ │ ├── __init__.py │ │ │ │ ├── RepositoryException.py │ │ │ │ └── Repository.py │ │ │ ├── util.py │ │ │ └── UndoExampleMedium.py │ │ ├── seminar_11 │ │ │ ├── __init__.py │ │ │ ├── repository │ │ │ │ ├── __init__.py │ │ │ │ ├── RepositoryException.py │ │ │ │ └── Repository.py │ │ │ └── main.py │ │ ├── seminar_14.py │ │ └── seminar_04.py │ ├── group_912 │ │ ├── __init__.py │ │ ├── seminar_05 │ │ │ ├── __init__.py │ │ │ ├── ui.py │ │ │ └── functions.py │ │ ├── seminar_06_09 │ │ │ ├── __init__.py │ │ │ ├── domain │ │ │ │ ├── __init__.py │ │ │ │ ├── client_validators.py │ │ │ │ ├── rental_validators.py │ │ │ │ ├── client.py │ │ │ │ ├── exceptions.py │ │ │ │ ├── rental.py │ │ │ │ └── car_validators.py │ │ │ ├── repository │ │ │ │ ├── repository_exception.py │ │ │ │ ├── client_repo.py │ │ │ │ └── rental_repo.py │ │ │ └── services │ │ │ │ ├── client_service.py │ │ │ │ └── rental_service.py │ │ ├── seminar_09 │ │ │ ├── __init__.py │ │ │ ├── domain │ │ │ │ ├── __init__.py │ │ │ │ ├── CarRentalException.py │ │ │ │ ├── ValidatorException.py │ │ │ │ ├── Client.py │ │ │ │ └── Rental.py │ │ │ ├── service │ │ │ │ ├── __init__.py │ │ │ │ ├── CarRentalException.py │ │ │ │ ├── CarService.py │ │ │ │ ├── ClientService.py │ │ │ │ └── RentalService.py │ │ │ ├── repository │ │ │ │ ├── __init__.py │ │ │ │ ├── RepositoryException.py │ │ │ │ └── Repository.py │ │ │ ├── util.py │ │ │ └── UndoExampleMedium.py │ │ ├── seminar_11 │ │ │ ├── __init__.py │ │ │ └── repository │ │ │ │ ├── __init__.py │ │ │ │ ├── RepositoryException.py │ │ │ │ └── Repository.py │ │ ├── seminar_14.py │ │ ├── seminar_04.py │ │ └── seminar_11.py │ ├── group_913 │ │ └── __init__.py │ ├── group_914 │ │ ├── __init__.py │ │ └── s01 │ │ │ ├── .idea │ │ │ ├── misc.xml │ │ │ ├── .gitignore │ │ │ ├── inspectionProfiles │ │ │ │ └── profiles_settings.xml │ │ │ ├── modules.xml │ │ │ └── s01.iml │ │ │ └── main.py │ ├── group_915 │ │ ├── __init__.py │ │ └── s01 │ │ │ ├── .idea │ │ │ ├── misc.xml │ │ │ ├── .gitignore │ │ │ ├── inspectionProfiles │ │ │ │ └── profiles_settings.xml │ │ │ ├── modules.xml │ │ │ └── s01.iml │ │ │ └── main.py │ ├── group_916 │ │ ├── __init__.py │ │ └── s01 │ │ │ ├── .idea │ │ │ ├── misc.xml │ │ │ ├── .gitignore │ │ │ ├── inspectionProfiles │ │ │ │ └── profiles_settings.xml │ │ │ ├── modules.xml │ │ │ └── s01.iml │ │ │ └── main.py │ └── group_917 │ │ ├── __init__.py │ │ ├── seminar_05 │ │ ├── ui.py │ │ ├── service.py │ │ └── __init__.py │ │ ├── seminar_05b │ │ ├── __init__.py │ │ └── functions.py │ │ ├── seminar_06_09 │ │ ├── __init__.py │ │ ├── domain │ │ │ ├── __init__.py │ │ │ ├── client_validators.py │ │ │ ├── rental_validators.py │ │ │ ├── client.py │ │ │ ├── exceptions.py │ │ │ ├── rental.py │ │ │ └── car_validators.py │ │ ├── repository │ │ │ ├── repository_exception.py │ │ │ ├── client_repo.py │ │ │ └── rental_repo.py │ │ └── services │ │ │ ├── client_service.py │ │ │ └── rental_service.py │ │ ├── seminar_09 │ │ ├── __init__.py │ │ ├── domain │ │ │ ├── __init__.py │ │ │ ├── CarRentalException.py │ │ │ ├── ValidatorException.py │ │ │ ├── Client.py │ │ │ └── Rental.py │ │ ├── service │ │ │ ├── __init__.py │ │ │ ├── CarRentalException.py │ │ │ ├── CarService.py │ │ │ ├── UndoService.py │ │ │ ├── ClientService.py │ │ │ └── RentalService.py │ │ ├── repository │ │ │ ├── __init__.py │ │ │ ├── RepositoryException.py │ │ │ └── Repository.py │ │ ├── util.py │ │ └── UndoExampleMedium.py │ │ ├── seminar_11 │ │ ├── __init__.py │ │ └── repository │ │ │ ├── __init__.py │ │ │ ├── RepositoryException.py │ │ │ └── Repository.py │ │ ├── seminar_14.py │ │ ├── seminar_04.py │ │ └── seminar_10.py └── .DS_Store ├── README.md ├── .DS_Store ├── .idea ├── vcs.xml ├── misc.xml ├── .gitignore ├── inspectionProfiles │ ├── profiles_settings.xml │ └── Project_Default.xml ├── modules.xml └── FP.iml └── .gitignore /src/lecture/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/lecture/examples/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_911/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_912/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_913/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_914/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_915/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_916/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_917/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/lecture/livecoding/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_05/ui.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/lecture/examples/ex24_gui/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_05/service.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/lecture/examples/ex09_modules/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/lecture/examples/ex24_gui/domain/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/lecture/examples/ex24_gui/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/lecture/examples/ex24_gui/ui/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_04/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_05/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_06_08/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_05/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_06_09/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_09/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_11/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_05/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_06_09/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_09/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_11/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_05/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_05b/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_06_09/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_09/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_11/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/lecture/examples/ex10_modular_calc/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/lecture/examples/ex10_modular_calc/ui/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/lecture/examples/ex24_gui/controllers/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/lecture/examples/ex24_gui/repository/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_06_08/repo/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_06_08/ui/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_09/domain/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_09/service/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_09/domain/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_09/service/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_09/domain/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_09/service/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # FP 2 | Lecture and seminar work at FP. 3 | -------------------------------------------------------------------------------- /src/lecture/examples/ex09_modules/rational/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/lecture/examples/ex10_modular_calc/domain/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/lecture/examples/ex16_rationalCalculator/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_06_08/domain/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_06_08/services/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_06_09/domain/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_09/repository/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_11/repository/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_06_09/domain/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_09/repository/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_11/repository/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_06_09/domain/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_09/repository/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_11/repository/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/lecture/examples/ex24_gui/teststudent.txt: -------------------------------------------------------------------------------- 1 | 1;Ion;str;3;Cluj 2 | -------------------------------------------------------------------------------- /src/lecture/examples/ex24_gui/repository/teststudent.txt: -------------------------------------------------------------------------------- 1 | 1;Ion;str;3;Cluj 2 | -------------------------------------------------------------------------------- /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cs-ubbcluj-ro/FP-2021-2022/HEAD/.DS_Store -------------------------------------------------------------------------------- /src/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cs-ubbcluj-ro/FP-2021-2022/HEAD/src/.DS_Store -------------------------------------------------------------------------------- /src/lecture/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cs-ubbcluj-ro/FP-2021-2022/HEAD/src/lecture/.DS_Store -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_06_08/ingredients.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cs-ubbcluj-ro/FP-2021-2022/HEAD/src/lecture/livecoding/lecture_06_08/ingredients.bin -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_06_09/domain/client_validators.py: -------------------------------------------------------------------------------- 1 | class ClientValidator: 2 | # TODO Implement 3 | 4 | def validate(self, client): 5 | return True 6 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_06_09/domain/client_validators.py: -------------------------------------------------------------------------------- 1 | class ClientValidator: 2 | # TODO Implement 3 | 4 | def validate(self, client): 5 | return True 6 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_06_09/domain/client_validators.py: -------------------------------------------------------------------------------- 1 | class ClientValidator: 2 | # TODO Implement 3 | 4 | def validate(self, client): 5 | return True 6 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_06_08/domain/IdObject.py: -------------------------------------------------------------------------------- 1 | class IdObject: 2 | def __init__(self, _id): 3 | self._id = _id 4 | 5 | @property 6 | def id(self): 7 | return self._id 8 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Datasource local storage ignored files 5 | /dataSources/ 6 | /dataSources.local.xml 7 | # Editor-based HTTP Client requests 8 | /httpRequests/ 9 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_09/service/CarRentalException.py: -------------------------------------------------------------------------------- 1 | class CarRentalException(Exception): 2 | def __init__(self, msg): 3 | self.__msg = msg 4 | 5 | def __str__(self): 6 | return str(self.__msg) 7 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_09/service/CarRentalException.py: -------------------------------------------------------------------------------- 1 | class CarRentalException(Exception): 2 | def __init__(self, msg): 3 | self.__msg = msg 4 | 5 | def __str__(self): 6 | return str(self.__msg) 7 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_09/service/CarRentalException.py: -------------------------------------------------------------------------------- 1 | class CarRentalException(Exception): 2 | def __init__(self, msg): 3 | self.__msg = msg 4 | 5 | def __str__(self): 6 | return str(self.__msg) 7 | -------------------------------------------------------------------------------- /src/seminar/group_914/s01/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /src/seminar/group_915/s01/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /src/seminar/group_916/s01/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /src/lecture/examples/ex10_modular_calc/rational_calc.py: -------------------------------------------------------------------------------- 1 | """ 2 | Start the calculator application 3 | """ 4 | from src.lecture.examples.ex10_modular_calc.ui.console import run 5 | 6 | # invoke the run method from the module ui.console 7 | run() 8 | -------------------------------------------------------------------------------- /src/seminar/group_914/s01/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /src/seminar/group_915/s01/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /src/seminar/group_916/s01/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Editor-based HTTP Client requests 5 | /httpRequests/ 6 | # Datasource local storage ignored files 7 | /dataSources/ 8 | /dataSources.local.xml 9 | -------------------------------------------------------------------------------- /src/seminar/group_914/s01/.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /src/seminar/group_915/s01/.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /src/seminar/group_916/s01/.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_06_08/ingredients.txt: -------------------------------------------------------------------------------- 1 | 100,Bread Flour (White, 550) 2 | 101,Yeast (dry) 3 | 102,Sugar (white) 4 | 103,Salt (regular) 5 | 104,Oil (canola) 6 | 105,Butter 7 | 106,Egg (chicken) 8 | 107,Cake flour 9 | 108,Baking powder 10 | 109,Vanilla (extract) 11 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_09/domain/CarRentalException.py: -------------------------------------------------------------------------------- 1 | class CarRentalException(Exception): 2 | def __init__(self, msg): 3 | self._message = msg 4 | 5 | def getMessage(self): 6 | return self._message 7 | 8 | def __str__(self): 9 | return self._message -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_09/domain/CarRentalException.py: -------------------------------------------------------------------------------- 1 | class CarRentalException(Exception): 2 | def __init__(self, msg): 3 | self._message = msg 4 | 5 | def getMessage(self): 6 | return self._message 7 | 8 | def __str__(self): 9 | return self._message -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_09/domain/CarRentalException.py: -------------------------------------------------------------------------------- 1 | class CarRentalException(Exception): 2 | def __init__(self, msg): 3 | self._message = msg 4 | 5 | def getMessage(self): 6 | return self._message 7 | 8 | def __str__(self): 9 | return self._message -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_09/repository/RepositoryException.py: -------------------------------------------------------------------------------- 1 | class RepositoryException(Exception): 2 | def __init__(self, message): 3 | self._message = message 4 | 5 | def getMessage(self): 6 | return self._message 7 | 8 | def __str__(self): 9 | return self._message -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_11/repository/RepositoryException.py: -------------------------------------------------------------------------------- 1 | class RepositoryException(Exception): 2 | def __init__(self, message): 3 | self._message = message 4 | 5 | def getMessage(self): 6 | return self._message 7 | 8 | def __str__(self): 9 | return self._message -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_09/repository/RepositoryException.py: -------------------------------------------------------------------------------- 1 | class RepositoryException(Exception): 2 | def __init__(self, message): 3 | self._message = message 4 | 5 | def getMessage(self): 6 | return self._message 7 | 8 | def __str__(self): 9 | return self._message -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_11/repository/RepositoryException.py: -------------------------------------------------------------------------------- 1 | class RepositoryException(Exception): 2 | def __init__(self, message): 3 | self._message = message 4 | 5 | def getMessage(self): 6 | return self._message 7 | 8 | def __str__(self): 9 | return self._message -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_09/repository/RepositoryException.py: -------------------------------------------------------------------------------- 1 | class RepositoryException(Exception): 2 | def __init__(self, message): 3 | self._message = message 4 | 5 | def getMessage(self): 6 | return self._message 7 | 8 | def __str__(self): 9 | return self._message -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_11/repository/RepositoryException.py: -------------------------------------------------------------------------------- 1 | class RepositoryException(Exception): 2 | def __init__(self, message): 3 | self._message = message 4 | 5 | def getMessage(self): 6 | return self._message 7 | 8 | def __str__(self): 9 | return self._message -------------------------------------------------------------------------------- /src/seminar/group_914/s01/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/seminar/group_915/s01/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/seminar/group_916/s01/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_06_09/repository/repository_exception.py: -------------------------------------------------------------------------------- 1 | class RepositoryException(Exception): 2 | def __init__(self, message): 3 | self._message = message 4 | 5 | @property 6 | def message(self): 7 | return self._message 8 | 9 | def __str__(self): 10 | return self._message 11 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_06_09/repository/repository_exception.py: -------------------------------------------------------------------------------- 1 | class RepositoryException(Exception): 2 | def __init__(self, message): 3 | self._message = message 4 | 5 | @property 6 | def message(self): 7 | return self._message 8 | 9 | def __str__(self): 10 | return self._message 11 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_06_09/repository/repository_exception.py: -------------------------------------------------------------------------------- 1 | class RepositoryException(Exception): 2 | def __init__(self, message): 3 | self._message = message 4 | 5 | @property 6 | def message(self): 7 | return self._message 8 | 9 | def __str__(self): 10 | return self._message 11 | -------------------------------------------------------------------------------- /src/seminar/group_914/s01/.idea/s01.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/seminar/group_915/s01/.idea/s01.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/seminar/group_916/s01/.idea/s01.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_06_08/services/productService.py: -------------------------------------------------------------------------------- 1 | from lecture.livecoding.lecture_06_08.repo.repository import Repository 2 | 3 | 4 | class ProductService: 5 | # TODO Fill in this skeleton class 6 | def __init__(self, product_repo): 7 | self.__repo = product_repo 8 | 9 | def add_product(self, product): 10 | self.__repo.add(product) 11 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_09/util.py: -------------------------------------------------------------------------------- 1 | def print_repos_with_message(msg, client_repo, car_repo, rent_repo): 2 | print("-" * 15 + msg + "-" * 15) 3 | if client_repo is not None: 4 | print("Clients:\n" + str(client_repo)) 5 | if car_repo is not None: 6 | print("Cars:\n" + str(car_repo)) 7 | if rent_repo is not None: 8 | print("Rentals:\n" + str(rent_repo)) 9 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_09/util.py: -------------------------------------------------------------------------------- 1 | def print_repos_with_message(msg, client_repo, car_repo, rent_repo): 2 | print("-" * 15 + msg + "-" * 15) 3 | if client_repo is not None: 4 | print("Clients:\n" + str(client_repo)) 5 | if car_repo is not None: 6 | print("Cars:\n" + str(car_repo)) 7 | if rent_repo is not None: 8 | print("Rentals:\n" + str(rent_repo)) 9 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_09/util.py: -------------------------------------------------------------------------------- 1 | def print_repos_with_message(msg, client_repo, car_repo, rent_repo): 2 | print("-" * 15 + msg + "-" * 15) 3 | if client_repo is not None: 4 | print("Clients:\n" + str(client_repo)) 5 | if car_repo is not None: 6 | print("Cars:\n" + str(car_repo)) 7 | if rent_repo is not None: 8 | print("Rentals:\n" + str(rent_repo)) 9 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_06_08/services/ingredientService.py: -------------------------------------------------------------------------------- 1 | from lecture.livecoding.lecture_06_08.repo.repository import Repository 2 | 3 | 4 | class IngredientService: 5 | # TODO Fill in this skeleton class 6 | def __init__(self, ingredient_repo): 7 | self.__repo = ingredient_repo 8 | 9 | def add_ingredient(self, ingredient): 10 | self.__repo.add(ingredient) 11 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_06_08/domain/Stock.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | class Stock: 5 | def __init__(self, ingredient, quantity): 6 | self._ingredient = ingredient 7 | self._quantity = quantity 8 | 9 | @property 10 | def ingredient(self): 11 | return self._ingredient 12 | 13 | @property 14 | def quantity(self): 15 | return self._quantity 16 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_06_08/domain/testingredient.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from lecture.livecoding.lecture_06_08.domain.Ingredient import Ingredient 4 | 5 | 6 | class IngredientTest(unittest.TestCase): 7 | def test_ingredient(self): 8 | ingr = Ingredient(103, "Salt (regular)") 9 | self.assertEqual(ingr.id, 103) 10 | self.assertEqual(ingr.description, "Salt (regular)") 11 | -------------------------------------------------------------------------------- /src/lecture/examples/ex24_gui/students.txt: -------------------------------------------------------------------------------- 1 | 123;sadsadas;asdas;asdasd;343 2 | 123213;213123;123123;123123;12312 3 | 1;Ion;asda;asdas;dsa 4 | 345;322;23;3;4 5 | 44;saasdsa;asd;; 6 | 2;ASA;sadasd;2;Cluj 7 | 245;ewrwer;werwer;werwer;werwere 8 | 3;Ionescu;Kogalniceanu;12;Cluj 9 | 1234;Popescu;hhh;4;Cluj 10 | 12;231;13123;12323;123123 11 | 1233;new Name;asd;asd2; 12 | 9998;Popescu Maria;Victoria;80;Abrud 13 | 19288;Popescu;Dacia;99;Cluj 14 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_06_08/domain/Product.py: -------------------------------------------------------------------------------- 1 | from lecture.livecoding.lecture_06_08.domain.IdObject import IdObject 2 | from lecture.livecoding.lecture_06_08.repo.repository import Repository 3 | 4 | 5 | class Product(IdObject): 6 | def __init__(self, _id, recipe): 7 | super().__init__(_id) 8 | self._recipe = recipe 9 | 10 | @property 11 | def recipe(self): 12 | return self._recipe 13 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_09/domain/ValidatorException.py: -------------------------------------------------------------------------------- 1 | class ValidatorException(Exception): 2 | def __init__(self, messageList=["Validation error!"]): 3 | self._messageList = messageList 4 | 5 | def getMessage(self): 6 | return self._messageList 7 | 8 | def __str__(self): 9 | result = "" 10 | for message in self.getMessage(): 11 | result += message 12 | result += "\n" 13 | return result 14 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_09/domain/ValidatorException.py: -------------------------------------------------------------------------------- 1 | class ValidatorException(Exception): 2 | def __init__(self, messageList=["Validation error!"]): 3 | self._messageList = messageList 4 | 5 | def getMessage(self): 6 | return self._messageList 7 | 8 | def __str__(self): 9 | result = "" 10 | for message in self.getMessage(): 11 | result += message 12 | result += "\n" 13 | return result 14 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_09/domain/ValidatorException.py: -------------------------------------------------------------------------------- 1 | class ValidatorException(Exception): 2 | def __init__(self, messageList=["Validation error!"]): 3 | self._messageList = messageList 4 | 5 | def getMessage(self): 6 | return self._messageList 7 | 8 | def __str__(self): 9 | result = "" 10 | for message in self.getMessage(): 11 | result += message 12 | result += "\n" 13 | return result 14 | -------------------------------------------------------------------------------- /src/lecture/examples/ex09_modules/rational/rational_list.py: -------------------------------------------------------------------------------- 1 | """ 2 | Docstring for Rational number represented using a list 3 | 4 | Created on Oct 21, 2018 5 | @author: Arthur 6 | """ 7 | from math import gcd 8 | 9 | 10 | def create_rational(nom, den=1): 11 | if den == 0: 12 | raise ValueError("Denominator cannot be 0") 13 | d = gcd(nom, den) 14 | return [nom // d, den // d] 15 | 16 | 17 | def get_numerator(q): 18 | return q[0] 19 | 20 | 21 | def get_denominator(q): 22 | return q[1] 23 | -------------------------------------------------------------------------------- /src/lecture/examples/ex09_modules/rational/rational_dict.py: -------------------------------------------------------------------------------- 1 | """ 2 | Docstring for Rational number represented using a dict 3 | 4 | Created on Oct 21, 2018 5 | @author: Arthur 6 | """ 7 | import math 8 | 9 | 10 | def create_rational(nom, den=1): 11 | if den == 0: 12 | raise ValueError("Denominator cannot be 0") 13 | 14 | d = math.gcd(nom, den) 15 | return {"nom": nom // d, "denom": den // d} 16 | 17 | 18 | def get_numerator(q): 19 | return q["nom"] 20 | 21 | 22 | def get_denominator(q): 23 | return q["denom"] 24 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_06_09/repository/client_repo.py: -------------------------------------------------------------------------------- 1 | from seminar.group_911.seminar_06_09.domain.client import Client 2 | from seminar.group_911.seminar_06_09.repository.repository_exception import RepositoryException 3 | 4 | 5 | class ClientRepo: 6 | # TODO Finish implementation 7 | def __init__(self): 8 | self._clients = {} 9 | 10 | def add(self, client): 11 | if client.id in self._data.keys(): 12 | raise RepositoryException("Duplicate Client id") 13 | self._data[client.id] = client 14 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_06_09/repository/client_repo.py: -------------------------------------------------------------------------------- 1 | from seminar.group_912.seminar_06_09.domain.client import Client 2 | from seminar.group_912.seminar_06_09.repository.repository_exception import RepositoryException 3 | 4 | 5 | class ClientRepo: 6 | # TODO Finish implementation 7 | def __init__(self): 8 | self._clients = {} 9 | 10 | def add(self, client): 11 | if client.id in self._data.keys(): 12 | raise RepositoryException("Duplicate Client id") 13 | self._data[client.id] = client 14 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_06_09/repository/client_repo.py: -------------------------------------------------------------------------------- 1 | from seminar.group_917.seminar_06_09.domain.client import Client 2 | from seminar.group_917.seminar_06_09.repository.repository_exception import RepositoryException 3 | 4 | 5 | class ClientRepo: 6 | # TODO Finish implementation 7 | def __init__(self): 8 | self._clients = {} 9 | 10 | def add(self, client): 11 | if client.id in self._data.keys(): 12 | raise RepositoryException("Duplicate Client id") 13 | self._data[client.id] = client 14 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_06_08/ui/ui.py: -------------------------------------------------------------------------------- 1 | from lecture.livecoding.lecture_06_08.services.ingredientService import IngredientService 2 | from lecture.livecoding.lecture_06_08.services.productService import ProductService 3 | from lecture.livecoding.lecture_06_08.repo.repository import Repository 4 | 5 | 6 | class UI: 7 | def __init__(self, ingredient_service, product_service): 8 | self.__ingr_service = ingredient_service 9 | self.__prod_service = product_service 10 | 11 | def start(self): 12 | print("menu") 13 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_06_08/domain/Ingredient.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from lecture.livecoding.lecture_06_08.domain.IdObject import IdObject 4 | 5 | 6 | class Ingredient(IdObject): 7 | """ 8 | - id, description, stock (default in grams), expiration date 9 | """ 10 | 11 | def __init__(self, _id, description="n/a"): 12 | # TODO Add expiration date 13 | super().__init__(_id) 14 | self.__description = description 15 | 16 | @property 17 | def description(self): 18 | return self.__description 19 | -------------------------------------------------------------------------------- /src/lecture/examples/ex05_ParameterPassing.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Sep 29, 2016 3 | 4 | @author: http://www.python-course.eu/passing_arguments.php 5 | """ 6 | 7 | """ 8 | Example for parameter passing. 9 | Use the locals() and globals() functions to better 10 | understand what goes on 11 | """ 12 | 13 | 14 | def references_demo(x): 15 | print("2. x=", x, " id=", id(x)) 16 | x = 42 17 | print("3. x=", x, " id=", id(x)) 18 | 19 | 20 | x = 10 21 | print("1. x=", x, " id=", id(x)) 22 | 23 | references_demo(x) 24 | print("4. x=", x, " id=", id(x)) -------------------------------------------------------------------------------- /src/lecture/examples/ex11_existingDataTypes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Nov 1, 2016 3 | 4 | @author: Arthur 5 | """ 6 | 7 | ''' 8 | We define two list objects! 9 | - list is a predefined data type in Python 10 | - list is implemented as a class! 11 | ''' 12 | list_one = [1, 2, 3] 13 | list_two = [4, 5, 6] 14 | 15 | ''' 16 | The 'append()' method is called on the 'list_one' object 17 | - list has a __init__ method 18 | - list has an 'append' method (and many more!) 19 | ''' 20 | list_one.append(5) 21 | print(list_one) 22 | print(list_two) 23 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_06_08/domain/Recipe.py: -------------------------------------------------------------------------------- 1 | from lecture.livecoding.lecture_06_08.domain.IdObject import IdObject 2 | 3 | 4 | class Recipe(IdObject): 5 | def __init__(self, _id, description, *required_stocks): 6 | # TODO Finish implementation for required stocks 7 | super().__init__(_id) 8 | self._description = description 9 | self._required_stocks = list(required_stocks) 10 | 11 | @property 12 | def description(self): 13 | return self._description 14 | 15 | @property 16 | def required_stocks(self): 17 | return self._required_stocks 18 | -------------------------------------------------------------------------------- /.idea/FP.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 14 | 15 | 17 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_05/functions.py: -------------------------------------------------------------------------------- 1 | import rectangle 2 | # from rectangle import rectangle 3 | from random import randint 4 | 5 | 6 | class functions: 7 | def __init__(self): 8 | self._rectangles = [] 9 | 10 | def generate_rectangles(self, n): 11 | for i in range(n): 12 | x1 = randint(0, 15) 13 | x2 = randint(x1 + 1, 20) 14 | 15 | y1 = randint(0, 15) 16 | y2 = randint(y1 + 1, 20) 17 | 18 | self._rectangles.append(rectangle.rectangle(x1, y1, x2, y2)) 19 | 20 | def sort_rectangles(self): 21 | return sorted(self._rectangles, reverse=True, key=max_side) 22 | 23 | 24 | def max_side(rect): 25 | return max(rect.width, rect.height) 26 | -------------------------------------------------------------------------------- /.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16 | -------------------------------------------------------------------------------- /src/lecture/examples/ex06_SideEffects.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Sep 29, 2016 3 | 4 | @author: http://www.python-course.eu/passing_arguments.php 5 | """ 6 | 7 | """ 8 | Example for function side effects. Run the code below calling each of 9 | the functions in turn. Examine the result 10 | """ 11 | 12 | 13 | def no_side_effect(lst): 14 | print(2, id(lst), lst) 15 | lst = [0, 1, 2, 3] 16 | print(3, id(lst), lst) 17 | 18 | 19 | def side_effect(lst): 20 | print(5, id(lst), lst) 21 | lst.append(999) 22 | print(6, id(lst), lst) 23 | 24 | 25 | my_list = [0, 1, 2] 26 | print(1, id(my_list), my_list) 27 | no_side_effect(my_list) 28 | print(4, id(my_list), my_list) 29 | side_effect(my_list) 30 | print(7, id(my_list), my_list) 31 | -------------------------------------------------------------------------------- /src/lecture/examples/ex01_BasicSyntax.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Sep 23, 2016 3 | 4 | @author: Arthur 5 | """ 6 | 7 | """ 8 | Print a message to the console 9 | """ 10 | print("Hello world!") 11 | 12 | """ 13 | Read from the console 14 | """ 15 | a = input("Enter the first number: ") 16 | b = input("Enter the second number: ") 17 | 18 | """ 19 | NB! 20 | What is printed out and why? 21 | """ 22 | print(a + b) 23 | 24 | # This is a line comment 25 | 26 | """ 27 | NB! 28 | What does this do? 29 | """ 30 | x = int(a) 31 | y = int(b) 32 | 33 | print(x + y) 34 | 35 | """ 36 | NB! 37 | This is all very confusing... how do I know what is what? 38 | """ 39 | print("this should be a string - ", type(a)) 40 | print("and this is an integer -", type(x)) -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_06_09/domain/rental_validators.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | 3 | from seminar.group_911.seminar_06_09.domain.exceptions import ValidatorException 4 | from seminar.group_911.seminar_06_09.domain.rental import Rental 5 | 6 | 7 | class RentalValidator: 8 | def validate(self, rental): 9 | if isinstance(rental, Rental) is False: 10 | raise TypeError("Not a Rental") 11 | 12 | _errorList = [] 13 | now = date(2000, 1, 1) 14 | if rental.start < now: 15 | _errorList.append("Rental starts in past;") 16 | if len(rental) < 1: 17 | _errorList.append("Rental must be at least 1 day;") 18 | if len(_errorList) > 0: 19 | raise ValidatorException(_errorList) 20 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_06_09/domain/rental_validators.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | 3 | from seminar.group_912.seminar_06_09.domain.exceptions import ValidatorException 4 | from seminar.group_912.seminar_06_09.domain.rental import Rental 5 | 6 | 7 | class RentalValidator: 8 | def validate(self, rental): 9 | if isinstance(rental, Rental) is False: 10 | raise TypeError("Not a Rental") 11 | 12 | _errorList = [] 13 | now = date(2000, 1, 1) 14 | if rental.start < now: 15 | _errorList.append("Rental starts in past;") 16 | if len(rental) < 1: 17 | _errorList.append("Rental must be at least 1 day;") 18 | if len(_errorList) > 0: 19 | raise ValidatorException(_errorList) 20 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_06_09/domain/rental_validators.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | 3 | from seminar.group_911.seminar_06_09.domain.exceptions import ValidatorException 4 | from seminar.group_911.seminar_06_09.domain.rental import Rental 5 | 6 | 7 | class RentalValidator: 8 | def validate(self, rental): 9 | if isinstance(rental, Rental) is False: 10 | raise TypeError("Not a Rental") 11 | 12 | _errorList = [] 13 | now = date(2000, 1, 1) 14 | if rental.start < now: 15 | _errorList.append("Rental starts in past;") 16 | if len(rental) < 1: 17 | _errorList.append("Rental must be at least 1 day;") 18 | if len(_errorList) > 0: 19 | raise ValidatorException(_errorList) 20 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_06_09/repository/rental_repo.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | from seminar.group_911.seminar_06_09.repository.repository_exception import RepositoryException 4 | 5 | 6 | class RentalRepository: 7 | # TODO Finish implementation 8 | def __init__(self): 9 | self._data = {} 10 | 11 | def add(self, rental): 12 | if rental.id in self._data.keys(): 13 | raise RepositoryException("Duplicate Rental ID") 14 | self._data[rental.id] = rental 15 | 16 | def remove(self, rental_id): 17 | if rental_id in self._data.keys(): 18 | del self.data[rental_id] 19 | else: 20 | raise RepositoryException("Rental was not found") 21 | 22 | def get_all(self): 23 | return list(self._data.values()) -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_06_09/repository/rental_repo.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | from seminar.group_912.seminar_06_09.repository.repository_exception import RepositoryException 4 | 5 | 6 | class RentalRepository: 7 | # TODO Finish implementation 8 | def __init__(self): 9 | self._data = {} 10 | 11 | def add(self, rental): 12 | if rental.id in self._data.keys(): 13 | raise RepositoryException("Duplicate Rental ID") 14 | self._data[rental.id] = rental 15 | 16 | def remove(self, rental_id): 17 | if rental_id in self._data.keys(): 18 | del self.data[rental_id] 19 | else: 20 | raise RepositoryException("Rental was not found") 21 | 22 | def get_all(self): 23 | return list(self._data.values()) -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_06_09/repository/rental_repo.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | 3 | from seminar.group_917.seminar_06_09.repository.repository_exception import RepositoryException 4 | 5 | 6 | class RentalRepository: 7 | # TODO Finish implementation 8 | def __init__(self): 9 | self._data = {} 10 | 11 | def add(self, rental): 12 | if rental.id in self._data.keys(): 13 | raise RepositoryException("Duplicate Rental ID") 14 | self._data[rental.id] = rental 15 | 16 | def remove(self, rental_id): 17 | if rental_id in self._data.keys(): 18 | del self.data[rental_id] 19 | else: 20 | raise RepositoryException("Rental was not found") 21 | 22 | def get_all(self): 23 | return list(self._data.values()) -------------------------------------------------------------------------------- /src/lecture/examples/ex24_gui/appCoord.py: -------------------------------------------------------------------------------- 1 | # Application coordinator 2 | # Use dependency injection pattern to asemble the application 3 | 4 | from lecture.examples.ex24_gui.controllers.controllers import StudentController 5 | from lecture.examples.ex24_gui.domain.validators import StudentValidator 6 | from lecture.examples.ex24_gui.repository.file import StudentFileRepository 7 | from lecture.examples.ex24_gui.ui.gui import StudentGUI 8 | 9 | val = StudentValidator() 10 | 11 | # create repository 12 | # repo = StudentRepository() 13 | 14 | repo = StudentFileRepository("students.txt") 15 | 16 | # create controller and inject dependencies 17 | ctr = StudentController(val, repo) 18 | 19 | # create console ui and provide (inject) the controller 20 | # ui = ConsoleUI(ctr) 21 | ui = StudentGUI(ctr) 22 | ui.start() 23 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_06_09/domain/client.py: -------------------------------------------------------------------------------- 1 | class Client: 2 | def __init__(self, client_id, cnp, name): 3 | self._clientId = client_id 4 | self._cnp = cnp 5 | self._name = name 6 | 7 | @property 8 | def id(self): 9 | return self._clientId 10 | 11 | @property 12 | def cnp(self): 13 | return self._cnp 14 | 15 | @property 16 | def name(self): 17 | return self._name 18 | 19 | @name.setter 20 | def name(self, value): 21 | self._name = value 22 | 23 | def __eq__(self, z): 24 | if isinstance(z, Client) is False: 25 | return False 26 | return self.id == z.id 27 | 28 | def __str__(self): 29 | return "Id=" + str(self.id) + ", Name=" + str(self.name) 30 | 31 | def __repr__(self): 32 | return str(self) 33 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_06_09/domain/client.py: -------------------------------------------------------------------------------- 1 | class Client: 2 | def __init__(self, client_id, cnp, name): 3 | self._clientId = client_id 4 | self._cnp = cnp 5 | self._name = name 6 | 7 | @property 8 | def id(self): 9 | return self._clientId 10 | 11 | @property 12 | def cnp(self): 13 | return self._cnp 14 | 15 | @property 16 | def name(self): 17 | return self._name 18 | 19 | @name.setter 20 | def name(self, value): 21 | self._name = value 22 | 23 | def __eq__(self, z): 24 | if isinstance(z, Client) is False: 25 | return False 26 | return self.id == z.id 27 | 28 | def __str__(self): 29 | return "Id=" + str(self.id) + ", Name=" + str(self.name) 30 | 31 | def __repr__(self): 32 | return str(self) 33 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_06_09/domain/client.py: -------------------------------------------------------------------------------- 1 | class Client: 2 | def __init__(self, client_id, cnp, name): 3 | self._clientId = client_id 4 | self._cnp = cnp 5 | self._name = name 6 | 7 | @property 8 | def id(self): 9 | return self._clientId 10 | 11 | @property 12 | def cnp(self): 13 | return self._cnp 14 | 15 | @property 16 | def name(self): 17 | return self._name 18 | 19 | @name.setter 20 | def name(self, value): 21 | self._name = value 22 | 23 | def __eq__(self, z): 24 | if isinstance(z, Client) is False: 25 | return False 26 | return self.id == z.id 27 | 28 | def __str__(self): 29 | return "Id=" + str(self.id) + ", Name=" + str(self.name) 30 | 31 | def __repr__(self): 32 | return str(self) 33 | -------------------------------------------------------------------------------- /src/lecture/examples/ex33_lambdas.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Dec 20, 2016 3 | 4 | @author: Arthur 5 | """ 6 | 7 | ''' 8 | 1. Lambda examples for sorting a list 9 | ''' 10 | pairs = [('Joanna', 6), ('Anna', 10), ('Carl', 9), ('Betty', 8), ('Xavier', 5), ('Sophia', 7), ('Richard', 7)] 11 | 12 | # Sort by name 13 | pairs.sort(key=lambda pair: pair[0]) 14 | print(pairs) 15 | 16 | # Sort by the integer 17 | pairs.sort(key=lambda pair: pair[1]) 18 | print(pairs) 19 | 20 | ''' 21 | 2. The square of a number, using a named function and a lambda 22 | ''' 23 | 24 | 25 | def p(n): 26 | return n ** 2 27 | 28 | 29 | g = lambda x: x ** 2 30 | 31 | print(p(8)) 32 | print(g(8)) 33 | 34 | ''' 35 | 3. Filter a list using some criteria 36 | ''' 37 | print('Student ''Anna''') 38 | for p in filter(lambda p: p[0] == 'Anna', pairs): 39 | print('\t', p) 40 | 41 | print('Where integer is >6') 42 | for p in filter(lambda p: p[1] > 6, pairs): 43 | print('\t', p) 44 | -------------------------------------------------------------------------------- /src/lecture/examples/ex03_ProgramFlow.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Sep 23, 2016 3 | 4 | @author: Arthur 5 | """ 6 | 7 | """ 8 | Read a number and check whether it is prime 9 | """ 10 | x = input("Give the number: ") 11 | x = int(x) 12 | 13 | isPrime = True 14 | for i in range(2, x // 2): 15 | if x % i == 0: 16 | isPrime = False 17 | 18 | if isPrime == True: 19 | print("Number is prime!") 20 | else: 21 | print("Number is not prime!") 22 | 23 | """ 24 | NB! 25 | Let's break program flow as soon as we know it's not a prime 26 | """ 27 | x = input("Give the number: ") 28 | x = int(x) 29 | 30 | isPrime = True 31 | i = 2 32 | while isPrime == True and i <= x // 2: 33 | i += 1 34 | if x % i == 0: 35 | isPrime = False 36 | 37 | if isPrime == True: 38 | print("Number is prime!") 39 | else: 40 | print("Number is not prime!") 41 | 42 | """ 43 | Open question! 44 | How can you check the functions above do what they are supposed to? 45 | """ -------------------------------------------------------------------------------- /src/lecture/examples/ex10_modular_calc/domain/rational.py: -------------------------------------------------------------------------------- 1 | """ 2 | Utility module to work with rational numbers 3 | """ 4 | from math import gcd 5 | 6 | 7 | def create_rational(nom, den=1): 8 | if den == 0: 9 | raise ValueError("Denominator cannot be 0") 10 | d = gcd(nom, den) 11 | return [nom // d, den // d] 12 | 13 | 14 | def get_numerator(q): 15 | return q[0] 16 | 17 | 18 | def get_denominator(q): 19 | return q[1] 20 | 21 | 22 | def add(q1, q2): 23 | """ 24 | Return the sum of two rational numbers. 25 | q1, q2 the rational numbers 26 | return the sum 27 | """ 28 | return create_rational(get_numerator(q1) * get_denominator(q2) + get_numerator(q2) * get_denominator(q1), get_denominator(q1) * get_denominator(q2)) 29 | 30 | 31 | def test_add(): 32 | """ 33 | Test function for rational_add 34 | """ 35 | assert add(create_rational(1, 2), create_rational(1, 3)) == create_rational(5, 6) 36 | assert add(create_rational(1, 2), create_rational(1, 2)) == create_rational(1) 37 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_14.py: -------------------------------------------------------------------------------- 1 | """ 2 | Dynamic programming 3 | """ 4 | 5 | """ 6 | 1. Calculate the maximum subarray sum (subarray = elements having continuous indices) 7 | a. Naive implementation 8 | b. Divide & conquer implementation 9 | 10 | e.g. 11 | for data = [-2, -5, 6, -2, -3, 1, 5, -6], maximum subarray sum is 7. 12 | """ 13 | 14 | """ 15 | 2. Count in how many ways we can provide change to a given sum of money (N), when provided infinite 16 | supply of given coin denominations. 17 | 18 | e.g. Let's say N = 10, and we have coins of values (1, 5, 10); we can give change in 4 ways (10, 5 + 5, 5 + 1 + ... 19 | and 1 + ... + 1) 20 | """ 21 | 22 | """ 23 | 3. 0-1 Knapsack problem. Given the weights and values of N items, put them in a knapsack having capacity W so that you 24 | maximize the value of the stored items. Items cannot be broken up (0-1 property) 25 | """ 26 | 27 | """ 28 | 4. Gold mine problem (a.k.a checkerboard problem) 29 | https://www.geeksforgeeks.org/gold-mine-problem 30 | """ 31 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_14.py: -------------------------------------------------------------------------------- 1 | """ 2 | Dynamic programming 3 | """ 4 | 5 | """ 6 | 1. Calculate the maximum subarray sum (subarray = elements having continuous indices) 7 | a. Naive implementation 8 | b. Divide & conquer implementation 9 | 10 | e.g. 11 | for data = [-2, -5, 6, -2, -3, 1, 5, -6], maximum subarray sum is 7. 12 | """ 13 | 14 | """ 15 | 2. Count in how many ways we can provide change to a given sum of money (N), when provided infinite 16 | supply of given coin denominations. 17 | 18 | e.g. Let's say N = 10, and we have coins of values (1, 5, 10); we can give change in 4 ways (10, 5 + 5, 5 + 1 + ... 19 | and 1 + ... + 1) 20 | """ 21 | 22 | """ 23 | 3. 0-1 Knapsack problem. Given the weights and values of N items, put them in a knapsack having capacity W so that you 24 | maximize the value of the stored items. Items cannot be broken up (0-1 property) 25 | """ 26 | 27 | """ 28 | 4. Gold mine problem (a.k.a checkerboard problem) 29 | https://www.geeksforgeeks.org/gold-mine-problem 30 | """ 31 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_14.py: -------------------------------------------------------------------------------- 1 | """ 2 | Dynamic programming 3 | """ 4 | 5 | """ 6 | 1. Calculate the maximum subarray sum (subarray = elements having continuous indices) 7 | a. Naive implementation 8 | b. Divide & conquer implementation 9 | 10 | e.g. 11 | for data = [-2, -5, 6, -2, -3, 1, 5, -6], maximum subarray sum is 7. 12 | """ 13 | 14 | """ 15 | 2. Count in how many ways we can provide change to a given sum of money (N), when provided infinite 16 | supply of given coin denominations. 17 | 18 | e.g. Let's say N = 10, and we have coins of values (1, 5, 10); we can give change in 4 ways (10, 5 + 5, 5 + 1 + ... 19 | and 1 + ... + 1) 20 | """ 21 | 22 | """ 23 | 3. 0-1 Knapsack problem. Given the weights and values of N items, put them in a knapsack having capacity W so that you 24 | maximize the value of the stored items. Items cannot be broken up (0-1 property) 25 | """ 26 | 27 | """ 28 | 4. Gold mine problem (a.k.a checkerboard problem) 29 | https://www.geeksforgeeks.org/gold-mine-problem 30 | """ 31 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_05/ui.py: -------------------------------------------------------------------------------- 1 | from functions import functions 2 | 3 | 4 | class console: 5 | def __init__(self): 6 | self._func = functions() 7 | 8 | def _show_menu(self): 9 | print("1. Generate rectangles") 10 | print("2. View rectangles") 11 | print("3. Exit") 12 | 13 | def _generate_rectangles(self): 14 | n = input("n=") 15 | self._func.generate_rectangles(int(n)) 16 | 17 | def _show_rectangles(self): 18 | rectangles = self._func.sort_rectangles() 19 | for rect in rectangles: 20 | print(str(rect)) 21 | 22 | def start(self): 23 | while True: 24 | self._show_menu() 25 | opt = input("") 26 | 27 | if opt == '1': 28 | self._generate_rectangles() 29 | elif opt == '2': 30 | self._show_rectangles() 31 | elif opt == '3': 32 | return 33 | else: 34 | print("Invalid menu choice") 35 | 36 | 37 | ui = console() 38 | ui.start() 39 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_06_09/domain/exceptions.py: -------------------------------------------------------------------------------- 1 | class ValidatorException(Exception): 2 | def __init__(self, message_list=["Validation error!"]): 3 | self._message_list = message_list 4 | 5 | @property 6 | def messages(self): 7 | return self._message_list 8 | 9 | def __str__(self): 10 | result = "" 11 | for message in self.messages: 12 | result += message 13 | result += "\n" 14 | return result 15 | 16 | 17 | class CarException(Exception): 18 | # TODO Some more code is required here 19 | def __init__(self, msg): 20 | self._msg = msg 21 | 22 | def __str__(self): 23 | return self._msg 24 | 25 | 26 | class CarValidationException(CarException): 27 | # TODO Some more code is required here 28 | def __init__(self, error_list): 29 | self._errors = error_list 30 | 31 | def __str__(self): 32 | result = '' 33 | 34 | for er in self._errors: 35 | result += er 36 | result += '\n' 37 | return result 38 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_06_09/domain/exceptions.py: -------------------------------------------------------------------------------- 1 | class ValidatorException(Exception): 2 | def __init__(self, message_list=["Validation error!"]): 3 | self._message_list = message_list 4 | 5 | @property 6 | def messages(self): 7 | return self._message_list 8 | 9 | def __str__(self): 10 | result = "" 11 | for message in self.messages: 12 | result += message 13 | result += "\n" 14 | return result 15 | 16 | 17 | class CarException(Exception): 18 | # TODO Some more code is required here 19 | def __init__(self, msg): 20 | self._msg = msg 21 | 22 | def __str__(self): 23 | return self._msg 24 | 25 | 26 | class CarValidationException(CarException): 27 | # TODO Some more code is required here 28 | def __init__(self, error_list): 29 | self._errors = error_list 30 | 31 | def __str__(self): 32 | result = '' 33 | 34 | for er in self._errors: 35 | result += er 36 | result += '\n' 37 | return result 38 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_06_09/domain/exceptions.py: -------------------------------------------------------------------------------- 1 | class ValidatorException(Exception): 2 | def __init__(self, message_list=["Validation error!"]): 3 | self._message_list = message_list 4 | 5 | @property 6 | def messages(self): 7 | return self._message_list 8 | 9 | def __str__(self): 10 | result = "" 11 | for message in self.messages: 12 | result += message 13 | result += "\n" 14 | return result 15 | 16 | 17 | class CarException(Exception): 18 | # TODO Some more code is required here 19 | def __init__(self, msg): 20 | self._msg = msg 21 | 22 | def __str__(self): 23 | return self._msg 24 | 25 | 26 | class CarValidationException(CarException): 27 | # TODO Some more code is required here 28 | def __init__(self, error_list): 29 | self._errors = error_list 30 | 31 | def __str__(self): 32 | result = '' 33 | 34 | for er in self._errors: 35 | result += er 36 | result += '\n' 37 | return result 38 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_05/ui.py: -------------------------------------------------------------------------------- 1 | from functions import functions 2 | 3 | 4 | class ui: 5 | def __init__(self): 6 | self._func = functions() 7 | 8 | def _main_menu(self): 9 | print("1. Generate circles") 10 | print("3. Print circles") 11 | print("4. Exit") 12 | 13 | def _generate_circles(self): 14 | n = input("How many circles? ") 15 | self._func.generate_circles(int(n)) 16 | 17 | def _print_circles(self): 18 | circles = self._func.sort_circle_list() 19 | for c in circles: 20 | print(str(c)) # no more to_str functions, we use Python provided syntax 21 | 22 | def start(self): 23 | while True: 24 | self._main_menu() 25 | opt = input() 26 | if opt == "1": 27 | self._generate_circles() 28 | elif opt == "3": 29 | self._print_circles() 30 | elif opt == "4": 31 | return 32 | else: 33 | print("Bad selection!") 34 | 35 | 36 | console = ui() 37 | 38 | console.start() 39 | -------------------------------------------------------------------------------- /src/lecture/examples/ex15_instanceVsClassAttributes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Nov 2, 2016 3 | 4 | @author: Arthur 5 | """ 6 | 7 | 8 | class student: 9 | # Class field is shared by all instances 10 | __studentCount = 0 11 | 12 | def __init__(self, name="Anonymous"): 13 | self.__name = name 14 | 15 | ''' 16 | NB! 17 | Make sure to prefix the attribute name with: 18 | - class name, or 19 | - type(self) 20 | ''' 21 | student.__studentCount += 1 22 | 23 | def set_name(self, name): 24 | self.__name = name 25 | 26 | def get_name(self): 27 | return self.__name 28 | 29 | @staticmethod 30 | def get_student_count(): 31 | return student.__studentCount 32 | 33 | 34 | ''' 35 | We create some students 36 | ''' 37 | s1 = student() 38 | s2 = student() 39 | 40 | s1.set_name("Anna") 41 | s2.set_name("Carla") 42 | 43 | print(s1.get_name()) 44 | print(s2.get_name()) 45 | 46 | print(student.get_student_count()) 47 | 48 | ''' 49 | What happens here? 50 | ''' 51 | # print(Student.__studentCount) 52 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_01.py: -------------------------------------------------------------------------------- 1 | print("Hello World!") 2 | 3 | # char value[10]; // int value; 4 | 5 | # static typing - each var's type is known at compile time 6 | # dynamic typing - Python interpreter keeps track of var type during runtime 7 | # class = type 8 | # str = Python string 9 | 10 | 11 | """ 12 | a few more observations: 13 | 14 | 1. Most things in Python work, but they might not do what you expect 15 | 2. Python has a Boolean type so True/False 16 | 3. f() -> function call operator applied on function f 17 | """ 18 | 19 | # print(type(str(int("3072")))) 20 | print(str(print("x"))) 21 | 22 | # a = input("Enter a : ") 23 | # b = input("Enter b : ") 24 | # 25 | # print(type(a)) 26 | # print(type(b)) 27 | # 28 | # print(a + b) 29 | # 30 | # a = int(a) # str() converts to a string 31 | # b = int(b) 32 | # 33 | # print(type(a)) 34 | # print(type(b)) 35 | # 36 | # print(a + b) 37 | 38 | """ 39 | Main git operations: 40 | commit - tells git to "remember" the changes that we've just made (they are stored locally) 41 | push - tells git to syncronize the remote repo (changes show up on github.com) 42 | """ -------------------------------------------------------------------------------- /src/lecture/examples/ex24_gui/tests/tests.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from lecture.examples.ex24_gui.domain.entities import Student, Address 4 | from lecture.examples.ex24_gui.domain.validators import StudentValidator, ValidationException 5 | 6 | 7 | class TestStudentValidator(unittest.TestCase): 8 | def test_validate_student(self): 9 | val = StudentValidator() 10 | # student invalid if id is empty 11 | st = Student("", "Ion", Address("Adr", 1, "Cluj")) 12 | try: 13 | val.validate(st) 14 | self.assertFalse() 15 | except ValidationException: 16 | pass 17 | 18 | # student invalid if name is empty 19 | st = Student("3", "", Address("Adr", 1, "Cluj")) 20 | try: 21 | val.validate(st) 22 | self.assertFalse() 23 | except ValidationException: 24 | pass 25 | 26 | # student invalid if adr is empty 27 | st = Student("3", "Ion", Address("", 1, "Cluj")) 28 | try: 29 | val.validate(st) 30 | self.assertFalse() 31 | except ValidationException: 32 | pass 33 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_05/functions.py: -------------------------------------------------------------------------------- 1 | from circles import circle 2 | from random import randint 3 | 4 | 5 | class functions: 6 | def __init__(self): 7 | self._circle_list = [] 8 | 9 | def generate_circles(self, n): 10 | """ 11 | Generate circles 12 | :param n: How many circles to create 13 | :return: None 14 | """ 15 | for i in range(n): 16 | self._circle_list.append(circle(randint(1, 20), randint(1, 20), randint(1, 5))) 17 | 18 | def delete_circles(self, x, y, width, height): 19 | """ 20 | Delete all circles in rectangle (x,y) - (x + width, y + height) 21 | :param x: 22 | :param y: 23 | :param width: 24 | :param height: 25 | :return: The number of deleted circles 26 | """ 27 | pass 28 | 29 | def sort_circle_list(self): 30 | """ 31 | Sort list of circles descending by radius 32 | :return: Sorted copy of the original list 33 | """ 34 | return sorted(self._circle_list, key=get_radius, reverse=True) 35 | 36 | 37 | def get_radius(c): 38 | return c.r 39 | -------------------------------------------------------------------------------- /src/lecture/examples/ex16_rationalCalculator/calculator.py: -------------------------------------------------------------------------------- 1 | from lecture.examples.ex16_rationalCalculator.domain import Rational 2 | 3 | 4 | class Calculator: 5 | def __init__(self): 6 | self._total = Rational(0) 7 | self._history = [] 8 | 9 | @property 10 | def get_total(self): 11 | # Total is a read-only property 12 | return self._total 13 | 14 | def add(self, r): 15 | """ 16 | Add a number to the calculator. Adding 0 will not create an undo point 17 | param: 18 | r - the number to add 19 | """ 20 | if r == Rational(0): 21 | return 22 | # Record for undo 23 | self._history.append(self._total) 24 | # Add the value to calculator total 25 | self._total += r 26 | 27 | def undo(self): 28 | if len(self._history) == 0: 29 | raise ValueError('No more undo steps!') 30 | self._total = self._history.pop() 31 | 32 | @staticmethod 33 | def get_number_count(): 34 | return Rational.get_total_number_of_instances() 35 | 36 | def reset(self): 37 | self._total = Rational(0) 38 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_06_09/services/client_service.py: -------------------------------------------------------------------------------- 1 | from seminar.group_911.seminar_06_09.domain.client import Client 2 | 3 | 4 | class ClientService: 5 | def __init__(self, rental_service, validator, repository): 6 | self._validator = validator 7 | self._repository = repository 8 | self._rental_service = rental_service 9 | 10 | def create(self, client_id, client_cnp, client_name): 11 | client = Client(client_id, client_cnp, client_name) 12 | self._validator.validate(client) 13 | self._repository.add(client) 14 | return client 15 | 16 | def delete(self, client_id): 17 | """ 18 | 1. Delete the client 19 | """ 20 | client = self._repository.delete(client_id) 21 | 22 | ''' 23 | 2. Delete their rentals 24 | NB! This implementation is not transactional, i.e. the two delete operations are performed separately 25 | ''' 26 | rentals = self._rental_service.filter_rentals(client, None) 27 | for rent in rentals: 28 | self._rental_service.delete_rental(rent.id, False) 29 | 30 | return client 31 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_06_09/services/client_service.py: -------------------------------------------------------------------------------- 1 | from seminar.group_912.seminar_06_09.domain.client import Client 2 | 3 | 4 | class ClientService: 5 | def __init__(self, rental_service, validator, repository): 6 | self._validator = validator 7 | self._repository = repository 8 | self._rental_service = rental_service 9 | 10 | def create(self, client_id, client_cnp, client_name): 11 | client = Client(client_id, client_cnp, client_name) 12 | self._validator.validate(client) 13 | self._repository.add(client) 14 | return client 15 | 16 | def delete(self, client_id): 17 | """ 18 | 1. Delete the client 19 | """ 20 | client = self._repository.delete(client_id) 21 | 22 | ''' 23 | 2. Delete their rentals 24 | NB! This implementation is not transactional, i.e. the two delete operations are performed separately 25 | ''' 26 | rentals = self._rental_service.filter_rentals(client, None) 27 | for rent in rentals: 28 | self._rental_service.delete_rental(rent.id, False) 29 | 30 | return client 31 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_06_09/services/client_service.py: -------------------------------------------------------------------------------- 1 | from seminar.group_917.seminar_06_09.domain.client import Client 2 | 3 | 4 | class ClientService: 5 | def __init__(self, rental_service, validator, repository): 6 | self._validator = validator 7 | self._repository = repository 8 | self._rental_service = rental_service 9 | 10 | def create(self, client_id, client_cnp, client_name): 11 | client = Client(client_id, client_cnp, client_name) 12 | self._validator.validate(client) 13 | self._repository.add(client) 14 | return client 15 | 16 | def delete(self, client_id): 17 | """ 18 | 1. Delete the client 19 | """ 20 | client = self._repository.delete(client_id) 21 | 22 | ''' 23 | 2. Delete their rentals 24 | NB! This implementation is not transactional, i.e. the two delete operations are performed separately 25 | ''' 26 | rentals = self._rental_service.filter_rentals(client, None) 27 | for rent in rentals: 28 | self._rental_service.delete_rental(rent.id, False) 29 | 30 | return client 31 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_04.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program that manages circles. Each circle has an (x,y) center (x,y - integers) and a the radius r 3 | (r > 0, r is an integer). Functionalities will be available using a command-based UI: 4 | 5 | 1. Generate 'n' circles. 6 | - n is a positive integer read from the keyboard. 7 | - program generates and stores n distinct, random circles (distinct = at least one of x,y,radius must differ) , 8 | each completely enclosed in the square defined by corners (0,0) and (40,40) 9 | 10 | 2. Delete all circles from a given rectangle 11 | - read rectangle data (x, y, width, height) # rect corner coordinates (x,y) - (x + width, y + height) 12 | - delete all circles that are fully enclosed in this rectangle 13 | 14 | 3. Display all circle data on the console, sorted descending by radius 15 | 16 | 4. Exit 17 | 18 | Requirements: 19 | - handle input errors with exceptions 20 | - unit test for 2. delete 21 | 22 | Required modules: 23 | circle.py (functions that work directly with circles) 24 | functions.py (implement program functionalities) 25 | console.py (user interface) 26 | 27 | function calls 28 | console.py -> function.py -> circle.py 29 | -> circle.py 30 | """ -------------------------------------------------------------------------------- /src/lecture/examples/ex02_BasicCompoundTypes.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Sep 26, 2016 3 | 4 | @author: Arthur 5 | """ 6 | 7 | """ 8 | List 9 | """ 10 | 11 | myList = [1, 2, 3] 12 | print(myList) 13 | 14 | print(myList[1]) 15 | 16 | print('The list has', len(myList), 'elements') 17 | print('Tha first element is', myList[0], 'and the last one is', myList[len(myList) - 1]) 18 | 19 | x = myList 20 | print(myList, x) 21 | 22 | """ 23 | What happens here? 24 | """ 25 | x[1] = '?' 26 | print(myList, x) 27 | 28 | """ 29 | List slicing 30 | """ 31 | myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 32 | print(myList[:2]) 33 | print(myList[2:]) 34 | myList[5:] = ['a', 'b', 'c'] 35 | print(myList) 36 | 37 | myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 38 | myList[1:9] = 'x' 39 | print(myList) 40 | 41 | """ 42 | Tuple 43 | """ 44 | tup = 1, 2, 'a' 45 | print(tup) 46 | print(tup[1]) 47 | 48 | for e in tup: 49 | print(e) 50 | 51 | """ 52 | What happens if we uncomment this line? 53 | """ 54 | # tup[1] = 'x' 55 | 56 | """ 57 | Dictionary 58 | """ 59 | d = {'num':1,'den':2} 60 | print(d) 61 | 62 | print(d['num']) 63 | d['num'] = 99 64 | print(d['num']) 65 | 66 | if 'num' in d: 67 | print('We have num!') 68 | 69 | del d['num'] 70 | 71 | if 'num' in d: 72 | print('We have num!') -------------------------------------------------------------------------------- /src/lecture/examples/ex31_stableSort.py: -------------------------------------------------------------------------------- 1 | from random import choice 2 | 3 | 4 | class Person: 5 | def __init__(self, name, age): 6 | self._name = name 7 | self._age = age 8 | 9 | @property 10 | def name(self): 11 | return self._name 12 | 13 | @property 14 | def age(self): 15 | return self._age 16 | 17 | def __str__(self): 18 | return str(self.age) + ' ' + self.name 19 | 20 | 21 | def generate(): 22 | """ 23 | Generate some people instances 24 | """ 25 | result = [] 26 | 27 | famName = ['Popescu', 'Marian', 'Pop', 'Lazarescu', 'Dincu'] 28 | givName = ['Anca', 'Emilia', 'Liviu', 'Marius'] 29 | age = [17, 18, 19, 20] 30 | 31 | for i in range(20): 32 | result.append(Person(choice(famName) + ' ' + choice(givName), choice(age))) 33 | 34 | return result 35 | 36 | 37 | ''' 38 | 1. Generate people 39 | ''' 40 | result = generate() 41 | 42 | ''' 43 | 2. First we sort the list by name (ascending) 44 | ''' 45 | result.sort(key=lambda p: p.name) 46 | 47 | ''' 48 | 3. Then we sort by age (descending) - the sorts are STABLE 49 | ''' 50 | result.sort(key=lambda p: p.age, reverse=True) 51 | 52 | ''' 53 | 4. People of the same age are ordered by name 54 | ''' 55 | for p in result: 56 | print(p) 57 | -------------------------------------------------------------------------------- /src/lecture/examples/ex34_backtracking.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Jan 10, 2017 3 | 4 | @author: Arthur 5 | """ 6 | 7 | import time 8 | from texttable import * 9 | 10 | 11 | def generate_test(array, DIM): 12 | if len(array) == DIM: 13 | # print (array) 14 | pass 15 | if len(array) > DIM: 16 | return 17 | array.append(0) 18 | for i in range(0, DIM): 19 | array[-1] = i 20 | generate_test(array[:], DIM) 21 | 22 | 23 | def backtracking(array, DIM): 24 | if len(array) == DIM: 25 | print(array) 26 | pass 27 | if len(array) > DIM: 28 | return 29 | array.append(0) 30 | for i in range(0, DIM): 31 | array[-1] = i 32 | if len(set(array)) == len(array): 33 | backtracking(array, DIM) 34 | array.pop() 35 | 36 | 37 | ''' 38 | And here we build our experiment 39 | ''' 40 | functions = [generate_test, backtracking] 41 | data_sizes = [3, 4, 5, 6, 7] 42 | 43 | t = Texttable() 44 | t.add_row(['Functions'] + data_sizes) 45 | for function in functions: 46 | row = [function.__name__] 47 | for size in data_sizes: 48 | t1 = time.perf_counter() 49 | function([], size) 50 | t2 = time.perf_counter() 51 | row = row + [t2 - t1] 52 | t.add_row(row) 53 | print(t.draw()) 54 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_11.py: -------------------------------------------------------------------------------- 1 | """ 2 | Recursion 3 | 4 | 1. A recursive step -> progress towards a base case 5 | 2. A non-recursive step must exist 6 | """ 7 | 8 | 9 | def factorial(n): 10 | """ 11 | Determine the factorial of given number 12 | :param n: Determine n! 13 | :return: n! 14 | """ 15 | if n == 0: 16 | # Base case, without recursion 17 | return 1 18 | 19 | # Take the recursive step 20 | return n * factorial(n - 1) 21 | 22 | 23 | # print(factorial(6)) 24 | 25 | # 0,1, 1, 2, 3, 5, 8, 11, ... 26 | def fib(n): 27 | """ 28 | Determine n-th term of Fibonacci 29 | :param n: 30 | :return: 31 | """ 32 | if n == 0: 33 | return 0 34 | if n == 1: 35 | return 1 36 | 37 | return fib(n - 2) + fib(n - 1) 38 | 39 | 40 | # T(n) = T(n-2) + T(n-1) + 1, n > 1 41 | # T(n) = 1, n <= 1 42 | # T(n) = ( 2^(n-1) ) + 1 43 | 44 | # Store precalculated values here 45 | memory = {0: 1, 1: 1} 46 | 47 | 48 | def fib_2(n): 49 | """ 50 | Determine n-th term of Fibonacci 51 | :param n: 52 | :return: 53 | """ 54 | if n not in memory: 55 | memory[n] = fib_2(n - 2) + fib_2(n - 1) 56 | return memory[n] 57 | 58 | 59 | # T(n) = n 60 | 61 | 62 | print(fib(40)) 63 | # print(fib_2(400)) 64 | -------------------------------------------------------------------------------- /src/lecture/examples/ex12_pythonClassParticularities.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Nov 1, 2016 3 | 4 | @author: Arthur 5 | """ 6 | 7 | 8 | class FirstClass: 9 | pass 10 | 11 | 12 | class SecondClass: 13 | def __init__(self): 14 | self.test_one = "Test One" 15 | self._test_two = "Test Two" 16 | self.__test_three = "Test Three" 17 | 18 | 19 | x = FirstClass() 20 | 21 | ''' 22 | What is the type of x ? 23 | ''' 24 | print(type(x)) 25 | 26 | ''' 27 | An empty class, such as FirstClass can be used as a Pascal record or a C struct 28 | ''' 29 | x.name = "Alice" 30 | x.salary = 100 31 | x.salary += 20 32 | print("Name of x=", x.name) 33 | print("Salary of x=", x.salary) 34 | 35 | y = FirstClass() 36 | y.name = "Bob" 37 | y.salary = 1000 38 | print("Name of y=", y.name) 39 | print("Salary of y=", y.salary) 40 | 41 | ''' 42 | What happens if we add another field on-the-fly? 43 | ''' 44 | y.hello = "Say hello" 45 | print(y.hello) 46 | # Field 'hello' is not a part of instance 'x' 47 | # print(x.hello) 48 | 49 | ''' 50 | How about the more complex, SecondClass example? 51 | ''' 52 | obj = SecondClass() 53 | print(obj.test_one) 54 | # print(obj._test_two) 55 | 56 | ''' 57 | This is Python's name mangling at work 58 | ''' 59 | # print(obj.__test_three) 60 | # print(obj._SecondClass__test_three) 61 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_12.py: -------------------------------------------------------------------------------- 1 | """ 2 | Product of even numbers in a list that are on even positions 3 | """ 4 | import random 5 | 6 | data = list(range(1, 10)) 7 | random.shuffle(data) 8 | print(data) 9 | 10 | # _enum = [y for x, y in enumerate(data) if x % 2 == 0 and y % 2 == 0] 11 | # print(list(enumerate(data))) 12 | # 13 | # 14 | # print(sum([y for x, y in enumerate(data) if x % 2 == 0 and y % 2 == 0])) 15 | 16 | 17 | """ 18 | V1 - chip & conquer ( T(1) + T(n-1) ) 19 | """ 20 | 21 | 22 | def chip_conquer(data, start): 23 | # past the end of the list 24 | if start == len(data): 25 | return 1 26 | 27 | return data[start] * chip_conquer(data, start + 1) if start % 2 == 0 and data[start] % 2 == 0 else chip_conquer( 28 | data, 29 | start + 1) 30 | 31 | 32 | # print(chip_conquer(data, 0)) 33 | 34 | """ 35 | V2 - T(n/2) + T(n/2) 36 | """ 37 | 38 | 39 | def product_rec(data, start, end): 40 | if start == end: 41 | if start % 2 == 0 and data[start] % 2 == 0: 42 | return data[start] 43 | else: 44 | return 1 45 | 46 | middle = (start + end) // 2 47 | return product_rec(data, start, middle) * product_rec(data, middle + 1, end) 48 | 49 | 50 | print(chip_conquer(data, 0)) 51 | print(product_rec(data, 0, len(data) - 1)) 52 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_09/service/CarService.py: -------------------------------------------------------------------------------- 1 | from seminar.group_911.seminar_09.domain.Car import Car 2 | 3 | 4 | class CarService: 5 | def __init__(self, undo_service, rental_service, validator, repository): 6 | self._validator = validator 7 | self._repository = repository 8 | self._rental_service = rental_service 9 | self._undo_service = undo_service 10 | 11 | def create(self, car_id, license_plate, car_make, car_model): 12 | car = Car(car_id, license_plate, car_make, car_model) 13 | self._validator.validate(car) 14 | self._repository.store(car) 15 | return car 16 | 17 | def delete(self, car_id): 18 | """ 19 | 1. Delete the car from the repository 20 | """ 21 | car = self._repository.delete(car_id) 22 | 23 | ''' 24 | 2. Delete its rentals 25 | NB! This implementation is not transactional, i.e. the two delete operations are performed separately 26 | ''' 27 | rentals = self._rental_service.filter_rentals(None, car) 28 | for rent in rentals: 29 | self._rental_service.delete_rental(rent.id) 30 | return car 31 | 32 | def update(self, car): 33 | """ 34 | NB! Undo/redo is also needed here 35 | """ 36 | # TODO Implement later... 37 | pass 38 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_09/service/CarService.py: -------------------------------------------------------------------------------- 1 | from seminar.group_912.seminar_09.domain.Car import Car 2 | 3 | 4 | class CarService: 5 | def __init__(self, undo_service, rental_service, validator, repository): 6 | self._validator = validator 7 | self._repository = repository 8 | self._rental_service = rental_service 9 | self._undo_service = undo_service 10 | 11 | def create(self, car_id, license_plate, car_make, car_model): 12 | car = Car(car_id, license_plate, car_make, car_model) 13 | self._validator.validate(car) 14 | self._repository.store(car) 15 | return car 16 | 17 | def delete(self, car_id): 18 | """ 19 | 1. Delete the car from the repository 20 | """ 21 | car = self._repository.delete(car_id) 22 | 23 | ''' 24 | 2. Delete its rentals 25 | NB! This implementation is not transactional, i.e. the two delete operations are performed separately 26 | ''' 27 | rentals = self._rental_service.filter_rentals(None, car) 28 | for rent in rentals: 29 | self._rental_service.delete_rental(rent.id) 30 | return car 31 | 32 | def update(self, car): 33 | """ 34 | NB! Undo/redo is also needed here 35 | """ 36 | # TODO Implement later... 37 | pass 38 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_09/service/CarService.py: -------------------------------------------------------------------------------- 1 | from seminar.group_917.seminar_09.domain.Car import Car 2 | 3 | 4 | class CarService: 5 | def __init__(self, undo_service, rental_service, validator, repository): 6 | self._validator = validator 7 | self._repository = repository 8 | self._rental_service = rental_service 9 | self._undo_service = undo_service 10 | 11 | def create(self, car_id, license_plate, car_make, car_model): 12 | car = Car(car_id, license_plate, car_make, car_model) 13 | self._validator.validate(car) 14 | self._repository.store(car) 15 | return car 16 | 17 | def delete(self, car_id): 18 | """ 19 | 1. Delete the car from the repository 20 | """ 21 | car = self._repository.delete(car_id) 22 | 23 | ''' 24 | 2. Delete its rentals 25 | NB! This implementation is not transactional, i.e. the two delete operations are performed separately 26 | ''' 27 | rentals = self._rental_service.filter_rentals(None, car) 28 | for rent in rentals: 29 | self._rental_service.delete_rental(rent.id) 30 | return car 31 | 32 | def update(self, car): 33 | """ 34 | NB! Undo/redo is also needed here 35 | """ 36 | # TODO Implement later... 37 | pass 38 | -------------------------------------------------------------------------------- /src/lecture/examples/ex24_gui/domain/validators.py: -------------------------------------------------------------------------------- 1 | class StudentCRUDException(Exception): 2 | pass 3 | 4 | 5 | class ValidationException(StudentCRUDException): 6 | def __init__(self, msgs): 7 | """ 8 | Initialise 9 | msg is a list of strings (errors) 10 | """ 11 | self.__msgs = msgs 12 | 13 | @property 14 | def messages(self): 15 | return self.__msgs 16 | 17 | def __str__(self): 18 | return str(self.__msgs) 19 | 20 | 21 | class StudentValidator: 22 | """ 23 | Class responsible with the validation for students 24 | GRASP - Protect Variation 25 | 26 | """ 27 | 28 | def __init__(self): 29 | pass 30 | 31 | @staticmethod 32 | def validate(st): 33 | """ 34 | Validate student 35 | raise ValidationException if id, name, or addres is empty 36 | """ 37 | error_messages = [] 38 | if st.id == "": 39 | error_messages.append("Id can not be empty") 40 | if st.name == "": 41 | error_messages.append("Name can not be empty") 42 | if st.address is None or st.address.street == "": 43 | error_messages.append("Address can not be empty") 44 | # if there is a validation error throw exception 45 | if len(error_messages) > 0: 46 | raise ValidationException(error_messages) 47 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_04/ui.py: -------------------------------------------------------------------------------- 1 | """ 2 | Tic Tac Toe ui! 3 | Can call functions from game/board 4 | All input/print statements go here 5 | """ 6 | # import board 7 | from board import init_board, to_str, is_board_full, is_board_won, set_board_pos 8 | from game import move_computer 9 | 10 | 11 | def read_position(): 12 | x = int(input("X=")) 13 | y = int(input("Y=")) 14 | return x, y 15 | 16 | 17 | def start(): 18 | board = init_board() 19 | 20 | is_human_turn = True 21 | 22 | while not is_board_won(board) and not is_board_full(board): 23 | print("Game board:") 24 | print(to_str(board)) 25 | 26 | try: 27 | if is_human_turn: 28 | x, y = read_position() 29 | set_board_pos(board, x, y, 'X') 30 | else: 31 | x, y = move_computer(board) 32 | set_board_pos(board, x, y, 'O') 33 | print("Computer moves (" + str(x) + "," + str(y) + ")") 34 | is_human_turn = not is_human_turn 35 | except ValueError as ve: 36 | print(str(ve)) 37 | 38 | if is_board_won(board): 39 | if is_human_turn: 40 | # Var is flipped after the last move was made 41 | print("Computer wins!") 42 | else: 43 | print("You win!") 44 | print(to_str(board)) 45 | else: 46 | print("It's a draw!") 47 | 48 | 49 | start() 50 | -------------------------------------------------------------------------------- /src/lecture/examples/ex08_Exceptions.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Oct 25, 2016 3 | 4 | @author: Arthur 5 | 6 | Part of this code is taken from: 7 | https://docs.python.org/3/tutorial/errors.html 8 | """ 9 | 10 | """ 11 | Try to enter various (non-integer) values at the prompt given by the code snippet below 12 | """ 13 | 14 | # while True: 15 | # try: 16 | # x = int(input("Please enter a number: ")) 17 | # break 18 | # except ValueError: 19 | # print("Oops! That was no valid number. Try again...") 20 | 21 | 22 | ''' 23 | Try running the program below, and see what happens on different inputs 24 | 25 | NB! 26 | This is not a correct way to implement error handling, it's just example code :) 27 | ''' 28 | end = False 29 | while not end: 30 | try: 31 | val = input("T - TypeError, V - ValueErorr, K - KeyError, 0 - Exit") 32 | 33 | if val.lower() == 't': 34 | raise TypeError("Well this is a type error!") 35 | elif val.lower() == 'k': 36 | raise KeyError("Your program just raised a key error!") 37 | elif val.lower() == 'v': 38 | raise ValueError("value error!") 39 | else: 40 | end = True 41 | except KeyError as ke: 42 | print("There was a " + str(type(ke)) + " " + str(ke)) 43 | except ValueError as ve: 44 | print("There was a ValueError") 45 | except: 46 | print("There was an exception that was not handled above!") 47 | else: 48 | print("There was no error") 49 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_04.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program that manages rectangles. Each rectangle is defined by two of its opposing corners, having coordinates 3 | (x1,y1) and (x2,y2) (for example, points (0,0) and (1,1) define a 'unit rectangle'). 4 | 5 | Functionalities will be available using a menu or commands: 6 | 7 | 1. Generate 'n' rectangles 8 | random.randint(a,b) -> use to generate random integers 9 | 10 | - n is a positive integer read from the keyboard. 11 | - program generates and stores n distinct rectangles (distinct = at least one different corner), 12 | - each rectangle is completely enclosed in the square defined by corners (0,0) and (20,20) 13 | 14 | 2. Display all rectangle data, sorted descending by area 15 | rectangle: (0,0) - (10,10) -> area is 100 (0,0), (0,10), (10,0), (10,10) 16 | rectangle: (14,15) - (18,18) -> area is 12 17 | 18 | - display area and coordinates for each rectangle, using right justification (str.rjust) 19 | 20 | 3. Delete all rectangles that have at least one corner below the line x = y 21 | 22 | Requirements: 23 | - handle input errors with exceptions 24 | - specification for all noi-UI functions (except getters and setters) 25 | - unit test for 3. delete 26 | 27 | Required modules: 28 | rectangle.py (functions that work directly with rectangles) 29 | functions.py (implement program functionalities) 30 | console.py (user interface) 31 | 32 | Function calls between modules: 33 | console -> functions -> rectangle 34 | console -> rectangle 35 | """ -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_04.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a program that manages rectangles. Each rectangle is defined by two of its opposing corners, having coordinates 3 | (x1,y1) and (x2,y2) (for example, points (0,0) and (1,1) define a 'unit rectangle'). 4 | 5 | Functionalities will be available using a command-driven UI: 6 | 7 | 1. Generate 'n' rectangles 8 | random.randint(a,b) -> use to generate random integers 9 | 10 | - n is a positive integer read from the keyboard. 11 | - program generates and stores n distinct rectangles (distinct = at least one different corner), 12 | - each rectangle is completely enclosed in the square defined by corners (0,0) and (20,20) 13 | 14 | 2. Display all rectangle data, sorted descending by the length of its longest side 15 | rectangle: (0,0) - (10,10) -> area is 100 (0,0), (0,10), (10,0), (10,10) 16 | rectangle: (14,15) - (18,18) -> area is 12 17 | 18 | - display area and coordinates for each rectangle, using right justification (str.rjust) 19 | 20 | 3. Delete all rectangles that are contained within a given rectangle 21 | 22 | Requirements: 23 | - handle input errors with exceptions 24 | - specification for all noi-UI functions (except getters and setters) 25 | - unit test for 3. delete 26 | 27 | Required modules: 28 | rectangle.py (functions that work directly with rectangles) 29 | functions.py (implement program functionalities) 30 | console.py (user interface) 31 | 32 | Function calls between modules: 33 | console -> functions -> rectangle 34 | console -> rectangle 35 | """ 36 | -------------------------------------------------------------------------------- /src/seminar/group_914/s01/main.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | @author: radu 4 | Problem 1 5 | a) Compute the sum of the first n natural numbers. 6 | b) Check if a given integer number n is prime. 7 | c) Compute the greatest common divisor between two integers a and b. 8 | d) Compute the first prime number greater than a given integer n. 9 | e) Print the first k prime numbers greater than a given integer n. 10 | 11 | 12 | """ 13 | from math import sqrt 14 | 15 | 16 | def sum_of_first_n_natural_numbers(n): 17 | """ Computes the sum of the first n natural numbers. 18 | 19 | Given n, a natural number, the function return the sum of the first n natural numbers. 20 | n: natural number 21 | Returns: the sum of the first n natural numbers 22 | """ 23 | s = 0 24 | for i in range(n): 25 | s += i 26 | 27 | return s 28 | 29 | 30 | def is_prime(n): 31 | # todo: docs 32 | if n == 2: 33 | return True 34 | if n < 2 or n % 2 == 0: 35 | return False 36 | for i in range(3, int(sqrt(n)) + 1, 2): 37 | if n % i == 0: 38 | return False 39 | return True 40 | 41 | 42 | def gcd(a, b): 43 | while b != 0: 44 | a, b = b, a % b 45 | return a if a > 0 else -a 46 | 47 | 48 | def next_prime(n): 49 | while True: 50 | n = n + 1 51 | if is_prime(n): 52 | return n 53 | 54 | 55 | if __name__ == '__main__': 56 | print("hello") 57 | print(sum_of_first_n_natural_numbers(3)) 58 | print(is_prime(49)) 59 | print(gcd(12, -18)) 60 | print(next_prime(17)) 61 | print("bye") 62 | -------------------------------------------------------------------------------- /src/seminar/group_915/s01/main.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | @author: radu 4 | Problem 1 5 | a) Compute the sum of the first n natural numbers. 6 | b) Check if a given integer number n is prime. 7 | c) Compute the greatest common divisor between two integers a and b. 8 | d) Compute the first prime number greater than a given integer n. 9 | e) Print the first k prime numbers greater than a given integer n. 10 | 11 | 12 | """ 13 | from math import sqrt 14 | 15 | 16 | def sum_of_first_n_natural_numbers(n): 17 | """ Computes the sum of the first n natural numbers. 18 | 19 | Given n, a natural number, the function return the sum of the first n natural numbers. 20 | n: natural number 21 | Returns: the sum of the first n natural numbers 22 | """ 23 | s = 0 24 | for i in range(n): 25 | s += i 26 | 27 | return s 28 | 29 | 30 | def is_prime(n): 31 | # todo: docs 32 | if n == 2: 33 | return True 34 | if n < 2 or n % 2 == 0: 35 | return False 36 | for i in range(3, int(sqrt(n)) + 1, 2): 37 | if n % i == 0: 38 | return False 39 | return True 40 | 41 | 42 | def gcd(a, b): 43 | while b != 0: 44 | a, b = b, a % b 45 | return a if a > 0 else -a 46 | 47 | 48 | def next_prime(n): 49 | while True: 50 | n = n + 1 51 | if is_prime(n): 52 | return n 53 | 54 | 55 | if __name__ == '__main__': 56 | print("hello") 57 | print(sum_of_first_n_natural_numbers(3)) 58 | print(is_prime(49)) 59 | print(gcd(12, -18)) 60 | print(next_prime(17)) 61 | print("bye") 62 | -------------------------------------------------------------------------------- /src/seminar/group_916/s01/main.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | @author: radu 4 | Problem 1 5 | a) Compute the sum of the first n natural numbers. 6 | b) Check if a given integer number n is prime. 7 | c) Compute the greatest common divisor between two integers a and b. 8 | d) Compute the first prime number greater than a given integer n. 9 | e) Print the first k prime numbers greater than a given integer n. 10 | 11 | 12 | """ 13 | from math import sqrt 14 | 15 | 16 | def sum_of_first_n_natural_numbers(n): 17 | """ Computes the sum of the first n natural numbers. 18 | 19 | Given n, a natural number, the function return the sum of the first n natural numbers. 20 | n: natural number 21 | Returns: the sum of the first n natural numbers 22 | """ 23 | s = 0 24 | for i in range(n): 25 | s += i 26 | 27 | return s 28 | 29 | 30 | def is_prime(n): 31 | # todo: docs 32 | if n == 2: 33 | return True 34 | if n < 2 or n % 2 == 0: 35 | return False 36 | for i in range(3, int(sqrt(n)) + 1, 2): 37 | if n % i == 0: 38 | return False 39 | return True 40 | 41 | 42 | def gcd(a, b): 43 | while b != 0: 44 | a, b = b, a % b 45 | return a if a > 0 else -a 46 | 47 | 48 | def next_prime(n): 49 | while True: 50 | n = n + 1 51 | if is_prime(n): 52 | return n 53 | 54 | 55 | if __name__ == '__main__': 56 | print("hello") 57 | print(sum_of_first_n_natural_numbers(3)) 58 | print(is_prime(49)) 59 | print(gcd(12, -18)) 60 | print(next_prime(17)) 61 | print("bye") 62 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_06_09/domain/rental.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | 3 | 4 | class Rental: 5 | def __init__(self, rental_id, start, end, client, car): 6 | self._rentalId = rental_id 7 | self._client = client 8 | self._car = car 9 | self._start = start 10 | self._end = end 11 | 12 | @property 13 | def id(self): 14 | return self._rentalId 15 | 16 | @property 17 | def client(self): 18 | return self._client 19 | 20 | @client.setter 21 | def client(self, client): 22 | self._client = client 23 | 24 | @property 25 | def car(self): 26 | return self._car 27 | 28 | @car.setter 29 | def car(self, car): 30 | self._car = car 31 | 32 | @property 33 | def start(self): 34 | return self._start 35 | 36 | @start.setter 37 | def start(self, start): 38 | self._start = start 39 | 40 | @property 41 | def end(self): 42 | return self._end 43 | 44 | @end.setter 45 | def end(self, end): 46 | self._end = end 47 | 48 | # len(rental) 49 | def __len__(self): 50 | if self._end is not None: 51 | return (self._end - self._start).days + 1 52 | today = date.today() 53 | return (today - self._start).days + 1 54 | 55 | def __repr__(self): 56 | return str(self) 57 | 58 | def __str__(self): 59 | return "Rental: " + str(self.id) + "\nCar: " + str(self.car) + "\nClient: " + str( 60 | self.client) + "\nPeriod: " + self._start.strftime("%Y-%m-%d") + " to " + self._end.strftime("%Y-%m-%d") 61 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_06_09/domain/rental.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | 3 | 4 | class Rental: 5 | def __init__(self, rental_id, start, end, client, car): 6 | self._rentalId = rental_id 7 | self._client = client 8 | self._car = car 9 | self._start = start 10 | self._end = end 11 | 12 | @property 13 | def id(self): 14 | return self._rentalId 15 | 16 | @property 17 | def client(self): 18 | return self._client 19 | 20 | @client.setter 21 | def client(self, client): 22 | self._client = client 23 | 24 | @property 25 | def car(self): 26 | return self._car 27 | 28 | @car.setter 29 | def car(self, car): 30 | self._car = car 31 | 32 | @property 33 | def start(self): 34 | return self._start 35 | 36 | @start.setter 37 | def start(self, start): 38 | self._start = start 39 | 40 | @property 41 | def end(self): 42 | return self._end 43 | 44 | @end.setter 45 | def end(self, end): 46 | self._end = end 47 | 48 | # len(rental) 49 | def __len__(self): 50 | if self._end is not None: 51 | return (self._end - self._start).days + 1 52 | today = date.today() 53 | return (today - self._start).days + 1 54 | 55 | def __repr__(self): 56 | return str(self) 57 | 58 | def __str__(self): 59 | return "Rental: " + str(self.id) + "\nCar: " + str(self.car) + "\nClient: " + str( 60 | self.client) + "\nPeriod: " + self._start.strftime("%Y-%m-%d") + " to " + self._end.strftime("%Y-%m-%d") 61 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_06_09/domain/rental.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | 3 | 4 | class Rental: 5 | def __init__(self, rental_id, start, end, client, car): 6 | self._rentalId = rental_id 7 | self._client = client 8 | self._car = car 9 | self._start = start 10 | self._end = end 11 | 12 | @property 13 | def id(self): 14 | return self._rentalId 15 | 16 | @property 17 | def client(self): 18 | return self._client 19 | 20 | @client.setter 21 | def client(self, client): 22 | self._client = client 23 | 24 | @property 25 | def car(self): 26 | return self._car 27 | 28 | @car.setter 29 | def car(self, car): 30 | self._car = car 31 | 32 | @property 33 | def start(self): 34 | return self._start 35 | 36 | @start.setter 37 | def start(self, start): 38 | self._start = start 39 | 40 | @property 41 | def end(self): 42 | return self._end 43 | 44 | @end.setter 45 | def end(self, end): 46 | self._end = end 47 | 48 | # len(rental) 49 | def __len__(self): 50 | if self._end is not None: 51 | return (self._end - self._start).days + 1 52 | today = date.today() 53 | return (today - self._start).days + 1 54 | 55 | def __repr__(self): 56 | return str(self) 57 | 58 | def __str__(self): 59 | return "Rental: " + str(self.id) + "\nCar: " + str(self.car) + "\nClient: " + str( 60 | self.client) + "\nPeriod: " + self._start.strftime("%Y-%m-%d") + " to " + self._end.strftime("%Y-%m-%d") 61 | -------------------------------------------------------------------------------- /src/lecture/examples/ex18_TestDrivenDevelopment1.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Sep 30, 2016 3 | 4 | @author: Arthur 5 | """ 6 | 7 | ''' 8 | 1. Write a test function 9 | ''' 10 | 11 | 12 | def test_gcd(): 13 | assert gcd(0, 2) == 2 14 | assert gcd(2, 0) == 2 15 | assert gcd(1, 2) == 1 16 | assert gcd(2, 1) == 1 17 | assert gcd(6, 2) == 2 18 | assert gcd(6, 3) == 3 19 | assert gcd(21, 2) == 1 20 | assert gcd(2, 21) == 1 21 | assert gcd(210, 15) == 15 22 | assert gcd(15, 210) == 15 23 | 24 | 25 | ''' 26 | Write a first version of the function 27 | ''' 28 | 29 | 30 | def gcd(a, b): 31 | """ 32 | Calculates the GCD of a and b 33 | a,b - input integers, a,b >= 0 34 | Returns the GCD of positive integers a and b 35 | """ 36 | pass 37 | 38 | 39 | ''' 40 | 2. Run the test function. 41 | 42 | NB! 43 | If it passes, you've done something wrong :-) 44 | ''' 45 | test_gcd() 46 | 47 | ''' 48 | 3. Write the gcd function according to its specification 49 | ''' 50 | # def gcd(a, b): 51 | # ''' 52 | # Calculates the GCD of a and b 53 | # a,b - input integers, a,b >= 0 54 | # Returns the GCD of positive integers a and b 55 | # ''' 56 | # if a == 0: 57 | # return b 58 | # if b == 0: 59 | # return a 60 | # while a != b: 61 | # if a > b: 62 | # a -= b 63 | # else: 64 | # b -= a 65 | # return a 66 | 67 | ''' 68 | 4. Run the test(s) again 69 | 70 | NB! 71 | If they fail, you've done something wrong :-< 72 | ''' 73 | # test_gcd() 74 | 75 | 76 | ''' 77 | 5. Refactor / optimize the function 78 | ''' 79 | -------------------------------------------------------------------------------- /src/lecture/examples/ex36_longestIncreasingSubsequence.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Jan 11, 2017 3 | 4 | @author: Arthur 5 | """ 6 | 7 | 8 | def longest_increasing_subsequence(A): 9 | """ 10 | Maximum length of subsequence recorded so far, as well as its end index 11 | """ 12 | max_length = 1 13 | best_end = 0 14 | 15 | indices_array = [1] 16 | previous_indices = [-1] 17 | 18 | for i in range(1, len(A)): 19 | ''' 20 | The maximum length of the increasing subsequence ending at index i 21 | ''' 22 | indices_array.append(1) 23 | previous_indices.append(-1) 24 | 25 | ''' 26 | The maximum length is increased by 1 if 'j' exists, so that: 27 | A[j] < A[i] and the length of the subsequence would increase 28 | ''' 29 | for j in range(i - 1, -1, -1): 30 | if (indices_array[j] + 1 > indices_array[i]) and (A[j] < A[i]): 31 | indices_array[i] = indices_array[j] + 1 32 | previous_indices[i] = j 33 | 34 | ''' 35 | Record the end index in the same go 36 | ''' 37 | if indices_array[i] > max_length: 38 | best_end = i 39 | max_length = indices_array[i] 40 | 41 | ''' 42 | Build the solution using the previous_indices list 43 | ''' 44 | solution = [A[best_end]] 45 | while previous_indices[best_end] != -1: 46 | solution.append(A[previous_indices[best_end]]) 47 | best_end = previous_indices[best_end] 48 | 49 | solution.reverse() 50 | return solution 51 | 52 | 53 | A = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15] 54 | print(longest_increasing_subsequence(A)) 55 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_09/domain/Client.py: -------------------------------------------------------------------------------- 1 | class Client: 2 | def __init__(self, clientId, cnp, name): 3 | self._id = clientId 4 | self._cnp = cnp 5 | self._name = name 6 | 7 | @property 8 | def id(self): 9 | return self._id 10 | 11 | @property 12 | def cnp(self): 13 | return self._cnp 14 | 15 | @property 16 | def name(self): 17 | return self._name 18 | 19 | def __eq__(self, z): 20 | if isinstance(z, Client) == False: 21 | return False 22 | return self.id == z.id 23 | 24 | def __str__(self): 25 | return "Id=" + str(self.id) + ", Name=" + str(self.name) 26 | 27 | def __repr__(self): 28 | return str(self) 29 | 30 | class ClientValidator: 31 | def _isCNPValid(self, cnp): 32 | # SAALLZZJJNNNC 33 | if len(cnp) != 13: 34 | # This is not x full CNP validation 35 | return False 36 | for x in cnp: 37 | if x < '0' or x > '9': 38 | return False 39 | return True 40 | 41 | def validate(self, client): 42 | """ 43 | Validate if provided Client instance is valid 44 | client - Instance of Client type 45 | Return List of validation errors. An empty list if instance is valid. 46 | """ 47 | if isinstance(client, Client) == False: 48 | raise TypeError("Not x Client") 49 | _errors = [] 50 | if self._isCNPValid(client.cnp) == False: 51 | _errors.append("CNP not valid.;") 52 | if len(client.name) == 0: 53 | _errors.append("Name not valid.") 54 | if len(_errors) != 0: 55 | raise ValueError(_errors) -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_09/domain/Rental.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | 3 | from seminar.group_911.seminar_09.domain.ValidatorException import ValidatorException 4 | 5 | 6 | class Rental: 7 | def __init__(self, rentalId, start, end, client, car): 8 | self._id = rentalId 9 | self._client = client 10 | self._car = car 11 | self._start = start 12 | self._end = end 13 | 14 | @property 15 | def id(self): 16 | return self._id 17 | 18 | @property 19 | def client(self): 20 | return self._client 21 | 22 | @property 23 | def car(self): 24 | return self._car 25 | 26 | @property 27 | def start(self): 28 | return self._start 29 | 30 | @property 31 | def end(self): 32 | return self._end 33 | 34 | def __len__(self): 35 | return (self._end - self._start).days + 1 36 | 37 | def __repr__(self): 38 | return str(self) 39 | 40 | def __str__(self): 41 | return "Rental: " + str(self.id) + "\nCar: " + str(self.car) + "\nClient: " + str( 42 | self.client) + "\nPeriod: " + self.start.strftime("%Y-%m-%d") + " to " + self.end.strftime("%Y-%m-%d") 43 | 44 | 45 | class RentalValidator: 46 | 47 | def validate(self, rental): 48 | if isinstance(rental, Rental) == False: 49 | raise TypeError("Not a Rental") 50 | _errorList = [] 51 | now = date(2000, 1, 1) 52 | if rental.start < now: 53 | _errorList.append("Rental starts in past;") 54 | if len(rental) < 1: 55 | _errorList.append("Rental must be at least 1 day;") 56 | if len(_errorList) > 0: 57 | raise ValidatorException(_errorList) 58 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_09/domain/Client.py: -------------------------------------------------------------------------------- 1 | class Client: 2 | def __init__(self, clientId, cnp, name): 3 | self._id = clientId 4 | self._cnp = cnp 5 | self._name = name 6 | 7 | @property 8 | def id(self): 9 | return self._id 10 | 11 | @property 12 | def cnp(self): 13 | return self._cnp 14 | 15 | @property 16 | def name(self): 17 | return self._name 18 | 19 | def __eq__(self, z): 20 | if isinstance(z, Client) == False: 21 | return False 22 | return self.id == z.id 23 | 24 | def __str__(self): 25 | return "Id=" + str(self.id) + ", Name=" + str(self.name) 26 | 27 | def __repr__(self): 28 | return str(self) 29 | 30 | class ClientValidator: 31 | def _isCNPValid(self, cnp): 32 | # SAALLZZJJNNNC 33 | if len(cnp) != 13: 34 | # This is not x full CNP validation 35 | return False 36 | for x in cnp: 37 | if x < '0' or x > '9': 38 | return False 39 | return True 40 | 41 | def validate(self, client): 42 | """ 43 | Validate if provided Client instance is valid 44 | client - Instance of Client type 45 | Return List of validation errors. An empty list if instance is valid. 46 | """ 47 | if isinstance(client, Client) == False: 48 | raise TypeError("Not x Client") 49 | _errors = [] 50 | if self._isCNPValid(client.cnp) == False: 51 | _errors.append("CNP not valid.;") 52 | if len(client.name) == 0: 53 | _errors.append("Name not valid.") 54 | if len(_errors) != 0: 55 | raise ValueError(_errors) -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_09/domain/Rental.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | 3 | from seminar.group_912.seminar_09.domain.ValidatorException import ValidatorException 4 | 5 | 6 | class Rental: 7 | def __init__(self, rentalId, start, end, client, car): 8 | self._id = rentalId 9 | self._client = client 10 | self._car = car 11 | self._start = start 12 | self._end = end 13 | 14 | @property 15 | def id(self): 16 | return self._id 17 | 18 | @property 19 | def client(self): 20 | return self._client 21 | 22 | @property 23 | def car(self): 24 | return self._car 25 | 26 | @property 27 | def start(self): 28 | return self._start 29 | 30 | @property 31 | def end(self): 32 | return self._end 33 | 34 | def __len__(self): 35 | return (self._end - self._start).days + 1 36 | 37 | def __repr__(self): 38 | return str(self) 39 | 40 | def __str__(self): 41 | return "Rental: " + str(self.id) + "\nCar: " + str(self.car) + "\nClient: " + str( 42 | self.client) + "\nPeriod: " + self.start.strftime("%Y-%m-%d") + " to " + self.end.strftime("%Y-%m-%d") 43 | 44 | 45 | class RentalValidator: 46 | 47 | def validate(self, rental): 48 | if isinstance(rental, Rental) == False: 49 | raise TypeError("Not a Rental") 50 | _errorList = [] 51 | now = date(2000, 1, 1) 52 | if rental.start < now: 53 | _errorList.append("Rental starts in past;") 54 | if len(rental) < 1: 55 | _errorList.append("Rental must be at least 1 day;") 56 | if len(_errorList) > 0: 57 | raise ValidatorException(_errorList) 58 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_09/domain/Client.py: -------------------------------------------------------------------------------- 1 | class Client: 2 | def __init__(self, clientId, cnp, name): 3 | self._id = clientId 4 | self._cnp = cnp 5 | self._name = name 6 | 7 | @property 8 | def id(self): 9 | return self._id 10 | 11 | @property 12 | def cnp(self): 13 | return self._cnp 14 | 15 | @property 16 | def name(self): 17 | return self._name 18 | 19 | def __eq__(self, z): 20 | if isinstance(z, Client) == False: 21 | return False 22 | return self.id == z.id 23 | 24 | def __str__(self): 25 | return "Id=" + str(self.id) + ", Name=" + str(self.name) 26 | 27 | def __repr__(self): 28 | return str(self) 29 | 30 | class ClientValidator: 31 | def _isCNPValid(self, cnp): 32 | # SAALLZZJJNNNC 33 | if len(cnp) != 13: 34 | # This is not x full CNP validation 35 | return False 36 | for x in cnp: 37 | if x < '0' or x > '9': 38 | return False 39 | return True 40 | 41 | def validate(self, client): 42 | """ 43 | Validate if provided Client instance is valid 44 | client - Instance of Client type 45 | Return List of validation errors. An empty list if instance is valid. 46 | """ 47 | if isinstance(client, Client) == False: 48 | raise TypeError("Not x Client") 49 | _errors = [] 50 | if self._isCNPValid(client.cnp) == False: 51 | _errors.append("CNP not valid.;") 52 | if len(client.name) == 0: 53 | _errors.append("Name not valid.") 54 | if len(_errors) != 0: 55 | raise ValueError(_errors) -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_09/domain/Rental.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | 3 | from seminar.group_917.seminar_09.domain.ValidatorException import ValidatorException 4 | 5 | 6 | class Rental: 7 | def __init__(self, rentalId, start, end, client, car): 8 | self._id = rentalId 9 | self._client = client 10 | self._car = car 11 | self._start = start 12 | self._end = end 13 | 14 | @property 15 | def id(self): 16 | return self._id 17 | 18 | @property 19 | def client(self): 20 | return self._client 21 | 22 | @property 23 | def car(self): 24 | return self._car 25 | 26 | @property 27 | def start(self): 28 | return self._start 29 | 30 | @property 31 | def end(self): 32 | return self._end 33 | 34 | def __len__(self): 35 | return (self._end - self._start).days + 1 36 | 37 | def __repr__(self): 38 | return str(self) 39 | 40 | def __str__(self): 41 | return "Rental: " + str(self.id) + "\nCar: " + str(self.car) + "\nClient: " + str( 42 | self.client) + "\nPeriod: " + self.start.strftime("%Y-%m-%d") + " to " + self.end.strftime("%Y-%m-%d") 43 | 44 | 45 | class RentalValidator: 46 | 47 | def validate(self, rental): 48 | if isinstance(rental, Rental) == False: 49 | raise TypeError("Not a Rental") 50 | _errorList = [] 51 | now = date(2000, 1, 1) 52 | if rental.start < now: 53 | _errorList.append("Rental starts in past;") 54 | if len(rental) < 1: 55 | _errorList.append("Rental must be at least 1 day;") 56 | if len(_errorList) > 0: 57 | raise ValidatorException(_errorList) 58 | -------------------------------------------------------------------------------- /src/lecture/examples/ex16_BlackBoxWhiteBox.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Nov 14, 2016 3 | 4 | @author: Arthur 5 | """ 6 | 7 | """ 8 | A function that we want tested 9 | """ 10 | 11 | 12 | def is_prime(nr): 13 | """ 14 | Verify if a number is prime 15 | return True if nr is prime, False otherwise 16 | raise ValueError if nr <= 0 17 | """ 18 | if nr <= 0: 19 | raise ValueError("nr needs to be positive") 20 | if nr == 1: 21 | return False 22 | if nr <= 3: 23 | return True 24 | for i in range(2, nr): 25 | if nr % i == 0: 26 | return False 27 | return True 28 | 29 | 30 | """ 31 | Black-box testing assumes we only have its specification 32 | """ 33 | 34 | 35 | def test_is_prime_black_box(): 36 | for i in range(-100, 1): 37 | try: 38 | is_prime(i) 39 | assert False 40 | except ValueError: 41 | pass 42 | 43 | primes = [2, 3, 5, 7, 11, 13, 17, 19] 44 | for i in range(2, 20): 45 | assert is_prime(i) == (i in primes), "this is the value where it fails: " + str(i) 46 | 47 | 48 | """ 49 | White-box testing - we can see the source code, so we only write the required test cases 50 | """ 51 | 52 | 53 | def test_is_prime_white_box(): 54 | try: 55 | is_prime(-5) 56 | assert False 57 | except ValueError: 58 | pass 59 | 60 | assert is_prime(1) is False, 1 61 | assert is_prime(2) is True, 2 62 | assert is_prime(3) is True, 3 63 | assert is_prime(6) is False, 4 64 | assert is_prime(7) is True, 7 65 | assert is_prime(8) is False, 8 66 | 67 | 68 | """ 69 | Let's run the tests - they should work regardless 70 | """ 71 | test_is_prime_black_box() 72 | test_is_prime_white_box() 73 | -------------------------------------------------------------------------------- /src/lecture/examples/ex22_pickleFiles.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Nov 22, 2016 3 | 4 | @author: Arthur 5 | """ 6 | import pickle 7 | 8 | 9 | class Person: 10 | def __init__(self, person_id, family_name, given_name): 11 | self._personId = person_id 12 | self._familyName = family_name 13 | self._givenName = given_name 14 | 15 | @property 16 | def id(self): 17 | return self._personId 18 | 19 | @property 20 | def family_name(self): 21 | return self._familyName 22 | 23 | @property 24 | def given_name(self): 25 | return self._givenName 26 | 27 | def __str__(self): 28 | return str(self._personId) + " - " + self._familyName + " " + self._givenName 29 | 30 | 31 | def write_binary_file(file_name, persons): 32 | f = open(file_name, "wb") 33 | pickle.dump(persons, f) 34 | f.close() 35 | 36 | 37 | def read_binary_file(file_name): 38 | result = [] 39 | try: 40 | f = open(file_name, "rb") 41 | return pickle.load(f) 42 | except EOFError: 43 | """ 44 | This is raised if input file is empty 45 | """ 46 | return [] 47 | except IOError as e: 48 | """ 49 | Here we 'log' the error, and throw it to the outer layers 50 | """ 51 | print("An error occured - " + str(e)) 52 | raise e 53 | 54 | return result 55 | 56 | 57 | """ 58 | Initialize a list of objects 59 | """ 60 | persons = [Person(1, "Pop", "Anca"), Person(2, "Morariu", "Sergiu"), Person(3, "Moldovean", "Iuliu")] 61 | 62 | """ 63 | Write it to a text file 64 | """ 65 | write_binary_file("persons.pickle", persons) 66 | 67 | """ 68 | Read it back and see what we have 69 | """ 70 | for p in read_binary_file("persons.pickle"): 71 | print(p) 72 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_04/game.py: -------------------------------------------------------------------------------- 1 | """ 2 | Functions for the Tic Tac Toe game go here 3 | These functions can call functions from board 4 | There is no UI ! (communicate with params / exceptions)No UI 5 | """ 6 | from board import get_board_pos 7 | from random import shuffle 8 | 9 | 10 | def move_computer(board): 11 | """ 12 | Alternate computer strategies (read strategy from a file ??) 13 | 14 | Strategy design pattern - https://en.wikipedia.org/wiki/Strategy_pattern 15 | 16 | :param board: 17 | :return: 18 | """ 19 | # return move_computer_first_position(board) 20 | return move_computer_random_position(board) 21 | # move_computer_prevent_human_win(board) 22 | 23 | 24 | def move_computer_first_position(board): 25 | """ 26 | The computer moves in the first square it finds available 27 | :param board: The game board 28 | :return: (x,y) of computer move 29 | """ 30 | for row in range(3): 31 | for col in range(3): 32 | if get_board_pos(board, row, col) == 0: 33 | return row, col 34 | raise ValueError("No moves available") 35 | 36 | 37 | def move_computer_random_position(board): 38 | """ 39 | The computer moves in a random, but valid square. 40 | :param board: 41 | :return: 42 | """ 43 | # TODO Computer wins if possible 44 | choices_choices = [] 45 | for row in range(3): 46 | for col in range(3): 47 | if get_board_pos(board, row, col) == 0: 48 | choices_choices.append((row, col)) 49 | shuffle(choices_choices) 50 | return choices_choices[0] 51 | 52 | 53 | def move_computer_prevent_human_win(board): 54 | """ 55 | The computer moves to prevent the human winning on the next move 56 | :param board: 57 | :return: 58 | """ 59 | pass 60 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_09/service/UndoService.py: -------------------------------------------------------------------------------- 1 | class UndoService: 2 | """ 3 | 1. Command design pattern 4 | -> tell the computer what to do (call a method), but not to do it now, but sometime later 5 | (store the command and call it when it's needed) 6 | 7 | 2. Memento design pattern 8 | -> Keep a copy of the program's (entity's etc.) previous state(s) and restore to it when needed 9 | """ 10 | 11 | def __init__(self): 12 | # History of program operations 13 | self._history = [] 14 | # Where are we in the operation history 15 | self._index = -1 16 | 17 | def undo(self): 18 | pass 19 | 20 | def redo(self): 21 | pass 22 | 23 | def record(self, operation): 24 | """ 25 | Record operation for undo/redo 26 | :param operation: 27 | :return: 28 | """ 29 | pass 30 | 31 | 32 | class Operation: 33 | def __init__(self, undo_call, redo_call): 34 | self._undo_call = undo_call 35 | self._redo_call = redo_call 36 | 37 | def undo(self): 38 | self._undo_call.call() 39 | 40 | def redo(self): 41 | self._redo_call.call() 42 | 43 | 44 | class ComplexOperation: 45 | def __init__(self, *operation): 46 | self._operations = operation 47 | 48 | def undo(self): 49 | for operation in self._operations: 50 | operation.undo() 51 | 52 | def redo(self): 53 | for operation in self._operations: 54 | operation.redo() 55 | 56 | 57 | class Call: 58 | def __init__(self, function_name, *function_params): 59 | self._function_name = function_name 60 | self._function_params = function_params 61 | 62 | def call(self): 63 | # TODO Unpack parameters? 64 | self._function_name(self._function_params) 65 | -------------------------------------------------------------------------------- /src/lecture/examples/ex24_gui/domain/entities.py: -------------------------------------------------------------------------------- 1 | class Address: 2 | """ 3 | Represent an address 4 | """ 5 | 6 | def __init__(self, street, nr, city): 7 | self._street = street 8 | self._nr = nr 9 | self._city = city 10 | 11 | @property 12 | def street(self): 13 | return self._street 14 | 15 | @property 16 | def number(self): 17 | return self._nr 18 | 19 | @property 20 | def city(self): 21 | return self._city 22 | 23 | def __str__(self): 24 | """ 25 | Give a string representation for the address 26 | return string 27 | """ 28 | return self._street + " nr." + self._nr + " " + self._city 29 | 30 | 31 | class Student: 32 | """ 33 | Represent a student 34 | """ 35 | 36 | def __init__(self, id, name, adr): 37 | """ 38 | Create a new student 39 | id, name String 40 | address - Address 41 | """ 42 | self.__id = id 43 | self.__name = name 44 | self.__adr = adr 45 | 46 | @property 47 | def id(self): 48 | return self.__id 49 | 50 | @property 51 | def name(self): 52 | return self.__name 53 | 54 | @property 55 | def address(self): 56 | return self.__adr 57 | 58 | def __str__(self): 59 | """ 60 | Give a string representation for the student 61 | return string 62 | """ 63 | return self.__id + " " + self.__name + " " + str(self.__adr) 64 | 65 | def __eq__(self, ot): 66 | """ 67 | Define equal for students 68 | ot - student 69 | return True if ot and the current instance represent the same student 70 | """ 71 | if isinstance(ot, Student) is False: 72 | return False 73 | return self.__id == ot.__id 74 | -------------------------------------------------------------------------------- /src/lecture/examples/ex10_modular_calc/ui/console.py: -------------------------------------------------------------------------------- 1 | """ 2 | The user interface of the calculator 3 | Contains functions related to the user interaction (console) 4 | """ 5 | from src.lecture.examples.ex10_modular_calc.domain.calculator import \ 6 | calculator_add, undo, get_calculator_total, get_undo_list, set_calculator_total, reset_calc 7 | from src.lecture.examples.ex10_modular_calc.domain.rational import create_rational 8 | 9 | 10 | def print_menu(): 11 | """ 12 | Print out the main menu of the calculator 13 | """ 14 | print("Calculator menu:") 15 | print(" + for adding a rational number") 16 | print(" c to clear the calculator") 17 | print(" u to undo the last operation") 18 | print(" x to close the calculator") 19 | 20 | 21 | def print_current(calc): 22 | """ 23 | Print the current total 24 | """ 25 | print("Total:", get_calculator_total(calc)) 26 | 27 | 28 | def run(): 29 | """ 30 | Implement the user interface 31 | """ 32 | calc = reset_calc() 33 | finish = False 34 | print_current(calc) 35 | while not finish: 36 | print_menu() 37 | m = input().strip() 38 | if m == 'x': 39 | finish = True 40 | elif m == '+': 41 | m = input("Give numerator:") 42 | n = input("Give denominator:") 43 | try: 44 | calculator_add(calc, create_rational(int(m), int(n))) 45 | print_current(calc) 46 | except ValueError: 47 | print("Enter integers for m, n, with not null n") 48 | elif m == 'c': 49 | calc = reset_calc() 50 | print_current(calc) 51 | elif m == 'u': 52 | try: 53 | undo(calc) 54 | print_current(calc) 55 | except ValueError as ve: 56 | print(ve) 57 | else: 58 | print("Invalid command") 59 | -------------------------------------------------------------------------------- /src/lecture/examples/ex39_eggDroppingPuzzle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Jan 11, 2017 3 | 4 | @author: Arthur 5 | """ 6 | import math 7 | 8 | ''' 9 | Function to get minimum number of trails needed in worst # case with n eggs and k floors 10 | 11 | input: 12 | n - Number of eggs remaining 13 | k - Number of floors 14 | 15 | output: 16 | The number of minimum drops, if following optimal solution 17 | 18 | credit - This code is contributed by Bhavya Jain 19 | http://www.geeksforgeeks.org/dynamic-programming-set-11-egg-dropping-puzzle/ 20 | ''' 21 | 22 | 23 | def egg_drop(n, k): 24 | """ 25 | A 2D table where every egg_floor[i][j] will represent minimum 26 | number of trials needed for i eggs and j floors. 27 | """ 28 | egg_floor = [[0 for x in range(k + 1)] for x in range(n + 1)] 29 | 30 | ''' 31 | We need one trial for one floor and0 trials for 0 floors 32 | ''' 33 | for i in range(1, n + 1): 34 | egg_floor[i][1] = 1 35 | egg_floor[i][0] = 0 36 | 37 | ''' 38 | We always need j trials for one egg and j floors. 39 | ''' 40 | for j in range(1, k + 1): 41 | egg_floor[1][j] = j 42 | 43 | ''' 44 | Fill rest of the entries in table using optimal substructure property 45 | ''' 46 | for i in range(2, n + 1): 47 | for j in range(2, k + 1): 48 | egg_floor[i][j] = math.inf 49 | for x in range(1, j + 1): 50 | res = 1 + max(egg_floor[i - 1][x - 1], egg_floor[i][j - x]) 51 | if res < egg_floor[i][j]: 52 | egg_floor[i][j] = res 53 | 54 | ''' 55 | eggFloor[n][k] holds the result 56 | ''' 57 | return egg_floor[n][k] 58 | 59 | 60 | def test_egg_drop(): 61 | n = 2 62 | k = 100 63 | print("Minimum number of drops in the worst case with " + str(n) + " eggs and " + str(k) + " floors is " + str( 64 | egg_drop(n, k))) 65 | 66 | 67 | test_egg_drop() 68 | -------------------------------------------------------------------------------- /src/lecture/examples/ex04_VariableScope.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Sep 29, 2016 3 | 4 | @author: http://www.python-course.eu/global_vs_local_variables.php 5 | """ 6 | 7 | """ 8 | NB! 9 | Uncomment each of the sections separated by ### below, 10 | one at a time and run them 11 | """ 12 | 13 | 14 | # def f(): 15 | # print(s) 16 | # 17 | # 18 | # s = 'I hate spam' 19 | # f() 20 | 21 | ############################# 22 | 23 | # def f(): 24 | # # PyCharm complains that 's' shadows the name from the outer scope 25 | # # Of course it does, that's the whole point :) 26 | # s = "Me too." 27 | # print(s) 28 | # 29 | # 30 | # s = "I hate spam." 31 | # f() 32 | # print(s) 33 | 34 | ############################# 35 | 36 | # def f(): 37 | # """ 38 | # Variables created or changed inside functions 39 | # are local, unless declared global 40 | # """ 41 | # print(s) 42 | # s = "Me too." 43 | # print(s) 44 | # 45 | # 46 | # s = "I hate spam." 47 | # f() 48 | # print(s) 49 | 50 | ############################# 51 | 52 | # def f(): 53 | # global s 54 | # print(s) 55 | # s = "That's clear." 56 | # print(s) 57 | # 58 | # 59 | # s = "Python is great again!" 60 | # f() 61 | # print(s) 62 | 63 | ############################# 64 | 65 | # def f(): 66 | # s = "I am globally not known" 67 | # print(s) 68 | # 69 | # 70 | # f() 71 | # print(s) 72 | 73 | ############################# 74 | """ 75 | Exercise: 76 | What happens in the example below? 77 | """ 78 | # def foo(x, y): 79 | # global a 80 | # a = 42 81 | # x,y = y,x 82 | # b = 33 83 | # b = 17 84 | # c = 100 85 | # print(a,b,x,y) 86 | # ''' 87 | # NB! 88 | # Learn to use the locals() and globals() functions to figure out what's what 89 | # 90 | # print(locals()) 91 | # print(globals()) 92 | # ''' 93 | # 94 | # a,b,x,y = 1,15,3,4 95 | # foo(17,4) 96 | # print(a,b,x,y) 97 | -------------------------------------------------------------------------------- /src/lecture/examples/ex38_01knapsack.py: -------------------------------------------------------------------------------- 1 | # 2 | # 0-1 Knapsack problem 3 | # 4 | 5 | W = 10 6 | values_data = [5, 3, 10, 4, 2] 7 | weights_data = [2, 3, 4, 3, 6] 8 | 9 | 10 | # 11 | # Version 1 - non dynamic programming 12 | # 13 | def knapsack(W, values, weights, index): 14 | # Basic case - no more room or we've gone through all items 15 | if W == 0 or index < 0: 16 | return 0 17 | 18 | # Item we are currently does not fit in knapsack 19 | if weights[index] > W: 20 | return knapsack(W, values, weights, index - 1) 21 | else: 22 | # Maximum between the decision of including it or not 23 | return max(values[index] + knapsack(W - weights[index], values, weights, index - 1), 24 | knapsack(W, values, weights, index - 1)) 25 | 26 | 27 | # 28 | # Version 2 - dynamic programming 29 | # 30 | 31 | # Pretty-print auxiliary table, this should help follow the algorithm's steps 32 | from texttable import Texttable 33 | 34 | 35 | def pretty_print(v): 36 | t = Texttable() 37 | t.header(['X'] + list(range(W + 1))) 38 | for i in range(len(v)): 39 | t.add_row([i] + v[i]) 40 | print(t.draw()) 41 | 42 | 43 | def knapsack_dp(W, values, weights): 44 | V = [[0 for x in range(W + 1)] for x in range(len(values) + 1)] 45 | 46 | # Go over every item 47 | for i in range(len(values) + 1): 48 | # Go over every possible weight 49 | for j in range(W + 1): 50 | if i == 0 or j == 0: 51 | V[i][j] = 0 52 | elif weights[i - 1] > j: 53 | # Current item does not fit, do not include it 54 | V[i][j] = V[i - 1][j] 55 | else: 56 | # Maximum between skipping the item and including it 57 | V[i][j] = max(V[i - 1][j], values[i - 1] + V[i - 1][j - weights[i - 1]]) 58 | pretty_print(V) 59 | return V[len(values)][W] 60 | 61 | 62 | print(knapsack_dp(W, values_data, weights_data)) 63 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_06_09/domain/car_validators.py: -------------------------------------------------------------------------------- 1 | from seminar.group_911.seminar_06_09.domain.exceptions import CarValidationException 2 | 3 | 4 | class CarValidatorES: 5 | @staticmethod 6 | def _is_license_valid(self, license_): 7 | # TODO Implement full validation 8 | """ 9 | Implement Spanish license plate validation 10 | @param license_: 11 | @return: ... 12 | """ 13 | return len(license_) > 2 14 | 15 | # FIXME Duplicated code across validators, use inheritance to remove it 16 | def validate(self, car): 17 | errors = [] 18 | # V1 - All properties are non-empty 19 | if not self._is_license_valid(car.license_plate): 20 | errors.append('Invalid license plate') 21 | if len(car.make) < 3: 22 | errors.append('Car make should have at least 3 letters') 23 | if len(car.model) < 3: 24 | errors.append('Car model should have at least 3 letters') 25 | 26 | if len(errors) > 0: 27 | raise CarValidationException(errors) 28 | 29 | 30 | class CarValidatorRO: 31 | @staticmethod 32 | def _is_license_valid(self, license): 33 | # TODO Implement full validation 34 | """ 35 | Implement Romanian license plate validation 36 | @param license: 37 | @return: ... 38 | """ 39 | return len(license) > 2 40 | 41 | # FIXME Duplicated code across validators, use inheritance to remove it 42 | def validate(self, car): 43 | errors = [] 44 | # V1 - All properties are non-empty 45 | if not self._is_license_valid(car.license_plate): 46 | errors.append('Invalid license plate') 47 | if len(car.make) < 2: 48 | errors.append('Car make should have at least 3 letters') 49 | if len(car.model) < 2: 50 | errors.append('Car model should have at least 3 letters') 51 | 52 | if len(errors) > 0: 53 | raise CarValidationException(errors) 54 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_06_09/domain/car_validators.py: -------------------------------------------------------------------------------- 1 | from seminar.group_912.seminar_06_09.domain.exceptions import CarValidationException 2 | 3 | 4 | class CarValidatorES: 5 | @staticmethod 6 | def _is_license_valid(self, license_): 7 | # TODO Implement full validation 8 | """ 9 | Implement Spanish license plate validation 10 | @param license_: 11 | @return: ... 12 | """ 13 | return len(license_) > 2 14 | 15 | # FIXME Duplicated code across validators, use inheritance to remove it 16 | def validate(self, car): 17 | errors = [] 18 | # V1 - All properties are non-empty 19 | if not self._is_license_valid(car.license_plate): 20 | errors.append('Invalid license plate') 21 | if len(car.make) < 3: 22 | errors.append('Car make should have at least 3 letters') 23 | if len(car.model) < 3: 24 | errors.append('Car model should have at least 3 letters') 25 | 26 | if len(errors) > 0: 27 | raise CarValidationException(errors) 28 | 29 | 30 | class CarValidatorRO: 31 | @staticmethod 32 | def _is_license_valid(self, license): 33 | # TODO Implement full validation 34 | """ 35 | Implement Romanian license plate validation 36 | @param license: 37 | @return: ... 38 | """ 39 | return len(license) > 2 40 | 41 | # FIXME Duplicated code across validators, use inheritance to remove it 42 | def validate(self, car): 43 | errors = [] 44 | # V1 - All properties are non-empty 45 | if not self._is_license_valid(car.license_plate): 46 | errors.append('Invalid license plate') 47 | if len(car.make) < 2: 48 | errors.append('Car make should have at least 3 letters') 49 | if len(car.model) < 2: 50 | errors.append('Car model should have at least 3 letters') 51 | 52 | if len(errors) > 0: 53 | raise CarValidationException(errors) 54 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_06_09/domain/car_validators.py: -------------------------------------------------------------------------------- 1 | from seminar.group_917.seminar_06_09.domain.exceptions import CarValidationException 2 | 3 | 4 | class CarValidatorES: 5 | @staticmethod 6 | def _is_license_valid(self, license_): 7 | # TODO Implement full validation 8 | """ 9 | Implement Spanish license plate validation 10 | @param license_: 11 | @return: ... 12 | """ 13 | return len(license_) > 2 14 | 15 | # FIXME Duplicated code across validators, use inheritance to remove it 16 | def validate(self, car): 17 | errors = [] 18 | # V1 - All properties are non-empty 19 | if not self._is_license_valid(car.license_plate): 20 | errors.append('Invalid license plate') 21 | if len(car.make) < 3: 22 | errors.append('Car make should have at least 3 letters') 23 | if len(car.model) < 3: 24 | errors.append('Car model should have at least 3 letters') 25 | 26 | if len(errors) > 0: 27 | raise CarValidationException(errors) 28 | 29 | 30 | class CarValidatorRO: 31 | @staticmethod 32 | def _is_license_valid(self, license): 33 | # TODO Implement full validation 34 | """ 35 | Implement Romanian license plate validation 36 | @param license: 37 | @return: ... 38 | """ 39 | return len(license) > 2 40 | 41 | # FIXME Duplicated code across validators, use inheritance to remove it 42 | def validate(self, car): 43 | errors = [] 44 | # V1 - All properties are non-empty 45 | if not self._is_license_valid(car.license_plate): 46 | errors.append('Invalid license plate') 47 | if len(car.make) < 2: 48 | errors.append('Car make should have at least 3 letters') 49 | if len(car.model) < 2: 50 | errors.append('Car model should have at least 3 letters') 51 | 52 | if len(errors) > 0: 53 | raise CarValidationException(errors) 54 | -------------------------------------------------------------------------------- /src/lecture/examples/ex09_modules/operations.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Oct 21, 2018 3 | 4 | @author: Arthur 5 | """ 6 | 7 | # TODO Import statements should be at the top 8 | 9 | ''' 10 | Switch the order of the import statements below. What happens? 11 | ''' 12 | # import src.lecture.examples.ex09_modules.rational.rational_dict as rational 13 | # import src.lecture.examples.ex09_modules.rational.rational_list as rational 14 | # print(rational.create_rational(1,3)) 15 | 16 | ''' 17 | Code below works by directly referencing the create_rational function 18 | ''' 19 | from src.lecture.examples.ex09_modules.rational import rational_dict 20 | from src.lecture.examples.ex09_modules.rational import rational_list 21 | print('Rational number as dict') 22 | print(rational_dict.create_rational(1,3)) 23 | print('Rational number as list') 24 | print(rational_list.create_rational(1,3)) 25 | 26 | """ 27 | Switch the commented line below and check what happens 28 | """ 29 | from src.lecture.examples.ex09_modules.rational.rational_dict import create_rational, get_numerator, get_denominator 30 | # from src.lecture.examples.ex09_modules.rational.rational_list import create_rational, get_numerator, get_denominator 31 | 32 | 33 | def add(q1, q2): 34 | """ 35 | Function to add rational numbers that works with both list and dict representations 36 | :param q1: 37 | :param q2: 38 | :return: 39 | """ 40 | return create_rational(get_numerator(q1) * get_denominator(q2) + get_numerator(q2) * get_denominator(q1), get_denominator(q1) * get_denominator(q2)) 41 | 42 | 43 | q1 = create_rational(1, 2) 44 | q2 = create_rational(3, 4) 45 | print(add(q1, q2)) 46 | 47 | 48 | """ 49 | Let's see what the dir(...) and help(...) functions do 50 | Switch between the commented lines and check the output 51 | """ 52 | print('-' * 50) 53 | print(dir(rational_dict)) 54 | print('-' * 50) 55 | print(help(rational_dict)) 56 | 57 | # print('-' * 50) 58 | # print(dir(rational_list)) 59 | # print('-' * 50) 60 | # print(help(rational_list)) 61 | -------------------------------------------------------------------------------- /src/lecture/examples/ex21_textFiles.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Nov 22, 2016 3 | 4 | @author: Arthur 5 | """ 6 | 7 | 8 | class Person: 9 | def __init__(self, person_id, family_name, given_name): 10 | self._personId = person_id 11 | self._familyName = family_name 12 | self._givenName = given_name 13 | 14 | @property 15 | def id(self): 16 | return self._personId 17 | 18 | @property 19 | def family_name(self): 20 | return self._familyName 21 | 22 | @property 23 | def given_name(self): 24 | return self._givenName 25 | 26 | def __str__(self): 27 | return str(self._personId) + " - " + self._familyName + " " + self._givenName 28 | 29 | 30 | def write_text_file(file_name, persons): 31 | f = open(file_name, "w") 32 | try: 33 | for p in persons: 34 | person_str = str(p.id) + ";" + p.family_name + ";" + p.given_name + "\n" 35 | f.write(person_str) 36 | f.close() 37 | except Exception as e: 38 | print("An error occurred -" + str(e)) 39 | 40 | 41 | def read_text_file(file_name): 42 | result = [] 43 | try: 44 | f = open(file_name, "r") 45 | line = f.readline().strip() 46 | while len(line) > 0: 47 | line = line.split(";") 48 | result.append(Person(int(line[0]), line[1], line[2])) 49 | line = f.readline().strip() 50 | f.close() 51 | except IOError as e: 52 | """ 53 | Here we 'log' the error, and throw it to the outer layers 54 | """ 55 | print("An error occured - " + str(e)) 56 | raise e 57 | 58 | return result 59 | 60 | 61 | """ 62 | Initialize a list of objects 63 | """ 64 | persons = [Person(1, "Pop", "Anca"), Person(2, "Morariu", "Sergiu"), Person(3, "Moldovean", "Iuliu")] 65 | 66 | """ 67 | Write it to a text file 68 | """ 69 | write_text_file("persons.txt", persons) 70 | 71 | """ 72 | Read it back and see what we have 73 | """ 74 | for p in read_text_file("persons.txt"): 75 | print(p) 76 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_09/repository/Repository.py: -------------------------------------------------------------------------------- 1 | from seminar.group_911.seminar_09.repository.RepositoryException import RepositoryException 2 | 3 | 4 | class Repository: 5 | """ 6 | Repository for storing IDObject instances 7 | """ 8 | 9 | def __init__(self): 10 | self._objects = [] 11 | 12 | def store(self, obj): 13 | if self.find(obj.id) != None: 14 | raise RepositoryException("Element having id=" + str(obj.id) + " already stored!") 15 | self._objects.append(obj) 16 | 17 | def update(self, object): 18 | """ 19 | Update the instance given as parameter. The provided instance replaces the one having the same ID 20 | object - The object that will be updated 21 | Raises RepositoryException in case the object is not contained within the repository 22 | """ 23 | el = self.find(object.id) 24 | if el == None: 25 | raise RepositoryException("Element not found!") 26 | idx = self._objects.index(el) 27 | self._objects.remove(el) 28 | self._objects.insert(idx, object) 29 | 30 | def find(self, objectId): 31 | for e in self._objects: 32 | if objectId == e.id: 33 | return e 34 | return None 35 | 36 | def delete(self, objectId): 37 | """ 38 | Remove the object with given objectId from repository 39 | objectId - The objectId that will be removed 40 | Returns the object that was removed 41 | Raises RepositoryException if object with given objectId is not contained in the repository 42 | """ 43 | object = self.find(objectId) 44 | if object == None: 45 | raise RepositoryException("Element not in repository!") 46 | self._objects.remove(object) 47 | return object 48 | 49 | def getAll(self): 50 | return self._objects; 51 | 52 | def __len__(self): 53 | return len(self._objects) 54 | 55 | def __str__(self): 56 | r = "" 57 | for e in self._objects: 58 | r += str(e) 59 | r += "\n" 60 | return r 61 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_11/repository/Repository.py: -------------------------------------------------------------------------------- 1 | from seminar.group_911.seminar_11.repository.RepositoryException import RepositoryException 2 | 3 | 4 | class Repository: 5 | """ 6 | Repository for storing IDObject instances 7 | """ 8 | 9 | def __init__(self): 10 | self._objects = [] 11 | 12 | def store(self, obj): 13 | if self.find(obj.id) is not None: 14 | raise RepositoryException("Element having id=" + str(obj.id) + " already stored!") 15 | self._objects.append(obj) 16 | 17 | def update(self, object): 18 | """ 19 | Update the instance given as parameter. The provided instance replaces the one having the same ID 20 | object - The object that will be updated 21 | Raises RepositoryException in case the object is not contained within the repository 22 | """ 23 | el = self.find(object.id) 24 | if el is None: 25 | raise RepositoryException("Element not found!") 26 | idx = self._objects.index(el) 27 | self._objects.remove(el) 28 | self._objects.insert(idx, object) 29 | 30 | def find(self, objectId): 31 | for e in self._objects: 32 | if objectId == e.id: 33 | return e 34 | return None 35 | 36 | def delete(self, objectId): 37 | """ 38 | Remove the object with given objectId from repository 39 | objectId - The objectId that will be removed 40 | Returns the object that was removed 41 | Raises RepositoryException if object with given objectId is not contained in the repository 42 | """ 43 | object = self.find(objectId) 44 | if object is None: 45 | raise RepositoryException("Element not in repository!") 46 | self._objects.remove(object) 47 | return object 48 | 49 | def getAll(self): 50 | return self._objects 51 | 52 | def __len__(self): 53 | return len(self._objects) 54 | 55 | def __str__(self): 56 | r = "" 57 | for e in self._objects: 58 | r += str(e) 59 | r += "\n" 60 | return r 61 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_09/repository/Repository.py: -------------------------------------------------------------------------------- 1 | from seminar.group_912.seminar_09.repository.RepositoryException import RepositoryException 2 | 3 | 4 | class Repository: 5 | """ 6 | Repository for storing IDObject instances 7 | """ 8 | 9 | def __init__(self): 10 | self._objects = [] 11 | 12 | def store(self, obj): 13 | if self.find(obj.id) != None: 14 | raise RepositoryException("Element having id=" + str(obj.id) + " already stored!") 15 | self._objects.append(obj) 16 | 17 | def update(self, object): 18 | """ 19 | Update the instance given as parameter. The provided instance replaces the one having the same ID 20 | object - The object that will be updated 21 | Raises RepositoryException in case the object is not contained within the repository 22 | """ 23 | el = self.find(object.id) 24 | if el == None: 25 | raise RepositoryException("Element not found!") 26 | idx = self._objects.index(el) 27 | self._objects.remove(el) 28 | self._objects.insert(idx, object) 29 | 30 | def find(self, objectId): 31 | for e in self._objects: 32 | if objectId == e.id: 33 | return e 34 | return None 35 | 36 | def delete(self, objectId): 37 | """ 38 | Remove the object with given objectId from repository 39 | objectId - The objectId that will be removed 40 | Returns the object that was removed 41 | Raises RepositoryException if object with given objectId is not contained in the repository 42 | """ 43 | object = self.find(objectId) 44 | if object == None: 45 | raise RepositoryException("Element not in repository!") 46 | self._objects.remove(object) 47 | return object 48 | 49 | def getAll(self): 50 | return self._objects; 51 | 52 | def __len__(self): 53 | return len(self._objects) 54 | 55 | def __str__(self): 56 | r = "" 57 | for e in self._objects: 58 | r += str(e) 59 | r += "\n" 60 | return r 61 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_11/repository/Repository.py: -------------------------------------------------------------------------------- 1 | from seminar.group_912.seminar_11.repository.RepositoryException import RepositoryException 2 | 3 | 4 | class Repository: 5 | """ 6 | Repository for storing IDObject instances 7 | """ 8 | 9 | def __init__(self): 10 | self._objects = [] 11 | 12 | def store(self, obj): 13 | if self.find(obj.id) is not None: 14 | raise RepositoryException("Element having id=" + str(obj.id) + " already stored!") 15 | self._objects.append(obj) 16 | 17 | def update(self, object): 18 | """ 19 | Update the instance given as parameter. The provided instance replaces the one having the same ID 20 | object - The object that will be updated 21 | Raises RepositoryException in case the object is not contained within the repository 22 | """ 23 | el = self.find(object.id) 24 | if el is None: 25 | raise RepositoryException("Element not found!") 26 | idx = self._objects.index(el) 27 | self._objects.remove(el) 28 | self._objects.insert(idx, object) 29 | 30 | def find(self, objectId): 31 | for e in self._objects: 32 | if objectId == e.id: 33 | return e 34 | return None 35 | 36 | def delete(self, objectId): 37 | """ 38 | Remove the object with given objectId from repository 39 | objectId - The objectId that will be removed 40 | Returns the object that was removed 41 | Raises RepositoryException if object with given objectId is not contained in the repository 42 | """ 43 | object = self.find(objectId) 44 | if object is None: 45 | raise RepositoryException("Element not in repository!") 46 | self._objects.remove(object) 47 | return object 48 | 49 | def getAll(self): 50 | return self._objects; 51 | 52 | def __len__(self): 53 | return len(self._objects) 54 | 55 | def __str__(self): 56 | r = "" 57 | for e in self._objects: 58 | r += str(e) 59 | r += "\n" 60 | return r 61 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_09/repository/Repository.py: -------------------------------------------------------------------------------- 1 | from seminar.group_917.seminar_09.repository.RepositoryException import RepositoryException 2 | 3 | 4 | class Repository: 5 | """ 6 | Repository for storing IDObject instances 7 | """ 8 | 9 | def __init__(self): 10 | self._objects = [] 11 | 12 | def store(self, obj): 13 | if self.find(obj.id) != None: 14 | raise RepositoryException("Element having id=" + str(obj.id) + " already stored!") 15 | self._objects.append(obj) 16 | 17 | def update(self, object): 18 | """ 19 | Update the instance given as parameter. The provided instance replaces the one having the same ID 20 | object - The object that will be updated 21 | Raises RepositoryException in case the object is not contained within the repository 22 | """ 23 | el = self.find(object.id) 24 | if el == None: 25 | raise RepositoryException("Element not found!") 26 | idx = self._objects.index(el) 27 | self._objects.remove(el) 28 | self._objects.insert(idx, object) 29 | 30 | def find(self, objectId): 31 | for e in self._objects: 32 | if objectId == e.id: 33 | return e 34 | return None 35 | 36 | def delete(self, objectId): 37 | """ 38 | Remove the object with given objectId from repository 39 | objectId - The objectId that will be removed 40 | Returns the object that was removed 41 | Raises RepositoryException if object with given objectId is not contained in the repository 42 | """ 43 | object = self.find(objectId) 44 | if object == None: 45 | raise RepositoryException("Element not in repository!") 46 | self._objects.remove(object) 47 | return object 48 | 49 | def getAll(self): 50 | return self._objects; 51 | 52 | def __len__(self): 53 | return len(self._objects) 54 | 55 | def __str__(self): 56 | r = "" 57 | for e in self._objects: 58 | r += str(e) 59 | r += "\n" 60 | return r 61 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_11/repository/Repository.py: -------------------------------------------------------------------------------- 1 | from seminar.group_917.seminar_11.repository.RepositoryException import RepositoryException 2 | 3 | 4 | class Repository: 5 | """ 6 | Repository for storing IDObject instances 7 | """ 8 | 9 | def __init__(self): 10 | self._objects = [] 11 | 12 | def store(self, obj): 13 | if self.find(obj.id) is not None: 14 | raise RepositoryException("Element having id=" + str(obj.id) + " already stored!") 15 | self._objects.append(obj) 16 | 17 | def update(self, object): 18 | """ 19 | Update the instance given as parameter. The provided instance replaces the one having the same ID 20 | object - The object that will be updated 21 | Raises RepositoryException in case the object is not contained within the repository 22 | """ 23 | el = self.find(object.id) 24 | if el is None: 25 | raise RepositoryException("Element not found!") 26 | idx = self._objects.index(el) 27 | self._objects.remove(el) 28 | self._objects.insert(idx, object) 29 | 30 | def find(self, objectId): 31 | for e in self._objects: 32 | if objectId == e.id: 33 | return e 34 | return None 35 | 36 | def delete(self, objectId): 37 | """ 38 | Remove the object with given objectId from repository 39 | objectId - The objectId that will be removed 40 | Returns the object that was removed 41 | Raises RepositoryException if object with given objectId is not contained in the repository 42 | """ 43 | object = self.find(objectId) 44 | if object is None: 45 | raise RepositoryException("Element not in repository!") 46 | self._objects.remove(object) 47 | return object 48 | 49 | def getAll(self): 50 | return self._objects; 51 | 52 | def __len__(self): 53 | return len(self._objects) 54 | 55 | def __str__(self): 56 | r = "" 57 | for e in self._objects: 58 | r += str(e) 59 | r += "\n" 60 | return r 61 | -------------------------------------------------------------------------------- /src/lecture/examples/ex16_rationalCalculator/ui.py: -------------------------------------------------------------------------------- 1 | from lecture.examples.ex16_rationalCalculator.calculator import Calculator 2 | from lecture.examples.ex16_rationalCalculator.domain import Rational 3 | 4 | 5 | class UI: 6 | def __init__(self, calculator): 7 | self._commands = {'+': self.add_number, 'c': self.clear, 'u': self.undo, '?': self.count} 8 | self._calculator = calculator 9 | 10 | def _print_menu(self): 11 | """ 12 | Print out the calculator menu 13 | """ 14 | print("Calculator:") 15 | print(" + for adding a rational number") 16 | print(" c to clear the calculator") 17 | print(" u to undo the last operation") 18 | print(" ? to count the rational numbers created") 19 | print(" x to close the calculator") 20 | 21 | def add_number(self): 22 | a = int(input("Give numerator:")) 23 | b = int(input("Give denominator:")) 24 | q = Rational(a, b) 25 | self._calculator.add(q) 26 | 27 | def undo(self): 28 | self._calculator.undo() 29 | 30 | def clear(self): 31 | self._calculator.reset() 32 | 33 | def count(self): 34 | print("Number of rational instances created so far: " + str(self._calculator.get_number_count())) 35 | 36 | def start(self): 37 | 38 | self._calculator.reset() 39 | while True: 40 | self._print_menu() 41 | print("Total: " + str(self._calculator.get_total)) 42 | _command = input().strip().lower() 43 | # Exit program 44 | if _command == 'x': 45 | return 46 | # Invalid option 47 | if _command not in self._commands: 48 | print("Bad command") 49 | # Run user option 50 | try: 51 | self._commands[_command]() 52 | except ValueError as ve: 53 | print("error - " + str(ve)) 54 | 55 | 56 | # Initialize the calculator class 57 | calc = Calculator() 58 | # This allows us to use the UI class with any implementation of the Calculator 59 | ui = UI(calc) 60 | # Start the UI 61 | ui.start() 62 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_05b/functions.py: -------------------------------------------------------------------------------- 1 | """" 2 | 1. Generate 'n' rectangles 3 | random.randint(a,b) -> use to generate random integers 4 | - n is a positive integer read from the keyboard. 5 | - program generates and stores n distinct rectangles (distinct = at least one different corner), 6 | - each rectangle is completely enclosed in the square defined by corners (0,0) and (20,20) 7 | 2. Display all rectangle data, sorted descending by area 8 | rectangle: (0,0) - (10,10) -> area is 100 (0,0), (0,10), (10,0), (10,10) 9 | rectangle: (14,15) - (18,18) -> area is 12 10 | - display area and coordinates for each rectangle, using right justification (str.rjust) 11 | 3. Delete all rectangles that have at least one corner below the line x = y 12 | """ 13 | import random 14 | from rectangle import * 15 | 16 | 17 | class functions: 18 | def __init__(self): 19 | self._rectangle_list = [] 20 | 21 | def check_previous_rectangles_for_uniqueness(self, r): 22 | for rect in self._rectangle_list: 23 | if equal_rectangles(rect, r): 24 | return False 25 | return True 26 | 27 | def delete_rectangles_below_the_line(self): 28 | i = 0 29 | while i < len(self._rectangle_list): 30 | if below_the_line(get_corner1(self._rectangle_list[i])) == True or below_the_line( 31 | get_corner2(self._rectangle_list[i])) == True: 32 | self._rectangle_list.pop(i) 33 | i -= 1 34 | i += 1 35 | 36 | def rectangles_list_by_area(self): 37 | rectangles_sorted = sorted(self._rectangle_list, key=area_of_rectangle, reverse=True) 38 | return rectangles_sorted 39 | 40 | 41 | def generate_a_rectangle(): 42 | p1 = create_point(0, 0) 43 | p2 = create_point(0, 0) 44 | while equal_points(p1, p2) and points_on_different_lines(p1, p2) == False: 45 | x = random.randint(0, 20) 46 | y = random.randint(0, 20) 47 | p1 = create_point(x, y) 48 | a = random.randint(0, 20) 49 | b = random.randint(0, 20) 50 | p2 = create_point(a, b) 51 | return create_rectangle(p1, p2) 52 | -------------------------------------------------------------------------------- /src/lecture/examples/ex13_rationalNumberBasic.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Nov 1, 2016 3 | 4 | @author: Arthur 5 | """ 6 | from math import gcd 7 | 8 | 9 | class rational: 10 | """ 11 | Abstract data type rational number 12 | Domain: {a/b where a,b integer numbers, b!=0, greatest common divisor a, b =1} 13 | """ 14 | 15 | def __init__(self, a, b=1): 16 | """ 17 | Initialise a rational number 18 | a,b integer numbers 19 | """ 20 | if b == 0: 21 | raise ValueError("Denominator cannot be 0!") 22 | 23 | d = gcd(a, b) 24 | self.__nominator = a // d 25 | self.__denominator = b // d 26 | 27 | def get_numerator(self): 28 | """ 29 | Getter method 30 | return the denominator of the rational number 31 | """ 32 | return self.__denominator 33 | 34 | def get_denominator(self): 35 | """" 36 | Getter method 37 | return the nominator of the method 38 | """ 39 | return self.__nominator 40 | 41 | def add(self, a): 42 | """ 43 | add 2 rational numbers 44 | a is a rational number 45 | Return the sum of two rational numbers as an instance of rational number. 46 | Raise ValueError if the denominators are zero. 47 | """ 48 | if self.get_numerator() == 0 or a.get_numerator() == 0: 49 | raise ValueError("0 denominator not allowed") 50 | return rational(self.get_denominator() * a.get_numerator() + self.get_numerator() * a.get_denominator(), 51 | self.get_numerator() * a.get_numerator()) 52 | 53 | 54 | def test_rational_add(): 55 | r1 = rational(1, 2) 56 | r2 = rational(1, 3) 57 | r3 = r1.add(r2) 58 | assert r3.get_denominator() == 5 59 | assert r3.get_numerator() == 6 60 | 61 | 62 | def test_create(): 63 | r1 = rational(1, 3) # create the rational number 1/3 64 | assert r1.get_denominator() == 1 65 | assert r1.get_numerator() == 3 66 | r1 = rational(4, 3) # create the rational number 4/3 67 | assert r1.get_denominator() == 4 68 | assert r1.get_numerator() == 3 69 | 70 | 71 | test_create() 72 | test_rational_add() 73 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_05/ui.py: -------------------------------------------------------------------------------- 1 | """ 2 | Tic Tac Toe ui! 3 | Can call functions from game/board 4 | All input/print statements go here 5 | 6 | A few problems with modular Tic Tac Toe 7 | 1. All functions are exposed ("public") and can be called at any time 8 | 2. We don't have any custom types defined (our board is a Python list) 9 | 3. We can modify the board in unexpected ways -> board[1][1] = 'A' 10 | 4. Some params have to carried around (e.g. board) 11 | 5. We can't use many of Python's inbuilt functions (e.g. to_str(board) vs. str(board)) 12 | """ 13 | # import board 14 | from board import board 15 | from game import Game, GameState 16 | 17 | 18 | class GameUI: 19 | def __init__(self): 20 | self._game = Game() 21 | 22 | def _read_position(self): 23 | x = int(input("X=")) 24 | y = int(input("Y=")) 25 | return x, y 26 | 27 | def start(self): 28 | is_human_turn = True 29 | 30 | while self._game.get_state() == GameState.ONGOING: 31 | print("Game board:") 32 | # V1 - board getter 33 | # print(str(self._game.get_board())) 34 | # V2 - board property 35 | print(str(self._game.board)) 36 | 37 | try: 38 | if is_human_turn: 39 | x, y = self._read_position() 40 | self._game.board.set_pos(x, y, 'X') 41 | else: 42 | x, y = self._game.move_computer() 43 | # TODO Should be moved into game 44 | self._game.board.set_pos(x, y, 'O') 45 | print("Computer moves (" + str(x) + "," + str(y) + ")") 46 | is_human_turn = not is_human_turn 47 | except ValueError as ve: 48 | print(str(ve)) 49 | 50 | if self._game.get_state() == GameState.WON: 51 | if is_human_turn: 52 | # Var is flipped after the last move was made 53 | print("Computer wins!") 54 | else: 55 | print("You win!") 56 | print(str(self._game.board)) 57 | else: 58 | print("It's a draw!") 59 | 60 | print(__name__) 61 | ui = GameUI() 62 | ui.start() 63 | -------------------------------------------------------------------------------- /src/lecture/examples/ex35_coins.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Jan 10, 2017 3 | 4 | @author: Arthur 5 | """ 6 | 7 | 8 | def compute_sum(b, sum): 9 | """ 10 | Compute the paid amount with the current candidate 11 | """ 12 | amount = 0 13 | for coin in b: 14 | nr_coins = (sum - amount) // coin 15 | # If this is a candidate solution, 16 | # we need to use at least 1 coin 17 | if nr_coins == 0: 18 | nr_coins = 1 19 | amount += nr_coins * coin 20 | return amount 21 | 22 | 23 | def select_most_promising(c): 24 | """ 25 | Select the largest coin from the remaining 26 | input: 27 | c - candidate coins 28 | Return the largest coin 29 | """ 30 | return max(c) 31 | 32 | 33 | def acceptable(b, sum): 34 | """ 35 | Verify if a candidate solution is valid (we are not over amount) 36 | """ 37 | amount = compute_sum(b, sum) 38 | return amount <= sum 39 | 40 | 41 | def solution(b, sum): 42 | """ 43 | Verify if a candidate solution is an actual solution 44 | (we are at the required amount) 45 | """ 46 | amount = compute_sum(b, sum) 47 | return amount == sum 48 | 49 | 50 | def build_solution_string(b, sum): 51 | """ 52 | Pretty print the solution 53 | """ 54 | sol_str = '' 55 | amount = 0 56 | for coin in b: 57 | nr_coins = (sum - amount) // coin 58 | sol_str += str(nr_coins) + '*' + str(coin) 59 | amount += nr_coins * coin 60 | if sum - amount > 0: 61 | sol_str += " + " 62 | return sol_str 63 | 64 | 65 | def greedy(c, sum): 66 | """ 67 | Main function 68 | """ 69 | # The empty set is the candidate solution 70 | b = [] 71 | while not solution(b, sum) and c != []: 72 | # Select best candidate (local optimum) 73 | candidate = select_most_promising(c) 74 | c.remove(candidate) 75 | # If the candidate is acceptable, add it 76 | if acceptable(b + [candidate], sum): 77 | b.append(candidate) 78 | if solution(b, sum): 79 | return build_solution_string(b, sum) 80 | 81 | 82 | ''' 83 | Let's see how it works 84 | ''' 85 | for amount in range(1, 55): 86 | print('Amount ' + str(amount) + "=" + greedy([1, 5, 10], amount)) 87 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_09/service/ClientService.py: -------------------------------------------------------------------------------- 1 | from seminar.group_912.seminar_09.domain.Client import Client 2 | from seminar.group_912.seminar_09.service.UndoService import FunctionCall, Operation, CascadedOperation 3 | 4 | 5 | class ClientService: 6 | def __init__(self, undo_service, rental_service, validator, repository): 7 | self._validator = validator 8 | self._repository = repository 9 | self._rental_service = rental_service 10 | self._undo_service = undo_service 11 | 12 | def create(self, client_id, client_cnp, client_name): 13 | client = Client(client_id, client_cnp, client_name) 14 | self._validator.validate(client) 15 | self._repository.store(client) 16 | return client 17 | 18 | def delete(self, client_id): 19 | """ 20 | 1. Delete the client 21 | """ 22 | client = self._repository.delete(client_id) 23 | 24 | """ 25 | Record client deletion for undo/redo 26 | """ 27 | fc_undo = FunctionCall(self.create, client.id, client.cnp, client.name) 28 | fc_redo = FunctionCall(self.delete, client.id) 29 | 30 | cope = CascadedOperation() 31 | cope.add(Operation(fc_undo, fc_redo)) 32 | 33 | ''' 34 | 2. Delete their rentals 35 | NB! This implementation is not transactional, i.e. the two delete operations are performed separately 36 | ''' 37 | rentals = self._rental_service.filter_rentals(client, None) 38 | for rent in rentals: 39 | self._rental_service.delete_rental(rent.getId(), False) 40 | """ 41 | Record deleting rentals for undo/redo 42 | """ 43 | fc_undo = FunctionCall(self._rental_service.create_rental, rent.id, rent.client, rent.car, rent.start, 44 | rent.end) 45 | fc_redo = FunctionCall(self._rental_service.delete_rental, rent.id) 46 | cope.add(Operation(fc_undo, fc_redo)) 47 | 48 | self._undo_service.record_operation(cope) 49 | return client 50 | 51 | def get_client_count(self): 52 | return len(self._repository) 53 | 54 | def update(self, car): 55 | """ 56 | NB! Undo/redo is also needed here 57 | """ 58 | pass 59 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_09/service/ClientService.py: -------------------------------------------------------------------------------- 1 | from seminar.group_917.seminar_09.domain.Client import Client 2 | from seminar.group_917.seminar_09.service.UndoService import Call, Operation, ComplexOperation 3 | 4 | 5 | class ClientService: 6 | def __init__(self, undo_service, rental_service, validator, repository): 7 | self._validator = validator 8 | self._repository = repository 9 | self._rental_service = rental_service 10 | self._undo_service = undo_service 11 | 12 | def create(self, client_id, client_cnp, client_name): 13 | client = Client(client_id, client_cnp, client_name) 14 | self._validator.validate(client) 15 | self._repository.store(client) 16 | return client 17 | 18 | def delete(self, client_id): 19 | """ 20 | 1. Delete the client 21 | """ 22 | client = self._repository.delete(client_id) 23 | """ 24 | undo -> repo.store(...) 25 | redo -> repo.delete(...) 26 | """ 27 | # TODO Make sure you don't create object create/delete loops 28 | undo_call = Call(self._repository.store, client) 29 | redo_call = Call(self._repository.delete, client.id) 30 | 31 | operations_ur = [] 32 | operations_ur.append(Operation(undo_call, redo_call)) 33 | 34 | ''' 35 | 2. Delete their rentals 36 | NB! This implementation is not transactional, i.e. the two delete operations are performed separately 37 | ''' 38 | rentals = self._rental_service.filter_rentals(client, None) 39 | for rent in rentals: 40 | self._rental_service.delete_rental(rent.id, False) 41 | # Operation for undo/redo 42 | redo_call = Call(self._rental_service.delete_rental, rent.id) 43 | undo_call = Call(self._rental_service.create_rental, rent.id, rent.client, rent.car, rent.start, rent.end) 44 | operations_ur.append(Operation(undo_call, redo_call)) 45 | 46 | self._undo_service.record(ComplexOperation(operations_ur)) 47 | return client 48 | 49 | def get_client_count(self): 50 | return len(self._repository) 51 | 52 | def update(self, car): 53 | """ 54 | NB! Undo/redo is also needed here 55 | """ 56 | pass 57 | -------------------------------------------------------------------------------- /src/lecture/examples/ex10_modular_calc/domain/calculator.py: -------------------------------------------------------------------------------- 1 | """ 2 | Calculator module, contains functions related to the calculator 3 | """ 4 | from src.lecture.examples.ex10_modular_calc.domain.rational import add, create_rational 5 | 6 | ''' 7 | Calculator state 8 | ''' 9 | 10 | 11 | def get_calculator_total(calc): 12 | return calc[0] 13 | 14 | 15 | def set_calculator_total(calc, total): 16 | calc[0] = total 17 | 18 | 19 | def get_undo_list(calc): 20 | return calc[1] 21 | 22 | 23 | def reset_calc(): 24 | return [create_rational(0), []] 25 | 26 | 27 | """ 28 | Other calculator operations 29 | """ 30 | 31 | 32 | def undo(calc): 33 | """ 34 | Undo the last user operation 35 | post: restore the previous current total 36 | """ 37 | if len(get_undo_list(calc)) == 0: 38 | raise ValueError("No more undos!") 39 | 40 | set_calculator_total(calc, get_undo_list(calc)[-1]) 41 | get_undo_list(calc).pop 42 | 43 | 44 | def calculator_add(calc, q): 45 | """ 46 | add a rational number to the current total 47 | a, b integer number, b<>0 48 | post: add a/b to the current total 49 | """ 50 | # add the current total to the undo list 51 | 52 | get_undo_list(calc).append(get_calculator_total(calc)) 53 | set_calculator_total(calc, add(get_calculator_total(calc), q)) 54 | 55 | 56 | def test_calculator_add(): 57 | """ 58 | Test function for calculator_add 59 | """ 60 | c = reset_calc() 61 | assert get_calculator_total(c) == create_rational(0) 62 | calculator_add(c, create_rational(1, 2)) 63 | assert get_calculator_total(c) == create_rational(1, 2) 64 | calculator_add(c, create_rational(1, 3)) 65 | assert get_calculator_total(c) == create_rational(5, 6) 66 | calculator_add(c, create_rational(1, 6)) 67 | assert get_calculator_total(c) == create_rational(1) 68 | 69 | 70 | def test_undo(): 71 | """ 72 | Test function for undo 73 | """ 74 | c = reset_calc() 75 | calculator_add(c, create_rational(1, 3)) 76 | undo(c) 77 | assert get_calculator_total(c) == create_rational(0) 78 | c = reset_calc() 79 | calculator_add(c, create_rational(1, 3)) 80 | calculator_add(c, create_rational(1, 3)) 81 | calculator_add(c, create_rational(1, 3)) 82 | undo(c) 83 | assert get_calculator_total(c) == create_rational(2, 3) 84 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_10.py: -------------------------------------------------------------------------------- 1 | """ 2 | Alg. complexity 101 3 | 4 | n -> size of the program's input (length of a list, the n-th term in a sequence, side of a square) 5 | T(n) -> approximation of how many operations the algorithm needs for size n 6 | O(n) -> high bound for the number of operations 7 | 8 | 1. 9 | BC = AC = WC 10 | T(n) = n => O(n) = n, but O(n) is a high bound, so O(n) is also n^2, n^3 and so on 11 | 12 | 2. 13 | WC (worst case): O(n) = n 14 | BC (best case) : O(n) = 1 15 | 16 | AC (average case) : (1 + 2 + 3 + ... + n) / n = n(n+1)/2n = (n+1)/2 => O(n) = n 17 | """ 18 | 19 | 20 | def bs(data): 21 | swapped = True 22 | n = len(data) - 1 23 | while swapped: 24 | swapped = False 25 | for i in range(n): 26 | if data[i] > data[i + 1]: 27 | data[i], data[i + 1] = data[i + 1], data[i] 28 | swapped = True 29 | n -= 1 30 | 31 | 32 | """ 33 | BC - list already sorted, O(n) = n (yay!) 34 | WC - list sorted in reverse, O(n) = n^2 35 | explain it: 36 | iteration 1 -> n - 1 swaps 37 | iteration 2 -> n - 2 38 | ... 39 | iteration n - 1: 1 swap 40 | 41 | """ 42 | 43 | 44 | def merge(array_1, array_2): 45 | result = [] 46 | i = 0 # array_1 47 | j = 0 # array_2 48 | 49 | while i < len(array_1) and j < len(array_2): 50 | if array_1[i] <= array_2[j]: 51 | result.append(array_1[i]) 52 | i += 1 53 | else: 54 | result.append(array_2[j]) 55 | j += 1 56 | 57 | if i < len(array_1): 58 | result.extend(array_1[i:]) 59 | if j < len(array_2): 60 | result.extend(array_2[j:]) 61 | 62 | return result 63 | 64 | 65 | def merge_sort(data): 66 | if len(data) == 1: 67 | return data 68 | 69 | m = len(data) // 2 70 | # TODO Don't create list copies 71 | left = merge_sort(data[:m]) 72 | right = merge_sort(data[m:]) 73 | return merge(left, right) 74 | 75 | 76 | """ 77 | Time complexity of merge sort 78 | T(n) = 2 * T(n/2) + n/2 + n/2 = 2 * T(n/2) + n 79 | T(n) = 1, n <= 1 80 | 81 | merging a list of n elems with a list of m elems is O(n,m) = n + m 82 | 83 | 84 | """ 85 | 86 | data = list(range(20)) 87 | data.reverse() 88 | print(data) 89 | # bs(data) 90 | data = merge_sort(data) 91 | print(data) 92 | -------------------------------------------------------------------------------- /src/lecture/livecoding/lecture_06_08/repo/test_repo.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from lecture.livecoding.lecture_06_08.domain.Ingredient import Ingredient 4 | from lecture.livecoding.lecture_06_08.repo.repository import RepositoryException, Repository 5 | 6 | 7 | class RepositoryTest(unittest.TestCase): 8 | """ 9 | class RepositoryTest "is a" unittest.TestCase 10 | RepositoryTest has all the methods that TestCase has 11 | """ 12 | 13 | def setUp(self) -> None: 14 | """ 15 | Runs before every test method 16 | """ 17 | self._repo = Repository() 18 | 19 | def tearDown(self) -> None: 20 | """ 21 | Runs after every test method 22 | """ 23 | pass 24 | 25 | def test_empty_repo(self): 26 | self.assertEqual(len(self._repo), 0) 27 | # assert len(repo) == 0 28 | 29 | def test_repo_add_one(self): 30 | self._repo.add(Ingredient(100, "White flour 550")) 31 | # assert len(repo) == 1 32 | self.assertEqual(len(self._repo), 1) 33 | 34 | def test_repo_exception(self): 35 | self._repo.add(Ingredient(100, "White flour 550")) 36 | 37 | with self.assertRaises(RepositoryException): 38 | self._repo.add(Ingredient(100, "White flour 550")) 39 | 40 | def test_repository(self): 41 | yeast = Ingredient(101, "Yeast (dry)") 42 | self._repo.add(yeast) 43 | self._repo.add(Ingredient(102, "Sugar (white)")) 44 | # assert len(repo) == 3 45 | self.assertEqual(len(self._repo), 2) 46 | # assert repo[101] == yeast 47 | self.assertEqual(self._repo[101], yeast) 48 | 49 | # try: 50 | # x = repo[103] 51 | # assert False 52 | # except RepositoryException: 53 | # pass 54 | 55 | # self.assertRaises(RepositoryException,self.__getItem__,103) 56 | with self.assertRaises(RepositoryException) as re: 57 | x = self._repo[103] 58 | self.assertEqual(str(re.exception), "Item with ID not found") 59 | 60 | del self._repo[102] 61 | # assert len(repo) == 2 62 | self.assertEqual(len(self._repo), 2) 63 | 64 | # try: 65 | # del repo[102] 66 | # assert False 67 | # except RepositoryException: 68 | # pass 69 | 70 | with self.assertRaises(RepositoryException): 71 | x = self._repo[102] 72 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_06_09/services/rental_service.py: -------------------------------------------------------------------------------- 1 | from seminar.group_911.seminar_06_09.domain.rental import Rental 2 | from seminar.group_911.seminar_06_09.domain.exceptions import CarException 3 | 4 | 5 | class RentalService: 6 | """ 7 | Service for rental operations 8 | """ 9 | 10 | def __init__(self, validator, rental_repo, car_repo, client_repo): 11 | self._validator = validator 12 | self._carRepo = car_repo 13 | self._cliRepo = client_repo 14 | self._repository = rental_repo 15 | 16 | def create_rental(self, rental_id, client, car, start, end): 17 | rental = Rental(rental_id, start, end, client, car) 18 | self._validator.validate(rental) 19 | 20 | ''' 21 | Check the car's availability for the given period 22 | ''' 23 | if self._is_car_available(rental.car, rental.start, rental.end) is False: 24 | raise CarException("Car is not available during that time!") 25 | 26 | self._repository.add(rental) 27 | return rental 28 | 29 | def _is_car_available(self, car, start, end): 30 | """ 31 | Check the availability of the given car to be rented in the provided time period 32 | car - The availability of this car is verified 33 | start, end - The time span. The car is available if it is not rented in this time span 34 | Return True if the car is available, False otherwise 35 | """ 36 | rentals = self.filter_rentals(None, car) 37 | for rent in rentals: 38 | if start > rent.end or end < rent.start: 39 | continue 40 | return False 41 | return True 42 | 43 | def filter_rentals(self, client, car): 44 | """ 45 | Return a list of rentals performed by the provided client for the provided car 46 | client - The client performing the rental. None means all clients 47 | cars - The rented car. None means all cars 48 | """ 49 | result = [] 50 | for rental in self._repository.getAll(): 51 | if client is not None and rental.client != client: 52 | continue 53 | if car is not None and rental.car != car: 54 | continue 55 | result.append(rental) 56 | return result 57 | 58 | def delete_rental(self, rental_id): 59 | rental = self._repository.delete(rental_id) 60 | return rental 61 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_06_09/services/rental_service.py: -------------------------------------------------------------------------------- 1 | from seminar.group_912.seminar_06_09.domain.rental import Rental 2 | from seminar.group_912.seminar_06_09.domain.exceptions import CarException 3 | 4 | 5 | class RentalService: 6 | """ 7 | Service for rental operations 8 | """ 9 | 10 | def __init__(self, validator, rental_repo, car_repo, client_repo): 11 | self._validator = validator 12 | self._carRepo = car_repo 13 | self._cliRepo = client_repo 14 | self._repository = rental_repo 15 | 16 | def create_rental(self, rental_id, client, car, start, end): 17 | rental = Rental(rental_id, start, end, client, car) 18 | self._validator.validate(rental) 19 | 20 | ''' 21 | Check the car's availability for the given period 22 | ''' 23 | if self._is_car_available(rental.car, rental.start, rental.end) is False: 24 | raise CarException("Car is not available during that time!") 25 | 26 | self._repository.add(rental) 27 | return rental 28 | 29 | def _is_car_available(self, car, start, end): 30 | """ 31 | Check the availability of the given car to be rented in the provided time period 32 | car - The availability of this car is verified 33 | start, end - The time span. The car is available if it is not rented in this time span 34 | Return True if the car is available, False otherwise 35 | """ 36 | rentals = self.filter_rentals(None, car) 37 | for rent in rentals: 38 | if start > rent.end or end < rent.start: 39 | continue 40 | return False 41 | return True 42 | 43 | def filter_rentals(self, client, car): 44 | """ 45 | Return a list of rentals performed by the provided client for the provided car 46 | client - The client performing the rental. None means all clients 47 | cars - The rented car. None means all cars 48 | """ 49 | result = [] 50 | for rental in self._repository.getAll(): 51 | if client is not None and rental.client != client: 52 | continue 53 | if car is not None and rental.car != car: 54 | continue 55 | result.append(rental) 56 | return result 57 | 58 | def delete_rental(self, rental_id): 59 | rental = self._repository.delete(rental_id) 60 | return rental 61 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_06_09/services/rental_service.py: -------------------------------------------------------------------------------- 1 | from seminar.group_917.seminar_06_09.domain.rental import Rental 2 | from seminar.group_917.seminar_06_09.domain.exceptions import CarException 3 | 4 | 5 | class RentalService: 6 | """ 7 | Service for rental operations 8 | """ 9 | 10 | def __init__(self, validator, rental_repo, car_repo, client_repo): 11 | self._validator = validator 12 | self._carRepo = car_repo 13 | self._cliRepo = client_repo 14 | self._repository = rental_repo 15 | 16 | def create_rental(self, rental_id, client, car, start, end): 17 | rental = Rental(rental_id, start, end, client, car) 18 | self._validator.validate(rental) 19 | 20 | ''' 21 | Check the car's availability for the given period 22 | ''' 23 | if self._is_car_available(rental.car, rental.start, rental.end) is False: 24 | raise CarException("Car is not available during that time!") 25 | 26 | self._repository.add(rental) 27 | return rental 28 | 29 | def _is_car_available(self, car, start, end): 30 | """ 31 | Check the availability of the given car to be rented in the provided time period 32 | car - The availability of this car is verified 33 | start, end - The time span. The car is available if it is not rented in this time span 34 | Return True if the car is available, False otherwise 35 | """ 36 | rentals = self.filter_rentals(None, car) 37 | for rent in rentals: 38 | if start > rent.end or end < rent.start: 39 | continue 40 | return False 41 | return True 42 | 43 | def filter_rentals(self, client, car): 44 | """ 45 | Return a list of rentals performed by the provided client for the provided car 46 | client - The client performing the rental. None means all clients 47 | cars - The rented car. None means all cars 48 | """ 49 | result = [] 50 | for rental in self._repository.getAll(): 51 | if client is not None and rental.client != client: 52 | continue 53 | if car is not None and rental.car != car: 54 | continue 55 | result.append(rental) 56 | return result 57 | 58 | def delete_rental(self, rental_id): 59 | rental = self._repository.delete(rental_id) 60 | return rental 61 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_09/service/UndoService.py: -------------------------------------------------------------------------------- 1 | class UndoService: 2 | """ 3 | How can we implement multiple undo/redo with cascade? 4 | 5 | 1. Keep track of program operations and reverse them (undo) / repeat them (redo) 6 | => Command design pattern 7 | (command = tell the program to do something, but later) 8 | 9 | 2. Keep copies of repositories at each operation (deep-copy) 10 | => Memento design pattern (remember the state of the repos and restore them) 11 | (kinda like A34) 12 | 13 | 3. State-diffing 14 | 1. + 2. 15 | """ 16 | 17 | def __init__(self): 18 | self._history = [] 19 | self._index = -1 20 | 21 | def record(self, operation): 22 | self._history.append(operation) 23 | self._index = len(self._history) - 1 24 | 25 | def undo(self): 26 | if self._index == -1: 27 | # TODO Nice to have - UndoRedoException 28 | raise Exception("No more undos") 29 | self._history[self._index].undo() 30 | self._index -= 1 31 | 32 | def redo(self): 33 | pass 34 | 35 | 36 | class Call: 37 | def __init__(self, function_name, *function_params): 38 | self._function_name = function_name 39 | self._function_params = function_params 40 | 41 | def call(self): 42 | self._function_name(*self._function_params) 43 | 44 | 45 | ''' 46 | private ArrayList history; 47 | ''' 48 | 49 | 50 | class Operation: 51 | def __init__(self, undo_call, redo_call): 52 | self._undo_call = undo_call 53 | self._redo_call = redo_call 54 | 55 | def undo(self): 56 | self._undo_call.call() 57 | 58 | def redo(self): 59 | self._redo_call.call() 60 | 61 | 62 | class CascadedOperation: 63 | def __init__(self): 64 | self._operations = [] 65 | 66 | def add(self, operation): 67 | self._operations.append(operation) 68 | 69 | def undo(self): 70 | for oper in self._operations: 71 | oper.undo() 72 | 73 | def redo(self): 74 | for oper in self._operations: 75 | oper.redo() 76 | 77 | 78 | """ 79 | Short example for undo/redo 80 | def a(x, y, z): 81 | print(x, y, z) 82 | 83 | 84 | def b(x, y, z, t, s): 85 | print(x, y, z, t, s) 86 | 87 | call_a = Call(a, 97, 98, 99) 88 | call_a.call() 89 | 90 | call_b = Call(b, 97, 98, 99, 1001, 1002) 91 | call_b.call() 92 | """ 93 | -------------------------------------------------------------------------------- /src/lecture/examples/ex30_iterators.py: -------------------------------------------------------------------------------- 1 | """ 2 | 1. Example of iterable collection 3 | """ 4 | 5 | 6 | class Collection: 7 | def __init__(self): 8 | self._data = [] 9 | 10 | def add(self, elem): 11 | self._data.append(elem) 12 | 13 | def __iter__(self): 14 | # Returns an iterator over this data structure 15 | self._poz = 0 16 | return self 17 | 18 | def __next__(self): 19 | # Stop iteration when other elements are not available 20 | if self._poz == len(self._data): 21 | raise StopIteration() 22 | # Move to the next element 23 | self._poz += 1 24 | return self._data[self._poz - 1] 25 | 26 | 27 | ''' 28 | 2. Add a few items to our collection 29 | ''' 30 | c = Collection() 31 | for i in range(3): 32 | c.add(i) 33 | 34 | ''' 35 | Iterate over the collection 36 | ''' 37 | for elem in c: 38 | print(elem) 39 | 40 | ''' 41 | Let's try to use two iterators at the same time. We expect this to be printed out: 42 | 0 0 43 | 0 1 44 | 0 2 45 | 1 0 46 | 1 1 47 | 1 2 48 | 2 0 49 | 2 1 50 | 2 2 51 | ''' 52 | for elem in c: 53 | for elem2 in c: 54 | print(elem, elem2) 55 | ''' 56 | hmm... 57 | 58 | We need to separate the iterator implementation from the collection itself 59 | Each iterator must have its own _poz field => the Iterator design pattern 60 | ''' 61 | 62 | 63 | class better_collection: 64 | class MyIterator(): 65 | def __init__(self, col): 66 | self._collection = col 67 | self._poz = 0 68 | 69 | def __next__(self): 70 | # Stop iteration when other elements are not available 71 | if self._poz == len(self._collection._data): 72 | raise StopIteration() 73 | # Move to the next element 74 | self._poz += 1 75 | return self._collection._data[self._poz - 1] 76 | 77 | def __init__(self): 78 | self._data = [] 79 | 80 | def add(self, elem): 81 | self._data.append(elem) 82 | 83 | def __iter__(self): 84 | # Returns an iterator over this data structure 85 | return self.MyIterator(self) 86 | 87 | 88 | ''' 89 | Once more with feeling... 90 | ''' 91 | c = better_collection() 92 | for i in range(3): 93 | c.add(i) 94 | print('Improved iterator over collection:') 95 | for elem in c: 96 | for elem2 in c: 97 | print(elem, elem2) 98 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_11.py: -------------------------------------------------------------------------------- 1 | """ 2 | Computational complexity 101 3 | 4 | n -> size of the algorithm's input 5 | T(n) -> nr. of operations the algorithm makes for input of size "n" 6 | T(n) = n 7 | 8 | O(n) -> upper bound on the number of operations 9 | 10 | 1. 11 | T(n) = n => T(n) belongs to O(n) 12 | 13 | 2. 14 | T(n) between 1 and n -> depends on the structure of the input 15 | 16 | BC: T(n) = 1, O(n) = 1 17 | WC: T(n) = n, O(n) = n 18 | 19 | 5. 20 | 21 | T(n) = 1, n = 1 22 | = 4 * T(n/2) + 1 23 | = 4 * [ 4 * T(n/4) + 1 ] + 1 24 | 25 | 26 | 6. Binary search 27 | T(n) = 1, n =1 28 | = T(n/2) + 1 29 | 30 | 31 | T(n) = T(n/2) + 1 = T(n/4) + 1 + 1 32 | """ 33 | import random 34 | 35 | """ 36 | Bubble sort 37 | """ 38 | data = list(range(20, 0, -1)) 39 | # random.shuffle(data) 40 | # 20 - rabbit 41 | # 1 - turtle 42 | 43 | """ 44 | WC: T(n) = (n-1) + (n-2) + ... + 2 + 1 => n^2 45 | BC: T(n) = n 46 | """ 47 | 48 | 49 | def bs(data): 50 | swapped = True 51 | n = len(data) - 1 52 | 53 | while swapped: 54 | swapped = False 55 | print(data) 56 | for i in range(n): 57 | if data[i] > data[i + 1]: 58 | data[i], data[i + 1] = data[i + 1], data[i] 59 | swapped = True 60 | n -= 1 61 | 62 | 63 | """ 64 | Insertion sort 65 | """ 66 | 67 | 68 | def insert_sort(data): 69 | pass 70 | 71 | 72 | """ 73 | Merge sort 74 | """ 75 | 76 | 77 | def merge(left, right): 78 | i = 0 # left 79 | j = 0 # right 80 | result = [] 81 | 82 | while i < len(left) and j < len(right): 83 | if left[i] < right[j]: 84 | result.append(left[i]) 85 | i += 1 86 | else: 87 | result.append(right[j]) 88 | j += 1 89 | 90 | result += left[i:] + right[j:] 91 | 92 | # result.extend(left[i:]) 93 | # result.extend(right[j:]) 94 | return result 95 | 96 | 97 | """ 98 | Merge Sort 99 | T(n) = 1, n = 1 100 | = 2 * T(n/2) + n 101 | """ 102 | 103 | 104 | def merge_sort(data): 105 | if len(data) == 1: 106 | return data 107 | 108 | m = len(data) // 2 109 | left = merge_sort(data[:m]) 110 | right = merge_sort(data[m:]) 111 | return merge(left, right) 112 | 113 | 114 | print(data) 115 | print(merge_sort(data)) 116 | # print(data,id(data)) 117 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_09/service/RentalService.py: -------------------------------------------------------------------------------- 1 | from seminar.group_911.seminar_09.domain.CarRentalException import CarRentalException 2 | from seminar.group_911.seminar_09.domain.Rental import Rental 3 | 4 | 5 | class RentalService: 6 | """ 7 | Service for rental operations 8 | """ 9 | 10 | def __init__(self, undo_service, validator, rental_repo, car_repo, client_repo): 11 | self._validator = validator 12 | self._carRepo = car_repo 13 | self._cliRepo = client_repo 14 | self._repository = rental_repo 15 | 16 | self._undoController = undo_service 17 | 18 | def create_rental(self, rental_id, client, car, start, end): 19 | rental = Rental(rental_id, start, end, client, car) 20 | self._validator.validate(rental) 21 | 22 | ''' 23 | Check the car's availability for the given period 24 | ''' 25 | if self.is_car_available(rental.car, rental.start, rental.end) is False: 26 | raise CarRentalException("Car is not available during that time!") 27 | 28 | self._repository.store(rental) 29 | return rental 30 | 31 | def is_car_available(self, car, start, end): 32 | """ 33 | Check the availability of the given car to be rented in the provided time period 34 | car - The availability of this car is verified 35 | start, end - The time span. The car is available if it is not rented in this time span 36 | Return True if the car is available, False otherwise 37 | """ 38 | rentals = self.filter_rentals(None, car) 39 | for rent in rentals: 40 | if start > rent.end or end < rent.start: 41 | continue 42 | return False 43 | return True 44 | 45 | def filter_rentals(self, client, car): 46 | """ 47 | Return a list of rentals performed by the provided client for the provided car 48 | client - The client performing the rental. None means all clients 49 | cars - The rented car. None means all cars 50 | """ 51 | result = [] 52 | for rental in self._repository.getAll(): 53 | if client is not None and rental.client != client: 54 | continue 55 | if car is not None and rental.car != car: 56 | continue 57 | result.append(rental) 58 | return result 59 | 60 | def delete_rental(self, rental_id): 61 | rental = self._repository.delete(rental_id) 62 | return rental 63 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_09/service/RentalService.py: -------------------------------------------------------------------------------- 1 | from seminar.group_912.seminar_09.domain.CarRentalException import CarRentalException 2 | from seminar.group_912.seminar_09.domain.Rental import Rental 3 | 4 | 5 | class RentalService: 6 | """ 7 | Service for rental operations 8 | """ 9 | 10 | def __init__(self, undo_service, validator, rental_repo, car_repo, client_repo): 11 | self._validator = validator 12 | self._carRepo = car_repo 13 | self._cliRepo = client_repo 14 | self._repository = rental_repo 15 | 16 | self._undoController = undo_service 17 | 18 | def create_rental(self, rental_id, client, car, start, end): 19 | rental = Rental(rental_id, start, end, client, car) 20 | self._validator.validate(rental) 21 | 22 | ''' 23 | Check the car's availability for the given period 24 | ''' 25 | if self.is_car_available(rental.car, rental.start, rental.end) is False: 26 | raise CarRentalException("Car is not available during that time!") 27 | 28 | self._repository.store(rental) 29 | return rental 30 | 31 | def is_car_available(self, car, start, end): 32 | """ 33 | Check the availability of the given car to be rented in the provided time period 34 | car - The availability of this car is verified 35 | start, end - The time span. The car is available if it is not rented in this time span 36 | Return True if the car is available, False otherwise 37 | """ 38 | rentals = self.filter_rentals(None, car) 39 | for rent in rentals: 40 | if start > rent.end or end < rent.start: 41 | continue 42 | return False 43 | return True 44 | 45 | def filter_rentals(self, client, car): 46 | """ 47 | Return a list of rentals performed by the provided client for the provided car 48 | client - The client performing the rental. None means all clients 49 | cars - The rented car. None means all cars 50 | """ 51 | result = [] 52 | for rental in self._repository.getAll(): 53 | if client is not None and rental.client != client: 54 | continue 55 | if car is not None and rental.car != car: 56 | continue 57 | result.append(rental) 58 | return result 59 | 60 | def delete_rental(self, rental_id): 61 | rental = self._repository.delete(rental_id) 62 | return rental 63 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_09/service/RentalService.py: -------------------------------------------------------------------------------- 1 | from seminar.group_917.seminar_09.domain.CarRentalException import CarRentalException 2 | from seminar.group_917.seminar_09.domain.Rental import Rental 3 | 4 | 5 | class RentalService: 6 | """ 7 | Service for rental operations 8 | """ 9 | 10 | def __init__(self, undo_service, validator, rental_repo, car_repo, client_repo): 11 | self._validator = validator 12 | self._carRepo = car_repo 13 | self._cliRepo = client_repo 14 | self._repository = rental_repo 15 | 16 | self._undoController = undo_service 17 | 18 | # def get_repo(self): 19 | # return self._repository 20 | 21 | def create_rental(self, rental_id, client, car, start, end): 22 | rental = Rental(rental_id, start, end, client, car) 23 | self._validator.validate(rental) 24 | 25 | ''' 26 | Check the car's availability for the given period 27 | ''' 28 | if self.is_car_available(rental.car, rental.start, rental.end) is False: 29 | raise CarRentalException("Car is not available during that time!") 30 | 31 | self._repository.store(rental) 32 | return rental 33 | 34 | def is_car_available(self, car, start, end): 35 | """ 36 | Check the availability of the given car to be rented in the provided time period 37 | car - The availability of this car is verified 38 | start, end - The time span. The car is available if it is not rented in this time span 39 | Return True if the car is available, False otherwise 40 | """ 41 | rentals = self.filter_rentals(None, car) 42 | for rent in rentals: 43 | if start > rent.end or end < rent.start: 44 | continue 45 | return False 46 | return True 47 | 48 | def filter_rentals(self, client, car): 49 | """ 50 | Return a list of rentals performed by the provided client for the provided car 51 | client - The client performing the rental. None means all clients 52 | cars - The rented car. None means all cars 53 | """ 54 | result = [] 55 | for rental in self._repository.getAll(): 56 | if client is not None and rental.client != client: 57 | continue 58 | if car is not None and rental.car != car: 59 | continue 60 | result.append(rental) 61 | return result 62 | 63 | def delete_rental(self, rental_id): 64 | rental = self._repository.delete(rental_id) 65 | return rental 66 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_09/UndoExampleMedium.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Nov 17, 2018 3 | 4 | @author: Arthur 5 | """ 6 | from seminar.group_911.seminar_09.domain.Car import CarValidator 7 | from seminar.group_911.seminar_09.domain.Client import ClientValidator 8 | from seminar.group_911.seminar_09.domain.Rental import RentalValidator 9 | from seminar.group_911.seminar_09.repository.Repository import Repository 10 | from seminar.group_911.seminar_09.service.CarService import CarService 11 | from seminar.group_911.seminar_09.service.ClientService import ClientService 12 | from seminar.group_911.seminar_09.service.RentalService import RentalService 13 | from seminar.group_911.seminar_09.service.UndoService import UndoService 14 | from seminar.group_911.seminar_09.util import print_repos_with_message 15 | 16 | 17 | def undo_example_medium(): 18 | undo_service = UndoService() 19 | client_repo = Repository() 20 | car_repo = Repository() 21 | 22 | ''' 23 | Start rental Controller 24 | ''' 25 | rent_repo = Repository() 26 | rent_validator = RentalValidator() 27 | rent_service = RentalService(undo_service, rent_validator, rent_repo, car_repo, client_repo) 28 | 29 | ''' 30 | Start client Controller 31 | ''' 32 | client_validator = ClientValidator() 33 | client_service = ClientService(undo_service, rent_service, client_validator, client_repo) 34 | 35 | ''' 36 | Start car Controller 37 | ''' 38 | car_validator = CarValidator() 39 | car_service = CarService(undo_service, rent_service, car_validator, car_repo) 40 | 41 | ''' 42 | We add 3 clients 43 | ''' 44 | sophia = client_service.create(103, "2990511035588", "Sophia") 45 | carol = client_service.create(104, "2670511035588", "Carol") 46 | bob = client_service.create(105, "2590411035588", "Bob") 47 | print_repos_with_message("We added 3 clients", client_repo, None, None) 48 | 49 | ''' 50 | We delete 2 of the clients 51 | ''' 52 | client_service.delete(103) 53 | client_service.delete(105) 54 | print_repos_with_message("Deleted Sophia and Bob", client_repo, None, None) 55 | 56 | ''' 57 | We undo twice 58 | ''' 59 | undo_service.undo() 60 | print_repos_with_message("1 undo, so Bob is back", client_repo, None, None) 61 | undo_service.undo() 62 | print_repos_with_message("Another undo, so Sophia is back too", client_repo, None, None) 63 | 64 | ''' 65 | We redo once 66 | ''' 67 | undo_service.redo() 68 | print_repos_with_message("1 redo, so Sophia is again deleted", client_repo, None, None) 69 | 70 | 71 | undo_example_medium() 72 | -------------------------------------------------------------------------------- /src/seminar/group_912/seminar_09/UndoExampleMedium.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Nov 17, 2018 3 | 4 | @author: Arthur 5 | """ 6 | from seminar.group_912.seminar_09.domain.Car import CarValidator 7 | from seminar.group_912.seminar_09.domain.Client import ClientValidator 8 | from seminar.group_912.seminar_09.domain.Rental import RentalValidator 9 | from seminar.group_912.seminar_09.repository.Repository import Repository 10 | from seminar.group_912.seminar_09.service.CarService import CarService 11 | from seminar.group_912.seminar_09.service.ClientService import ClientService 12 | from seminar.group_912.seminar_09.service.RentalService import RentalService 13 | from seminar.group_912.seminar_09.service.UndoService import UndoService 14 | from seminar.group_912.seminar_09.util import print_repos_with_message 15 | 16 | 17 | def undo_example_medium(): 18 | undo_service = UndoService() 19 | client_repo = Repository() 20 | car_repo = Repository() 21 | 22 | ''' 23 | Start rental Controller 24 | ''' 25 | rent_repo = Repository() 26 | rent_validator = RentalValidator() 27 | rent_service = RentalService(undo_service, rent_validator, rent_repo, car_repo, client_repo) 28 | 29 | ''' 30 | Start client Controller 31 | ''' 32 | client_validator = ClientValidator() 33 | client_service = ClientService(undo_service, rent_service, client_validator, client_repo) 34 | 35 | ''' 36 | Start car Controller 37 | ''' 38 | car_validator = CarValidator() 39 | car_service = CarService(undo_service, rent_service, car_validator, car_repo) 40 | 41 | ''' 42 | We add 3 clients 43 | ''' 44 | sophia = client_service.create(103, "2990511035588", "Sophia") 45 | carol = client_service.create(104, "2670511035588", "Carol") 46 | bob = client_service.create(105, "2590411035588", "Bob") 47 | print_repos_with_message("We added 3 clients", client_repo, None, None) 48 | 49 | ''' 50 | We delete 2 of the clients 51 | ''' 52 | client_service.delete(103) 53 | client_service.delete(105) 54 | print_repos_with_message("Deleted Sophia and Bob", client_repo, None, None) 55 | 56 | ''' 57 | We undo twice 58 | ''' 59 | undo_service.undo() 60 | print_repos_with_message("1 undo, so Bob is back", client_repo, None, None) 61 | undo_service.undo() 62 | print_repos_with_message("Another undo, so Sophia is back too", client_repo, None, None) 63 | 64 | ''' 65 | We redo once 66 | ''' 67 | undo_service.redo() 68 | print_repos_with_message("1 redo, so Sophia is again deleted", client_repo, None, None) 69 | 70 | 71 | undo_example_medium() 72 | -------------------------------------------------------------------------------- /src/seminar/group_917/seminar_09/UndoExampleMedium.py: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Nov 17, 2018 3 | 4 | @author: Arthur 5 | """ 6 | from seminar.group_917.seminar_09.domain.Car import CarValidator 7 | from seminar.group_917.seminar_09.domain.Client import ClientValidator 8 | from seminar.group_917.seminar_09.domain.Rental import RentalValidator 9 | from seminar.group_917.seminar_09.repository.Repository import Repository 10 | from seminar.group_917.seminar_09.service.CarService import CarService 11 | from seminar.group_917.seminar_09.service.ClientService import ClientService 12 | from seminar.group_917.seminar_09.service.RentalService import RentalService 13 | from seminar.group_917.seminar_09.service.UndoService import UndoService 14 | from seminar.group_917.seminar_09.util import print_repos_with_message 15 | 16 | 17 | def undo_example_medium(): 18 | undo_service = UndoService() 19 | client_repo = Repository() 20 | car_repo = Repository() 21 | 22 | ''' 23 | Start rental Controller 24 | ''' 25 | rent_repo = Repository() 26 | rent_validator = RentalValidator() 27 | rent_service = RentalService(undo_service, rent_validator, rent_repo, car_repo, client_repo) 28 | 29 | ''' 30 | Start client Controller 31 | ''' 32 | client_validator = ClientValidator() 33 | client_service = ClientService(undo_service, rent_service, client_validator, client_repo) 34 | 35 | ''' 36 | Start car Controller 37 | ''' 38 | car_validator = CarValidator() 39 | car_service = CarService(undo_service, rent_service, car_validator, car_repo) 40 | 41 | ''' 42 | We add 3 clients 43 | ''' 44 | sophia = client_service.create(103, "2990511035588", "Sophia") 45 | carol = client_service.create(104, "2670511035588", "Carol") 46 | bob = client_service.create(105, "2590411035588", "Bob") 47 | print_repos_with_message("We added 3 clients", client_repo, None, None) 48 | 49 | ''' 50 | We delete 2 of the clients 51 | ''' 52 | client_service.delete(103) 53 | client_service.delete(105) 54 | print_repos_with_message("Deleted Sophia and Bob", client_repo, None, None) 55 | 56 | ''' 57 | We undo twice 58 | ''' 59 | undo_service.undo() 60 | print_repos_with_message("1 undo, so Bob is back", client_repo, None, None) 61 | undo_service.undo() 62 | print_repos_with_message("Another undo, so Sophia is back too", client_repo, None, None) 63 | 64 | ''' 65 | We redo once 66 | ''' 67 | undo_service.redo() 68 | print_repos_with_message("1 redo, so Sophia is again deleted", client_repo, None, None) 69 | 70 | 71 | undo_example_medium() 72 | -------------------------------------------------------------------------------- /src/seminar/group_911/seminar_11/main.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | 3 | from seminar.group_911.seminar_09.domain.Car import Car 4 | from seminar.group_911.seminar_09.domain.Client import Client 5 | from seminar.group_911.seminar_09.domain.Rental import Rental 6 | from seminar.group_911.seminar_11.repository.Repository import Repository 7 | 8 | alice = Client(101, "2801010266699", "Alice") 9 | bob = Client(102, "1800101248899", "Bob") 10 | carol = Client(103, "2670511035588", "Carol") 11 | sophia = Client(104, "2990511035588", "Sophia") 12 | 13 | hyundai_tucson = Car(201, "CJ 02 TWD", "Hyundai", "Tucson") 14 | toyota_corolla = Car(202, "CJ 02 FWD", "Toyota", "Corolla") 15 | dacia_sandero = Car(203, "IS 99 RTY", "Dacia", "Sandero") 16 | 17 | # 301, 104, 201, 2016-11-1, 2016-11-30 18 | # when loading, first load client 104 and car 201 -> then load rental repo data 19 | rental_sophia_tucson = Rental(301, date(2016, 11, 1), date(2016, 11, 30), sophia, hyundai_tucson) 20 | rental_sophia_toyota = Rental(302, date(2016, 12, 1), date(2016, 12, 31), sophia, hyundai_tucson) 21 | rental_bob_dacia = Rental(303, date(2021, 12, 1), date(2021, 12, 31), bob, dacia_sandero) 22 | 23 | """ 24 | 1. Start up an in-memory repository 25 | """ 26 | car_repo = Repository() 27 | car_repo.store(hyundai_tucson) 28 | car_repo.store(toyota_corolla) 29 | car_repo.store(dacia_sandero) 30 | 31 | client_repo = Repository() 32 | client_repo.store(alice) 33 | client_repo.store(bob) 34 | client_repo.store(carol) 35 | client_repo.store(sophia) 36 | 37 | rental_repo = Repository() 38 | rental_repo.store(rental_sophia_toyota) 39 | rental_repo.store(rental_sophia_tucson) 40 | rental_repo.store(rental_bob_dacia) 41 | 42 | # TODO Implement 2. and test it in a PyUnit test case 43 | """ 44 | 2. Switch to a text-file based repository 45 | """ 46 | 47 | 48 | class CarTextFileRepo(Repository): 49 | pass 50 | 51 | 52 | class ClientTextFileRepo(Repository): 53 | pass 54 | 55 | 56 | class RentalTextFileRepo(Repository): 57 | pass 58 | 59 | 60 | # TODO Implement 3. and test it in a PyUnit test case 61 | # use pickle or another Python serialization library 62 | """ 63 | 3. Implement a binary file repository 64 | """ 65 | 66 | 67 | class BinaryFileRepo(Repository): 68 | pass 69 | 70 | 71 | """ 72 | 4. Implement a single text file Repository 73 | """ 74 | 75 | 76 | # TODO 77 | # pass a function reference (callable type) to __init__ to convert between and 78 | # _to_ (e.g. car_to_str) 79 | # _to_ (e.g. str_to_car) 80 | class TextFileRepo(Repository): 81 | def __init__(self, entity_to_str, str_to_entity): 82 | super().__init__() 83 | --------------------------------------------------------------------------------