Friday, December 12, 2014

1.3.8 Activity response: While loops

Here I made a guessing game where you have to guess a number between 1 and 20 inclusive. It tells you if you guessed too high or too low, and even if you guessed a number outside of 1-20.

import random
def goguess():
    maxval = 20
    minval = 1
    target = random.randint(minval, maxval)
    print("I have a number between " + str(minval) + " and " + str(maxval) + ".")
    guess = int(raw_input("Guess: ")) #We put our first guess here because we check
    count = 1                         #the guess at the beginning of the while loop.
    while (not (guess == target)): #the while loop ends when you guess the number.
        if (guess <= maxval and guess >= minval):
            if (guess < target):
                print(str(guess) + " is too low.")
            else:
                print(str(guess) + " is too high.") # Tells if the guess is high or low.
            count += 1 #adds 1  to the count... count.
        else:
            if guess > maxval:    #Remind them if they guess outside the range.
                print(str(guess) + "is higher than " + str(maxval) + ".")
            else:
                print(str(guess) + "is lower than " + str(minval) + ".")
        guess = int(raw_input("Guess: "))
    print("You got it! The number was " + str(target) + ", and you guessed it in " + str(count) + " turns.") #This prints when the 'while' loop ends.

Conclusion question answers:

Q1: If you change between 1 and 20 from the previous program to between 1 and 6000, how many guesses will you need to guarantee that you have the right answer? Explain.

A1: To figure out how many guesses you need, you need find the first power of two above the maximum number. For example, guessing a number in a range 1-7 inclusive would take only three guesses.
2^guesses > max
2^3   = 8       > 7       --3 guesses for a range 1-7
2^5   = 32     > 20     --5 guesses for a range 1-20
2^13 = 8192 > 6000 --13 guesses for a range 1-6000.


Q2: Explain the difference between a while loop and a for loop.

A1: A "while" loop repeats constantly until a condition is met, whereas a "for" loop iterates through a list of values. In some languages like java you could use them interchangeably, but it's generally easier and faster to use whichever one makes more sense for the situation.

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.

Thursday, December 4, 2014

1.3.6 Activity response: lists and tuples

Hilariously, I only used lists to test the second function despite the lesson being on lists and tuples.

import random
def roll_two_dice():
    a = random.randint(1,6)
    b = random.randint(1,6)
    return a+b

def guess_letter():
    letters = 'abcdefghijklmnopqrstuvwxyz'
    return letters[random.randint(0,len(letters)-1)]

Question answers:

  1. A can be printed and concatenated as a standard string, B can be appended and store different string lengths in each element, and C can only be read from.
  2. Languages have different variable types because different variables' contents are incompatible by nature.  "A" + 32 + True - (1,2,3) = ????
  3. Technically speaking, everything COULD be represented as integers since computers store everything as 1s and 0s anyways, but using integers to store a string would be incredibly difficult and inefficient.

Wednesday, December 3, 2014

1.3.5 Activity response: Strings

So recently I was asked to make a "Tweet verifier" in Python for a fictional "inspirational quote" contest. The Tweet needs to be 140 characters or less and needs a comma, a quote, a question mark and an exclamation mark.

The code:

from __future__ import print_function
def CheckTweet(Tweet):
    com = ',' in Tweet
    quo = '"' in Tweet
    que = "?" in Tweet #These are true of the character is in the tweet.
    exc = "!" in Tweet
    length = len(Tweet)<=140 #This is false if the tweet is over 140 characters.
    over = str(len(Tweet)-140) #Store how many characters the tweet is over the limit.
    errors = []
    if not com:
        errors.append("a comma") #Put what's missing in proper english in a list.
    if not quo:
        errors.append("a quote")
    if not que:
        errors.append("a question")
    if not exc:
        errors.append("an exclamation mark")
    if com and quo and exc and que: #If nothing is missing...
        if length:
            return "Tweet verified. You're good to go!" #AND if it's short enough.
        else:
            return "Sorry, but your Tweet is " + over + " characters over the limit (140)." 
    else:
        msg = "Sorry, but your tweet needs " #Starting off the 'missing stuff' message
        
        if len(errors)==1: #Add commas, periods and 'and's between what's missing to make proper english!
            msg = msg + errors[0] + "."
        elif len(errors)==2:
            msg = msg + errors[0] + " and " + errors[1] + "."
        elif len(errors)==3:
            msg = msg + errors[0] + ", " + errors[1] + " and " + errors[2] + "."
        else:
            msg = msg + errors[0] + ", " + errors[1] + ", " + errors[2] + " and " + errors[3] + "."
        if not length: #If you're ALSO over the limit, add this in a second line.
            msg = msg + "\nAdditionally, your Tweet is " + over + " characters over the limit (140)."
        return msg
 
tweet = raw_input('Your Tweet: ')
print(CheckTweet(tweet))

Conclusion question answers:
  1. There are 41 characters in "How many characters are in this sentence?", and it doesn't matter how many bytes Python uses to store each character; either way, Python would return the same number of characters.
  2. In lines 1 and 2, variables A and B are assigned 'one string' and 'another' respectively. In line 3, variable C is assigned a combination the first three characters of A ('one'), ' and ' and the contents of variable B ('another') to get 'one and another'. Line 4 prints characters 7-10 of variable C, which is just 'd a'.