Tuesday, December 9, 2014

1.3.7 Activity response: For loops

On this assignment I only needed to do two of these three, but I went ahead and did all of them.

The first function, hangman_display(), will return the 'secret' string with letters that aren't in 'guessed' hidden or crossed out, much like in Hangman.
ex: hangman_display("aeiou", "hello world") -> "-e--o -o---"

The second, matches(), counts how many items between the two lists match, assuming neither list has duplicate items.
ex: matches([1,2,3], [2,3,4]) -> 2

The last function, report(), functions like the game Mastermind, returning how many items are the same in value and position, and how many items are in both lists but in different positions.
ex: report([a, b, c, d], [a, c, b, e]) -> [1, 2]

def hangman_display(guessed, secret):
    ret = ""
    for i in secret:
        x = 0
        for j in guessed:
            if i.lower() in j.lower():
                x = 1
        if x == 1 or (i in " !,.?"):
            ret = ret + i
        else:
            ret = ret + "-"
    return ret


def matches(tickets, winners):
    ret = 0
    for i in tickets:
        x=0
        for j in winners:
            if i==j:
                x = 1
        if x==1:
            ret += 1
    return ret


def report(guess, secret):
    ret = [0, 0]
    used = []
    for i in range(len(secret)):
        if secret[i]==guess[i]:
            used.append(i)
            ret[0] += 1
    for i in range(len(secret)):
        for j in range(len(guess)):
            if (not(j in used or i in used)) and secret[i]==guess[j]:
                ret[1] += 1
                used.append(j)
    return ret

Conclusion question answers:

  1. This practice, known as "loop unrolling", is actually used in some cases to speed up program execution at the cost of increasing the program size. Using unrolled loops during development is tedious, boring and just plain inefficient- it'd be a royal pain to change an unrolled version of "for i in range(10):" to "for i in range(1000):", and even more painful to change anything inside said loop.
  2. A grocery store computer might iterate over a list of items in stock.
  3. Both iteration and data analysis deal with large amounts of data. Iteration reads from and/or changes information about each item, whereas data analysis only reads from them to get statistics.

2 comments: