Download presentation
Presentation is loading. Please wait.
Published byAugustus Rafe Boyd Modified over 7 years ago
1
List Algorithms Taken from notes by Dr. Neil Moore & Dr. Debby Keen
CS 115 Lecture 16 List Algorithms Taken from notes by Dr. Neil Moore & Dr. Debby Keen
2
Functions that mutate lists
Let’s write a function that mutates a list Scaling: multiply all elements by the same number Parameters: a list and a scaling factor Postconditions: mutates the list, returns nothing Usually a mutating function needs to loop over indexes, not elements scale.py What happens if we pass it a string instead of a list?
3
List algorithms Let’s implement several algorithms for lists
Pretty much all list algorithms use a loop Usually a for loop, occasionally a while Sum: add together all the elements Count: find the number of occurrences of a value Max/min: find the largest/smallest value Sort: rearrange the elements to be in order All of them are available as built-in functions or methods But we’ll still write them ourselves. Why? It’s good to understand how they work And sometimes we need a slightly different variant, which is NOT built-in.
4
Sum Adding up the elements of a list works like adding up user input, which we’ve done before. Need an accumulator with an initial value. Zero is the additive identity (adding zero doesn’t change anything) One is the multiplicative identity For a string, it’s the “” empty string for concatenation For a list, it’s the [] empty list for concatenation or appending The algorithm Initialize the accumulator to the identity factor for the operation involved For each element in the list, add it to the accumulator (or whatever operation is called for)
5
Sum In Python we can also use the built-in function sum, for addition
total = sum(mylist) Variations (which are NOT built-in): sum of squares, product of elements Concatentation can also be done by the join method, for strings in a list addup.py
6
Count The in operator tells us whether a value is in a list. Sometimes we also need to know how many times it is there Two parameters: a list and the value to search for We’ll need an accumulator (counter) to keep track of the count The algorithm: Initialize the counter to zero for each element in the list: 2.1 if it equals the search value, add 1 to the counter Python has a count method numzeros = mylist.count(0) Variations: count the elements with a certain property (> 0, even, …) count.py
7
Maximum and minimum What if we want to find the largest element?
Use a variable to keep track of the “largest seen so far” What to initialize it to? a dummy value? 0? what if list is all negative numbers? ? same problem: the elements might all be smaller than the dummy Best to use the first element of the list! “the largest” doesn’t make sense for an empty list! The algorithm: Initialize the “best” variable to the first element of the list for each element in the rest of the list: 2.1 if its bigger than the best, it’s the new best
8
Maximum and minimum Python has functions max and min:
largest = max(mylst) Elements must be comparable (all strings or all numbers, not a mix of types) Variations: location of the maximum, maximum of a function applied to each element maximum.py
9
Sorting We already know the sort function But how does it work?
There are several algorithms for sorting: Selection sort, insertion sort, quick sort, merge sort, etc. Most of these algorithms are based around: Comparing elements Then swapping them into the right place Different algorithms have different trade-offs Some require fewer comparisons some require fewer swaps Some require less memory Some are good on “almost-sorted” data
10
Sorting We’ll look at one algorithm: selection sort
Not the fastest, but one of the simplest Algorithm requires the fewest swaps The idea behind selection sort: iterate through the list in multiple passes First, put the smallest element in the right place (that is, 0) You can find the smallest with min function and index method Then swap it with the first element in the list lst[0], lst[minpos] = lst[minpos], lst[0] This is pass 1
11
Selection sort Then put the second-smallest element in the right place (that is, 1) Use min function and index method on the UNsorted part of the list you never have to touch the first element in the list after pass 1 then swap it with the second element ([1]) That’s pass 2 And then the third-smallest, and then the fourth, and … Sounds like a loop!
12
Selection sort algorithm
For each index in the list (each pass) Find the smallest element after index i swap that element with the one in position I Now all the elements up to index i are sorted That’s all! Each pass makes more of the list sorted than before Each pass gets us closer to the goal, but not all the way there Then you repeat passes until you reach the goal: a common algorithmic technique Have to make sure you are getting closer to the goal! In each pass, there are fewer numbers unsorted than in the previous pass.
13
Selection sort algorithm
It turns out we can stop just before the last index. Why? If everything else is in the right place, it must be too! selsort.py
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.