0% found this document useful (0 votes)
12 views44 pages

Computer Programming: Prepared Mohammed Esmaail Shakfah Spring 2024

Uploaded by

jana.adeel08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views44 pages

Computer Programming: Prepared Mohammed Esmaail Shakfah Spring 2024

Uploaded by

jana.adeel08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 44

Computer

Programming
Chapter 6
Prepared Mohammed Esmaail Shakfah 1
Spring 2024

11/28/2024
Contents
 Basic Properties of Lists
 List Operations
 Common List Algorithms
 Using Lists with Functions
 Problem Solving: Adapting Algorithms
 Problem Solving: Discovering Algorithms by Manipulating Physical Objects
 Tables

Pag
11/28/2024
e2
Creating a List
 Specify a list variable with the subscript operator []

 A list is a sequence of elements, each


of which has an integer position or
index
 To access a list element, you specify
which index you want to use. That is
done with the subscript operator in the
same way that you access individual
characters in a string
Accessing list Replacing list
elements elements

print(values[5] values[5] = 87
)

Pag
11/28/2024
e3
Creating Lists/Accessing Elements
 Both lists and strings
are sequences, and
the [] operator is used
to access an element in
any sequence
 There are two
differences between
lists and strings:
 Lists can hold values
of any type, whereas
strings are sequences
of characters
# 1: Creating a list  Moreover:
values = [32, 54, 67.5, 29, 35, 80, 115, 44.5, 100,
 strings are
65] List Size of 10
immutable— you
cannot change the
# 2: Accessing a list element characters in the
values[5] = 87 sequence
 Lists are mutable
Pag
11/28/2024
e4
Out of Range Errors
 Out-of-Range Errors:
 Perhaps the most common error in using lists is accessing The following code ensures that
a nonexistent element you only access the list when the
index variable i is within the legal
values = [2.3, 4.5, 7.2, 1.0, 12.2, 9.0, 15.2, 0.5] bounds:
values[8] = 5.4
# Error––values has 8 elements, if 0 <= i and i < len(values) :
# and the index can range from 0 to 7
 values[i] = number
Note that there are two
distinct uses of the square
 If your program accesses a list through an out-of-range brackets. When the square
index, the program will generate an exception at run time brackets immediately follow a
variable name, they are
 You can use the len() function to obtain the length of treated as the subscript
values[4
the list; that is, the number of elements: operator: ]
• When the square brackets
numElements = len(values)
follow an “=“ they create a list:

values =
[4] Pag
11/28/2024
e5
Example
 Given the list definition below,

 Write a statement correctly sets the third element to 15?


 Write a statement correctly to show value on the fifth element?

values = [4, 3, 5, 2, 0, 1, 6]

11/28/2024 6
Example
 What is the value of temp1?
 What is the value of temp2?
 What is the value of size?
 What is the value of value[4]?
 What is the new value of value[4]??

11/28/2024 7
Loop Over the Index Values
 Given the values list that contains 10 elements, we will want to set a
variable, say i, to 0, 1, 2, and so on, up to 9

# First version (list index used) What output is generated by the code
for i in range(10) : segment below?
print(i, values[i])
numbers = [5, 10, 15, 20, 25, 30, 35, 40,
# Better version (list index used) 45]
for i in range(len(values)) : for i in range(1, 8, 2) :
print(i, values[i]) print(numbers[i], end=" ")

# Third version: index values not needed (traverse


# list elements)
for element in values :
print(element)

Pag
11/28/2024
e8
List References  When you copy a list
variable into another, both
 Make sure you see the difference between the:
variables refer to the same
 List variable: The named ‘alias’ or pointer to the list list
 List contents: Memory where the values are stored  The second variable is an
alias for the first because
values = [32, 54, 67.5, 29, 35, 80, 115, 44.5, 100, both variables reference
65] the same list
List variable List contents scores = [10, 9, 7, 4,
5]
values = scores
Reference A list variable specifies
the location of a list.
Copying the reference
yields a second
reference to the same
list. List contents
Values

scores[3] = 10 References Pag


11/28/2024
print(values[3]) # Prints e9
Reverse Subscripts
 Python, unlike other
last = values[-1]
languages, uses negative
print("The last element in
subscripts to provide access
the list is", last)
to the list elements in reverse
order.
 For example, a subscript of
–1 provides access to the
last element in the list:
 Similarly, values[-2] is the
second-to-last element.
Just because you can do
this, does not mean you
should…

Pag
11/28/2024
e 10
Example
 What are the contents of b?
 What is the value of b[0]?
 What is the value of x?

To check Viability of number in the list:


values = [ . . . ]
noneAreZero = not (0 in values) #True or False

11/28/2024 11
List Operations
 Appending Elements
 Inserting an Element
 Finding an Element
 Removing an Element
 Concatenation
 Equality / Inequality Testing
 Sum, Maximum, Minimum, and Sorting
 Copying Lists

Pag
11/28/2024
e 12
Appending Elements
 Sometimes we may not know the values that will be contained in the list
when it’s created
 In this case, we can create an empty list and add elements to the end as
needed

#1
friends = []

#2
friends.append("Harry")

#3
friends.append("Emily")
friends.append("Bob")
friends.append("Cari")

Page
13
11/28/2024
Inserting an Element
 Sometimes the order in which elements are added to a list is important
 A new element has to be inserted at a specific position in the list

#1
friends = ["Harry", "Emily", "Bob", "Cari"]

#2
friends.insert(1, "Cindy")

Pag
11/28/2024
e 14
Finding an Element
 If you simply want to know whether an element is
present in a list, use the in operator:

if "Cindy" in friends :
print("She's a friend")

• Often, you want to know the position at which an element


occurs
• The index() method yields the index of the first match

friends = ["Harry", "Emily", "Bob", "Cari", "Emily"]


n = friends.index("Emily") # Sets n to 1

If a value occurs more than once, you may want to find the position of all
occurrences. You can call the index method and specify a starting position for
the search. Here, we start the search after the index of the previous match:
n = friends.index("Emily")
n2 = friends.index("Emily", n + 1) 11/28/2024
Pag
e 15
Removing an Element
 The pop() method removes the element at a given
position
friends = ["Harry", "Cindy", "Emily", "Bob",
"Cari","Bill"]
friends.pop(1)

• All of the elements following the removed element are


moved up one position to close the gap
• The length of the list is reduced by 1
• friends.pop() “Remove last name”

Removing by name of the element Pag


11/28/2024
friends.remove("Cari") e 16
Concatenation & Replication
 The concatenation of two lists is a new list that contains the
elements of the first list, followed by the elements of the second

myFriends = ["Fritz", "Cindy"]


yourFriends = ["Lee", "Pat", "Phuong"]

• Two lists can be concatenated by using the plus (+)


operator:
ourFriends = myFriends + yourFriends
# Sets ourFriends to ["Fritz", "Cindy", "Lee",
"Pat","Phuong"]
 As with string replication of two lists is a new list that contains the
elements of the first list, followed by the elements of the second

monthInQuarter = [ 1, 2, 3] *
4
• Results in the list [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2 ,3]
• You can place the integer on either side of the “*” operator monthlyScores = [0] *
12
• The integer specifies how many copies of the list should be concatenated Pag
11/28/2024
e 17
• One common use of replication is to initialize a list with a fixed value
Equality / Inequality Testing Sorting
 You can use the == operator to compare  The sort() method sorts a list
whether two lists have the same elements, in of numbers or strings.
the same order.
[1, 4, 9] == [1, 4, 9] # values = [1, 16, 9, 4]
True values.sort() # [1, 4 , 9,
[1, 4,opposite
9 ] == of[4, 1,!=.
9] # 16]
• The == is
False.
[1, 4, 9] != [4, 9] #
True.
Sum, Maximum, Minimum
 If you have a list of numbers, the
sum() function yields the sum of all
values in the list.
sum([1, 4, 9, 16]) # Yields
30
• For a list of numbers or strings, the max() and min()
functions return the largest and smallest value:

max([1, 16, 9, 4]) # Yields 16 Pag


11/28/2024
min("Fred", "Ann", "Sue") # Yields e 18
Copying Lists
 As discussed, list variables do not themselves hold list elements
 They hold a reference to the actual list
 If you copy the reference, you get another reference to the same list:

prices = values

 Sometimes, you want to make a copy of a list; that


is, a new list that has the same elements in the
same order as a given list
 Use the list() function:

prices = list(values)
Pag
11/28/2024
e 19
Slices of a List
 Sometimes you want to look at a part of a list. Suppose  Both indexes used with the slice
you are given a list of temperatures, one per month: operator are optional
temperatures = [18, 21, 24, 33, 39, 40, 39, 36, 30,  If the first index is omitted, all
22, 18] elements from the first are
 You are only interested in the temperatures for the third included
quarter, with index values 6, 7, and 8  The slice
 You can use the slice operator to obtain them: temperatures[ : 6]
thirdQuarter = temperatures[6 : 9]  Includes all elements up to, but
 The arguments are the first element to include, and the not including, position 6
first to exclude  The slice
 So in our example we get elements 6, 7, and 8
temperatures[6 : ]
 Includes all elements starting at
position 6 to the end of the list
 You can assign values to a slice:
friends[ : 2] = ["Peter", "Paul", "Mary"]
replaces the first two elements of friends with three new temperatures[6 : 9] = [45, 44,
elements, increasing the length of the list. 40]
greeting = "Hello, World!" Pag
 Replaces the values11/28/2024
in elements
e 20
greeted = greeting[7 : 12] # The substring "World"
Common List Functions And Operators

Pag
11/28/2024
e 21
Common List Functions And Operators (2)

Pag
11/28/2024
e 22
Common List Methods

Pag
11/28/2024
e 23
Built-In Operations For Lists
 Use the insert() method to insert a new element at any position in a list
 The in operator tests whether an element is contained in a list
 Use the pop() method to remove an element from any position in a list
 Use the remove() method to remove an element from a list by value
 Two lists can be concatenated using the plus (+) operator
 Use the list() function to copy lists
 Use the slice operator (:) to extract a sublist or substrings

Pag
11/28/2024
e 24
Example
 values = [17, 25, 5, 30, 100, 96, 48, 5, 14, 1. data = [2] * 3
30]
2. data = 3 * [2]
x = values.index(96) 3. data = [1, 2, 3] * 2
print(x)
4. data = [0] * 50
print(values.index(33)) 5. data = [3] * [2]
if 5 in values :
6. nums = [1, 2, 3, 4, 5]
nums2 = [5, 4, 3, 2, 1]
x = values.index(5)
else : if nums == nums2 :
x = -1 print("lists are equal")
print(x) else :
print("lists are not equal")
7. names = ["Fred", "Ann", "Sue", "betsy"]
found = 14 in values names.sort()
print(found)
8. values = [5, 20, 18, -3, 67, 85, 32]
print(max(values))
x = values.index(30)
x = values.index(30, x + 1) 9. letters = list("abcdefg") 11/28/2024 25
print(x
Filling a List
 This loop creates and fills a list with squares (0, 1, 4, 9, 16, ...)

values = []
for i in range(n) :
values.append(i * i)
 If you want to print values without
Combining List Elements adding them to a string:
 Here is how to compute a sum of numbers: for i in range(len(values)) :
if i > 0 :
result = 0.0 print(" | ", end="")
for element in values : print(values[i], end="")
result = result + print()
element
• To concatenate strings, you only need
to change the initial value:

result = "" for i in range(len(names)) :


for element in names : if i > 0 :
result = result + ", "
result = result +
result = result + names[i]
element 11/28/2024
Pag
e 26
Example

 What is printed by the following code segment?

students = ["Harry", "Cindy", "Emily"]


result = ""
for name in students :
result = result + name.upper()
print(result)

11/28/2024 27
Linear Search
 Finding the first value that is > 100. You need to visit all elements until you
have found a match or you have come to the end of the list:
A linear search
limit = 100 inspects
pos = 0
elements
found = False
in sequence
while pos < len(values) and not found :
if values[pos] > limit : until a
found = True match is found.
else :
pos = pos + 1
if found :
print("Found at position:", pos)
else :
print("Not found")
Pag
11/28/2024
e 28
Collecting and Counting
Matches
Collecting all matches
limit = 100
result = []
for element in values :
if (element > limit) :
result.append(element)

• Counting matches

limit = 100
counter = 0
for element in values :
if (element > limit) :
counter = counter + 1

Pag
11/28/2024
e 29
Removing Matches
 Remove all elements that match a particular condition
 Example: remove all strings of length < 4 from a list

i = 0
while i < len(words) :
word = words[i]
if len(word) < 4 :
words.pop(i)
else :
i = i + 1

Pag
11/28/2024
e 30
Swapping Elements
 For example, you can sort a list by repeatedly swapping elements that are
not in order
 Swap the elements at positions i and j of a list values
 We’d like to set values[i] to values[j]. But that overwrites the value that is
currently stored in values[i], so we want to save that first:

Before moving a new value into a


location (say blue) copy blue’s value
elsewhere and then move black’s value
into blue. Then move the temporary
value (originally in blue) into black.

Pag
11/28/2024
e 31
Swapping Elements (2)
 Swapping elements [1] and [3]
 This sets up the scenario for the actual code that will follows

Pag
11/28/2024
e 32
Swapping Elements (3)
# Step 2
temp = values[i]

# Step 3
values[i] = values[j]

Pag
11/28/2024
e 33
Swapping Elements (4)
# Step 4
# temp contains values[i]
values[j] = temp

Pag
11/28/2024
e 34
Reading Input
 It is very common to read input from a user and store it in a list for later
processing.
values = []
print("Please enter values, Q to quit:")
userInput = input("")
while userInput.upper() != "Q" :
values.append(float(userInput))
userInput = input("")

Please enter values, Q to quit:


32
29 Program execution
67.5
Q
Pag
11/28/2024
e 35
Using Lists With Functions
 A function can accept a list as an argument
 The following function visits the list elements, but it does not modify them

def sum(values) :
total = 0
for element in values :
total = total + element
return total

The following function multiplies all elements of a list by a given factor:

def multiply(values, factor) :


for i in range(len(values)) :
values[i] = values[i] * factor

Pag
11/28/2024
e 36
Returning Lists From Functions
 Simply build up the result in the function and return it
 In this example, the squares() function returns a list of squares from 02 up to (n – 1)2:

def squares(n) :
result = []
for i in range(n) :
result.append(i * i)
return result

# Function definition
 It is common practice in Python, however,
def readDate() :
to use tuples to return multiple values. print("Enter a date:")
 A tuple is similar to a list, but once created, its month = int(input(" month: "))
contents cannot be modified (a tuple is an immutable day = int(input(" day: "))
version of a list). year = int(input(" year: "))
 A tuple is created by specifying its contents as a return (month, day, year) # Returns a
comma-separated sequence. You can enclose the tuple.
sequence in parentheses:
triple = (5, 10, 15) # Function call: assign entire value to a
• If you prefer, you can omit the parentheses: tuple
date = readDate() 11/28/2024
Pag
triple = 5, 10, 15 e 37
Example

 What output is generated by the program below?

def main() :
scores = [45.6, 67.8, 89.4]
addBonus(scores, 3.0)
print(scores[2])

def addBonus(values, bonus) :


for k in range(len(values)) :
values[k] = values[k] + bonus

main()

11/28/2024 38
Tables
 Lists can be used to store data in two dimensions (2D) like a spreadsheet
 Rows and Columns
 Also known as a ‘matrix’

Pag
11/28/2024
e 39
Creating Tables
 Here is the code for creating a table that contains 8 rows and 3 columns,
which is suitable for holding our medal count data:

Pag
11/28/2024
e 40
Creating Tables (3)
 Sometimes, you may need to create a table with a size that is too large to
initialize with literal values
 First, create a list that will be used to store the individual rows

table = []
 Then create a new list using replication (with the
number of columns as the size) for each row in the
table and append it to the list of rows:
ROWS = 5
COLUMNS = 20
for i in range(ROWS) :
row = [0] * COLUMNS
table.append(row)

• The result is a table that consists of 5 rows and 20


columns

11/28/2024
Pag
e 41
Accessing Elements
 Use two index values:
 Row then column

medalCount = counts[3][1]

• To print
• Use nested for loops
• Outer row(i) , inner column(j) :

for i in range(COUNTRIES):
# Process the ith row
for j in range(MEDALS) :
# Process the jth column in the ith row
print("%8d" % counts[i][j], end="")
print() # Start a new line at the end of the
row

Pag
11/28/2024
e 42
Locating Neighboring
Elements
 Some programs that work with two-dimensional lists need to locate the
elements that are adjacent to an element
 This task is particularly common in games
 You are at loc i, j
 Watch out for edges!
 No negative indexes!
 Not off the ‘board’

Pag
11/28/2024
e 43
Adding Rows and Columns

 Rows (x) Columns (y)

total = 0
for j in range(MEDALS):
total = total + counts[i]
[j]

total = 0
for i in range(MEDALS):
total = total + counts[i][j]

Pag
11/28/2024
e 44

You might also like