# Solutions to suggested exercises -- Python review 1C
# Revised 2011 Sep 1 for Python 3 compatibility

# 1.  Accumulate lines of input

def accumLines ():
    results = []
    line = input("? ")
    while line != "":
        results.append(line)
        line = input("? ")
    return results

# Test ...

# 2.  The same, functionally, using recursion and without mutation.

def accumLinesF ():
    line = input("? ")
    if line == "":
        return []
    else:
        return [line] + accumLinesF()

# Test ...

# 3.  "firsts" with map
# Find first character of each string in a list, using map

def firsts1 (slist):
    return map (lambda s: s[0], slist)

# Test

names = ["Annabella", "Jo", "Art", "Fil", "Fibonacci", "Gilbert", "Horatio", ]
print(list(firsts1(names)))     # convert map object to list

# 4.  "shorts" with filter
# Find strings of length 4 or less in a list, using filter

def shorts1 (slist):
    return filter (lambda s: len(s) <= 4, slist)

# Test
print(list(shorts1(names)))     # convert filter object to list

# 5.  "firsts" with a list comprehension

def firsts2 (slist):
    return [s[0] for s in slist]

# Test
print(firsts2(names))

# 6.  "shorts" with a list comprehension

def shorts2 (slist):
    return [s for s in slist if len(s) <= 4]

# Test

print(shorts2(names))

# 7.  "firsts" of "shorts"
# First character of each string of length 4 or less in a list

# a.  using filter and map
def firsts_shorts1 (slist):
    return map(lambda s: s[0], filter(lambda s: len(s) <= 4, slist))

# b.  using a list comprehension

def firsts_shorts2 (slist):
    return [s[0] for s in slist if len(s) <= 4]

# c.  And here is yet another way (not requested by the exercise):

def firsts_shorts3 (slist):
    return firsts2(shorts2(slist))

# Test

print(list(firsts_shorts1(names)))
print(firsts_shorts2(names))
print(firsts_shorts3(names))
