This lab has the following parts:
String
sList
s and String
s)Turn in this page for your group
a = "computational thinking" b = "duke university" c = "python code"
Use the slicing operator, string concatenation, string multiplication (by an int
,
as in "abc" * 3
), or indexing to form each of the words below. Each use
of any operator (slicing, indexing, concatenation, and multiplication) has a cost of one. Indicate
the cost of your construction as well as the operators you used. The first two are done for you to
serve as examples.
c[3:6]+b[2]
This has a cost of three: one slice, one catenation, one index.
a[3:5]+a[18:]
Again the cost is three: two slices and one catenation with +.
string method | purpose |
---|---|
s.upper() | returns string upper case version of string s |
s.count(sub) | returns int number of (non-overlapping) occurrences of sub in s |
s.endswith(sub) | returns boolean depending on whether s ends with sub |
s.find(sub) | returns int: first index at which sub occurs in s or -1 if no occurrences |
s.split() | returns list of s split on whitespace |
s.split(sep) | returns list of s split on sep, a delimiter |
s.strip() | returns copy of s withOUT leading and trailing whitespace |
list method | purpose |
---|---|
lst.count(elt) | returns number of occurrences of elt in lst |
lst.index(elt) | returns first/least index at which elt occurs in lst, generates error if elt not in lst |
lst.append(elt) | append elt to end of lst, None returned |
Functions are applied to objects. For example, len
returns an int: the length of the given string or list or other sequence/iterable. So len("apple")
is 5 and len([1,2,3])
is 3. For example, the table below shows some common string methods.
function call | result returned | type returned |
---|---|---|
len([1,2,3,"apple"]) | 4 | int |
sum([1,2,3,4]) | 10 | int |
max([5,4,1,2,9,3]) | 9 | same as list elements |
max("ape", "bee", "zebra", "wildebeast"] | "zebra" | same as list elements |
min([5,4,1,2,9,3]) | 1 | same as list elements |
sorted([5,4,1,2,7]) | [1,2,4,5,7] | list |
reversed([1,2,3,6]) | [6,3,2,1] | list |
max
returns the maximal value of a string as well as a list. What is max("science")
and why? reversed(sorted([5,4,1,2,8]))
and why? sorted(lst).index(min(lst))
for any list lst? Why? What's the value if min
is replaced by max
? st.endswith(st[-3:])
guaranteed to always be true? st.upper().endswith(st)
true?