Programming

  • Algorithm A set of rules or steps used to solve a problem

  • Data Structure - A particular way of organizing data in a computer

Primitive data: one value in variable

primitive data type: int, float, str بيانات أولية وليست تجميعية ، فقط استطيع تخزين قيمة واحدة في المتغير

In [1]:
x = 10 
print(x)
x = 20 
print(x)
10
20

Store more than one value in one variable (collection)

List is a collect. We can store many values in one variable

In [2]:
x = [10, 20]
print(x)
print(type(x))
[10, 20]
<class 'list'>

Different types in one collection

In [3]:
# differet types in one collection 
x = [10, 'Ahmed']
print(x)
[10, 'Ahmed']
In [4]:
# different types: str, int, float
print(['red', 24, 98.6])
['red', 24, 98.6]

list constant

In [5]:
# list constant 
print(3)
print([1, 24, 76])
3
[1, 24, 76]

list in a list / collection in a collection

In [6]:
x = [1, [5, 6], 7]
print(x)
[1, [5, 6], 7]
In [7]:
print(x[0])
1
In [8]:
print(x[1])
[5, 6]
In [9]:
print(x[1][0])
5

Empty list

In [10]:
# empty lists 
x = []
y = list()
print('x = ', x)
print('y = ', y)
x =  []
y =  []
In [11]:
# Empty String 
empty_str = ''
print(empty_str)

iteration variable

In [12]:
# iteration variable 
for num in [5, 4, 3, 2, 1] :
    print(num)
print('Blastoff!')
5
4
3
2
1
Blastoff!
In [13]:
# iteration variable 
friends = ['Joseph', 'Glenn', 'Sally']
for name in friends:
    print('Happy New Year:',  name)
print('Done!')
Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
Done!

Looking inside the list

image.png

In [14]:
# loop using index
friends = ['Joseph', 'Glenn', 'Sally']
for i in range(len(friends)):
    print('Happy New Year:',  friends[i])
print('Done!')
Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
Done!
In [15]:
# access elements by index 
print(friends[1])
Glenn

mutable list: we can change the value of list elements

In [16]:
# mutable list 
friends[1] = 'Ahmed'
print(friends)
['Joseph', 'Ahmed', 'Sally']

immutable list (list of characters)

In [17]:
# immutable list 
fruit = 'banana'
print(fruit)
banana
In [18]:
print(fruit[1])
fruit[1] = 'e' # error 
a
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-18-8d0735ab921d> in <module>
      1 print(fruit[1])
----> 2 fruit[1] = 'e' # error

TypeError: 'str' object does not support item assignment
In [ ]:
# convert to mutable 
f = list(fruit)
print(f) # mutable 
f[1] = 'e'
print(f)
In [ ]:
fruit = ''.join(f)
print(fruit)

join a list of numbers

In [ ]:
# join list 
l1 = [1, 3, 10, 19]
print(l1)
l2 = [str(n) for n in l1]
print('\t'.join(l2))

loop on a list: way 1: iteration variable

In [ ]:
# loop on list 
friends = ['Joseph', 'Glenn', 'Sally']
# way 1: iteration variable 
for friend in friends :
    print('Happy New Year:',  friend)

loop on a list: way 2: using index

In [ ]:
# loop on list 
friends = ['Joseph', 'Glenn', 'Sally']
# way 2: index 
for i in range(len(friends)) :
    print('Happy New Year:',  friends[i])

list concatonation

In [1]:
a = [1, 2, 3]
b = [4, 5, 6]
# concat 
c = a + b 
print(c)
[1, 2, 3, 4, 5, 6]
In [ ]:
d = a - b # error 

sum 2 lists

In [2]:
# sum 2 lists 
a = [1, 2, 3]
b = [4, 5, 6]
c = [a[i] + b[i] for i in range(len(a))]  # using index 
print(c)
[5, 7, 9]
In [ ]:
# sum 2 lists 
a = [1, 2, 3]
b = [4, 5, 6]
c = [m + n for m, n in zip(a, b)] # using iteration variables  
print(c)

Understanding zip function

In [1]:
a = [1, 2, 3]
b = [4, 5, 6]
print(list(zip(a, b)))
[(1, 4), (2, 5), (3, 6)]

slicing a list

In [ ]:
# slicing a list 
t = [9, 41, 12, 3, 74, 15]
print(t)
print(t[2:4]) # index 2, 3 
In [ ]:
print(t[2:]) # index 2 to the end 
In [ ]:
print(t[:4]) # index 0 to 3 

list methods

In [2]:
# list mehtods 
t = [9, 41, 12, 3, 74, 15]
print(dir(t))
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

Append functions

In [ ]:
print(t)
t.append(10) # add 3 to the end of the list 
print(t)

Sum 2 lists using empty list with append

In [ ]:
# sum 2 lists using empty list with append 
a = [1, 2, 3]
b = [4, 5, 6]
c = []
print('before sum: c = ', c)
list_size = len(a)
for i in range(list_size):
    r = a[i] + b[i]
    c.append(r)
    print(i, c)
    
# in one line 
# c = [a[i] + b[i] for i in range(len(a))] 
# c = [m + n for m, n in zip(a, b)]

Count function

In [3]:
# count 
t = [9, 41, 12, 3, 74, 15]
print(t)
print(t.count(3))
[9, 41, 12, 3, 74, 15]
1
In [4]:
print(t.count(13))
0
In [5]:
print(t.count(74))
1
In [6]:
t.append(3)
print(t)
print(t.count(3))
[9, 41, 12, 3, 74, 15, 3]
2

Extend function

In [5]:
t = [9, 41, 12, 3, 74, 15]
print(t)
t.extend([1, 2, 15]) # similar to t + [1, 2, 5] # like concat 
print(t)
[9, 41, 12, 3, 74, 15]
[9, 41, 12, 3, 74, 15, 1, 2, 15]

extend vs append

In [4]:
# extend vs append 
t = [9, 41, 12, 3, 74, 15]
t.append([1, 2, 15])
print(t)
[9, 41, 12, 3, 74, 15, [1, 2, 15]]

Index function

In [3]:
t = [9, 41, 12, 3, 74, 15]
print(t)
t.index(9)
[9, 41, 12, 3, 74, 15]
Out[3]:
0
In [10]:
t.index(5) # does not exist --> value error 
------------------------------------------------------
ValueError           Traceback (most recent call last)
<ipython-input-10-0612edc4c425> in <module>
----> 1 t.index(5) # does not exist --> value error

ValueError: 5 is not in list

Insert function

In [11]:
t = [9, 41, 12, 3, 74, 15]
print(t)
t.insert(3, 5) # insert 5 at index 3 
print(t)
[9, 41, 12, 3, 74, 15]
[9, 41, 12, 5, 3, 74, 15]

Pop function

return value and remove from the end of list

In [13]:
t = [9, 41, 12, 3, 74, 15]
print('before', t)
print('call pop', t.pop())
print('after', t)
before [9, 41, 12, 3, 74, 15]
call pop 15
after [9, 41, 12, 3, 74]

Remove function

In [20]:
t = [9, 41, 12, 3, 74, 15, 3]
print(t)
t.remove(12)
print(t)
[9, 41, 12, 3, 74, 15, 3]
[9, 41, 3, 74, 15, 3]
In [21]:
t = [9, 41, 12, 3, 74, 15, 3]
print(t)
t.remove(3) # remove the first match 
print(t)
[9, 41, 12, 3, 74, 15, 3]
[9, 41, 12, 74, 15, 3]
In [22]:
t.remove(70) # error 
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-22-13d2c267ae31> in <module>
----> 1 t.remove(70) # error

ValueError: list.remove(x): x not in list

Reverse function

In [32]:
t = [9, 41, 12, 3, 74, 15]
print(t)
t.reverse()
print(t)
[9, 41, 12, 3, 74, 15]
[15, 74, 3, 12, 41, 9]

Sort function

In [33]:
t = [9, 41, 12, 3, 74, 15]
print(t)
t.sort()
print(t)
[9, 41, 12, 3, 74, 15]
[3, 9, 12, 15, 41, 74]
In [34]:
t = [9, 41, 12, 3, 74, 15]
print(t)
t.sort(reverse=True)
print(t)
[9, 41, 12, 3, 74, 15]
[74, 41, 15, 12, 9, 3]

Is Something in a List?

In [35]:
t = [9, 41, 12, 3, 74, 15]
print(t)
12 in t
[9, 41, 12, 3, 74, 15]
Out[35]:
True
In [36]:
5 in t
Out[36]:
False

Built-in Functions and Lists

In [37]:
nums = [3, 41, 12, 9, 74, 15]
print(len(nums))
6
In [38]:
print(max(nums))
74
In [39]:
print(min(nums))
3
In [40]:
print(sum(nums))
154
In [41]:
print(sum(nums)/len(nums))
25.666666666666668

split a string with a lot of spaces

In [42]:
line = 'A lot               of spaces' # white space 
line.split()
Out[42]:
['A', 'lot', 'of', 'spaces']

Split a string using a delimter

In [43]:
line = 'first;second;third'
line.split(';')
Out[43]:
['first', 'second', 'third']
In [16]:
line = '10\t13\t25'
print(line)
10	13	25
In [17]:
numbers = line.split('\t')
print(numbers)
['10', '13', '25']
In [18]:
int_numbers = [int(n) for n in numbers]
print(int_numbers)
[10, 13, 25]
In [46]:
print(sum(int_numbers))
48

Handle mail box

In [47]:
line = 'From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008'
words = line.split()
print(words)
['From', 'stephen.marquard@uct.ac.za', 'Sat', 'Jan', '5', '09:14:16', '2008']
In [48]:
email = words[1]
print(email)
stephen.marquard@uct.ac.za
In [49]:
pieces = email.split('@')
print(pieces)
['stephen.marquard', 'uct.ac.za']
In [50]:
year = words[-1]
print(year)
2008