240 likes | 350 Views
COMPSCI 101 Principles of Programming. Lecture 22 –Slices of Sequences Dr. Patricia J. Riddle. Learning outcomes. At the end of this lecture, students should be able to: Use slices of sequences Use step parameters on slices. Programs vs Functions.
E N D
COMPSCI 101Principles of Programming Lecture 22 –Slices of Sequences Dr. Patricia J. Riddle
Learning outcomes • At the end of this lecture, students should be able to: • Use slices of sequences • Use step parameters on slices COMPSCI 101 - Principles of Programming
Programs vs Functions • If you put a call to the function at the bottom of the file it will call it automatically. • Where does the return value go? • What happens with prints? COMPSCI 101 - Principles of Programming
Review of Sequences • Lists (mutable) >>> mylist = [1, 2, 3, 4, 5, 6] >>> mylist[0] 1 >>> mylist[1] 2 >>> mylist[-1] 6 >>> mylist[-2] 5 >>>mylist[2] = 7 >>>mylist [1, 2, 7, 4, 5, 6] COMPSCI 101 - Principles of Programming
Review of Sequences Continued • Strings (immutable) >>> mystring = "samuel” >>> mystring[0] 's' >>> mystring[1] 'a' >>> mystring[-1] 'l' >>> mystring[-2] 'e' >>>mystring[2] = "f" ERROR COMPSCI 101 - Principles of Programming
Slices • List slicing • Often want sublists rather than individual items • Done by extended indexing of the form “start:end+1” • Note that slice is up to but not including the second subscript • Missing first subscript defaults to 0 • Missing second subscript defaults to len(list) COMPSCI 101 - Principles of Programming
Examples mylist = ["sally", "mary", "sue", "fred", "sam", "mike"] >>> mylist[2:4] ["sue", "fred"] >>> mylist[:4] ["sally", "mary", "sue", "fred"] >>> mylist[3:] ["fred", "sam", "mike"] COMPSCI 101 - Principles of Programming
Assigning to Slices my_list[start:end] = another_list replaces the elements my_list[start] up to but not including my_list[end] with the elements from another_list Can do insertion too (but insert method is easier to read): but insert method will only insert a single item (see next page) my_list.insert(position,element) COMPSCI 101 - Principles of Programming
Examples >>> my_list= [1, 3, 5, 7, 9, 11] >>> my_list[2:4] = [-3, -9, -11, -13] >>> my_list [1, 3, -3, -9, -11, -13, 9, 11] >>> my_list = [1, 3, 5] >>> my_list[1:1] = [-9] >>>my_list [1, -9, 3, 5] COMPSCI 101 - Principles of Programming
More Examples >>> my_list = [1, 3, 5] >>> my_list .insert(1,-9) >>>my_list [1, -9, 3, 5] >>> my_list = [1, 3, 5] >>> my_list.insert(1,[-9]) >>>my_list [1, [-9], 3, 5] >>> my_list = [1, 3, 5] >>> my_list[1:1] = [-3, -9] >>>my_list [1, -3, -9, 3, 5] >>> my_list = [1, 3, 5] >>> my_list.insert(1,[-3,-9]) >>> my_list [1, [-3, -9], 3, 5] COMPSCI 101 - Principles of Programming
Boundary Examples Boundaries larger than the list will work But better style to use “missing boundary” >>> my_list[2:38] = [8, 12] (use my_list[2:] = [8,12] instead) >>> my_list [1, 3, 8, 12] >>> my_list[-28:2] = [7, 6] (use my_list[:2] = [7,6] instead) >>> my_list [7, 6, 8, 12] COMPSCI 101 - Principles of Programming
Extended Slices using Step Parameter • Step parameter • Default value is 1 • When the step parameter is not 1, it is called striding, sliding or stepping in different sources. I do not think they have settled on a single name. Format is [start: end: step] >>> s='abcd' >>> s[::2] 'ac' >>> s[::-1] 'dcba' COMPSCI 101 - Principles of Programming
What about strings? • Lists are mutable • Strings are immutable • String slices perform the same as list slices (except assignment) • So mylist[2] = "f" OK mystring[2] = "f" FAILS mylist[2:3] = "f" OK mystring[2:3] = "f" FAILS COMPSCI 101 - Principles of Programming
Assignment with Step Parameter >>> my_list = [1, 3, 5] >>> my_list[0::2] = [4] ValueError: attempt to assign sequence of size 1 to extended slice of size 2 >>> my_list[0::2] = [4, 6] >>> my_list [4, 3, 6] COMPSCI 101 - Principles of Programming
Exercise • Write a function named get_substring() that returns the substring from location i to j or an empty string if given an invalid range >>> get_substring(2,3,"fred") 'ed' >>> get_substring(2,3, "al") '' COMPSCI 101 - Principles of Programming
Answer defget_substring(i,j,string): if i <= j and j < len(string): return string[i:j+1] return "" COMPSCI 101 - Principles of Programming
Pig Latin • In words that begin with consonant sounds, the initial consonant is moved to the end of the word, and "ay" is added, as in the following examples: • beast ? east-bay • dough ? ough-day • In words that begin with vowel sounds or silent consonants, the syllable "way" is simply added to the end of the word • another? another-way • if? if-way COMPSCI 101 - Principles of Programming
Exercise • Write a function named pig_latin()that accepts a string and returns the string with the words transformed into Pig Latin. >>> pig_latin("If I am away.") 'If-way I-way am-way away-way.' >>> pig_latin("Here is another sentence") 'ere-Hay is-way another-way entence-say' COMPSCI 101 - Principles of Programming
Answer defpig_latin(sentence): last = 0 new_sentence = "" if sentence == "": return '' for i in range(0,len(sentence)): if sentence[i] == " " or sentence[i] == ".": new_sentence = new_sentence + pig_latin_word(sentence[last:i]) + sentence[i] last = i + 1 if not last == len(sentence): new_sentence = new_sentence + pig_latin_word(sentence[last:len(sentence)]) return new_sentence COMPSCI 101 - Principles of Programming
Helper Function defpig_latin_word(word): vowels = “aeiouy” #can use string or list capital_vowels = ["A","E","I","O","U","Y"] if word[0] in vowels or word[0] in capital_vowels: return word + "-way" return word[1:len(word)] + "-" + word[0] + "ay” COMPSCI 101 - Principles of Programming
Exercise • Write a function named rotate_matrix()that accepts a list and two integers representing the number of columns and rows in the initial matrix respectively and prints out the original matrix, and prints out the matrix in a rotated form. >>> rotate_matrix(["0","1","2","3","4","5","6","7","8","9","10","11"],4,3) ['0', '1', '2', '3'] ['4', '5', '6', '7'] ['8', '9', '10', '11'] ['0', '4', '8'] ['1', '5', '9'] ['2', '6', '10'] ['3', '7', '11'] >>> rotate_matrix(["0","1","2","3","4","5","6","7","8","9","10","11"],3,4) ['0', '1', '2'] ['3', '4', '5'] ['6', '7', '8'] ['9', '10', '11'] ['0', '3', '6', '9'] ['1', '4', '7', '10'] ['2', '5', '8', '11'] COMPSCI 101 - Principles of Programming
Answer defrotate_matrix(matrix,size1,size2): start = 0 for i in range(0,size2): print(matrix[start:start+size1]) start = size1+start print("") start=0 for i in range(0,size1): print(matrix[i:len(matrix):size1]) COMPSCI 101 - Principles of Programming
Summary • Slices can be used in any Sequence (strings or lists) • Slices can only be assigned in Lists, not strings • Because strings are immutable • Step parameter can be used to do Sliding/Striding COMPSCI 101 - Principles of Programming
Tomorrow • Nested Loops COMPSCI 101 - Principles of Programming