List and String Exercises

 

Tutorials

Here are some built-in Python methods for strings and lists, that may be useful in the exercises below.  I'd like to highlight a few of them here:

1. someList.index(someElement): this is just like .find() for strings, except it generates an error when the element is not found.  Examples:

	L = [3,4,'fred',4,-2,0,[5,1],'harry']
	L.index(4)  # results in 1, which is the position of the first occurrence of 4
	L.index([5,1])  # results in 6
	L.index(6)  # results in an error

2. someString.split(): this will take a string and split it into a list of short strings, the splitting occurring wherever there was "whitespace".  This is useful for splitting a string into a list of words.  Examples:

	"Hi there, you all.".split()  # results in ['Hi','there,','you','all.']  Notice that the splitting occurred at the original spaces
					# and that the punctuation symbols travel with the words that they're adjacent to.
	"  More     spaces   ".split()  # results in ['More','spaces']  Notice that the number of spaces between the words is not relevant.

3. someString.join(someList): This is the opposite of the .split() in that it will join the elements of someList together into a resultant string, with the someString used as a separator.  Examples:

	"beep".join(['My','name','is','Fred.'])  # results in 'MybeepnamebeepisbeepFred.'
	" ".join(['My','name','is','Fred.'])  # results in 'My name is Fred.'
	''.join(['a','b','c','d'])  # results in 'abcd'

4. There are several ways to modify a list -- remember that a list is mutable whereas a string is immutable.  Here are some samples:

	>>> L = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

	Replace a single element
	>>> L[1] = 37  
	>>> print L
	[0, 37, 2, 3, 4, 5, 6, 7, 8, 9]

	Replace and shrink
	>>> L[3:7] = [-3,12]
	>>> print L
	[0, 37, 2, -3, 12, 7, 8, 9]
	Replace and expand
	>>> L[-2:] = [10, 11, 12, 13]
	>>> print L
	[0, 37, 2, -3, 12, 7, 10, 11, 12, 13]

	Sort (Note: this method sorts the list, but returns nothing)
	>>> L.sort()
	>>> print L
	[-3, 0, 2, 7, 10, 11, 12, 12, 13, 37]
	Find and delete an element by its value
	>>> L.remove(10)
	>>> print L
	[-3, 0, 2, 7, 11, 12, 12, 13, 37]

	Return and remove an element by its position
	>>> a = L.pop(3)
	>>> print L
	[-3, 0, 2, 11, 12, 12, 13, 37]
	>>> print a
	7
	Append to the end (the preferred way to grow a list)
	>>> L.append(201)
	>>> print L
	[-3, 0, 2, 11, 12, 12, 13, 37, 201]
	Insert an element inside the list by position (first argument is the position before which to insert, second is the value)
	>>> L.insert(1,98)
	>>> print L
	[-3, 98, 0, 2, 11, 12, 12, 13, 37, 201]
	Delete a slice
	>>> del L[2:5]
	>>> print L
	[-3, 98, 12, 12, 13, 37, 201]

5. float(someNumber) will convert any number, either integer or floating-point, into a floating-point number.  This is useful when you want to divide one number by another, and don't want to worry about integer-type division that rounds down (as in 5/6 resulting in 0).  So, float(a)/b will not round, even if both a and b are integers.


Exercises:

1a. Create the function LFindWhile(someList,someElement) which will return the position of the first occurrence of someElement inside someList, or -1 if it's not found.  Use a while loop.

1b. Create the function LFindNoWhile(someList,someElement) which will do the same thing, but use no loops.  Test this function well (e.g. empty list, element not found, etc.).

2. Create the function CountSomeChars(s) which will return the number of upper- or lower-case letters inside s which are in the first half of the alphabet ('a' through 'm', 'A' through 'M').  You MUST use a for loop, and any other tools you want.  Example:

	CountSomeChars('Hi there')  # results in 5 because 'H', 'i' 'h' 'e' and 'e' are in the first half of the alphabet


3. Use for and range() to create the HarmonicSum(n) to add up the first n reciprocals of integers, starting with 1 -- remember point #5 in the Reminders section above.  Calculate the sum of the first 1,000 integers -- HarmonicSum(1000)-- and put that number (rounded to 3 decimal places) into the Comments-to-Teacher.  Example:

	HarmonicSum(3)  # returns the sum of 1 + 1/2 + 1/3 resulting in 1.83333333

4.  Create the function Select23(someList) which will be given a list (possibly empty) of non-negative integers and will return a list of only those elements which are evenly divisible by 2 or 3 or both.  Use for and .append(). Example:

	Select23([5,0,12,9,7,4])  # returns [0,12,9,4]
	Select23([5,7,1])  # returns []

5a. Create the function RemoveNegs(L) that will remove all the negative numbers from the list that it's given and return the resultant list.  Example:

	L = [2, -3, 0, -5, 12]
	print RemoveNegs(L)  # will print: [2, 0, 12]
	print L  # will print: [2, -3, 0, -5, 12]

5b. Challenge: Create the function RemoveNegsInPlace(L) that will modify the list that it's given, removing all negative numbers (it returns nothing). Be careful: inside a "for a in B" type loop, DO NOT change the loop variable (in this case, it's a, by doing something like a=a+1), and DO NOT change the list or string (in this case, it's B, by doing something like B.remove(12) or B[1:5]=[3,2]).  However, you can mess with things inside a while loop. 
Example:

	L = [2, -3, 0, -5, 12]
	print RemoveNegsInPlace(L)  # will print: None
	print L  # will print: [2, 0, 12]
	# Be sure to try it on:
	L2 = [-2, -3, -4]
	RemoveNegsInPlace(L2)
	print L2 # should print: []

Challenge Problem:  Create the function WordList(someString) which creates the list of all the words in someString.  The following characters are punctuation that can be elimintated: comma and period.  A comma and a period will only appear at the end of words.  Any number of consecutive spaces function together as a word separator.  Use .split().  Example:

	WordList('  Now, Scotty, use the dilithium crystals.')  # returns ['Now','Scotty','use','the','dilithium','crystals']

Hard Challenge Problem (but useful, if you can solve it):  Create the function MySplit(someString, separators) which will split the string into substrings containing no characters that are in the separators string.  This is a more powerful version of the .split() method, and more difficult to do. You may NOT use the .split() method. You will need to go through someString character by character, and figure out whether the character you're looking at is one of the separators or not.  And special care should be taken with the beginning and end of someString.  Hint: you can use a Boolean (True/False) variable to keep track of whether you are in the middle of a word or not.  Example:

	MySplit(" Hi there... Mr. Bleeper,  "," ,.e")  # returns  ['Hi','th','r','Mr','Bl','p','r']
	MySplit("What's up?"," ,!")  # returns ["What's",'up?']