'''
Created on Oct 17, 2011

@author: rodger
'''
import os
import tkFileDialog

    
def choose_file_to_open():
    """
    prompt for existing file, return the file (open for reading)
    """
    file = tkFileDialog.askopenfile(title="choose a file", initialdir=os.getcwd())
    return file

def processFile(file):
    '''
    process the lines in a file
    return a list of lists
    '''
    allLists = []
    for line in file:
        linelist = line.split()
        # remove course number
        allLists.append(linelist[1:])
    return allLists
        
        
def peopleTakingCourses(data):
    ''' data is a list of lists of names for each course,
    return list of all strings that appear at least once '''
    names = set([])
    for lista in data:
        seta = set(lista)
        names = names|seta
    #return [w for w in names]
    return list(names)
    
    
    
def peopleTakingOnlyOneCourse(data):
    ''' data is a list of lists of names for each course,
    returns list of people taking only one course '''
    names = set([])
    listOfSets = [set(w)  for w in data]
    
    for (index, s) in enumerate(listOfSets):
        unionOtherCourses = unionAllSetsButMe(listOfSets, index)
        for person in s:
            if person not in unionOtherCourses:
                names.add(person)
    return list(names)
    
    
def unionAllSetsButMe(allsets, me): 
    ''' allsets is a list of lists, me is the index number of
    one of the sets in allsets, returns the union of all the
    sets except the set in position me '''
    answer = set([])
    for (index,s) in enumerate(allsets):
        if index != me:
            answer = answer | s
    return answer


allcourses = processFile(choose_file_to_open())
print allcourses



allpersons = peopleTakingCourses(allcourses)
allpersons.sort()
print str(len(allpersons)) + " people taking one or more courses"
print allpersons


listOfSets = [set(w)  for w in allcourses]
print "is this a set"
print listOfSets
print unionAllSetsButMe(listOfSets, 3)

print
print "allcourses again after"
print allcourses
allonecourse = peopleTakingOnlyOneCourse(allcourses)
allonecourse.sort()
print str(len(allonecourse)) + " people taking only one course"
print allonecourse

