Tuesday, 30 January 2024

Looping over the dictionary using items() method in Python

Using items() method, we can iterate over a dictionary.

>>> emp_dict = {'id' : 1, 'name' : 'Krishna', 'age' : 34}
>>> 
>>> for key, value in emp_dict.items():
...   print(f'{key} --> {value}')
... 
id --> 1
name --> Krishna
age --> 34

 

Above code demonstrates how to iterate over a dictionary and print its key-value pairs.

 

emp_dict = {'id' : 1, 'name' : 'Krishna', 'age' : 34}

This line creates a dictionary named emp_dict. A dictionary in Python is a collection of key-value pairs. Here, the dictionary represents an employee with three pieces of information: their 'id' (which is 1), 'name' (which is 'Krishna'), and 'age' (which is 34).

 

for key, value in emp_dict.items():

This line starts a for loop. The .items() method is called on the dictionary emp_dict. This method returns a view object that displays a list of dictionary's (key, value) tuple pairs.

 

In each iteration of the loop, key and value will be assigned to the corresponding pair of items from the dictionary. For instance, in the first iteration, key will be 'id' and value will be 1, in the second iteration, key will be 'name' and value will be 'Krishna', and so on.

 

 

Previous                                                 Next                                                 Home

Think Differently, Code Differently: Demystifying Functional Programming

Functional programming is a different way of thinking about and writing code compared to structural, object-oriented programming. Here are some key principles of functional programming. I am using a functional programming language ‘Haskell’ to demonstrate the examples.

 

1. Functions are first class citizen

Functions are the basic building blocks in functional programming, unlike object oriented programming languages; a function is not enclosed inside a class. A function can be passed as an argument to other function, a function can return result as a function, You can assign a function to a variable etc., In summary, you can use a function like variable.

 

Example

let sum x y = (x + y)

 

Above statement define a function named sum, which takes two number arguments and return the sum of two numbers. In Haskell, let key word is used to define variables, functions in Haskell interpreter.

 

2. Pure functional programming is side effect free

A Pure functional programming language has no side effects. A function is said to have side effect, if the result is not completely depend on its arguments. For example, a particular function might modify a global variable or static variable, modify one of its arguments, raise an exception, write data to a display or file, read data, or call other side-effecting functions. In the presence of side effects, a program's behaviour may depend on history.

 

For example, observe following code.

 

public class ProcessData {
 private static int x = 10;

 public static int f(int a) {
  x = x + a;
  return x;
 }

 public static int g(int a) {
  x = x * a;
  return x;
 }
}

 

Result of functions f, g is depend on the global variable x, and result is also depend on the order of execution of functions f, g.

 

If you call function f(5) first followed by g(5), then f(5) return 15, g(5) return 75. If you call function g(5) first followed by f(5), then f(5) return 55, g(5) return 50.

 

A side effect free function always returns same value for same input, i.e., it doesn’t depend on any global variable, external data, and order of executions.

 

Note

Side effects (Such as writing data to external systems, read data from networks etc.,) are still possible in Haskell, but Haskell is designed like that, it separates the pure code from impure(side-affect) code.

 

3. Functional programming is lazy

In functional programming, expressions are not evaluated until their results are actually needed.

Prelude> take 5 [1..]
[1,2,3,4,5]

 

[1..] represent infinite list, take function takes a number ‘n’ and list as arguments and return first ‘n’ number of elements.

 

4. Immutable data

In functional programming, data is immutable. Once created, a data structure cannot be altered. Any modifications to a data structure result in a new data structure. This leads to safer and more predictable code, especially in concurrent and parallel programming

 

5. Function composition is every where

A function output can be passed as input to other function. Combining functions by passing output of one function as input to other function is called composition of functions.

 

For example,

Let g(x) = 2x, f(x) = x + 1

then

f(g(x)) = f(2x) = 2x + 1

g(f(x)) = g(x+1) = 2 (x+1) = 2x + 2

Prelude> let g x = 2 * x
Prelude> let f x = x + 1
Prelude> 
Prelude> f(g 10)
21
Prelude> g(f 10)
22

 

6. Advantages of Functional Programming:

 

a.   Reliable program: The use of immutable data and pure functions reduces the likelihood of bugs in the software.

b.   Better modularity and easier maintenance: The declarative nature and modular structure of the code make it simpler to comprehend, test, and troubleshoot.

c.    Effecient concurrent execution: The inherent parallelism of pure functions makes them ideal for use in environments with multiple cores and distributed systems.

 

Common functional programming languages include Haskell, Lisp, Erlang, Scala, and Clojure, though many modern languages like JavaScript, Python, and Ruby support functional programming concepts to varying degrees.

 

7. Quick sort algorithm in Haskell

Following snippet implements quick sort algorithm. By looking into the code, you can easily guess what is happening here.

qsort [] = []
qsort (x:xs) = (qsort left) ++ [x] ++ (qsort right)
               where
                   left = filter (<= x) xs
                   right = filter (> x) xs

Function Definition:

The program defines a function named qsort. In Haskell, functions are defined by specifying the function name, followed by its parameters. Here, qsort takes one parameter, which is a list.

 

Pattern Matching:

Haskell uses pattern matching to decide what action to take based on the input. In this case, qsort has two definitions:

 

qsort [] = []: This is the base case. It states that if qsort is called with an empty list ([]), it should return an empty list. This is an example of a base case in a recursive function.

 

qsort (x:xs): This is the recursive case. It's saying "if qsort is called with a non-empty list, split the list into a head (x) and a tail (xs). x is the first element of the list, and xs is the rest of the list.

 

Recursion:

qsort is defined in terms of itself, which is a common pattern in functional programming known as recursion. The sorted list is obtained by recursively sorting two smaller lists and then concatenating them together with the pivot element (x).

 

The where Clause:

This is a way to define local variables in Haskell. In this instance, left and right are two lists, defined as follows:

 

a.   left = filter (<= x) xs: This creates a list of all elements in xs that are less than or equal to x. It uses the filter function which, as its name suggests, filters a list based on a given condition.

b.   right = filter (> x) xs: Similarly, this list contains all elements in xs that are greater than x.

 

List Concatenation:

The ++ operator is used to concatenate lists. So, (qsort left) ++ [x] ++ (qsort right) means: take the sorted left list, concatenate it with a list containing only x, and then concatenate the result with the sorted right list.

 

Functional Concepts used in this program:

a.   Immutability: The list being sorted is never modified; instead, new lists are created during the sorting process.

b.   Pure Functions: qsort is a pure function. Given the same input list, it always produces the same output without causing any side effects.

c.    Recursion: Rather than using loops, qsort achieves repetition through recursive function calls.

d.   Understanding this program gives insight into functional programming's emphasis on using functions, recursion, and immutable data to create clear and concise programs.

 

In summary, although functional programming provides numerous advantages, it is not universally suitable for all scenarios. Imperative programming continues to dominate various fields, and adopting a functional programming approach needs a different mindset. Nonetheless, gaining knowledge of functional programming principles can be advantageous for any programmer, enhancing their ability to write clear code and develop robust reasoning skills.



                                                           System Design Questions

PlantUML: concurrent state in state diagram

A concurrent state allows multiple state flows to operate at the same time.

Concurrent state is expressed using either -- or ||

 

concurrentState1.txt

@startuml

left to right direction

state init

state processing {
	[*] --> S1
	S1 --> [*]

-- [*] --> S2 S2 --> S3 S3 --> S4 S4 --> S5 S5 --> [*] -- [*] --> S6 S6 --> S7 S7 --> [*] } state terminate [*] --> init init --> processing processing --> terminate processing --> [*] @enduml

 

Above snippet generate below diagram.

 

 

Using ||

 

concurrentState2.txt

@startuml

left to right direction

state init

state processing {
	[*] --> S1
	S1 --> [*]
	--
	[*] --> S2
	S2 --> S3
	S3 --> S4
    S4 --> S5
    S5 --> [*]
	--
	[*] --> S6
	S6 --> S7
	S7 --> [*]
}

state terminate

[*] --> init
init --> processing
processing --> terminate
processing --> [*]

@enduml

Above snippet generate below diagram.


 


Note

I used ‘left to right direction’ to draw image1, you can experiment by removing.

Previous                                                    Next                                                    Home

PlantUML: fork and join in state diagram

<<fork>> and <<join>> stereotypes used to define fork, join states in state diagram.

 

forkJoinStates.txt

@startuml

left to right direction

state init

state process {
	state fork_state1 <<fork>>
	fork_state1 --> p1
	fork_state1 --> p2
	fork_state1 --> p3

	state join_state1 <<join>>
	p1 --> join_state1
	p2 --> join_state1
	p3 --> join_state1
}

[*] --> init
init --> process
process --> stop
stop --> [*]

@enduml

 Above snippet generate below diagram.

 


 

  

Previous                                                    Next                                                    Home

PlantUML: History state in uml diagram

History state is shown by a circle with an H inside it. When a transition  leads to a history state, instead of history state becomes active, the “most recently visited state” becomes active.

historyState.txt

@startuml

left to right direction

state "power off" as off #pink

state running #palegreen{
	state washing 
	state rinsing
	state spinning

        off --> [H] : restore power
}


[*] --> washing : start
washing --> rinsing
rinsing --> spinning
running --> off : power cut
running --> [*] : stop

@enduml

 

Above snippet generate below diagram.


  

Previous                                                    Next                                                    Home

Understanding Structured Programming: A Foundation for Code Clarity and Control

 

Structured programming is a way of writing computer programs that focuses on making them clear and easy to understand. It does this by using lots of smaller parts called subroutines or functions, along with blocks of code and loops (like "for" and "while" loops).

 

In a structured program, the main program is split into many functions, and each one does a specific job. These functions can also use other functions. This approach helps in making programs that are of better quality, easier to read, and faster to develop.

 

Prior to structured programming

Before structured programming became popular in the late 1950s and early 1960s, most programming was done in a unstructured way. This wasn't really a single, organized method, but more like a mix of different ways of writing programs that didn't have the organized and clear rules that structured programming brought in. Here are some main points about unstructured programming:

 

1.   Using a lot of GOTO statements: In unstructured programming, there was a big emphasis on GOTO statements. These let the program jump around to different parts at any time. This often led to messy and complicated "spaghetti code" that was hard to follow, with lots of jumps and connections. This made it really tough to understand, fix, and look after the code.

2.   Limited use of control flow statements: In unstructured programming, even though control structures like if-else were available, they weren't used as much or in a standard way like in structured programming. This resulted in using GOTO statements for simple decisions and loops, which added to the complexity and made the program harder to manage.

3.   Widespread use of global variables: In unstructured programming, there was a strong reliance on global variables, which any part of the program could access. This approach, without specific scopes, limited the program's modularity and created strong links between different parts of the code. As a result, it was easier to accidentally change things and cause unpredictable outcomes.

4.   No modularity: Programs in unstructured programming were often composed of big, single-piece blocks of code with little organization. This approach made it difficult to use the same code again in different parts or to work together effectively on the same project. As a result, it was harder to develop and maintain these programs efficiently.

5.   Emphasis on machine architecture: Unstructured programming often reflected the underlying architecture of the computers of the time, focusing on direct manipulation of memory and hardware details. This made code less portable and adaptable to different machines and operating systems. Example: Assembly language is a low-level language directly interacts with the computer's hardware and instructions.

While unstructured programming played a key role in the early days of computing, it ultimately reached its limitations due to the issues mentioned above. The adoption of structured programming with its emphasis on clarity, control, and modularity represented a significant step forward in software development, leading to more reliable, maintainable, and efficient code.

 

Problems with Unstructured Programming

1.   Tangled Code: Programs often didn't have a well-defined structure, looking more like a jumbled mix of GOTO statements and jumps. This made them hard to follow, maintain, and fix.

2.   Unpredictable Flow: The overuse of GOTO statements created chaotic and hard-to-predict paths through the code, which raised the chances of mistakes and surprising outcomes.

3.   Problems with Data Handling: The common use of global variables created strong dependencies and accidental changes in the code, leading to errors and unstable programs.

4.   Ineffecient Development: The repetitive nature of the code and the lack of organized sections made it harder to work efficiently and collaborate with others.

 

Key concepts of structured programming

1.   Structured programming guides how a program runs using three key concepts or tools:

 

a.    Sequential execution: The program runs commands in the exact order they appear in the code.

b.    Conditional statements (if-else): This lets the program choose between different actions depending on certain conditions. If a condition is met, it follows one group of commands; if not, it takes a different path.

c.    Loops (for, while): These are used to repeat actions in the program several times, usually until a specific condition is fulfilled.

2.   Use of Subroutines or Functions: In structured programming, there's a strong focus on using subroutines, also called functions or procedures. This approach helps in reusing code and keeping it organized into separate modules. Each subroutine is designed to perform a particular task and can be tested separately from the rest of the program, making it easier to manage and debug.

3.   Using Local Variables and Scope: Structured programming involves using local variables within specific subroutines or code blocks. This method helps keep different parts of the program separate, cutting down on interdependencies and the likelihood of mistakes. In this setup, each section or function has its own defined scope.

4.   Clear Control Flow: Structured programming uses loops and conditional structures for controlling program flow, rather than relying on goto statements, which can create messy code. This approach enhances the readability of the code. While programming languages might still have goto statements, their use is generally limited. For more insights, you can read the paper https://homepages.cwi.nl/~storm/teaching/reader/Dijkstra68.pdf  to get more information

5.   Breaking Down the Problem: In structured programming, you start by outlining the big picture of your program and then gradually split it into smaller, more specific parts. This step-by-step refinement helps in handling complex programs more easily, making them easier to understand and develop.

6.   Use of Global Variables: In structured programming, global variables are often used to hold data that different functions within the program might need. This is straightforward for small programs, but in larger ones, it can lead to issues and make the code more difficult to manage.

 

Example of structured programming

Imagine writing a program to calculate the area of different shapes. Using structured programming, you could define separate functions for calculating the area of a square, rectangle, triangle, and so on. Each function would take the necessary dimensions as input and return the calculated area. The main program could then prompt the user for the desired shape and dimensions, call the appropriate function, and display the result.

 

ShapeAreaCalculator.c 

#include <stdio.h>

// Function prototypes
double squareArea(double side);
double rectangleArea(double length, double width);
double triangleArea(double base, double height);
void calculateAndDisplayArea();

int main() {
    // Call the function that handles the area calculation and display
    calculateAndDisplayArea();
    return 0;
}

// Function to calculate the area of a square
double squareArea(double side) {
    return side * side;
}

// Function to calculate the area of a rectangle
double rectangleArea(double length, double width) {
    return length * width;
}

// Function to calculate the area of a triangle
double triangleArea(double base, double height) {
    return 0.5 * base * height;
}

// Function to handle user input, calculate and display the area
void calculateAndDisplayArea() {
    int choice;
    double area, side, length, width, base, height;

    printf("Choose a shape to calculate the area:\n");
    printf("1. Square\n2. Rectangle\n3. Triangle\n");
    printf("Enter your choice (1-3): ");
    scanf("%d", &choice);

    switch (choice) {
        case 1: // Square
            printf("Enter the length of the side of the square: ");
            scanf("%lf", &side);
            area = squareArea(side);
            printf("Area of the square: %.2lf\n", area);
            break;

        case 2: // Rectangle
            printf("Enter the length and width of the rectangle: ");
            scanf("%lf %lf", &length, &width);
            area = rectangleArea(length, width);
            printf("Area of the rectangle: %.2lf\n", area);
            break;

        case 3: // Triangle
            printf("Enter the base and height of the triangle: ");
            scanf("%lf %lf", &base, &height);
            area = triangleArea(base, height);
            printf("Area of the triangle: %.2lf\n", area);
            break;

        default:
            printf("Invalid choice.\n");
    }
}

Sample Output

Choose a shape to calculate the area:
1. Square
2. Rectangle
3. Triangle
Enter your choice (1-3): 2
Enter the length and width of the rectangle: 10 35
Area of the rectangle: 350.00

 

This program defines calculateAndDisplayArea function encapsulates the logic for prompting the user, receiving input, calculating the area, and displaying the result. Based on the user input, the call goes to squareArea, rectangleArea, triangleArea functions.

 

Popular structured programming languages

1.   C,

2.   Pascal,

3.   Ada,

4.   ALGOL,

5.   PL/I (Programming Language One).

 

Even though Java and Python supports object-oriented features, its core structure reflects a strong foundation in structured programming principles.

 

Benefits of Structured Programming

1.   Code is easy to understand and debug: The code is well-arranged and follows a straightforward path, which makes it simpler to grasp the program's operations and pinpoint potential errors.

2.   Modular and Reusable: Functions can be reused in different programs, reducing redundancy and promoting code maintainability.

3.   Enhanced Readability: Programs written with this approach are easier to read and understand.

4.   Easier Testing and Debugging: The modular nature and separation of different parts of the program make testing and fixing issues more straightforward.

 

Drawbacks of Structured Programming

1.   Handling Complexity: As programs become bigger and more complex, managing global variables and function calls can become challenging.

2.   Less expressive: Compared to object-oriented and functional programming, structured programs are less expressive and might not be used for solving certain types of problems.

3.   Limited code reusability: Although structured programming allows for subroutine reuse within the same program, it doesn't naturally offer ways to easily reuse code across multiple programs. This is in contrast to Object-Oriented Programming (OOP), which focuses on objects and inheritance to facilitate code reuse.

 

In summary, structured programming laid the groundwork for further advancements in programming techniques, including object-oriented and functional programming.

 

 

                                                             System Design Questions