Upload
others
View
4
Download
0
Embed Size (px)
Citation preview
IntroductionTo start slowly
but surely
Who am I?
Goals
References
Format of the lectures
What’s an algorithm?
What’s a data structure?
2
Who am I?Bastien Pietropaoli, Ph.D.Insight Centre for Data AnalyticsDepartment of Computer ScienceUniversity College Cork
French, studied nuclear engineering, did some astrophysics, studied computer science mostly by myself, work in CS now
Please excuse my accent, and excuse me if I still struggle understanding yours sometimes.
3
GoalsAcquire deeper knowledge of key programming skills:
● Algorithms● Data Structures
Learn how to solve programming problems:
● Understanding problems● Implementing solutions
Dive deeper into Python 3
Have fun!4
ResourcesPython documentation: https://docs.python.org
Programming Challenges
Introduction to Algorithms
Algorithmic and Data Structures5
Format of the lectures (except for today)● 20-30 min of lecture● 50-60 min of practice● 5-10 min break● 20-30 min of lecture● 50-60 min of practice● 10 min of conclusion / discussion● If we have extra time, I’ll give bits of Python tricks
If you have a question, you should interrupt me!If you have a question outside of the course, you should contact me: [email protected]
6
The learning curve
7
Time
Confidence
Credit: medium.com
What’s an algorithm?An algorithm is a sequence of instructions transforming an input to an output.
Can you cite an example of algorithm?
9
What’s an algorithm?An algorithm is a series of instructions transforming an input into an output.
Example: Omelette recipe
1. Heat a nut of butter in a pan2. Take a bowl3. Break 3 eggs in the bowl4. Add half a cup of milk5. Add two pinches of grated cheese6. Add a pinch of salt and pepper7. Mix8. Add the mixture to the pan9. Wait 10 min
10. Voilà!10
The recipe is a series of instructions to transform a set of ingredients into a
delicious “omelette au fromage”!
Credit: lesfoodies.com
What’s a data structure?A convenient way of storing data, usually adapted to specific algorithms.
Can you cite an example of data structure?
12
What’s a data structure?A specialised way of storing data, usually adapted to specific algorithms.
Example: a queue
You can add people in the queue.
You can pick people from the queue.
They come following the rule of “first in, first out” (FIFO)
13Credit: Wikipedia
Refresher 1
Basic data types
Basic operations on numbers
Operations precedence
Basic operations on Booleans
Boolean operations precedence
Boolean logic basics
14
The very basics of programming
Basic data typesIntegers: -1, 2, 4, 35748902
Floats: 0.0, 1.2, 3.14159, 4/3, 3.
Booleans: True, False
Strings: “I’m a string”, ‘Me too!’
Tuples: (), (1, 4, 12), (True, “Hi”, 12, [])
Lists: [], [1, 4, 12], [True, “Hi”, 12, []]
Dictionaries: {1:”Hi”, 34:[], 5:{}, True:234}15
Iterable!
Basic operations on numbers+ (addition)
- (subtraction)
* (multiplication)
** (exponent / power)
/ (division)
// (Euclidian division)
% (modulo)
16
2 + 2 -> 4
2 - 2 -> 0
2 * 3 -> 6
2 ** 3 -> 8
11 / 3 -> 3.666…
11 // 3 -> 3
11 % 3 -> 2
Operations precedenceOperations are applied in the following order:
()
**
*, /, //, %
+, -
17
2 + 2 * 5 -> 12
2 ** 2 * (4 - 1) -> 12
34 % 4 + 10 -> 12
18 // 5 * 4 -> 12
3 ** 3 - 19 // 3 -> 21
((12*4+3)//(18%3+1)) -> 51
Basic operations on Booleansnot: invert the value of the Boolean
and: multiply two Booleans (True only if both are True)
or: add two Booleans (True if at least one is True)
18
not False -> Truenot True -> False
and False True
False False False
True False True
or False True
False False True
True True True
Comparison operatorsComparison operators return Booleans
< (lower than)
<= (lower or equal)
> (greater than)
>= (greater or equal)
== (equal)
!= (not equal)
12 < 13.34 -> True
12 <= 12.0 -> True
“What” > ‘Why’ -> False
[1, 2, 3] >= [] -> True
(2, 1) == (1, 2) -> False
(2, 1) != (1, 2) -> True
19
Boolean logic basics
Expression:
not not A
not (A < B)
not (A >= B)
not (A or B)
not (A and B)
Equivalent:
A
A >= B
A < B
not A and not B
not A or not B
20
De Morgan’s laws
Operations precedenceOperations are applied in the following order:
()***, /, //, %+, -==, !=, <, >, <=, >=notandor
21
2 + 2 * 5 == 12 -> True
4 < 2 ** 3 % 5 -> False
not “Cork” < “Dublin” -> False
not 3 < 4 and 4//3 > 1 -> False
True and 13%2 == 0 -> False
not (4>5 and 3*4%2==0) -> True
not (4>5 or 3*4%2==0) -> False
Refresher 2
Define a variable
Keywords
Conditions
Strings
Tuples, lists, and dictionaries
While loops
For loops
Define functions
22
The very basics of programming in Python
Syntax highlighting in this lecture
23
Normal characters: variable names, colons, operators, etc.
Numeric values: 12, 0, -6, 3.4, 775940
Strings: “Hey”, “How you doing?”
Keywords: True, False, for, while, in, return, def, etc.
Functions and internal variables: len(), print(), __name__
Comments: # I’m a comment
Define a variableSimply assign a value to a variable name.
Note: Python doesn’t care if a variable doesn’t exist. It will create it for you. Mind your variable names and spelling mistakes!
Multiple assignments are possible!
Even using variables
24
a_number = 12
a_string = “pouf pouf”
my_list = [“meh”, “whatever”]
a, b, c = 1, 2, 3
var1, var2 = True, “So what?”
a, b = b, a # Switches variables
Conditions (1/2)The classic ‘if’ statement:
OR
The ‘if-else” statement:
OR
26
if my_condition:do_something()
if my_condition:do_something()
else:do_something_else()
if my_condition: do_something() if my_condition: do_something()else: do_something_else()
Conditions (2/2)The complete ‘if-elif-else’ statement:
You can have as many ‘elifs’ as you want.
27
Ternary expressions:
You can use that in place of a value, to condition the value that will be actually used.
if my_condition:do_something()
elif another_condition:do_whatever()
else:do_something_else()
my_variable = a_value if \ my_condition else another_value
StringsDefining a string (double quotes or single quotes)
Accessing single characters using indices
Slicing a string
Adding stringsMultiplying strings
Getting the length of a string
28
s1 = “I’m a string”s2 = ‘Me too!’
s1[0] # Is2[-1] # !
s2[0:2] # Mes1[6:] # string
“Well” + “ done!” # “Well done!”“-” * 10 # “----------”
len(s1) # 12len(s2) # 7
Tuples
Tuples are ordered collections of objects of any type, mixed or not.
Manipulated the same way as strings
Like strings, tuples are immutable.
29
t1 = (2, ‘pouf’, True)t2 = (1,)
t1[-1] # Truet2[0] # 1
s2[0:2] # (2, ‘pouf’)s1[1:] # ()
t1 + t2 # (2, ‘pouf’, True, 1)t2 * 4 # (1, 1, 1, 1)
len(t1) # 3len(t2) # 1
Lists (1/2)
Ordered collections that can be modified
Again, the same operations can be performed.
30
l1 = [2, ‘pouf’, True]l2 = [1]
l1[-1] # Truel2[0] # 1
l2[0:2] # [2, ‘pouf’]l1[1:] # []
l1 + l2 # [2, ‘pouf’, True, 1]l2 * 4 # [1, 1, 1, 1]
len(l1) # 3len(l2) # 1
Lists (2/2)Some handy operations
Some operations modifying the list
… and other methods we might see later.
31
l = [“banana”, “apple”, “kiwi”]
l.count(“apple”) # 1l.index(“kiwi”) # 2
l.reverse() # [“kiwi”, “apple”, “banana”]l.sort() # [“apple”, “banana”, “kiwi”]
l.append(“grape”) # [“apple”, “banana”, “grape”]l.remove(“banana”) # [“apple”, “grape”]
DictionariesUnordered collections of key-value pairs
Accessing values via keys
Adding a key-value pair OR updating the value for a key
Deleting an key-value pair
Getting the number of key-value pairs in the dict
32
d = {3:”Yo”, “I’makey”:12}
d[3] # “Yo”d[“I’makey”] # 12
d[“whatever”] = “meh”# {3:”Yo”, “I’makey”:12, # “whatever”:”meh”}
del d[“whatever”]# {3:”Yo”, “I’makey”:12}
len(d) # 2
While loops
Repeats a block of code while the condition is True
33
while my_condition:do_stuff()...
while True:# I’m an infinite loop
def do_something(n):‘’’What do I do? (n > 0)’’’result = 0while n != 0:
result += 1n //= 2
return result
For loops (1/2)
Iterates over the elements of collection (string, tuple, list, dict, etc.)
34
for element in my_collection:do_stuff()...
l = [“yo”, “how”, “you”, “doing”]for word in l:
print(word)# Will print one word per line
def easy_one(l):“””len(l) > 0”””r = l[0]for i in l:
r += ireturn r
For loops (2/2)Loop N times
Loop and get the current index
Loop on key-value pairs for dictionaries
35
for i in range(N):...
for index, el in enumerate(l):...
for key, value in d.items():...
Built-in functions
36
https://docs.python.org/3/library/functions.html
Define functions
As since a bit earlier, a function needs the following:
● Keyword def● A name (has to be unique)● Arguments (optional)● A doc string (optional but it’s
good practice)● Instructions● May or may not return a result
(return ends the function!)
37
def function_name(arg1, arg2):“””I’m a doc string.”””# Do stuff herepass
def mystery():“””What do I do?”””d = {}i = 0while True:
d[i] = ii += 1
Find the max of a list of numbers
39
Write a function capable of returning the max of a list of numbers (without using max()).
Hint 1: Start small.
Hint 2: Keep track of where you are.
def find_max(l): """Finds the max of a provided list.""" max_value = float("-inf") for value in l: if value > max_value: max_value = value return max_value
# Testing the function:if __name__ == "__main__": l1 = [32, 12, 23, 64, 32, 64, 78, 12, -5] l2 = range(20) print(find_max(l1)) # 78 print(find_max(l2)) # 19
Reverse a string
40
Write a function that reverses a string. (s.reverse() won’t do it!)
Hint 1: Start anew.
Hint 2: Go backwards.
def reverse_str(s):“””Reverse the provided str.”””r = “”for l in s:
r = l + rreturn r
# Testing the function:if __name__ == “__main__”:
print(reverse_str(“peuh”)) # huepprint(reverse_str(“hello”)) # olleh
Anagrams
41
Write the following function:
● Takes two strings as input● Returns a Boolean● Returns True if the two strings are anagrams, False
otherwise
Examples:
● anagrams(“snake”, “sneak”) -> True● anagrams(“cake”, “sake”) -> False
Anagrams - One possible solution
Hint 1: There’s a trivial case.
Hint 2: Check off letters.
42
def anagrams(s1, s2):“””Test if the strings are anagrams”””if len(s1) != len(s2):
return False
for l in s1: if l in s2: s2.replace(l, '', 1) else: return False return True
# Testing the function:if __name__ == “__main__”:
print(anagrams(“snake”, “sneak”)) # Trueprint(anagrams(“cake”, “sake”)) # False
Discussion & conclusion
43
What we’ve seen today:
● Refreshers on the basics of programming● Refreshers on the basics of programming in Python● Some exercises to warm up
Where you are in algorithmic: pretty much nowhere.Where you are in Python: you know as much as most people saying they know Python (which is not much).
Discussion: Do you think our solution to the anagrams is good? Why?
Bonus materialBreak your own stuff
Casting a variable
Formatting strings
Parsing strings
45
Some basic thinking&
string manipulation
Break your own stuffAnagrams:
● What about capital letters?● What about punctuation?● What about tabs and spaces?
You might want to create a new function for that.
With next week lecture, we’ll see how to compare efficiency.
46
import string
def prepare_str(s):“””I prepare strings.”””result = s.lower()exclude = string.punctuation \ + “ “ + “\t”for ch in exclude:
result.replace(ch, “”)return result
# Testing our function:If __name__ == “__main__”:
s = “I’m a test!”print(prepare_str(s)) # Imatest
Casting a variable
47
You can transform a variable from one type to another if the transformation is defined.
Cast numbers
Cast into a str (always defined)
Cast into a list (for iterables)
a, b = 1, 12.5
float(a) # 1.0int(b) # 12
str(12) # “12”“test” + 12 # Error“test” + str(12) # “test12”
list(“abc”) # [“a”, “b”, “c”]str(list(“abc”)) # “[‘a’, ‘b’, ‘c’]”
Formatting stringsmy_string.format(): Takes as arguments what you want to insert into a str.
Insertion
Alignment
Percentage
... and many more things!48
https://docs.python.org/3.4/library/string.html#formatspec
s1 = “My variable = {0}.”s2 = “{0}{1}{0}”
nb_students = 15s1.format(nb_students)# “My variable = 15”s2.format(‘abra’, ‘cad’)# “abracadabra”
“{:<10}”.format(“la”)# “la ““{:>10}”.format(“ra”)# “ ra”“{:^10}”.format(“ce”)# “ ce ““{:.2%}”.format(19/22)# “86.36%”
Parsing stringsparse() is the opposite of format()
To install it: pip install parse
Used mainly to find patterns
49
https://pypi.org/project/parse/
from parse import *
# How to use the parse function:parse(pattern, str_to_search)
r = parse("It's {}, I love it!", "It's spam, I love it!")# Will return an object# <Result ('spam',) {}>
r[0] # ‘spam’
Programming Trivia
99 bottles of beerhttp://www.99-bottles-of-beer.net/
50