# Answers to the List and String Exercises

# ===========================================================
# 1. reversing strings inside lists
def Esrever(L):
    answer=[]
    for astring in L:
        answer.append(astring[::-1])
    return answer

# 1. using a list comprehension
def Esrever1(L):
    return [s[::-1] for s in L]


# =============================================================
#2. Average of numbers in a list
def Av(L):
    if len(L) == 0:
        return 0.0
    total=0.0
    for n in L:
        total+=n
    return total/len(L)

#2. But wait, there's a built-in sum function...
def Av1(L):
    if len(L)==0:
        return 0.0
    return sum(L)/float(len(L))     # convert at least one of your numbers to
                                    # or the division may involve only integers
                                    # and then you'll get a quotient

# ===============================================================
# 3. Find the position of the smallest element in a list
def SmallestPos(L):
    smallest=L[0]
    where=0
    for i in range(1,len(L)):
        if L[i]<smallest:
            smallest=L[i]
            where=i
    return where

#3. But wait, there's a built-in min() function, returning the smallest element.
def SmallestPos1(L):
    return L.index(min(L))

# ================================================================
# 4. Sort a list of numbers
def SortNums(L):
    answer=[]
    while len(L) > 0:
        pos=SmallestPos(L)
        answer.append(L[pos])
        del L[pos]  # or delete it this way: L[pos:pos+1]=[]
    return answer

# 4. Ah, the forbidden way:
def SortNums1(L):
    return sorted(L)

# ==================================================================
# Challenge
def NumInWords(n):
    To19=['zero','one','two','three','four','five','six','seven','eight','nine', \
          'ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen', \
          'seventeen','eighteen','nineteen']
    Tens=['','','twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']

    if n<=19:
        return To19[n]
    if n<100:
        if n%10==0:
            return Tens[n/10]
        return Tens[n/10]+'-'+To19[n%10]
    if n%100==0:
        return To19[n/100]+' hundred'
    return To19[n/100]+' hundred and '+NumInWords(n%100)