DATA ANALYTICS REFERENCE DOCUMENT |
|
---|---|
Document Title: | 52960 - Multi-Paradigm Programming |
Document No.: | 1569071117 |
Author(s): | Gerhard van der Linde, Rita Raher |
Contributor(s): |
REVISION HISTORY
Revision | Details of Modification(s) | Reason for modification | Date | By |
---|---|---|---|---|
0 | Draft release | Document description here | 2019/09/21 13:05 | Gerhard van der Linde |
LUI R1, #1 LUI R2, #2 DADD R3, R1, R2
(In fact this is syntactically valid in a lot of languages)
x = 1 + 2;
given point in the program's execution, is called the program's state.
var total = 0; var a = 1; var b = 5; total = a + b print total;
We shall have a brief look at each of these….
Goals of this session
Goals
Very General Structure First do this and next do that, then repeat this 10 times, then finish
Listing 1: Very Simple Function in Python
def my_function(): print("Hello from a function") my_function()
Listing 2: Slightly less simple Function in Python
def print_list(food): for x in food: print(x) fruits = ["apple", "banana", "cherry"] print_list(fruits)
Listing 3: C Language Example (Procedural)
#print numbers from 1 to 10 # include <stdio.h> int main(){ int i; for (i=1; i<11; ++i) { printf("%d ", i); } return 0; }
Listing 3: Python Language Example (Procedural)
def myFunction(): a = 0 for a in range(0, 10): a += 1 # Same as a = a + 1 print (a, sep=' ', end=' ', flush=True) myFunction()
Listing 4: Imperative with go-to
result = [] i = 0 start: numPeople = length(people) if i >= numPeople goto finished p = people[i] nameLength = length(p.name) if nameLength <= 5 goto nextOne upperName = toUpper(p.name) addToList(result, upperName) nextOne: i = i + 1 goto start finished: return sort(result)
Listing 1: Assembly Code for Hello World
global _main extern _printf section .text _main: push message call _printf add esp, 4 ret message: db ’Hello, World!’, 10, 0
Listing 2: Hello World in Standards Compliant C
#include <stdio.h> int main(void) { printf("hello, world\n"); }
Listing 2: Hello World in Standards Compliant python
def helloworld(): print("Hello, world") helloworld()
Write a C program to print your name, date of birth. and mobile number
#include <stdio.h> int main(void) { printf("Name: Dominic Carr\n"); printf("DOB: June 12th, 1920\n"); printf("086-1910000\n"); }
Write a python program to print your name, date of birth. and mobile number
def personinfo(): print("Name: Dominic Carr") print("DOB: June 12th, 1920") print("086-1910000") personinfo()
Write a C program to print a block F using hash (#), where the F has a height of six characters and width of five and four characters
#include <stdio.h> int main() { printf("######\n"); printf("#\n"); printf("#\n"); printf("#####\n"); printf("#\n"); printf("#\n"); printf("#\n"); }
Python
def fpattern(): print("######") print("#") print("#") print("#####") print("#") print("#") print("#") fpattern()
Listing 3: Another Answer this time with a function
#include <stdio.h> void print(int times, char a) { for(int i = 0; i< times; i++) { printf("%c", a); } printf("\n"); } int main() { print(6,'#'); print(1,'#'); print(1,'#'); print(5,'#'); print(1,'#'); print(1,'#'); }
python
def fpattern(n): for i in range(n): print("#", end='', flush=True) print(" ") fpattern(5) fpattern(1) fpattern(1) fpattern(5) fpattern(1) fpattern(1)
Write a C program to compute the sum of the two given integer values. If the two values are the same, then return triple their sum.
#include <stdio.h> int sum(int a, int b) { if (a==b) { return (a+b)*3; } else { return (a+b); } } int main() { int res = sum(1,2); printf("Result is %d\n", res); res = sum(3,3); printf("Result is %d\n", res); }
Python
def sumUp(a, b): if(a==b): return(a+b)*3 else: return(a+b) result = sumUp(1,2) print("Result is", result) result = sumUp(3,3) print("Result is", result)
Listing 4: C Example of representing a Person
#include <stdio.h> struct person { int age; float weight; }; int main() { struct person *personPtr, person1; personPtr = &person1; printf("Enter age: "); scanf("%d", &personPtr->age); printf("Enter weight: "); scanf("%f", &personPtr->weight); printf("Age: %d\n", personPtr->age); return 0; }
https://www.onlinegdb.com/online_c_compiler and Compile our C code online!
We will take a look at some of the “elementary” questions @ https://adriann.github.io/programming_problems.html Other
#include <stdio.h> int main() { printf("Hello, World\n"); return 0; }
print("Hello World")
#include <stdio.h> int main() { char name[20]; printf("What is your name?"); fgets(name,20,stdin); printf("Hello %s", name); return 0; }
name = raw_input("What is your name?") print("Hello %s, How are you?" %(name))
#include <stdio.h> #include <string.h> int main() { char* name; printf("What is your name?"); gets(name); if ((strcmp(name,"Alice")==0) || (strcmp(name,"Bob")==0)) { printf("Hello %s\n", name); } else { printf("Hello lowly peasant!\n"); } return 0; }
name = raw_input("What is your name?") if (name=="Bob") or (name=="Alice"): print("Hello %s, How are you?" %(name)) else: print("Hello lowly peasant!")
#include <stdio.h> #include <string.h> int main() { int n; int sum = 0; printf("Please enter a Number: "); scanf("%d", &n); for(int i = 1; i<=n; i++) { sum += i; } printf("The sum of 1 to %d, was %d\n", n, sum); return 0; }
n = input("Enter a number: ") sum = 0 for i in range(1,n+1): sum = sum + i print("The sum of 1 to %d, was %d" % (n, sum))
#include <stdio.h> #include <string.h> int main() { int n; int sum = 0; printf("Please enter a Number: "); scanf("%d", &n); for(int i = 1; i<=n; i++) { if (((i%3)==0) || ((i%5)==0)) { sum += i; } } printf("The sum of 1 to %d, was %d\n", n, sum); return 0; }
n = input("Enter a number: ") sum = 0 for i in range(1,n+1): if ((i % 3)==0) or ((1 % 5)==0): print i sum = sum + i print("The sum of 1 to %d, was %d" % (n, sum))
#include <stdio.h> #include <string.h> #include <stdlib.h> int main() { int n, sum = 0; int product = 1; char* choice = (char*) malloc(10 * sizeof(char)); printf("Please enter a Number: "); scanf("%d", &n); printf("Do you want to do product or sum?"); scanf("%s", choice); if (strcmp(choice, "product")==0) { for(int i = 1; i<=n; i++) { product *= i; } printf("The product of 1 to %d, was %d\n", n, product); } else if (strcmp(choice, "sum")==0) { for(int i = 1; i<=n; i++) { sum += i; } printf("The sum of 1 to %d, was %d\n", n, sum); } return 0; }
n = input("Enter a number: ") kind = raw_input("Do you want to do sum or product? ") sum = 0 product = 1 if (kind == "sum"): for i in range(1,n+1): sum = sum + i print("The sum of 1 to %d, was %d" % (n, sum)) elif (kind == "product"): for i in range(1,n+1): product = product * i print("The product of 1 to %d, was %d" % (n, product)) else: print("I did not understand your request")
Questions:
// Write a C program to get the absolute difference between n and 51. // If n is greater than 51 return triple the absolute difference. #include <stdio.h> #include <string.h> #include <stdlib.h> int main() { int n,val; if (n>51){ } else { } return val; }
// Write a C program to check two given integers, and return // true if one of them is 30 or if their sum is 30 #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> int main() { int n1,n2,val; if (n1==30 || n2==30 ||n1+n2==30){ val=true; } else { val=false; } if(val==1){ } else { } return val; }
#include <stdio.h> #include <string.h> #include <stdlib.h> struct Product { char* name; double price; }; struct ProductStock { struct Product product; int quantity; }; struct Shop { double cash; struct ProductStock stock[20]; int index; }; struct Customer { char* name; double budget; struct ProductStock shoppingList[10]; int index; }; void printProduct(struct Product p) { } void printCustomer(struct Customer c) { for(int i = 0; i < c.index; i++) { printProduct(c.shoppingList[i].product); double cost = c.shoppingList[i].quantity * c.shoppingList[i].product.price; } } struct Shop createAndStockShop() { struct Shop shop = { 200 }; FILE * fp; char * line = NULL; size_t len = 0; ssize_t read; if (fp == NULL) while ((read = getline(&line, &len, fp)) != -1) { // printf("Retrieved line of length %zu:\n", read); // printf("%s IS A LINE", line); // create variables from the strings to populate the structures // create a variable to make a permanent copy of the string that is pointed to only in n // instanssiate the first structure to go into the second structure and insert the values in struct Product product = { name, price }; struct ProductStock stockItem = { product, quantity }; // as pointed out in the video, a lot happens in this line, see the detailed description below shop.stock[shop.index++] = stockItem; // printf("NAME OF PRODUCT %s PRICE %.2f QUANTITY %d\n", name, price, quantity); } return shop; } void printShop(struct Shop s) { for (int i = 0; i < s.index; i++) { printProduct(s.stock[i].product); } } int main(void) { // struct Customer dominic = { "Dominic", 100.0 }; // // struct Product coke = { "Can Coke", 1.10 }; // struct Product bread = { "Bread", 0.7 }; // // printProduct(coke); // // struct ProductStock cokeStock = { coke, 20 }; // struct ProductStock breadStock = { bread, 2 }; // // dominic.shoppingList[dominic.index++] = cokeStock; // dominic.shoppingList[dominic.index++] = breadStock; // // printCustomer(dominic); struct Shop shop = createAndStockShop(); printShop(shop); // printf("The shop has %d of the product %s\n", cokeStock.quantity, cokeStock.product.name); return 0; }
This line of code on line 75 is packed with functionality and important to understand in order to reproduce the functionality for the assignments.
shop.stock[shop.index++] = stockItem;
You need to refer to the Shop
structure defined on line 15 in the c code sample above. This structure is then instantiated on
line 49 and named shop
. This structure shop
contains another structure ProducStock
named stock
and an array of 20
of this is defined.
So in order to loop through this array the index is created that needs to be maintained and used to fill the right indexed positions.
So in summary shop
contains three named values, cash
, stock
and index
therefore lines 72 and 73 creates the new
structured values that is required to populate into the stock
variable.
So in the line shop.stock[shop.index++] = stockItem;
we insert into shop.stock
at indexed position shop.index
the new
value created in lines 72 and 73 stockItem
and while doing this incrementing shop.index
by one by appending the ++
in the line of code.
Coke Can, 1.10, 100 Bread, 0.7, 30 Spaghetti, 1.20, 100 Tomato Sauce, 0.80, 100 Big Bags, 2.50, 4
Listing 1: Person Class in Java
public final class Person { private final String name; private final int age; public Person(String name, int age) { this.name = name; this.age = age; } public String toString() { return name + " " + info; } public static void main(String[] args) { Person a = new Person("Alice", 12); Person b = new Person("John", 34); } }
Listing 2: Person Class in Ruby
class Person def initialize(name, age) @name = name @age = age end def name # labelname is only in scope within the name method labelname = "Fname:" return labelname + @name end end
Listing 3: C Example of representing a Person
#include <stdio.h> struct person { int age; float weight; }; int main() { struct person *personPtr, person1; personPtr = &person1; printf("Enter age: "); scanf("%d", &personPtr->age); printf("Enter weight: "); scanf("%f", &personPtr->weight); printf("Age: %d\n", personPtr->age); return 0; }
receiver_object.method_name(argument1, argument2, ...)
math_solver.add(12, 30)
class Mammal def breathe puts "inhale and exhale" end end class Lion < Mammal def speak puts "Roar!!!" end end
class Mammal def breathe puts "inhale and exhale" end end class Lion < Mammal ...... end class Monkey < Mammal ...... end
“an interface is a shared boundary across which two or more separate components of a computer system exchange information”
https://www.computerhope.com/jargon/i/imp-programming.htm
https://en.wikipedia.org/wiki/Abstraction_(computer_science)
“Write once, run anywhere” - Java Language Tagline
Listing 1: Hello Java World!
public class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); // Prints the string to the console. } }
class subClass extends superClass { //methods and fields }
Listing 2: Person Object in Java
public class Person { private int age; private String name; public Person(String name, int age){ this.name = name; this.age = age; } public void setAge(int age){ if (!(age <= 0 || age >= 110)){ this.age = age; } }
public class Person { private int age; private String name; public Person(String name, int age){ this.name = name; this.age = age; } public String toString(){ return "Name:" + this.name + " Age: " + this.age; } public static void main(String[] args) { Person a = new Person("John", 23); Person b = new Person("Paul", 51); System.out.println(a); System.out.println(b); } }
How to run a java file on a mac in terminal?
$ javac Person.java $ java Person
output:
# Name:John Age: 23
# Name:Paul Age: 51
public class Person { private String name; private int age; public Person(String n, int a){ this.name = n; this.age = a; } public String toString(){ return "Name:" + this.name + " Age: " + this.age; } public void setAge(int n){ if (n < 0){ // this line is a comment, we want to finish method and not modify the age return; } this.age = n; } }
public class PersonAppRunner{ public static void main(String[] args) { Person a = new Person("John", 23); Person b = new Person("Paul", 51); System.out.println(a); //a.age = -1; a.setAge(40); System.out.println(a); System.out.println(b); } }
//inheritance example public class Student extends Person{ private String[] classes; public Student(String n, int a, String[] c){ super(n, a); this.classes = c; } public String toString(){ String repr = super.toString() + "\nCLASSES: \n"; for(int i=0; i<classes.length; i++){ repr += classes[i] + "\n"; } return repr; } public static void main(String[] args){ String[] classes = new String[] {"Introduction to Maths", "Management for Computing", "Programming 1"}; Student s = new Student("Pramod", 58, classes); s.setAge(59); System.out.println(s); } }
Paul is 25
* It looks like the student prints out just like a Person as it calls the superclass toString method
class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("John", 36) print(p1.name) print(p1.age)
https://www.computerhope.com/jargon/i/imp-programming.htm https://en.wikipedia.org/wiki/Abstraction_(computer_science) https://www.guru99.com/java-class-inheritance.html https://www.w3schools.com/python/python_classes.asp
Programming by specifying the result you want, not how you get it.
SELECT UPPER(name) FROM people WHERE LENGTH(name) > 5 ORDER BY name
SELECT * FROM Worker ORDER BY FIRST_NAME ASC;
SELECT OrderID, Quantity, CASE WHEN Quantity > 30 THEN "The quantity is greater than 30" WHEN Quantity = 30 THEN "The quantity is 30" ELSE "The quanity is under 30" END AS QuantityText FROM OrderDetails;
Imagine the schema looks like:
personId INTEGER PRIMARY KEY, name VARCHAR(20), sex CHAR(1), birthday DATE, placeOfBrith VARCHAR(20);
How would we find teh oldest person in the table?
SELECT * FROM people ORDER BYY birthday ASC LIMIT 1;
#include <stdio.h> #include <string.h> #include <stdlib.h> struct Person{ char* name; char sex; int age; char* placeOfBirth; } int main(void){ struct Person a = {"Anthony Stynes","M", 12, "New York"}; struct Person b = {"Bertie Corr", "M", 1000, "Boston"}; struct Person c = {"John Quin", "M", 33, "'Murica"}; } struct Person arr[] = {a, b, c}; int maxAge = -1; int index = 0; for(int 1=0;i<3;i++){ if(int i=0;i<3; i++){ maxAge=arr[i].age; index=i; } } printf("%s is oldest\n", arr[index].name); return 0; }
Greg Kemnitz, Postgres internals, embedded device db internals MySQL user level
“I wrote a reporting query once that was 700 lines long and visited 27 different tables in lookups or joins. It didn't do any fancy stuff - just straigh whereclause predicates and joiing - but it was pretty gnarly and took 3 days to compose, debug and tune”
Bill Karwin, author of “SQL Antipatterns: Avoiding the pitfalls of database programming”
“One of the fun, complex sql queries I wrote was for a demo I did during a talk at OSCON 2006, SQL Outer Joins for Fun and Profit. It was a query that solved Sudoku puzzles”
CFLAGS ?= -g all:helloworld helloworld: helloworld.o # Commands start with TAB not spaces $(CC) $(LDFLAGS) -o $@ $^ helloworld.o : helloworld.c $(CC) $(CFLAGS) -c -o $@ $< clean: FRC rm -f helloworld helloworld.o #This pseudo target causes all targets that depend on FRC # to be remade even in case a file with the name of the target exists # this works with any make implementation under the assumption that # there is no file FRC in the current directory FRC:
Functional programming is a subset of declarative programming.
Covered in this section:
Functional programming languages are declarative, meaning that a computation’s logic is expressed without describing its control flow Some languages support functional programming constructs without being purely functional.
Referential transparency is generally defined as the fact that an expression, in a program, may be replaced by its value (or anything having the same value) without changing the result of the program.
In other words we can replace any called to a pure function with it’s result as the function result depends only on it’s inputs.
def add(a, b): return a + b def mult(a, b): return a * b x = add(2, mult(3, 4)) print x
call_counter = 0 def add(a, b): return a + b def mult(a, b): global call_counter call_counter = call_counter + 1 return a * b x = add(2, mult(3, 4)) print x
Definition
class Person: def __init__(self, name, surname, age): self.name = name self.surname = surname self.age = age def can_vote(self, voting_age): if (self.age > voting_age): return True else: return False person = Person("Jane", "Doe", 12) print person.can_vote(18) person.age = 19 print person.can_vote(18)
#Consider the following addition to the person class: def same(self,p): if (p.name == self.name): p.name = "side effect" return True else: p.age = 101 return False #If we have person = Person( "Jane", "Doe", 12 ) john = Person( "John", "Joe", 59 ) #and we perform print person.same(john) print john.age
are there side effects?
Consider this example:
limit = 100 def calculatebonus(num_sales): return 0.10 * num_sales if num_sales > limit else 0 def calculatebonus2(numSales): return 0.10 * num_sales if num_sales > 100 else 0 print(calculatebonus2(174))
Of the two functions, which is pure and which is not pure?
The answer is option one is impure because limit exists outside the function and affects the outcome in unpredictable ways.
Definition
“Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem (as opposed to iteration). The approach can be applied to many types of problems, and recursion is one of the central ideas of computer science”
Mostly this means that the programming language allows a method to invoke itself.
Definition
“In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones”
0, 1, 1, 2, 3, 5, 8, 13, 21, 34…
Listing 1: Algorithm to determine the nth fibonacci number
def fib(n): if (n==1): return 0 a = 0 b = 1 for i in range(2,n): c = a + b a = b b = c return b for i in range(1,10): print fib(i)
This is an iterative solution to calculating the nth Fibonacci number, put simply this means that it is a method / function which loops to repeat some part of the code. A recursive method is one which calls itself to repeat the code.
This is an iterative solution to calculating the nth Fibonacci number, put simply this means that it is a method / function which loops to repeat some part of the code. A recursive method is one which calls itself to repeat the code.
Listing 2: Output of the program
0 1 1 2 3 5 8 13 21
So do we achieve a recursive solution for this problem?
File “1.py”, line 2, in fib
return fib(n-1) + fib(n-2)
RuntimeError: maximum recursion depth exceeded
For the Fibonacci we can define three conditions:
Listing 3: Recursive implementation of fib
def fib(n): if (n==1 or n==0): return n return fib(n-1) + fib(n-2) for i in range(1,10): print fib(i)
What we have done in this specific case can be applied to all recursive algorithms. As all such algorithms must have the following properties to operate.
Definition
“In mathematics, the factorial of a non-negative integer n, denoted by n!,is the product of all positive integers less than or equal to n.”
5! = 5 × 4 × 3 × 2 × 1 = 120
Listing 4: Iterative calculation of the factorial of n
def factorial(n): factorial = 1; for i in range(2,n+1): factorial = factorial * i return factorial print factorial(5)
How to do it recursively?
Listing 5: Recursive solution to factorial of N)
def factorial(n): if (n == 0): return 1 return n * factorial(n-1); print factorial(5)
Why do we not need a condition for 1 as a special case?
Recursive solutions to the following:
def pow(num, power): if (power == 1): return num return num * pow(num, power-1) if __name__ == '__main__': v=pow(3,4) print('{}'.format(v))
def palindrome(word): length = len(word) #print("length was %d" % length) if (length <= 1): return True #print( "comparing %s with %s result is %r" % (word[0], word[length-1], (word[0] == word[length-1]))) return (word[0] == word[length-1]) and palindrome(word[1:length-1]) if __name__ == '__main__': print('{}'.format(palindrome('madam')))
def reverse(word): length = len(word) if (length <= 1): return word return word[length-1] + reverse(word[:length-1]) if __name__ == '__main__': print('{}'.format(reverse('cinimod')))
This example in Python 2.7, the code below does not work for 3.7.
class StringIterator: def __init__(self, string): self.string = string self.index = 0 self.length = len(string) def __iter__(self): return self def next(self): if self.index >= self.length: raise StopIteration else: self.index+=1 return self.string[self.index-1] print filter((lambda x: x != "i"), StringIterator("dominic"))
x = [1,2,3,4,5,6] square = lambda x: x * x print (square(2)) result = list(map(square, x)) print (result) print (list(map(square, result)))
import functools print(functools.reduce((lambda x, y: x + y), [1,2,3,4,5,6])) # 21 print(list(filter((lambda x: x > 3), [1,2,3,4,5,6]))) #[4, 5, 6]