Sunday, October 20, 2013

Review from Term Test 1(Week 6)

We do not have classes this week, due to Thanksgiving Day and Term Test 1.

However, I still learnt a lot from our Term Test and Lab.

Firstly, I learnt when we compare tuples, we only compare the first index. If they have the same first, then we compare the second and so on.

For example:
>>>a = (1, 2, 3)
>>>b = (2, 1, 3)
>>>c = (1, 3, 2)
>>>a > b
False
>>>a < b
True
>>> a < c
True
>>> a > c
False

Secondly, we would like to talk about a very useful thing from our lab.

def squares_build_list(n: int) -> list:
    """list the squares of first n natural numbers
    >>> squares_build_list(6)
    [0, 1, 4, 9, 16, 25]
    """
    L = []
    for num in range(n):
        L.append(num ** 2)
    return L

def squares_use_comp(n: int) -> list:
    """list squares of first n natural numbers
    >>> squares_use_comp(6)
    [0, 1, 4, 9, 16, 25]
    """
    return [num ** 2 for num in range(n)]

By looking these two functions, they do the same things, but second one only wrote 1 line. This is amazing by using List Comprehensions.

No comments:

Post a Comment