Example #1
0
        return retval


my_photo = Photo(title="Photo1",
                 author="Ansel Adams",
                 tags=["Nature", "Mist", "Mountain"])

## Write code to create an instance of the photo class and store it in the variable my_photo.
## display_info(my_photo) should produce the following string. HINT: if you just call the constructor
## for the Photo class appropriately, everything will be taken care of for you. You just have to figure out,
## from the definition of the class, what to pass to the constructor.

display_string = "Photo: Photo1\nPhotographed by: Ansel Adams\nTags: Nature Mist Mountain "

try:
    test.testEqual(my_photo.display_info(), display_string, "Problem 2")
except:
    print "Failed Test for problem 2; my_photo not bound or code for display_info or display_string was changed"

# ----------------Don't change code in this seciton----------------

## You won't need to change any code below this line. But definitely
## read it and understand it! Hint: Thinking back and looking at the flow chart from
## the first user-played Hangman problem set may help.

# Below is the full set of Hangman code.
# If you run this code without adding or changing anything,
# the computer will play Hangman on manual mode, so
# if you keep pressing Enter, you can watch it play.

# Try it out! Then you'll build a couple functions that will make this game better.
Example #2
0
# Remember, requests.get() says 'go get data from the internet from...'.
print '---------------'
baseurl = 'http://services.faa.gov/airport/status/'
airport = 'DTW'
# Write your line of code below:
airport_response = requests.get( baseurl + airport, params = url_parameters )

# Again, simple -- we're doing this step by step.

## Testing problem 1
print
print "--------------"
print
try:
    test.testEqual(url_parameters, {'format':'json'}, "testing correct output for 1(a)")
except:
    print "test 1(a): The variable url_parameters is not defined or there is an error in your code."
try:
    test.testEqual(type(airport_response),type(requests.get("http://google.com")), "testing correct type of expression for 1(b)")
except:
    print "test 1(b): The variable airport_response is not defined or there is an error in your code."

# [PROBLEM 2]
## Grabbing data off the web
# (2)  Put the request you made in problem 1 in a proper try/except clause.
#      Then, use the .json() method on the response you get back to turn the data
#      in one big Python dictionary. Save that in the variable
#      airport_data.
#   Follow the comments!
Example #3
0
### PROBLEM 1.
# We have provided test cases for the first function, as an example. 
# Write at least two test cases each for the next three functions

def letter_freqs(word_list):
    letter_freq_dict = {}
    for w in word_list:
        for l in w:
            if l not in letter_freq_dict:
                letter_freq_dict[l] = 1
            else:
                letter_freq_dict[l] = letter_freq_dict[l] + 1
    return letter_freq_dict

test.testEqual(type(letter_freqs(["hello", "goodbye"])), type({}))
test.testEqual(letter_freqs(["good", "bad", "indifferent"]), {'a': 1, 'b': 1, 'e': 2, 'd': 3, 'g': 1, 'f': 2, 'i': 2, 'o': 2, 'n': 2, 'r': 1, 't': 1})
test.testEqual(letter_freqs(["good"]), {'g':1, 'o':2, 'd':1})
test.testEqual(letter_freqs([]), {})
    
def key_with_biggest_value(diction):    
    most_freq_letter = diction.keys()[0]
    for item in diction.keys():
        if diction[item] > diction[most_freq_letter]:
            most_freq_letter = item
    return most_freq_letter

test.testEqual(key_with_biggest_value({'a': 1, 'b': 1, 'e': 2, 'd': 3, 'g': 1, 'f': 2, 'i': 2, 'o': 2, 'n': 2, 'r': 1, 't': 1}), 'd') 
test.testEqual(key_with_biggest_value({'a': 1}), 'a') 
test.testEqual(key_with_biggest_value({'a': 1, 'b': 1, 'e': 2, 'd': 3, 'g': 1, 'f': 3, 'i': 2, 'o': 2, 'n': 3, 'r': 1, 't': 1}), 'd')
    
Example #4
0
            self.highscore = self.score
        self.score_label.text = "Score: %s Highscore: %s" % (self.score, self.highscore)
        
    
    def center_image(self, image):
        image.anchor_x = image.width/2
        image.anchor_y = image.height/2

    def sprites_collide(self, spr1, spr2):
        return (spr1.x-spr2.x)**2 + (spr1.y-spr2.y)**2 < (spr1.width/2 + spr2.width/2)**2

game_window = GameWindow()

# Test case to make sure that score is an integer because needs to get added to
# to other integers later on in update_score method
test.testEqual(type(game_window.score), type(1) )

# Test case to make sure that highscore is a integer in the __init__ method 
# so that it can be added to other integers later
test.testEqual(type(game_window.highscore), type(1))

# Test case to make sure that bluebus is a list so that elements can get added to it
# later on in update_bluebus method
test.testEqual(type(game_window.bluebus), type([]))

# I added this here to meet the list comprehension and sort requirement! I couldn't find
# a logical place to implement it in my game code. Hopefully this shows that I am capable of
# writing these kind of things!!
gamelist = ["Thank", 12, "you", "for", 2015, "playing", "Diag", "Squirrel","Doger", 14]
wordsonly = [element for element in gamelist if type(element) == type("")]
for element in wordsonly:
Example #5
0

print "\n\nInitializing the TextInformation class and the methods you can use it for" +'\n\n'
First_Instance = TextInformation(text)
First_Instance.top_five()
First_Instance.most_freqs_word()
First_Instance.most_freqs_lets()
First_Instance.word_count('Ah')

print "\n\nTime to see the accuracy of our Shannon Game Guesser" +'\n\n'
gameInstance = ShannonGameGuesser(text, rules_text)
gameInstance.performance()


print "That's the end of my project, hope you enjoyed it! If you would like to see a variance in accuracy of the guesser, simply change the position of the two letter rules and the initial rules created. Oddly enough, the two letter guesser is not very accurate."


Practice_Instance = TextInformation("This is a test string for my SI 106 final project. Let's see what TextInformation we can find out")
Testing_Instance = ShannonGameGuesser("This is a test string for my SI 106 final project. Let's see what TextInformation we can find out", rules_text)
test.testEqual(type(Practice_Instance.top_five()), type(Practice_Instance.word_count('Hey')))
test.testEqual(type(Testing_Instance.performance()), type(Practice_Instance.most_freqs_lets()))
test.testEqual(type(Practice_Instance.most_freqs_word), type(Testing_Instance.performance))








Example #6
0
    def getSong(self):
        return self.Song

    def getAlbum(self):
        return self.Album

    def getNumber(self):
        return self.Number

    def getCost(self):
        return self.Cost


example = Music('Drake', 'Jumpman', 'What a Time To Be Alive', '9', '9.99')
test.testEqual(example.getArtist(), 'Drake')
test.testEqual(example.getSong(), 'Jumpman')
test.testEqual(example.getAlbum(), 'What a Time To Be Alive')
test.testEqual(example.getNumber(), '9')
test.testEqual(example.getCost(), '9.99')

stars = "**********"
star_list = []
for char in stars:
    star_list.append(char)
star_line = reduce(lambda first, second: first + "*" + second, star_list)

print ""
print ""
print star_line
print " Top Music Artists"
Example #7
0
    if " (" in name:
        if "," in name:
            return name.replace(",", "").partition(" (")[0].lower()
        else:
            return name.partition(" (")[0].lower()
    if "(" in name:
        return name.partition("(")[0].lower()
    if "-" in name:
        return name.partition("-")[0].lower()
    if " -" in name:
        return name.partition(" -")[0].lower()
    else:
        return name.lower()


test.testEqual(clean_name('me, myself'), 'me myself')
test.testEqual(clean_name('me, myself-fear'), 'me myself')
test.testEqual(clean_name('me, myself (feat'), 'me myself')
test.testEqual(clean_name('one dance ('), 'one dance')
test.testEqual(clean_name('one dance '), 'one dance')
test.testEqual(clean_name('one dance- feat drake '), 'one dance', "Clean Name")

oauth = raw_input(
    "Enter the OAuth Token. To get ouath goto (https://developer.spotify.com/web-api/console/get-playlist/#complete) (owner id = spotify) (playlists id =4hOKQuZbraPDIfaGbM3lKI)"
)
#oauth = "BQBKBq2WKabFgZwFk5IQa1HVLnC3rwuDBjGh3bhKaUDNITzYOPbfL2xjho4Ff3QbpKwHF48CJfVLqZjGoNhZpR0Z718a838WfByMiNZtDCwslD1d6W_seEiqpNyVSaVBHj_qlyrG2oGE5Hk"


def spotify_source():
    baseurl_spotify = 'https://api.spotify.com/v1/users/'
    spotify_secret = 'bc8d25d34bcc4b34ab7a8ec3867a6cb9'
Example #8
0
### PROBLEM 1.
# We have provided test cases for the first function, as an example. 
# Write at least two test cases each for the next three functions

def letter_freqs(word_list):
    letter_freq_dict = {}
    for w in word_list:
        for l in w:
            if l not in letter_freq_dict:
                letter_freq_dict[l] = 1
            else:
                letter_freq_dict[l] = letter_freq_dict[l] + 1
    return letter_freq_dict

test.testEqual(type(letter_freqs(["hello", "goodbye"])), type({}), "Looks like you're good to go!")
test.testEqual(letter_freqs(["good", "bad", "indifferent"]), {'a': 1, 'b': 1, 'e': 2, 'd': 3, 'g': 1, 'f': 2, 'i': 2, 'o': 2, 'n': 2, 'r': 1, 't': 1})
test.testEqual(letter_freqs(["good"]), {'g':1, 'o':2, 'd':1})
test.testEqual(letter_freqs([]), {})
    
def key_with_biggest_value(diction):    
    most_freq_letter = diction.keys()[0]
    for item in diction.keys():
        if diction[item] > diction[most_freq_letter]:
            most_freq_letter = item
    return most_freq_letter

test.testEqual(key_with_biggest_value({'hi': 2, 'good': 4, 'bye': 3, 'hi': 6}), 'hi')
test.testEqual(type(key_with_biggest_value({'hi': 2, 'good': 4, 'bye': 3, 'hi': 6})), type(""))   

Example #9
0
# ----------------

## [PROBLEM 2] 

fall_list = ["leaves","apples","autumn","bicycles","pumpkin","squash","excellent"]
sorted_fall_list = sorted(fall_list, reverse = True)
print sorted_fall_list
# Write code to sort the list fall_list in reverse alphabetical order. 
# Assign the sorted list to the variable sorted_fall_list.

# Now write code to sort the list fall_list by length of the word, longest to shortest.
# Assign this sorted list to the variable length_fall_list.

length_fall_list = sorted(fall_list, key = len, reverse = True)
try:
    test.testEqual(sorted_fall_list[0], 'squash', "squash first")
    test.testEqual(length_fall_list[0], 'excellent', "excellent first")
except:
    print "sorted_fall_list or length_fall_list don't exist or have no items"

# -----------------

## [PROBLEM 3]

food_amounts = [{"sugar_grams":245,"carbohydrate":83,"fiber":67},{"carbohydrate":74,"sugar_grams":52,"fiber":26},{"fiber":47,"carbohydrate":93,"sugar_grams":6}]

# Write code to sort the list food_amounts by the key "sugar_grams", from lowest to highest.
# Assign the sorted list to the variable sorted_sugar.
sorted_sugar = sorted(food_amounts, key = lambda food_amounts: food_amounts['sugar_grams'])
print sorted_sugar
# Now write code to sort the list food_amounts by 
Example #10
0
        return retval


## Write one line of code to create an instance of the photo class and store the instance in a variable my_photo.
my_photo = Photo(title="Photo1",
                 author="Ansel Adams",
                 tags=("Nature", "Mist", "Mountain"))
## After you do that, my_photo.display_info() should produce the same string as the one stored in display_string.

# HINT: if you just call the constructor for the Photo class appropriately, everything will be taken care of for you. You just have to figure out, from the definition of the class, what to pass to the constructor. Remember the examples of creating a class instance from the textbook and from lecture/section!

# DO NOT CHANGE THE STRING STORED IN THIS VARIABLE - it is just for comparison!
display_string = "Photo: Photo1\nPhotographed by: Ansel Adams\nTags: Nature Mist Mountain "

try:
    test.testEqual(my_photo.display_info(), display_string, "Problem 2")
except:
    print "Failed Test for problem 2; my_photo variable not assigned or code for display_info or display_string was changed..."

### PART 2: Get data from Flickr - useful stuff for the rest of the Problem Set

flickr_key = "853af3d1deca3557393aa1d948e43a7d"  # paste your flickr key here, so the variable flickr_key contains a string (your flickr key!)
if not flickr_key:
    flickr_key = raw_input(
        "Enter your flickr API key, or paste it in the .py file to avoid this prompt in the future: \n>>"
    )

## Useful function definition provided for you below.
## (You've seen this before, in the textbook. Other functions provided for you in the textbook may be useful in this Problem Set, too, if you understand how to use them...)

Example #11
0
# In this line, we are creating a json formatted dictionary of the text file.
p = Post(sample_post_dict)
# In this line, we are making an instance of the class Post using the sample_post_dict.

# use the next lines of code if you're having trouble getting the tests to pass.
# they will help you understand what a post_dict contains, and what
# your code has actually extracted from it and assigned to the comments
# and likes instance variables.
#print pretty(sample_post_dict)
#print pretty(p.comments)
#print pretty(p.likes)

# Here are tests for instance variables set in your __init__ method
print "-----PROBLEM 1 tests"
try:
    test.testEqual(type(p.comments), type([]))
    test.testEqual(len(p.comments), 4)
    test.testEqual(type(p.comments[0]), type({}))
    test.testEqual(type(p.likes), type([]))
    test.testEqual(len(p.likes), 4)
    test.testEqual(type(p.likes[0]), type({}))
except:
    print "One or more of the test invocations is causing an error,\nprobably because p.comments or p.likes has no elements..."

# Here are some tests of the positive, negative, and emo_score methods.
print "-----PROBLEM 2 tests"
p.message = "adaptive acumen abuses acerbic aches for everyone"  # this line is to use for the tests, do not change it
test.testEqual(p.positive(), 2)
test.testEqual(p.negative(), 3)
test.testEqual(p.emo_score(), -1)
Example #12
0

def give_greeting(greet_word="Hello", name="SI106", num_exclam=3):
    final_string = greet_word + ", " + name + "!" * num_exclam
    return final_string


#### DO NOT change the function definition above this line (OK to add comments)

# Write your three function calls below

#### 2. Define a function called mult_both whose input is two integers, whose default parameter values are the integers 3 and 4, and whose return value is the two input integers multiplied together.

print "\n---\n\n"
print "Testing whether your function works as expected (calling the function mult_both)"
test.testEqual(mult_both(), 12)
test.testEqual(mult_both(5, 10), 50)

#### 3. Use a for loop to print the second element of each tuple in the list ``new_tuple_list``.

new_tuple_list = [(1, 2), (4, "umbrella"), ("chair", "hello"), ("soda", 56.2)]

#### 4. You can get data from Facebook that has nested structures which represent posts, or users, or various other types of things on Facebook. We won't put any of our actual Facebook group data on this textbook, because it's publicly available on the internet, but here's a structure that is almost exactly the same as the real thing, with fake data.

# Notice that the stuff in the variable ``fb_data`` is basically a big nested dictionary, with dictionaries and lists, strings and integers, inside it as keys and values. (Later in the course we'll learn how to get this kind of thing directly FROM facebook, and then it will be a bit more complicated and have real information from our Facebook group.)

# Follow the directions in the comments!

# first, look through the data structure saved in the variable fb_data to get a sense for it.

fb_data = {
Example #13
0
sample_post_dict = json.loads(sample)

p = Post(sample_post_dict)

# use the next lines of code if you're having trouble getting the tests to pass.
# they will help you understand what a post_dict contains, and what
# your code has actually extracted from it and assigned to the comments 
# and likes instance variables.
#print pretty(sample_post_dict)
#print pretty(p.comments)
#print pretty(p.likes)

# Here are tests for instance variables set in your __init__ method
print "-----PROBLEM 1 tests"
try:
    test.testEqual(type(p.comments), type([]))
    test.testEqual(len(p.comments), 4)
    test.testEqual(type(p.comments[0]), type({}))
    test.testEqual(type(p.likes), type([]))
    test.testEqual(len(p.likes), 4)
    test.testEqual(type(p.likes[0]), type({}))
except:
    print "One or more of the test invocations is causing an error,\nprobably because p.comments or p.likes has no elements..."

# Here are some tests of the positive, negative, and emo_score methods.
print "-----PROBLEM 2 tests"
p.message = "adaptive acumen abuses acerbic aches for everyone" # this line is to use for the tests, do not change it
test.testEqual(p.positive(), 2)
test.testEqual(p.negative(), 3)
test.testEqual(p.emo_score(), -1)        
    
Example #14
0
# ----------------

## [PROBLEM 2] 

fall_list = ["leaves","apples","autumn","bicycles","pumpkin","squash","excellent"]

# Write code to sort the list fall_list in reverse alphabetical order. 
# Assign the sorted list to the variable sorted_fall_list.
sorted_fall_list = sorted(fall_list, reverse = True)
# Now write code to sort the list fall_list by length of the word, longest to shortest.
# Assign this sorted list to the variable length_fall_list.
length_fall_list = sorted(fall_list, key = lambda x: len(x), reverse = True)
#NOTE: Please do not adjust any of the try/except code.
try:
    test.testEqual(sorted_fall_list[0], 'squash', "squash first")
    test.testEqual(length_fall_list[0], 'excellent', "excellent first")
except:
    print "sorted_fall_list or length_fall_list don't exist or have no items"

# -----------------

## [PROBLEM 3]

food_amounts = [{"sugar_grams":245,"carbohydrate":83,"fiber":67},{"carbohydrate":74,"sugar_grams":52,"fiber":26},{"fiber":47,"carbohydrate":93,"sugar_grams":6}]

# Write code to sort the list food_amounts by the key "sugar_grams", from lowest to highest.
# Assign the sorted list to the variable sorted_sugar.

sorted_sugar = sorted(food_amounts, key = lambda x: x["sugar_grams"])
Example #15
0
# [PROBLEM 2]

# Complete the following string interpolation/formatting problems.

# Convert this string interpolation to one using only the + operator, not %.
# Make the variable t equal to the same thing as the variable s.
x = 12.000001
y = 4
s = "You have $%0.06f. If you spend $%d, you will have $%d left." % (x, y, x-y)
print s
# fill in the next line to generate the same string using only the + operator.
# Don't write t = s or otherwise reference s -- use the + operator!
t = "You have $"+str(x)+". If you spend $" +str(y)+ ", you will have $" +str(x-y)+ " left." 

# testing 
test.testEqual(t, s, "convert string interpolation to one using only the + operator, not %")

# Convert this string concatenation to one using string interpolation.
# Assign the result to the variable t. Again, don't refer to s...
x = 12
fname = "Joe"
our_email = "*****@*****.**"
s = "Hello, " + fname + ", you may have won $" + str(x) + " million dollars. Please send your bank account number to " + our_email + " and we will deposit your winnings."
t = "Hello, %s, you may have won $%d million dollars. Please send your bank account number to %s and we will deposit your winnings." % (fname, x, our_email)

# testing
test.testEqual(t, s, "convert string concatenation to one using string interpolation")

# Write code, using string interpolation and the variables nm, min_mt, and mile_amt, to produce the string 
# "Albert walked 0.67 miles today in 50 minutes." Assign it to albert_str.
nm = "Albert"
Example #16
0
        Student.__init__(this_Student, name, years_at_umich)
        this_Student.number_programs_written = 0

    def write_programs(this_Student, progs=1):
        this_Student.number_programs_written += progs

    def __str__(this_Student):
        return "My name is {}, I've been at UMich for about {} years, and I have written {} programs while here.".format(
            this_Student.name, this_Student.years_UM,
            this_Student.number_programs_written)


# The following code should work if you have successfully defined Programming_Student as specified! Do not change this code, but feel free to make other print statements outside of it if that helps you!
print "==========="
pst = Programming_Student("Jess", 3)
test.testEqual(pst.number_programs_written, 0)
pst.write_programs()
test.testEqual(pst.number_programs_written, 1)
pst.write_programs(4)
test.testEqual(pst.number_programs_written, 5)
print pst  # should print: My name is Jess, I've been at UMich for about 3 years, and I have written 5 programs while here.
test.testEqual(
    pst.__str__(),
    "My name is Jess, I've been at UMich for about 3 years, and I have written 5 programs while here."
)
pst.shout("I'm doing awesome on this problem set."
          )  # Should print: I'm doing awesome on this problem set.
# Also, Python is pretty cool.
print "==========="

#### PART 2: Facebook API problem solving
Example #17
0
## [PROBLEM 2] 

fall_list = ["leaves","apples","autumn","bicycles","pumpkin","squash","excellent"]

# Write code to sort the list fall_list in reverse alphabetical order. 
# Assign the sorted list to the variable sorted_fall_list.
sorted_fall_list = sorted(fall_list, reverse = True)

# Now write code to sort the list fall_list by length of the word, longest to shortest.
# Assign this sorted list to the variable length_fall_list.
length_fall_list = sorted(fall_list, key = lambda x : len(x), reverse = True )


#NOTE: Please do not adjust any of the try/except code.
try:
    test.testEqual(sorted_fall_list[0], 'squash', "squash first")
    test.testEqual(length_fall_list[0], 'excellent', "excellent first")
except:
    print "sorted_fall_list or length_fall_list don't exist or have no items"

# -----------------

## [PROBLEM 3]

food_amounts = [{"sugar_grams":245,"carbohydrate":83,"fiber":67},{"carbohydrate":74,"sugar_grams":52,"fiber":26},{"fiber":47,"carbohydrate":93,"sugar_grams":6}]

# Write code to sort the list food_amounts by the key "sugar_grams", from lowest to highest.
# Assign the sorted list to the variable sorted_sugar.
sorted_sugar = sorted( food_amounts, key = lambda x : x["sugar_grams"] )

# # Now write code to sort the list food_amounts by 
                      api_key=flickr_key,
                      format='json',
                      id=0):
    d = {}
    d['method'] = method
    d['format'] = format
    d['api_key'] = api_key
    d['photo_id'] = id
    return requests.get(baseurl, params=d)


def fix_resp(flickr_string):
    return flickr_string[len("jsonFlickrApi("):-1]


test.testEqual(type(fix_resp("")), type(""))


def tags_2_dicts(list_of_tags):
    dict_tags = {}
    for tag in list_of_tags:
        if tag not in dict_tags:
            dict_tags[tag] = 0
        dict_tags[tag] = dict_tags[tag] + 1
    if len(dict_tags) > 0:
        return dict_tags


test.testEqual(
    tags_2_dicts([
        'nature', 'travel', 'nature', 'nature', 'architecture', 'vacations',
Example #19
0
def main():
    try:
        print "Accessing Spotify API"

        artist_id = get_artist_id()

        related_artists = get_related_artists(artist_id)

        for x in related_artists:
            x.get_events()

        sort_lst = sorted(related_artists,
                          key=lambda x: x.popularity,
                          reverse=True)

        #testing artist constructor
        p = Artist('testName', 0)

        test.testEqual(p.artist, 'testName')
        test.testEqual(p.popularity, 0)

        #testing get_related_artists using Adele's artist ID
        testList = get_related_artists('4dpARuHxo51G3z768sgnrY')
        test.testEqual("Amy Winehouse", str(testList[0].artist))

        #testing get_events
        s = Artist('Ellie Goulding', 88)
        s.get_events()
        test.testEqual('Ellie Goulding', str(s.events[0][0]))
        test.testEqual('Xcel Energy Center', str(s.events[0][1]))
        test.testEqual('2016-05-05', str(s.events[0][2]))

        for artist in sort_lst:
            artist.pretty_print()
    except ValueError:
        print 'Program Failed'
Example #20
0
 def test3( self ):
   self.updateStatus( 'GOOG' )
   test.testEqual( len( self.status ), 1, '** OK. test if status is updated.' )
   return
Example #21
0
# Convert this string interpolation to one using only the + operator, not %.
# Make the variable t equal to the same thing as the variable s.
x = 12.000001
y = 4
s = "You have $%0.06f. If you spend $%d, you will have $%d left." % (x, y,
                                                                     x - y)
print s
# fill in the next line to generate the same string using only the + operator.
# Don't write t = s or otherwise reference s -- use the + operator!
t = "You have $" + str(x) + ". If you spend $" + str(
    y) + ", you will have $" + str(x - y) + " left."

# testing
test.testEqual(
    t, s,
    "convert string interpolation to one using only the + operator, not %")

# Convert this string concatenation to one using string interpolation.
# Assign the result to the variable t. Again, don't refer to s...
x = 12
fname = "Joe"
our_email = "*****@*****.**"
s = "Hello, " + fname + ", you may have won $" + str(
    x
) + " million dollars. Please send your bank account number to " + our_email + " and we will deposit your winnings."
t = "Hello, %s, you may have won $%d million dollars. Please send your bank account number to %s and we will deposit your winnings." % (
    fname, x, our_email)

# testing
test.testEqual(
Example #22
0
 def test1( self ):
   currentStock = stock( 'FB' )
   test.testEqual( currentStock.stock, 'FB', '** OK. test if stock name is correctly initialized.')
   return
Example #23
0
 def test2( self ):
   test.testEqual( self.checkStock('ZZ'), False, '** OK. test if stock name is valid.' )
   return
Example #24
0
        retval += "Tags: "
        for tag in self.tags:
            retval += tag + " "
        return retval

## Write code to create an instance of the photo class and store it in the variable my_photo. 
## display_info(my_photo) should produce the following string. HINT: if you just call the constructor 
## for the Photo class appropriately, everything will be taken care of for you. You just have to figure out, 
## from the definition of the class, what to pass to the constructor.

my_photo = Photo( "Photo1", "Ansel Adams", ["Nature", "Mist", "Mountain"] )

display_string = "Photo: Photo1\nPhotographed by: Ansel Adams\nTags: Nature Mist Mountain "

try:
    test.testEqual(my_photo.display_info(), display_string, "Problem 2")
except:
    print "Failed Test for problem 2; my_photo not bound or code for display_info or display_string was changed"



# ----------------Don't change code in this seciton----------------

## You won't need to change any code below this line. But definitely
## read it and understand it! Hint: Thinking back and looking at the flow chart from
## the first user-played Hangman problem set may help.

# Below is the full set of Hangman code.
# If you run this code without adding or changing anything, 
# the computer will play Hangman on manual mode, so
# if you keep pressing Enter, you can watch it play.
Example #25
0

def blanked_word(secret_word, guesses):
    final_string = ""
    for ch in secret_word.upper():
        if ch in guesses.upper():
            final_string = final_string + ch
        else:
            final_string = final_string + "_"
    return final_string


# The function should accept 2 strings as input: a secret word for the player to guess in a Hangman game, and a collection of the letters that have already been guessed by the player. It should return a string with the letters of the word in the right places if they have been guessed, all in uppercase. If a letter has not been guessed, there should be a _ (an underscore) in that place.

# Write at least three non-trivial return-value tests to determine whether it works correctly, here:
test.testEqual(blanked_word('catsarecool', 'acs'), 'CA_SA__C___')
test.testEqual(blanked_word('dog', 'o'), '_O_')
test.testEqual(blanked_word('nate', 'at'), '_AT_')

## [PROBLEM 2]


# Write at least 3 return value tests and at least 4 side-effect tests for this class definition.
# At least one of your tests should apply to each method of the class.
class Song:
    def __init__(self, artist, title, album="Burned Mix"):
        self.artist = artist
        self.title = title
        self.album = album
        self.number_plays = 0
Example #26
0
# have an internet connection, you will get an error!

# Remember, requests.get() says 'go get data from the internet from...'.
print '---------------'
baseurl = 'http://services.faa.gov/airport/status/'
airport = 'DTW'
# Write your line of code below:

# Again, simple -- we're doing this step by step.

## Testing Problem 1
print
print "--------------"
print
try:
    test.testEqual(url_parameters, {'format': 'json'},
                   "testing correct output for 1(a)")
except:
    print "test 1(a): The variable url_parameters is not defined or there is an error in your code."
try:
    test.testEqual(type(airport_response),
                   type(requests.get("http://google.com")),
                   "testing correct type of expression for 1(b)")
except:
    print "test 1(b): The variable airport_response is not defined or there is an error in your code."

# [PROBLEM 2]
## Grabbing data off the web
# (2)  Put the request you made in problem 1 in a proper try/except clause.
#      Then, use the .json() method on the response you get back to turn the data
#      in one big Python dictionary. Save the Python dictionary in the variable
#      airport_data.
Example #27
0
## Write one line of code to create an instance of the photo class and store the instance in a variable my_photo. 

my_photo = Photo('Photo1','Ansel Adams',['Nature', 'Mist', 'Mountain'])

## After you do that, my_photo.display_info() should produce the same string as the one stored in display_string.

# HINT: if you just call the constructor for the Photo class appropriately, everything will be taken care of for you. You just have to figure out, from the definition of the class, what to pass to the constructor. Remember the examples of creating a class instance from the textbook and from lecture/section!



# DO NOT CHANGE THE STRING STORED IN THIS VARIABLE - it is just for comparison!
display_string = "Photo: Photo1\nPhotographed by: Ansel Adams\nTags: Nature Mist Mountain "

try:
	test.testEqual(my_photo.display_info(), display_string, "Problem 2")
except:
	print "Failed Test for problem 2; my_photo variable not assigned or code for display_info or display_string was changed..."



### PART 2: Get data from Flickr - useful stuff for the rest of the Problem Set

flickr_key = '574f48954b93ffc083e59a00ba556acb'

 # paste your flickr key here, so the variable flickr_key contains a string (your flickr key!)
if not flickr_key:
    flickr_key = raw_input("Enter your flickr API key, or paste it in the .py file to avoid this prompt in the future: \n>>")

## Useful function definition provided for you below.
## (You've seen this before, in the textbook. Other functions provided for you in the textbook may be useful in this Problem Set, too, if you understand how to use them...)
Example #28
0

text = promptUser()
rules_text = RuleMaker()

print "\n\nInitializing the TextInformation class and the methods you can use it for" + '\n\n'
First_Instance = TextInformation(text)
First_Instance.top_five()
First_Instance.most_freqs_word()
First_Instance.most_freqs_lets()
First_Instance.word_count('Ah')

print "\n\nTime to see the accuracy of our Shannon Game Guesser" + '\n\n'
gameInstance = ShannonGameGuesser(text, rules_text)
gameInstance.performance()

print "That's the end of my project, hope you enjoyed it! If you would like to see a variance in accuracy of the guesser, simply change the position of the two letter rules and the initial rules created. Oddly enough, the two letter guesser is not very accurate."

Practice_Instance = TextInformation(
    "This is a test string for my SI 106 final project. Let's see what TextInformation we can find out"
)
Testing_Instance = ShannonGameGuesser(
    "This is a test string for my SI 106 final project. Let's see what TextInformation we can find out",
    rules_text)
test.testEqual(type(Practice_Instance.top_five()),
               type(Practice_Instance.word_count('Hey')))
test.testEqual(type(Testing_Instance.performance()),
               type(Practice_Instance.most_freqs_lets()))
test.testEqual(type(Practice_Instance.most_freqs_word),
               type(Testing_Instance.performance))
Example #29
0
# We have provided test cases for the first function, as an example.
# Write at least two test cases each for the next three functions


def letter_freqs(word_list):
    letter_freq_dict = {}
    for w in word_list:
        for l in w:
            if l not in letter_freq_dict:
                letter_freq_dict[l] = 1
            else:
                letter_freq_dict[l] = letter_freq_dict[l] + 1
    return letter_freq_dict


test.testEqual(type(letter_freqs(["hello", "goodbye"])), type({}),
               "Looks like you're good to go!")
test.testEqual(
    letter_freqs(["good", "bad", "indifferent"]), {
        'a': 1,
        'b': 1,
        'e': 2,
        'd': 3,
        'g': 1,
        'f': 2,
        'i': 2,
        'o': 2,
        'n': 2,
        'r': 1,
        't': 1
    })
test.testEqual(letter_freqs(["good"]), {'g': 1, 'o': 2, 'd': 1})
Example #30
-1
#### DO NOT change the function definition above this line (OK to add comments)

# Write your three function calls below
print give_greeting()
print give_greeting(name = 'world')
print give_greeting(greet_word = 'Hey', name = 'everybody', num_exclam = 1)
                

#### 2. Define a function called mult_both whose input is two integers, whose default parameter values are the integers 3 and 4, and whose return value is the two input integers multiplied together.
def mult_both(x = 3, y = 4):
    return x*y
print mult_both()
print "\n---\n\n"
print "Testing whether your function works as expected (calling the function mult_both)"
test.testEqual(mult_both(), 12)
test.testEqual(mult_both(5,10), 50)

#### 3. Use a for loop to print the second element of each tuple in the list ``new_tuple_list``.

new_tuple_list = [(1,2),(4, "umbrella"),("chair","hello"),("soda",56.2)]
for (x, y) in new_tuple_list:
    print y

#### 4. You can get data from Facebook that has nested structures which represent posts, or users, or various other types of things on Facebook. We won't put any of our actual Facebook group data on this textbook, because it's publicly available on the internet, but here's a structure that is almost exactly the same as the real thing, with fake data. 

# Notice that the stuff in the variable ``fb_data`` is basically a big nested dictionary, with dictionaries and lists, strings and integers, inside it as keys and values. (Later in the course we'll learn how to get this kind of thing directly FROM facebook, and then it will be a bit more complicated and have real information from our Facebook group.)

# Follow the directions in the comments!

# first, look through the data structure saved in the variable fb_data to get a sense for it.