Documente Academic
Documente Profesional
Documente Cultură
PROGRAMMING PARADIGM
A programming paradigm is a fundamental style of computer programming, serving as a way of
building the structure and elements of computer programs. Capabilities and styles of various
programming languages are defined by their supported programming paradigms; some
programming languages are designed to follow only one paradigm, while others support multiple
paradigms.
Programming paradigms that are often distinguished include imperative, declarative, functional,
object-oriented, procedural, logic and symbolic programming. With different paradigms, programs
can be seen and built in different ways; for example, in object-oriented programming, a program is
a collection of objects interacting in explicitly defined ways, while in declarative programming the
computer is told only what the problem is, not how to actually solve it.
Pointer
A pointer is a data type whose value refers directly to (or "points to") another value stored elsewhere
in the computer memory using its address.
Pointers are incredibly important computing concepts as we need pointers to create many of the
ADTs (Abstract Data Types) we are going to talk about. Some languages don't allow you to directly
manipulate them, but all languages use them. For this section of the book you need to be familiar
with the concept of pointers as we'll be using them heavily when we talk about linked lists, queues
and stacks.
Quick examples of pointers might include the next free memory location in an array, or the location
in memory that an array is stored at.
Example: Pointers
Let's take a look at how pointers are used in the C programming Language.
We are going to deal with two variables:
a
ptr
Assume that a is located at address 0x8130 in memory and ptr at 0x8134; also assume this is a
32-bit machine such that an int is 32-bits in size. The following is what would be in memory after
the following code snippet is executed:
int a = 5;
int *ptr = NULL;
Address Contents
0x8130 0x00000005
0x8134 0x00000000
(The NULL pointer shown here is 0x00000000.) By assigning the address of a to ptr :
ptr = &a;
*ptr = 8;
the computer will take the contents of ptr (which is 0x8130), 'locate' that address, and assign 8
to that location yielding the following memory:
Address Contents
0x8130 0x00000008
0x8134 0x00008130
Clearly, accessing a will yield the value of 8 because the previous instruction modified the
contents of a by way of the pointer ptr .
Enum suits
HEARTS = 1
CLUBS = 2
SPADES = 3
DIAMONDS = 4
End Enum
dim cardset as suits
cardset = suits.HEARTS
This allows you to set meaningful names to the enum and its members, meaning it easier to
remember and makes your code more readable.
We might also create separate constants to store the points of football results
With enums we can create a datatype called Result and store the points within it, under easy to
remember name:
Enum Result
Win = 3
Lose = 1
Draw = 0
End Enum
Exercise
Question:
Declare an enum called months that holds the months along with how many days
in each for a non-leap year
Answer:
Enum months
January = 31
February = 28
March = 31
April = 30
May = 31
June = 30
July = 31
August = 31
September = 30
October = 31
November = 30
December = 31
End Enum
Using composite data, we can manage multiple pieces of related data as a single datum. For
example if you wanted to store information about a person you could store there date of birth, sex,
address etc. as single variables but then when you wanted to add another person you would have
to remember to create all the variables but with slightly different names. As the number of people
increased so would the complexity of your naming and the relationship between the variables would
be lost. In ActionScript you could create an object called person which had properties to store the
date of birth, sex, address etc, you would then create instances of that object. The composite data
types that ActionScript supports are:
(array.
object.
movie clip.
functions.)
set,
record
class/object
SET
It is a composite data type that can store data in any particular order, in which each element is
indexed. Sets cannot have data items repeated more than once
Constructing Sets
One way to construct sets is by passing any sequential object to the "set" constructor.
We can also add elements to sets one by one, using the "add" function.
Note that since a set does not contain duplicate elements, if we add one of the members of s to s
again, the add function will have no effect. This same behavior occurs in the "update" function,
which adds a group of elements to a set.
Note that you can give any type of sequential structure, or even another set, to the update function,
regardless of what structure was used to initialize the set.
The set function also provides a copy constructor. However, remember that the copy constructor
will copy the set, but not the individual elements.
>>> s2 = s.copy()
>>> s2
set([32, 9, 12, 14, 54, 26])
Membership Testing
We can check if an object is in the set using the same "in" operator as with sequential data types.
>>> 32 in s
True
>>> 6 in s
False
>>> 6 not in s
True
We can also test the membership of entire sets. Given two sets S1 and S2, we check if S1 is a subset or
a superset of S2.
Note that "issubset" and "issuperset" can also accept sequential data types as arguments
Note that the <= and >= operators also express the issubset and issuperset functions respectively.
Like lists, tuples, and string, we can use the "len" function to find the number of items in a set.
Removing Items
There are three functions which remove individual items from a set, called pop, remove, and discard.
The first, pop, simply removes an item from the set. Note that there is no defined behavior as to which
element it chooses to remove.
>>> s = set([1,2,3,4,5,6])
>>> s.pop()
1
>>> s
set([2,3,4,5,6])
>>> s.remove(3)
>>> s
set([2,4,5,6])
>>> s.remove(9)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: 9
If you wish to avoid this error, use "discard." It has the same functionality as remove, but will simply do
nothing if the element isn't in the set
We also have another operation for removing elements from a set, clear, which simply removes all
elements from the set.
>>> s.clear()
>>> s
set([])
>>> s = set("blerg")
>>> for n in s:
... print n,
...
r b e l g
Set Operations
Python allows us to perform all the standard mathematical set operations, using members of set.
Note that each of these set operations has several forms. One of these forms, s1.function(s2) will
return another set which is created by "function" applied to S1 and S2. The other form,
s1.function_update(s2), will change S1 to be the set created by "function" of S1 and S2. Finally, some
functions have equivalent special operators. For example, s1 & s2 is equivalent to s1.intersection(s2)
Intersection
Any element which is in both S1 and S2 will appear in their intersection.
Union
The union is the merger of two sets. Any element in S1 or S2 will appear in their union.
Symmetric Difference
The symmetric difference of two sets is the set of elements which are in one of either set, but not in
both.
>>> s1 ^ s2
set([8, 1, 4, 9])
>>> s1.symmetric_difference_update(s2)
>>> s1
set([8, 1, 4, 9])
Set Difference
Python can also find the set difference of and , which is the elements that are in but not
in .
Multiple sets
Starting with Python 2.6, "union", "intersection", and "difference" can work with multiple input by using
the set constructor. For example, using "set.intersection()":
frozenset
A frozenset is basically the same as a set, except that it is immutable - once it is created, its members
cannot be changed. Since they are immutable, they are also hashable, which means that frozensets
can be used as members in other sets and as dictionary keys. frozensets have the same functions as
normal sets, except none of the functions that change the contents (update, remove, pop, etc.)
are available.
frozenset([4])
>>> fs.add(6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'
Exercises
1. Create the set {'cat', 1, 2, 3}, call it s.
2. Create the set {'c', 'a', 't', '1', '2', '3'}.
3. Create the frozen set {'cat', 1, 2, 3}, call it fs.
4. Create a set containing the frozenset fs, it should look like {frozenset({'cat', 2, 3, 1})}.
Records are collections of data items (fields) stored about something. They allow you to combine
several data items (or fields) into one variable. An example at your college they will have a database
storing a record for each student. This student record would contain fields such as ID, Name and
Date of Birth. The following example that DOESN'T USE RECORDS might be simple enough for one
student:
Sub Main()
Console.write("insert the id: ")
newStudentid = console.readline()
console.write("insert the name: ")
newStudentname = console.readline()
console.write("insert the Date of Birth: ")
newStudentDoB = console.readline()
console.writeline("new record created: " & newStudentid & " " &
newStudentname & " " & newStudentDoB)
End Sub
But what if your college has more than one student, we'd have to write:
It would take an awfully long time to declare them all, let alone saving writing data to them. So how
do we solve this? Well we need to combine two things we have learnt about so far, the record and
the array. We are going to make an array of student records:
Sub Main()
Dim newStudents(400) As student 'declare an array of student
records, a school with 401 students
newStudents(x).name = Console.ReadLine()
Console.WriteLine("insert the Date of Birth")
newStudents(x).DoB = Console.ReadLine()
next
for x = 0 to 400 'print out each student
Console.WriteLine("new record created: " & newStudents(x).id & "
" & newStudents(x).name & " " & newStudents(x).DoB)
next
End Sub
This seems to solve our problem, you might want to try it out yourself but decrease the number of
students slightly!
Exercise: Records
Declare a record called player to store the following Role Playing Game attributes: health,
name, characterclass (barbarian, wizard, elf), gold, gender
Answer
Enum type
WIZARD
BARBARIAN
ELF
End Enum
Exercise
Creates 2 characters, Gandolf and Conan using the player record
Answer :
Gandolf.name = "Gandolf"
Gandolf.health = 70
Gandolf.gold = 50
Gandolf.gender = "m"
Gandolf.characterclass = type.WIZARD
CLASS
In object-oriented programming , a class is a template definition of the method s and variable s in a
particular kind of object . Thus, an object is a specific instance of a class; it contains real values
instead of variables.
Classes
Structures are very similar to Classes in that they collect data together. However, classes extend this
idea and are made from two different things:
Attributes - things that the object stores data in, generally variables.
Methods - Functions and Procedures attached to an Object and allowing the object to perform
actions
class car
private maxSpeed as integer
public fuel as integer
You can see that the class is called car and it has:
Remember this is a class and therefore only a template, we need to 'create' it using an object
Attributes
These store information about the object. In the example above we store the fuel and maxSpeed.
The attributes are attached to the classes, and if there are several instances (objects) of the classes
then each will store its own version of these variables. Note that instead of the usual dim, there is the
word private or public, we'll cover that in the encapsulation section.
Methods
Unlike structures, OOP allows you to attach functions and procedures to your code. This means that
not only can you store details about you car (the attributes), you can also allow for sub routines such
as drive() and refuel, which are attached to each class.
1. Question:
What is the difference between a class and an object?
Answer :
A class is a template which cannot be executed
An object is an instance of a class which can be executed
one class can be used to make many objects
2. Question:
What are the main components of a class?
Answer :
methods and attributes
3. Question:
What is the difference between a structure and a class
Answer :
Structures don't have methods
In most programming languages, all basic data types are built-in. In addition, many languages also
provide a set of composite data types. Opinions vary as to whether a built-in type that is not basic
should be considered "primitive"