JamCoders

💾 Download

JamCoders Week 2 Day 2 Lecture 2

Gunjan Mansingh

List Comprehension

In [19]:
[ n**2 for n in range(1,6)]
Out[19]:
[1, 4, 9, 16, 25]
In [21]:
[(x,y) for x in range (1,4) for y in range (1,4)]
Out[21]:
[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
In [3]:
[x+y for x in range (1,4) for y in range (1,4)]
Out[3]:
[2, 3, 4, 3, 4, 5, 4, 5, 6]
In [22]:
[x for x in range(1,30) if x%2==0]
Out[22]:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
In [23]:
a="lol"
a.upper()
Out[23]:
'LOL'
In [26]:
[x.upper() for x in ["This", "week", "will", "be", "fun"]]
Out[26]:
['THIS', 'WEEK', 'WILL', 'BE', 'FUN']

Question 1

You have been provided two functions stringList which given a string as an argument returns a list of strings and count_words which also takes a string and converts it to list of strings and then returns a list of the count of letters for each string

In [27]:
def stringList(str1):
    return str1.split()
In [28]:
stringList("This is a test run")
Out[28]:
['This', 'is', 'a', 'test', 'run']
In [29]:
def count_letters_in_words(str1):
    w_lst=stringList(str1)
    lst=[]
    for word in w_lst:
        l=len(word)
        lst=lst+[l]
    return lst
In [30]:
def count_letters_in_words2(str1):
    w_lst = stringList(str1)
    return [len(i) for i in w_lst]
In [31]:
count_letters_in_words2("This is a test run")
Out[31]:
[4, 2, 1, 4, 3]
In [15]:
def count_letters_in_words2(str1):
    w_lst =  stringList(str1)
    return [len(word) for word in w_lst]
In [16]:
count_letters_in_words2("This should be fun")
Out[16]:
[4, 6, 2, 3]

Question 2 Using list comprehension, define a python function unlucky, which returns all the days in a given year which have the date Friday 13th.

A list of daynames and a fucntion which returns day of the week for a date are provided Hint: you need two ranges one for day starting from 1 and going to 31 and another one for month starting from 1 going to 12. Using these and the year which comes as an argument and use the function day_of_week (Problem 2) in the if part of list comprehension to check if a given date is ‘Friday’ and also check if the day is equal to 13.

In [42]:
day_names = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
In [41]:
def day_of_week(d,m,y):
    day = (((13*m+3) // 5 + d + y + (y // 4) - (y // 100) + (y // 400)) %7)
    return day_names[day]
In [44]:
day_of_week(16,7,2022)
Out[44]:
'Saturday'
In [48]:
def unlucky(y):
 return [(d,m,y) for m in range(1,13) for d in range (1,32) if d == 13 and day_of_week(d,m,y) == "Friday"]
In [51]:
unlucky(2019)
Out[51]:
[(13, 1, 2019), (13, 9, 2019), (13, 12, 2019)]