#Quiz06

  • Define a function sum() and a function multiply() that sums and multiplies (respectively) all the numbers in a list of numbers. For example, sum([1, 2, 3, 4]) should return 10, and multiply([1, 2, 3, 4]) should return 24.

Screen Shot 2017-02-20 at 7.46.17 pm.png

For this exercise, we start by setting my_sum to 0 as inside the for loop the update occurs. my_sum is reassigned a new value which is my_sum + each element in the list.

 

  • Define a function reverse() that computes the reversal of a string. For example, reverse("I am testing") should return the string "gnitset ma I".

Screen Shot 2017-02-20 at 8.00.51 pm.png

Thanks to [::-1], we can have the sentence written by the user reversed!

 

  • Define a function is_palindrome() that recognises palindromes (i.e. words that look the same written backwards). For example, is_palindrome("radar") should return True.

Screen Shot 2017-02-21 at 6.22.04 pm.png

A useful trick for this function was to use the word.upper() Python string method. It allows you to ask the user either upper or lower case words. As stated above, the [::-1] is an easy way to have a whole string reversed. We insert a if statement inside the function asking to return True if the reverse of the word is equal to the word.

 

  • Write a function is_member() that takes a value (i.e. a number, string, etc) x and a list of values a, and returns True if x is a member of a, False otherwise. (Note that this is exactly what the in operator does, but for the sake of the exercise you should pretend Python did not have this operator.)

Screen Shot 2017-02-21 at 6.28.06 pm.png

I defined the function is_member with the two parameters x and alist. I used a for loop as it check for each of the elements in the list, one by one. If any of the element in the list [1,2,3,7,90] equals to x, the function returns true.

 

  • Define a function overlapping() that takes two lists and returns True if they have at least one member in common, False otherwise. You may use your is_member() function, or the in operator, but for the sake of the exercise, you should (also) write it using two nested for-loops.

Screen Shot 2017-02-21 at 6.31.26 pm.png

First, I defined the overlapping function which takes two arguments, x & y. Then I wrote a two nested for-loops. For each elements in x, and for each element in y. Finally comes the if statement which check if any of the elements in x are equal to any of the elements in y. If so, the function returns true.

Leave a comment