Dave_750
Dave_750

Reputation: 1245

Comparing string lists to find missing value of sequence

I have a list of days of the week that can potentially contain holidays, like Independence Day, instead of the day name, Friday. (doing weather data parsing) Looking for a way to compare my list to a list of days of the week and find the missing one (or more). I came up with the following and it will work fine for my purposes as long as there are not 2 in a row, but I'd really like to find a better approach and make it more solid and be able to repurpose it later. Might there be a standard library approach to this?

daysOfTheWeek = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]

days = ["NOTADAY", "saturday", "NOTADAY", "monday"]

repaired = []
for i, day in enumerate(days):
    try:
        dayIndex = daysOfTheWeek.index(day.lower())
    except ValueError:
        try:
            next = indices[i+1]
            dayIndex = next-1
        except IndexError:
            dayIndex = 6
    if dayIndex > 6:
        dayIndex = 0
    repaired.append(daysOfTheWeek[dayIndex])      

for r in repaired:
    print r.capitalize()

Upvotes: 1

Views: 2765

Answers (2)

dawg
dawg

Reputation: 103959

Assuming that you want to find at least one string in days that is contained in the rotating pattern of daysOfTheWeek so that the pattern of

days = ["NOTADAY", "sunday", "NOTADAY", "NOTADAY", "NOTADAY", "NOTADAY"]

Becomes:

['Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday']

This works:

if any(day in daysOfTheWeek for day in days):
    for i, day in enumerate(days):
        if day in daysOfTheWeek:
            j=daysOfTheWeek.index(day)
            repaired=[daysOfTheWeek[k % len(daysOfTheWeek)].capitalize() 
                                         for k in range(j-i, j+len(days)-i)]
            print days
            print repaired 
            break
else:
    print 'cannot be repaired'    

Upvotes: 1

Jeff Tsui
Jeff Tsui

Reputation: 1276

In python the general approach is to use sets.

set(daysOfTheWeek).difference(set(days))

will return the following set:

In [3]: set(daysOfTheWeek).difference(set(days))
Out[3]: {'friday', 'sunday', 'thursday', 'tuesday', 'wednesday'}

A collection of hashable objects can be converted into a set. Strings, tuples, ints are all hashable.

Upvotes: 0

Related Questions