Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Python Programming

Welcome to COMP102

1
Example: Sorting
“Given a list of numbers as input, sort that list in
ascending order”
The data is the list of numbers. To solve this we
have to do the following two things:
• Develop a set of instructions which anyone can
follow called an algorithm.
• Write that algorithm in a programming language
like Python so to run it on the computer.

2
Bubble Sort Algorithm
• If we are given a list with n numbers, do the
following steps n times.
• Starting from the beginning of the list compare
each adjacent pair of numbers.
• If the number at the lower index is greater than
the number at the larger index, swap them.
index means the position of a number in the list.

3
Bubble Sort Visualization

4
Bubble Sort Visualization

5
Bubble Sort Implementation
Requirements
• Facility to describe data (numbers).
• Ability to combine data together (list of numbers)
• Operations to manipulate data (comparing them,
moving them around etc.).
• Our implementation should be able to work with
any data (list) not just a particular one. This
ability is called abstraction.

6
Bubble Sort Implementation

7
• We have seen that basic programming
consists of the following two activities:
• Coming up with a systematic way
(algorithm) of solving a problem. This part
is independent of a programming
language (and in fact of a computer).
• Implementing that algorithm in a
programming language like Python.

8
Example: Text Data
We are going to analyze all the text of the plays written by
Shakespeare.
shakes = open('shakespeare.txt')
text = shakes.read().split()
text[:25]
len(text)
text.count('the')
text.count('thou')
text.count('you')
text.count(',')
text.count('the')/len(text)

9
Example: Text Data
words = set(text)
'forsooth' in words
len(words)
'draw'[::-1]
{w for w in words if w == w[::-1] and len(w)>4}
{w for w in words if w[::-1] in words and len(w) == 4}
{w for w in words if w[::-1] in words and len(w) == 5}
{w for w in words if w[::-1] in words and len(w) == 6}
len(words)
words = set(open('/usr/share/dict/words').read().split())
len(words)
{w for w in words if w[::-1] in words and len(w) == 6}

10
Example: Fractals

11
This Course
• Learn the fundamentals of programming.
• Not about learning the syntax of a
Particular Language
• How to control Complexity of large
Programs
• End Goal: Should be able to read and alter
large well written programs

12
Python Language
• The main reasons for choosing Python are:
– It is easy and fun to learn
– It is expressive enough to easily translate your ideas into code.
– It has an interpreted environment that lets you work with small
pieces of code at a time.
• The name Python language is not named after the
snake, it is name after a comedy group called “Monty
Python".

13

You might also like