trayceetrace
trayceetrace

Reputation: 7

How can I solve this function with list comprehension?

    yearlist = []
    unluckydates = []
    for year in range(end):
        unluckydates = unlucky(year)
        if len(unluckydates) == 3:
            yearlist.append(year)
    return yearlist

Here's what each of the variables is used for:

unlucky(year) is a function that accepts the year and returns the unlucky dates (Friday 13th) in a list.

unluckydates is used to store the list from unlucky(year)

yearlist is used to store years that have 3 unlucky dates (Friday 13th)

The function returns a list of all the years from 0 to 2016 that have 3 unlucky dates. I wrote it this way, now, I want to know how I can write it using list comprehension.

Here's the line I came up with:

yearlist.append([(unlucky(year), unluckydates == unlucky(year)) for year in range(0, end) if len(unluckydates) == 3])

Upvotes: 0

Views: 285

Answers (1)

Moses Koledoye
Moses Koledoye

Reputation: 78546

This is one way to do it:

def mostUnlucky1(end):
    return [year for year in range(end) if len(unlucky(year)) == 3]

Note that since the target variable of the for loop is named year (means it gets a new value at every iteration), the year += 1 at the end of the for loop is redundant.

And you can drop the zero start index for range.

Upvotes: 1

Related Questions