ExercisesΒΆ

  1. Create a list containing 100 random integers between 0 and 1000 (use iteration, append, and the random module). Write a function called average that will take the list as a parameter and return the average.


    
    
    

    (ex_9_4)

  2. Write a Python function that will take a the list of 100 random integers between 0 and 1000 and return the maximum value. (Note: there is a builtin function named max but pretend you cannot use it.)


    
    
    

    (ex_9_5)


    
    
    

    (q5_answer)

  3. Write a function sum_of_squares(xs) that computes the sum of the squares of the numbers in the list xs. For example, sum_of_squares([2, 3, 4]) should return 4+9+16 which is 29:


    
    
    

    (ex_7_11)

  4. Write a function to count how many odd numbers are in a list.


    
    
    

    (ex_9_6)


    
    
    

    (q7_answer)

  5. Sum up all the even numbers in a list.


    
    
    

    (ex_9_7)

  6. Sum up all the negative numbers in a list.


    
    
    

    (ex_9_8)


    
    
    

    (q9_answer)

  7. Count how many words in a list have length 5.


    
    
    

    (ex_9_9)

  8. Sum all the elements in a list up to but not including the first even number.


    
    
    

    (ex_9_10)


    
    
    

    (q11_answer)

  9. Count how many words occur in a list up to and including the first occurrence of the word “sam”.


    
    
    

    (ex_9_11)

  10. Although Python provides us with many list methods, it is good practice and very instructive to think about how they are implemented. Implement a Python function that works like the following:

    1. count
    2. in
    3. reverse
    4. index
    5. insert

    
    
    

    (ex_9_12)


    
    
    

    (q13_answer)

  11. Write a function replace(s, old, new) that replaces all occurences of old with new in a string s:

    test(replace('Mississippi', 'i', 'I'), 'MIssIssIppI')
    
    s = 'I love spom!  Spom is my favorite food.  Spom, spom, spom, yum!'
    test(replace(s, 'om', 'am'),
           'I love spam!  Spam is my favorite food.  Spam, spam, spam, yum!')
    
    test(replace(s, 'o', 'a'),
           'I lave spam!  Spam is my favarite faad.  Spam, spam, spam, yum!')
    

    Hint: use the split and join methods.


    
    
    

    (ex_9_13)

Next Section - Dividi et Impera