# find the position of a lower-case character in the alphabet
# e.g. 'a' -> 0, and 'z' -> 25, 'A' -> 0 and'Z' -> 25
def is_lower(c):
    return ord('a') <= ord(c) <= ord('z')

def is_upper(c):
    return ord('A') <= ord(c) <= ord('Z')

def alphapos(c):
    if is_lower(c):
        return ord(c) - ord('a')
    if is_upper(c):
        return ord(c) - ord('A')

# Problem 1a
def ToUpper(s):
    answer = ''
    for c in s:
        if is_lower(c):
            answer += chr(ord('A') + alphapos(c))
        else:
            answer += c
    return answer

# ... and while we're at it:
def ToLower(s):
    answer = ''
    for c in s:
        if is_upper(c):
            answer += chr(ord('a') + alphapos(c))
        else:
            answer += c
    return answer
    

# this is a more general technique of encrypting with a Caesar cipher
# with a shift of n positions

# Problem 1b
def Caesar(text_in, shift):
    answer = ''
    for c in text_in:
        if is_lower(c):
            answer += chr(ord('a') + (alphapos(c) + shift) % 26)
        elif is_upper(c):
            answer += chr(ord('A') + (alphapos(c) + shift) % 26)
        else:
            answer += c
    return answer

# Problem 2a
def IsSameName(name1,name2):
    return ToUpper(name1) == ToUpper(name2)

# Problem 2b
def CapWord(word):
    return ToUpper(word[0])+ToLower(word[1:])

# Problem 2c
def CapName(name):
    first_last = name.split(' ')
    return CapWord(first_last[0]) + ' ' + CapWord(first_last[1])

#Problem 3a
def FirstLast(name):
    first_last = name.split(' ')
    return first_last[1] + ' ' + first_last[0][:-1]

# Problem 3b
def FirstLastSequence(names):
    the_names = names.split(';')
    for i in range(len(the_names)):
        if the_names[i] != '':
            the_names[i] = FirstLast(the_names[i])
    return ';'.join(the_names)

# Problem 4
def FileClassifier(filename):
    suffixes = ['jpg', 'jpeg', 'mp3', 'nlogo', 'py']
    answers = ['picture','picture','music','Netlogo','Python']

    for i in range(len(suffixes)):
        n = len(suffixes[i])
        if suffixes[i] == ToLower(filename)[-n:]:
            return answers[i]

# Triple Challenge
def TCP():
    crypt_text = 'Zw z yrmv jvve wlikyvi zk zj sp jkreuzex fe kyv jyflcuvij fw Xzrekj'
    teams = ['jets','islanders','mets','yankees','giants','nets']

    text_lower = ToLower(crypt_text)
    for shift in range(1,26):
        plain = Caesar(text_lower,shift)
        for team in teams:
            if team in plain:
                return Caesar(crypt_text,shift)
            

def perfect_numbers(high):
    for n in range(2,high+1):
        factors = [1]
        for factor in range(2,int(n**.5)+1):
            if n%factor == 0:
                factors += [factor,int(n/factor)]
        if sum(factors) == n:
            answer = '%d = 1' % n
            for i in range(1,len(factors)):
                answer += ' + '+str(factors[i])
            print (answer)