CS 100

Logo

Scientific Computing

Activity 17 - Lists

Create a file activity17.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? Comment out any lines which produce syntax errors.
    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?
    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 print the number of words in the sentence "the quick brown fox" Hint: use split.
  5. Although Python provides many list methods, it’s good practice and instructive to think about how they are implemented. Write a function called checkIn(myList, key) that works similar to (but does not use) in. It returns True if the given key is in list, and False otherwise.

If you finish early

  1. 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.
  2. Write a function shuffle that takes a list as a prameter and returns a new list with the elements shuffled in a random order. Print out the original and the returned list to ensure the original list is in tact and the returned list is shuffled.

How to submit

Submit your working activity17.py to Moodle.