Python Week 4
27 February 2018
Python Week 4 Challenges
This week, we're going to encourage you to be a little more self-sufficient in your learning, which means you might have to google stuff on your own! That said, all of the following below can also be done with just the content that has been taught in lectures by using loops.
Generating a List from the user
Write a function which repeatedly keeps asking the user for number (float) input and puts it into a list. The function should keep going on (potentially forever) if the user keeps entering numbers. However, if the user enters
end, then the function terminates, and returns the created list.
Summing a list
Write a function which, given a list of numbers, sums up all the numbers within the list and returns the result. There should be no side effects on the original list. BONUS: Whilst you could certainly do this by using a loop and adding each element of the list to an accumulator variable, Python already has a built-in function which does this. Go into the depths of the internet and google your way to this solution!
Adding a number
n to a list
Write a function which takes a list of numbers, and a number
n, and returns a NEW list of the the original numbers plus
n. For example, calling this function with
10 should return
[15,17,19]. Once again, there should be no side effects on the original list. BONUS: Once again, there's a really, really easy way to do this that's already built into Python. You might want to look up what a
lambda function in Python is, as well as the
map() function. BONUS 2: There's also another REALLY easy way to do this on one line as well. Look up what a
list comprehension in Python is.
Multiplying a list of numbers by
Similar to the above question, instead of adding
n, multiply the number by
n instead. BONUS: Can you do it by using a map and lambdas (see above BONUS for details), or with a list comprehension?
Adding two lists of numbers together
Given two lists of numbers, returns a new list containing the sum of numbers. If the lists are not of the same length, then simply ignore the elements of the longer list at index greater than the length of the shorter list. BONUS: There's a recurring theme going on here! Once again, you can do this with a list comprehension as well. You might want to also google
Checking if an element is in a list
Given a list and an element
elem (both of any type), write a function that returns either
False, based on whether
elem has an identical (by value) element in the given list. BONUS: Python actually has a built-in 1 line way to do this. Can you google your way to find it?