Activity: Lists

Create a file lists-practice.py in your cs100/ch4 folder.

  1. Are the following correct? Put them in your python file and run them to check. What error do you get? Add a comment to describe why you get the error, and then comment out the lines which cause the error so that your program doesn’t have any issues running.
    myString = 'abc'
    myString[0] = 'd'
    print(myString)
       
    myList = ['a', 'b', 'c']
    myList[0] = 'd'
    print(myList)
    
  2. Add the following. What are the values of k1, k2, and k3? Write in comments.
    s = "I like apples"
    k1 = s.split()
    k2 = s.split('a')
    k3 = s.split('e')
    
  3. Split the string "mississippi" into a list uing the 'i' as a split point. Print the result.

  4. Write a function numWords(sentence) which takes a string as a parameter and returns the number of words in the given string. Call your function to test it works. For example,
    print( numWords("the quick brown fox") ) # will print 4
    
  5. Write a function makeString(myList) that takes a list of words as a parameter and returns one big string consisting of all words in the list separated by spaces. Call your function to test it works. For example,
    print( makeString(["the", "quick", "brown", "fox"]) ) # will print "the quick brown fox"
    

If you finish early

  1. Write a function shuffle(myList) that takes a list as a parameter and returns a new list with the elements shuffled in a random order. Hint: create a copy of myList, then repeatedly remove elements at random indicies of the copy list to put in the new list. It will help to use random.randint(start,end) from the random module which will give you a random integer between [start, end).

  2. Write a function partialEncrypt(myString) that takes a string as a parameter and returns a new string with all words shuffled in a random order. Hint: use the shuffle function you wrote earlier. For example, it might look something as follows:
    print( partialEncrypt("the quick brown fox")) # might print "quick fox the brown"
    
  3. Write a function anagram(myString) that takes a string as a parameter and returns a new string with all the words and letters shuffled in a random order. Hint: use the shuffle function you wrote earlier. For example, it might look as follows:
    print( anagram("the_quick_brown_fox")) # might print "o_ectquorhfxwkb_i_n"
    
  4. Write a function called indexOf(myList, key) that works similar to (but does not use) index. It should return the index where key belongs in myList, or -1 if it is not in the list.

How to submit

Submit your working python file to Moodle.