Added POP and functional programming. /JL

This commit is contained in:
Jan Lerking
2024-10-24 11:34:26 +02:00
parent 13f8d38ad3
commit 19c074ae52

View File

@@ -1,12 +1,20 @@
"""
A short description of the 3 main programming paradigms in Python
- Object oriented Programming - OOP
- Procedure Oriented programming
- Object Oriented Programming - OOP
- Procedure Oriented programming - POP
- Functional programming
"""
# Object Oriented Programming - OOP
# This style of programming revolves around objects (classes) as the key element.
# Advantages
# - Easy to describe real world objects and capabilities.
# - Easy to reuse code
# - Easy to abstract
# Disadvantages
# - Hard to data protect
# - Can't be used for all types of problems
# - Slow execution speed
# Lets say you're building cars.
# A car can be split into several components, each described by a class.
# i.e. Chassis, Wheels, Engine, Interior
@@ -60,4 +68,55 @@ class Car:
if __name__ == "__main__":
mycar = Car()
print(mycar.chassis.type)
print(mycar.engine.type, str(mycar.engine.cylinder)+" Cylinder", str(mycar.engine.volume)+" Litre", mycar.engine.fuel)
print(mycar.engine.type, str(mycar.engine.cylinder)+" Cylinder", str(mycar.engine.volume)+" Litre", mycar.engine.fuel)
# Procedural Oriented Programming - POP
# Computational steps are divided into separate modules containing grouped functions.
# Computations will be done step by step, by calling these functions in turn.
# Advantages
# - General-purpose programming
# - Code reusability
# - Portable code
# Disadvantages
# - Hard to data protect
# - Not suitable for real-world objects
# - Harder to write
# Example
numbers = [1, 2, 3, 4]
def sum_number_list(number_list) -> int|float:
res = 0
for val in number_list:
res += val
return res
print(sum_number_list(numbers))
# Function Programming
# Everything is bind in pure mathematical functions style.
# Functions are mathematical functions and statements are treated as
# functional expression being executed to generate a value.
# Lambda functions or recursion are usually used for implementation.
# This is a 'what to solve' as opposed to 'how to solve' paradigm.
# Advantages
# - Simple to understand
# - Easier debugging and testing
# - Better comprehension and code readability
# Disadvantages
# - Low performance
# - Writing programs is a masive task
# - Harder to read code
# Example
import functools
mylist = [11, 22, 33, 44]
def sum_the_list(mylist):
if len(mylist) == 1:
return mylist[0]
else:
return mylist[0] + sum_the_list(mylist[1:])
print(functools.reduce(lambda x, y: x + y, mylist))