#sample solution
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def print_grades(grades):
for grade in grades:
print grade
def grades_sum(grades):
total = 0
for grade in grades:
total += grade
return total
def grades_average(grades):
sum_of_grades = grades_sum(grades)
average = sum_of_grades / len(grades)
return average
def grades_variance(grades,average):
variance = 0
for grade in grades:
variance = variance + ((average - grade)**2)
return variance
print grades_variance(grades,grades_average(grades))
def grades_std_deviation(variance):
return variance**0.5
print grades_std_deviation(grades_variance(grades,grades_average(grades)))
Quotes help make search much faster. Example: "Practice Makes Perfect"
Friday, November 30, 2012
Codecademy: The Variance
#sample solution
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def print_grades(grades):
for grade in grades:
print grade
def grades_sum(grades):
total = 0
for grade in grades:
total += grade
return total
def grades_average(grades):
sum_of_grades = grades_sum(grades)
average = sum_of_grades / len(grades)
return average
def grades_variance(grades,average):
variance = 0
for grade in grades:
variance = variance + ((average - grade)**2)
return variance
print grades_variance(grades,grades_average(grades))
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def print_grades(grades):
for grade in grades:
print grade
def grades_sum(grades):
total = 0
for grade in grades:
total += grade
return total
def grades_average(grades):
sum_of_grades = grades_sum(grades)
average = sum_of_grades / len(grades)
return average
def grades_variance(grades,average):
variance = 0
for grade in grades:
variance = variance + ((average - grade)**2)
return variance
print grades_variance(grades,grades_average(grades))
Codecademy: Computing the average
#sample solution
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def grades_sum(grades):
sum = 0
for grade in grades:
sum = sum + grade
return sum
print grades_sum(grades)
def grade_average(grades):
sum = grades_sum(grades)
average = sum/len(grades)
return average
print grade_average(grades)
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def grades_sum(grades):
sum = 0
for grade in grades:
sum = sum + grade
return sum
print grades_sum(grades)
def grade_average(grades):
sum = grades_sum(grades)
average = sum/len(grades)
return average
print grade_average(grades)
Codecademy: The sum of scores
#sample solution
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def grade_sum(grades):
sum = 0
for grade in grades:
sum = sum + grade
return sum
print grade_sum(grades)
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def grade_sum(grades):
sum = 0
for grade in grades:
sum = sum + grade
return sum
print grade_sum(grades)
Codecademy: Print those grades
#sample solution
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def print_grades(grades):
for grade in grades:
print grade
print_grades(grades)
grades = [100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5]
def print_grades(grades):
for grade in grades:
print grade
print_grades(grades)
Codecademy: remove_duplicates
#sample solution
listOfNums = [1,2,3,4,3,1,2]
def remove_duplicates(listOfNums):
listOfNums.sort()
uniqueList = [1]
uniqueList[0] = listOfNums[0]
index=0
for num in listOfNums:
if uniqueList[index] != num:
uniqueList.append(num)
index = index + 1
return uniqueList
print remove_duplicates(listOfNums)
listOfNums = [1,2,3,4,3,1,2]
def remove_duplicates(listOfNums):
listOfNums.sort()
uniqueList = [1]
uniqueList[0] = listOfNums[0]
index=0
for num in listOfNums:
if uniqueList[index] != num:
uniqueList.append(num)
index = index + 1
return uniqueList
print remove_duplicates(listOfNums)
Codecademy: median
#sample solution
import math
aList = [4,4,5,5]
def median(aList):
#print aList
aList.sort()
#print aList
listLength = len(aList)
print str(listLength)
if listLength == 1:
#print aList[0]
return aList[0]
elif(listLength % 2 != 0):
index = (listLength/2)
#print index
return aList[index]
else:
index1 = (listLength/2)-1
#print index1
index2 = index1 + 1
#print index2
return (aList[index1]+aList[index2])/float(2)
print median(aList)
import math
aList = [4,4,5,5]
def median(aList):
#print aList
aList.sort()
#print aList
listLength = len(aList)
print str(listLength)
if listLength == 1:
#print aList[0]
return aList[0]
elif(listLength % 2 != 0):
index = (listLength/2)
#print index
return aList[index]
else:
index1 = (listLength/2)-1
#print index1
index2 = index1 + 1
#print index2
return (aList[index1]+aList[index2])/float(2)
print median(aList)
Codecademy: purify
#sample solution
def purify(listOfNums):
newList = []
for num in listOfNums:
if num % 2 == 0:
print num
#listOfNums.pop(index)
newList.append(num)
#print newList
return newList
def purify(listOfNums):
newList = []
for num in listOfNums:
if num % 2 == 0:
print num
#listOfNums.pop(index)
newList.append(num)
#print newList
return newList
Codecademy: is_int
#sample solution
def is_int(x):
for c in str(x):
if c == ".":
numlist = str(x).split(".")
#print numlist
if int(numlist[1])>0:
#print numlist[1]
return False
else:
return True
else:
if isinstance(x, int):
return True
def is_int(x):
for c in str(x):
if c == ".":
numlist = str(x).split(".")
#print numlist
if int(numlist[1])>0:
#print numlist[1]
return False
else:
return True
else:
if isinstance(x, int):
return True
Thursday, November 29, 2012
Codecademy: product
#sample solution
def product(intList):
intProduct = 1
for element in intList:
intProduct = intProduct * element
return intProduct
def product(intList):
intProduct = 1
for element in intList:
intProduct = intProduct * element
return intProduct
Codecademy: count
#sample solution
def count(sequence, item):
timesOccur = 0
for element in sequence:
if item == element:
timesOccur = timesOccur + 1
return timesOccur
def count(sequence, item):
timesOccur = 0
for element in sequence:
if item == element:
timesOccur = timesOccur + 1
return timesOccur
Codecademy: censor
#sample solution
def censor(text,word):
wordsInText = text.split()
censorString = ""
for i in range(len(word)):
censorString = censorString + '*'
#print "The censor string is: " + censorString
for index, individualWord in enumerate(wordsInText):
if word == individualWord:
#print "found match"
wordsInText[index] = censorString
return " ".join(wordsInText)
def censor(text,word):
wordsInText = text.split()
censorString = ""
for i in range(len(word)):
censorString = censorString + '*'
#print "The censor string is: " + censorString
for index, individualWord in enumerate(wordsInText):
if word == individualWord:
#print "found match"
wordsInText[index] = censorString
return " ".join(wordsInText)
Codecademy: scrabble_score
#sample solution
def scrabble_score(word):
word = word.lower()
#print "word in lowercase: " + word
sum = 0
for c in word:
for key in score:
if c == key:
#print score[c]
sum = sum + int(score[c])
return sum
def scrabble_score(word):
word = word.lower()
#print "word in lowercase: " + word
sum = 0
for c in word:
for key in score:
if c == key:
#print score[c]
sum = sum + int(score[c])
return sum
Codecademy: anti_vowel
#sample solution
def anti_vowel(text):
newText=""
for c in text:
#if statement should all be on one line
if c == "a" or c == "e" or c == "i" or c == "o" or c == "u" or c == "A" or c == "E" or c == "I" or c == "O" or c == "U":
newText = newText
else:
newText = newText + c
return newText
def anti_vowel(text):
newText=""
for c in text:
#if statement should all be on one line
if c == "a" or c == "e" or c == "i" or c == "o" or c == "u" or c == "A" or c == "E" or c == "I" or c == "O" or c == "U":
newText = newText
else:
newText = newText + c
return newText
Codecademy: reverse
#sample solution
def reverse(text):
textReversed=""
textLength=len(text)
while textLength>0:
textLength = textLength - 1
textReversed = textReversed+text[textLength]
return textReversed
def reverse(text):
textReversed=""
textLength=len(text)
while textLength>0:
textLength = textLength - 1
textReversed = textReversed+text[textLength]
return textReversed
Codecademy: is_prime
#sample solution
def is_prime(x):
x = int(x)
if x < 2:
return False
else:
i = 2
while i < x:
print "dividing "+str(x)+" by "+str(i)
if x % i == 0:
return False
else:
i = i + 1
return True
def is_prime(x):
x = int(x)
if x < 2:
return False
else:
i = 2
while i < x:
print "dividing "+str(x)+" by "+str(i)
if x % i == 0:
return False
else:
i = i + 1
return True
Codecademy: factorial
#sample solution
def factorial(x):
x = abs(x) #prevents error on negative numbers
product = 1
for i in range(x):
product = product * (i+1)
return product
print factorial(10)
def factorial(x):
x = abs(x) #prevents error on negative numbers
product = 1
for i in range(x):
product = product * (i+1)
return product
print factorial(10)
Codecademy: digit_sum
#sample solution
def digit_sum(n):
numConvertedToString = str(n)
sum = 0
for c in numConvertedToString:
sum = sum + int(c)
return sum
def digit_sum(n):
numConvertedToString = str(n)
sum = 0
for c in numConvertedToString:
sum = sum + int(c)
return sum
Codecademy: is_even
#sample solution
def is_even(x):
if x % 2 == 0:
return True
else:
return False
def is_even(x):
if x % 2 == 0:
return True
else:
return False
Codecademy: Change it up
#sample solution
fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']
print 'You have...'
for f in fruits:
if f == 'Tomato': #capitalize tomato
print 'A tomato is not a fruit!'
break
elif f[0] == "a" or f[0] == "e" or f[0] == "i" or f[0] == "o" or f[0] == "u":
print 'an', f
else:
print 'a', f
else:
print 'A fine selection of fruits!'
fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']
print 'You have...'
for f in fruits:
if f == 'Tomato': #capitalize tomato
print 'A tomato is not a fruit!'
break
elif f[0] == "a" or f[0] == "e" or f[0] == "i" or f[0] == "o" or f[0] == "u":
print 'an', f
else:
print 'a', f
else:
print 'A fine selection of fruits!'
Codecademy: For / else
#sample solution
fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']
print 'You have...'
for f in fruits:
if f == 'tomato':
print 'A tomato is not a fruit!' #it actually is.
break
#check if the word starts with a vowel
elif f[0] == "a" or f[0] == "e" or f[0] == "i" or f[0] == "o" or f[0] == "u":
print 'an', f
else:
print 'a', f
else:
print 'A fine selection of fruits!'
fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']
print 'You have...'
for f in fruits:
if f == 'tomato':
print 'A tomato is not a fruit!' #it actually is.
break
#check if the word starts with a vowel
elif f[0] == "a" or f[0] == "e" or f[0] == "i" or f[0] == "o" or f[0] == "u":
print 'an', f
else:
print 'a', f
else:
print 'A fine selection of fruits!'
Codecademy: Multiple lists
# sample solution
# the zip function will only iterate a number of times equal to the length of the shorter list
list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
for a, b in zip(list_a, list_b):
if a >= b:
print a
else:
print b
# the zip function will only iterate a number of times equal to the length of the shorter list
list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
for a, b in zip(list_a, list_b):
if a >= b:
print a
else:
print b
Codecademy: Counting as you go
#sample solution
choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are:'
for index, item in enumerate(choices):
print index+1, item
choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are:'
for index, item in enumerate(choices):
print index+1, item
Codecademy: Looping over a dictionary
#sample solution
d = {'x': 9, 'y': 10, 'z': 20}
for key in d:
print key +" "+ str(d[key])
d = {'x': 9, 'y': 10, 'z': 20}
for key in d:
print key +" "+ str(d[key])
Codecademy: For your lists
#sample solution
numbers = [7, 9, 12, 54, 99]
print "This list contains: ",
for num in numbers:
print num,
print #for nice printing
print " The numbers squared are: ",
for num in numbers:
print num ** 2,
numbers = [7, 9, 12, 54, 99]
print "This list contains: ",
for num in numbers:
print num,
print #for nice printing
print " The numbers squared are: ",
for num in numbers:
print num ** 2,
Codecademy: For your A
#sample solution
s = "A bird in the hand..."
#add your for loop
for c in s:
if c == 'A' or c == 'a':
print 'X'
else:
print c
s = "A bird in the hand..."
#add your for loop
for c in s:
if c == 'A' or c == 'a':
print 'X'
else:
print c
Codecademy: For your strings
#sample solution
thing = "spam!"
for c in thing:
print c
word = "eggs!"
for c in word:
print c
thing = "spam!"
for c in thing:
print c
word = "eggs!"
for c in word:
print c
Codecademy: For your hobbies
#sample solution
hobbies = []
for i in range(3):
hobby = raw_input("Enter one of your hobbies: ")
hobbies.append(hobby)
print hobbies
hobbies = []
for i in range(3):
hobby = raw_input("Enter one of your hobbies: ")
hobbies.append(hobby)
print hobbies
Codecademy: For your health
#sample solution
print "Counting..."
for i in range(20):
print i
print "Counting..."
for i in range(20):
print i
Codecademy: Your own while / else
#sample solution
from random import randrange
random_number = randrange(1, 10)
count = 0
#start your game!
while count<3:
print "Turn " + str(count+1) + ":"
count = count + 1
guess = int(raw_input("Enter a guess:"))
if guess == random_number:
print "You win!"
break
else:
print "You lose!"
from random import randrange
random_number = randrange(1, 10)
count = 0
#start your game!
while count<3:
print "Turn " + str(count+1) + ":"
count = count + 1
guess = int(raw_input("Enter a guess:"))
if guess == random_number:
print "You win!"
break
else:
print "You lose!"
Codecademy: Infinite loops
#sample solution
count = 0
while count < 10:
print count
count = count + 1
count = 0
while count < 10:
print count
count = count + 1
Codecademy: While you're at it
#sample solution
num = 1
while num < 11:#fill in the condition
#print num squared
print num ** 2
num = num + 1
num = 1
while num < 11:#fill in the condition
#print num squared
print num ** 2
num = num + 1
Codecademy: While you're here
#sample solution
count = 0
if count < 5:
print "Hello, I am an if statement and count is", count
while count < 10:
print "Hello, I am a while and count is", count
count += 1
count = 0
if count < 5:
print "Hello, I am an if statement and count is", count
while count < 10:
print "Hello, I am a while and count is", count
count += 1
Codecademy: Play It Again, Sam
#sample solution
import random
board = []
for x in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print "Let's play Battleship!"
print_board(board)
def random_row(board):
return random.randint(0,len(board)-1)
def random_col(board):
return random.randint(0,len(board[0])-1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
#Everything from here on should go in your for loop!
#Be sure to indent!
maxturns = 4
for turn in range(maxturns):
print_board(board)
print turn + 1
guess_row = input("Guess Row:")
guess_col = input("Guess Col:")
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battleship!"
else:
if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
print "Oops, that's not even in the ocean."
elif(board[guess_row][guess_col] == "X"):
print "You guessed that one already."
else:
print "You missed my battleship!"
board[guess_row][guess_col] = "X"
import random
board = []
for x in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print "Let's play Battleship!"
print_board(board)
def random_row(board):
return random.randint(0,len(board)-1)
def random_col(board):
return random.randint(0,len(board[0])-1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
#Everything from here on should go in your for loop!
#Be sure to indent!
maxturns = 4
for turn in range(maxturns):
print_board(board)
print turn + 1
guess_row = input("Guess Row:")
guess_col = input("Guess Col:")
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battleship!"
else:
if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
print "Oops, that's not even in the ocean."
elif(board[guess_row][guess_col] == "X"):
print "You guessed that one already."
else:
print "You missed my battleship!"
board[guess_row][guess_col] = "X"
Codecademy: A Real Win
#sample solution
import random
board = []
for x in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print "Let's play Battleship!"
print_board(board)
def random_row(board):
return random.randint(0,len(board)-1)
def random_col(board):
return random.randint(0,len(board[0])-1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
#Everything from here on should go in your for loop!
#Be sure to indent!
maxturns = 4
for turn in range(maxturns):
print_board(board)
guess_row = input("Guess Row:")
guess_col = input("Guess Col:")
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battleship!"
break
else:
if(turn > maxturns):
print "Game Over"
break
elif (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
print "Oops, that's not even in the ocean."
elif(board[guess_row][guess_col] == "X"):
print "You guessed that one already."
else:
print "You missed my battleship!"
board[guess_row][guess_col] = "X"
print "You are on turn: " + str(turn + 1)
import random
board = []
for x in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print "Let's play Battleship!"
print_board(board)
def random_row(board):
return random.randint(0,len(board)-1)
def random_col(board):
return random.randint(0,len(board[0])-1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
#Everything from here on should go in your for loop!
#Be sure to indent!
maxturns = 4
for turn in range(maxturns):
print_board(board)
guess_row = input("Guess Row:")
guess_col = input("Guess Col:")
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battleship!"
break
else:
if(turn > maxturns):
print "Game Over"
break
elif (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
print "Oops, that's not even in the ocean."
elif(board[guess_row][guess_col] == "X"):
print "You guessed that one already."
else:
print "You missed my battleship!"
board[guess_row][guess_col] = "X"
print "You are on turn: " + str(turn + 1)
Codecademy: Game Over
#sample solution
import random
board = []
for x in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print "Let's play Battleship!"
print_board(board)
def random_row(board):
return random.randint(0,len(board)-1)
def random_col(board):
return random.randint(0,len(board[0])-1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
#Everything from here on should go in your for loop!
#Be sure to indent!
maxturns = 4
for turn in range(maxturns):
print_board(board)
guess_row = input("Guess Row:")
guess_col = input("Guess Col:")
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battleship!"
else:
if(turn > maxturns):
print "Game Over"
break
elif (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
print "Oops, that's not even in the ocean."
elif(board[guess_row][guess_col] == "X"):
print "You guessed that one already."
else:
print "You missed my battleship!"
board[guess_row][guess_col] = "X"
print "You are on turn: " + str(turn + 1)
import random
board = []
for x in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print "Let's play Battleship!"
print_board(board)
def random_row(board):
return random.randint(0,len(board)-1)
def random_col(board):
return random.randint(0,len(board[0])-1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
#Everything from here on should go in your for loop!
#Be sure to indent!
maxturns = 4
for turn in range(maxturns):
print_board(board)
guess_row = input("Guess Row:")
guess_col = input("Guess Col:")
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battleship!"
else:
if(turn > maxturns):
print "Game Over"
break
elif (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
print "Oops, that's not even in the ocean."
elif(board[guess_row][guess_col] == "X"):
print "You guessed that one already."
else:
print "You missed my battleship!"
board[guess_row][guess_col] = "X"
print "You are on turn: " + str(turn + 1)
Codecademy: Not Again!
#sample solution
import random
board = []
for x in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print_board(board)
def random_row(board):
return random.randint(0,len(board)-1)
def random_col(board):
return random.randint(0,len(board[0])-1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
#for checking
board[4][4] = "X"
print_board(board)
guess_row = input("Guess Row:")
guess_col = input("Guess Col:")
if(guess_row == ship_row) and (guess_col == ship_col):
print "Congratulations! You sank my battleship!"
else:
if(guess_row < 0 or guess_row > (len(board)-1) or guess_col < 0 or guess_col > (len(board[0])-1)):
print "Oops, that's not even in the ocean."
elif(board[guess_row][guess_col] == "X"):
print "You guessed that one already."
else:
board[guess_row][guess_col] = "X"
print "You missed my battleship!"
import random
board = []
for x in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print_board(board)
def random_row(board):
return random.randint(0,len(board)-1)
def random_col(board):
return random.randint(0,len(board[0])-1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
#for checking
board[4][4] = "X"
print_board(board)
guess_row = input("Guess Row:")
guess_col = input("Guess Col:")
if(guess_row == ship_row) and (guess_col == ship_col):
print "Congratulations! You sank my battleship!"
else:
if(guess_row < 0 or guess_row > (len(board)-1) or guess_col < 0 or guess_col > (len(board[0])-1)):
print "Oops, that's not even in the ocean."
elif(board[guess_row][guess_col] == "X"):
print "You guessed that one already."
else:
board[guess_row][guess_col] = "X"
print "You missed my battleship!"
Codecademy: Bad Aim
#sample solution
import random
board = []
for x in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print_board(board)
def random_row(board):
return random.randint(0,len(board)-1)
def random_col(board):
return random.randint(0,len(board[0])-1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
guess_row = input("Guess Row:")
guess_col = input("Guess Col:")
if(guess_row == ship_row) and (guess_col == ship_col):
print "Congratulations! You sank my battleship!"
else:
if(guess_row < 0 or guess_row > (len(board)-1) or guess_col < 0 or guess_col > (len(board[0])-1)):
print "Oops, that's not even in the ocean."
else:
print "You missed my battleship!"
import random
board = []
for x in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print_board(board)
def random_row(board):
return random.randint(0,len(board)-1)
def random_col(board):
return random.randint(0,len(board[0])-1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
guess_row = input("Guess Row:")
guess_col = input("Guess Col:")
if(guess_row == ship_row) and (guess_col == ship_col):
print "Congratulations! You sank my battleship!"
else:
if(guess_row < 0 or guess_row > (len(board)-1) or guess_col < 0 or guess_col > (len(board[0])-1)):
print "Oops, that's not even in the ocean."
else:
print "You missed my battleship!"
Codecademy: "Danger, Will Robinson!!"
#sample solution
import random
board = []
for x in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print_board(board)
def random_row(board):
return random.randint(0,len(board)-1)
def random_col(board):
return random.randint(0,len(board[0])-1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
guess_row = input("Guess Row:")
guess_col = input("Guess Col:")
if(guess_row == ship_row) and (guess_col == ship_col):
print "Congratulations! You sank my battleship!"
else:
print "You missed my battleship!"
board[guess_row][guess_col] = "X"
print_board(board)
import random
board = []
for x in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print_board(board)
def random_row(board):
return random.randint(0,len(board)-1)
def random_col(board):
return random.randint(0,len(board[0])-1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
guess_row = input("Guess Row:")
guess_col = input("Guess Col:")
if(guess_row == ship_row) and (guess_col == ship_col):
print "Congratulations! You sank my battleship!"
else:
print "You missed my battleship!"
board[guess_row][guess_col] = "X"
print_board(board)
Codecademy: You Win!
#sample solution
import random
board = []
for x in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print_board(board)
def random_row(board):
return random.randint(0,len(board)-1)
def random_col(board):
return random.randint(0,len(board[0])-1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
guess_row = input("Guess Row:")
guess_col = input("Guess Col:")
if(guess_row == ship_row) and (guess_col == ship_col):
print "Congratulations! You sank my battleship!"
import random
board = []
for x in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print_board(board)
def random_row(board):
return random.randint(0,len(board)-1)
def random_col(board):
return random.randint(0,len(board[0])-1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
guess_row = input("Guess Row:")
guess_col = input("Guess Col:")
if(guess_row == ship_row) and (guess_col == ship_col):
print "Congratulations! You sank my battleship!"
Codecademy: It's not Cheating - It's Debugging!
#sample solution
import random
board = []
for x in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
def random_row(board):
return random.randint(0,len(board)-1)
def random_col(board):
return random.randint(0,len(board[0])-1)
ship_row = random_row(board)
ship_col = random_col(board)
print "row: " + str(ship_row) + ", " + "col: " + str(ship_col)
guess_row = input("Guess Row:")
guess_col = input("Guess Col:")
print ship_row
print ship_col
import random
board = []
for x in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
def random_row(board):
return random.randint(0,len(board)-1)
def random_col(board):
return random.randint(0,len(board[0])-1)
ship_row = random_row(board)
ship_col = random_col(board)
print "row: " + str(ship_row) + ", " + "col: " + str(ship_col)
guess_row = input("Guess Row:")
guess_col = input("Guess Col:")
print ship_row
print ship_col
Codecademy: ...and Seek!
#sample solution
import random
board = []
for x in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
def random_row(board):
return random.randint(0,len(board)-1)
def random_col(board):
return random.randint(0,len(board[0])-1)
ship_row = random_row(board)
ship_col = random_col(board)
guess_row = input("Guess Row:")
guess_col = input("Guess Col:")
import random
board = []
for x in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
def random_row(board):
return random.randint(0,len(board)-1)
def random_col(board):
return random.randint(0,len(board[0])-1)
ship_row = random_row(board)
ship_col = random_col(board)
guess_row = input("Guess Row:")
guess_col = input("Guess Col:")
Codecademy: Hide...
#sample solution
import random
board = []
for x in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
def random_row(board):
return random.randint(0,len(board)-1)
def random_col(board):
return random.randint(0,len(board[0])-1)
print random_row(board)
print random_col(board)
import random
board = []
for x in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
def random_row(board):
return random.randint(0,len(board)-1)
def random_col(board):
return random.randint(0,len(board[0])-1)
print random_row(board)
print random_col(board)
Codecademy: Printing Pretty
#sample solution
board = []
for i in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print_board(board)
board = []
for i in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print_board(board)
Codecademy: Custom Print
#sample solution
board = []
for i in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print row
print_board(board)
board = []
for i in range(0,5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print row
print_board(board)
Codecademy: Check it Twice
#sample solution
board = []
for i in range(0,5):
board.append(["O"] * 5)
print board
board = []
for i in range(0,5):
board.append(["O"] * 5)
print board
Codecademy: Make a List
#sample solution
board = []
for i in range(0,5):
board.append(["O"] * 5)
board = []
for i in range(0,5):
board.append(["O"] * 5)
Codecademy: Getting Our Feet Wet
#sample solution
board = []
board = []
Codecademy: Using a list of lists in a function
#sample solution
n = [[1,2,3],[4,5,6,7,8,9]]
#function goes here
def myFun(singleListOfSublists):
concatenatedSubLists = []
for subList in singleListOfSublists:
for num in subList:
concatenatedSubLists.append(num)
return concatenatedSubLists
print myFun(n)
n = [[1,2,3],[4,5,6,7,8,9]]
#function goes here
def myFun(singleListOfSublists):
concatenatedSubLists = []
for subList in singleListOfSublists:
for num in subList:
concatenatedSubLists.append(num)
return concatenatedSubLists
print myFun(n)
Wednesday, November 28, 2012
Codecademy: Using an arbitrary number of lists in a function
#sample solution
m = [1,2,3]
n = [4,5,6]
o = [7,8,9]
#function goes here
def myFun(*lists):
concatenatedLists = []
for list in lists:
for num in list:
concatenatedLists.append(num)
return concatenatedLists
print myFun(m,n,o)
m = [1,2,3]
n = [4,5,6]
o = [7,8,9]
#function goes here
def myFun(*lists):
concatenatedLists = []
for list in lists:
for num in list:
concatenatedLists.append(num)
return concatenatedLists
print myFun(m,n,o)
Codecademy: Using two lists as two arguments in a function
#sample solution
m = [1,2,3]
n = [4,5,6]
def myFun(x,y):
return x + y
print myFun(m,n)
m = [1,2,3]
n = [4,5,6]
def myFun(x,y):
return x + y
print myFun(m,n)
Codecademy: Using strings in lists...
#sample solution
n = ["Michael","Lieberman"]
#function goes here
def myFun(listOfStrings):
concatenatedList = ""
for string in listOfStrings:
concatenatedList = concatenatedList + string
return concatenatedList
print myFun(n)
n = ["Michael","Lieberman"]
#function goes here
def myFun(listOfStrings):
concatenatedList = ""
for string in listOfStrings:
concatenatedList = concatenatedList + string
return concatenatedList
print myFun(n)
Codecademy: Counting up the elements in a list of arbitrary size
#sample solution
# the course writer probably meant summing when he used the word counting
n = [3,5,7]
def myFun(numberList):
sum = 0
for number in numberList:
sum = sum + number
return sum
print myFun(n)
# the course writer probably meant summing when he used the word counting
n = [3,5,7]
def myFun(numberList):
sum = 0
for number in numberList:
sum = sum + number
return sum
print myFun(n)
Codecademy: Modifying each element in a list...
#sample solution
n = [3,5,7]
def myFun(x):
for i in range(0,len(x)):
x[i] = x[i] * 2
return x
print myFun(n)
n = [3,5,7]
def myFun(x):
for i in range(0,len(x)):
x[i] = x[i] * 2
return x
print myFun(n)
Codecademy: Printing out a list item by item
#sample solution
n = [3,5,7]
def myFun(x):
for i in range(0,len(x)):
print x[i]
myFun(n)
n = [3,5,7]
def myFun(x):
for i in range(0,len(x)):
print x[i]
myFun(n)
Codecademy: List manipulation in functions
#sample solution
n = [3,5,7]
#function goes here
def myFun(n):
n.append(9)
return n
print myFun(n)
n = [3,5,7]
#function goes here
def myFun(n):
n.append(9)
return n
print myFun(n)
Codecademy: Modifying an element of a list...
#sample solution
n = [3,5,7]
def myFun(x):
x[1] = x[1] + 3
return x
print myFun(n)
n = [3,5,7]
def myFun(x):
x[1] = x[1] + 3
return x
print myFun(n)
Codecademy: Using an element from a list...
#sample solution
n = [3,5,7]
def myFun(x):
return x[1]
print myFun(n)
n = [3,5,7]
def myFun(x):
return x[1]
print myFun(n)
Codecademy: Strings in functions
#sample solution
n = "Hello"
#function goes here
def myFun(stringArg):
return str(stringArg) + 'world'
print myFun(n)
n = "Hello"
#function goes here
def myFun(stringArg):
return str(stringArg) + 'world'
print myFun(n)
Codecademy: Arbitrary number of arguments
#sample solution
m = 5
n = 13
#function goes here
def myFun(*x):
sum = 0
for index in range(0,len(x)):
sum = sum + x[index]
return sum
print myFun(m,n)
print myFun(1,2,3,4,5,6,7,8,9,10)
m = 5
n = 13
#function goes here
def myFun(*x):
sum = 0
for index in range(0,len(x)):
sum = sum + x[index]
return sum
print myFun(m,n)
print myFun(1,2,3,4,5,6,7,8,9,10)
Codecademy: More than one argument
#sample solution
m = 5
n = 13
#function goes here
def myFun(m,n):
return m + n
print (myFun(m,n))
m = 5
n = 13
#function goes here
def myFun(m,n):
return m + n
print (myFun(m,n))
Codecademy: Changing the functionality of a function
#sample solution
n = 5
def myFun(x):
return x * 3
print myFun(n)
n = 5
def myFun(x):
return x * 3
print myFun(n)
Codecademy: Removing elements from lists
#sample solution
n = [1,3,5]
#Remove the first item in the list here.
n.pop(0)
print n
n = [1,3,5]
#Remove the first item in the list here.
n.pop(0)
print n
Codecademy: Appending to a list
#sample solution
n = [1,3,5]
#Append should go here.
n.append(4)
print n
n = [1,3,5]
#Append should go here.
n.append(4)
print n
Codecademy: List element modification
# sample solution
n = [1,3,5]
# entry manipulation goes here
n[1] = 5 * n[1]
# n[1] *= 5 would also work
print n
n = [1,3,5]
# entry manipulation goes here
n[1] = 5 * n[1]
# n[1] *= 5 would also work
print n
Codecademy: List Accessing
#sample solution
n = [1,3,5]
print n[1]
n = [1,3,5]
print n[1]
Codecademy: How is Everybody Doing?
#sample solution
Lloyd = {
"name":"Lloyd",
"homework": [90,97,75,92],
"quizzes": [ 88,40,94],
"tests": [ 75,90]
}
Alice = {
"name":"Alice",
"homework": [100,92,98,100],
"quizzes": [82,83,91],
"tests": [89,97]
}
Tyler = {
"name":"Tyler",
"homework": [0,87,75,22],
"quizzes": [0,75,78],
"tests": [100,100]
}
def average(stuff):
return sum(stuff)/len(stuff)
def getLetterGrade(score):
score = round(score)
if score >= 90: return "A"
elif 90 > score >= 80: return "B"
elif 80 > score >= 70: return "C"
elif 70 > score >= 60: return "D"
elif 60 > score: return "F"
def getAverage(kid):
bar = average
return bar(kid["homework"])*.1 + bar(kid["quizzes"])*.3 + bar(kid["tests"])*.6
students = [Lloyd,Alice,Tyler]
def getClassAverage(students):
sumIndivAve = 0
for student in students:
sumIndivAve += getAverage(student)
return (sumIndivAve/len(students))
print getClassAverage(students)
print getLetterGrade(getClassAverage(students))
Lloyd = {
"name":"Lloyd",
"homework": [90,97,75,92],
"quizzes": [ 88,40,94],
"tests": [ 75,90]
}
Alice = {
"name":"Alice",
"homework": [100,92,98,100],
"quizzes": [82,83,91],
"tests": [89,97]
}
Tyler = {
"name":"Tyler",
"homework": [0,87,75,22],
"quizzes": [0,75,78],
"tests": [100,100]
}
def average(stuff):
return sum(stuff)/len(stuff)
def getLetterGrade(score):
score = round(score)
if score >= 90: return "A"
elif 90 > score >= 80: return "B"
elif 80 > score >= 70: return "C"
elif 70 > score >= 60: return "D"
elif 60 > score: return "F"
def getAverage(kid):
bar = average
return bar(kid["homework"])*.1 + bar(kid["quizzes"])*.3 + bar(kid["tests"])*.6
students = [Lloyd,Alice,Tyler]
def getClassAverage(students):
sumIndivAve = 0
for student in students:
sumIndivAve += getAverage(student)
return (sumIndivAve/len(students))
print getClassAverage(students)
print getLetterGrade(getClassAverage(students))
Codecademy: Part of the Whole
#sample solution
Lloyd = {
"name":"Lloyd",
"homework": [90,97,75,92],
"quizzes": [ 88,40,94],
"tests": [ 75,90]
}
Alice = {
"name":"Alice",
"homework": [100,92,98,100],
"quizzes": [82,83,91],
"tests": [89,97]
}
Tyler = {
"name":"Tyler",
"homework": [0,87,75,22],
"quizzes": [0,75,78],
"tests": [100,100]
}
def average(stuff):
return sum(stuff)/len(stuff)
def getLetterGrade(score):
score = round(score)
if score >= 90: return "A"
elif 90 > score >= 80: return "B"
elif 80 > score >= 70: return "C"
elif 70 > score >= 60: return "D"
elif 60 > score: return "F"
def getAverage(kid):
bar = average
return bar(kid["homework"])*.1 + bar(kid["quizzes"])*.3 + bar(kid["tests"])*.6
students = [Lloyd,Alice,Tyler]
def getClassAverage(students):
sumIndivAve = 0
for student in students:
sumIndivAve += getAverage(student)
return (sumIndivAve/len(students))
Lloyd = {
"name":"Lloyd",
"homework": [90,97,75,92],
"quizzes": [ 88,40,94],
"tests": [ 75,90]
}
Alice = {
"name":"Alice",
"homework": [100,92,98,100],
"quizzes": [82,83,91],
"tests": [89,97]
}
Tyler = {
"name":"Tyler",
"homework": [0,87,75,22],
"quizzes": [0,75,78],
"tests": [100,100]
}
def average(stuff):
return sum(stuff)/len(stuff)
def getLetterGrade(score):
score = round(score)
if score >= 90: return "A"
elif 90 > score >= 80: return "B"
elif 80 > score >= 70: return "C"
elif 70 > score >= 60: return "D"
elif 60 > score: return "F"
def getAverage(kid):
bar = average
return bar(kid["homework"])*.1 + bar(kid["quizzes"])*.3 + bar(kid["tests"])*.6
students = [Lloyd,Alice,Tyler]
def getClassAverage(students):
sumIndivAve = 0
for student in students:
sumIndivAve += getAverage(student)
return (sumIndivAve/len(students))
Codecademy: Sending a Letter
#sample solution
Lloyd = {
"name":"Lloyd",
"homework": [90,97,75,92],
"quizzes": [ 88,40,94],
"tests": [ 75,90]
}
Alice = {
"name":"Alice",
"homework": [100,92,98,100],
"quizzes": [82,83,91],
"tests": [89,97]
}
Tyler = {
"name":"Tyler",
"homework": [0,87,75,22],
"quizzes": [0,75,78],
"tests": [100,100]
}
def average(numList):
sum = 0
for number in numList:
sum += number
return (float(sum)/len(numList))
def getAverage(studDict):
homeworkAve = average(studDict['homework'])
quizAve = average(studDict['quizzes'])
testAve = average(studDict['tests'])
weightedAve = (0.1*homeworkAve)+(0.3*quizAve)+(0.6*testAve)
return weightedAve
def get_letter_grade(score):
if score >= 90:
return "A"
elif score < 90 and score >=80:
return "B"
elif score < 80 and score >=70:
return "C"
elif score < 70 and score >=60:
return "D"
elif score < 60:
return "F"
print get_letter_grade(getAverage(Lloyd))
Lloyd = {
"name":"Lloyd",
"homework": [90,97,75,92],
"quizzes": [ 88,40,94],
"tests": [ 75,90]
}
Alice = {
"name":"Alice",
"homework": [100,92,98,100],
"quizzes": [82,83,91],
"tests": [89,97]
}
Tyler = {
"name":"Tyler",
"homework": [0,87,75,22],
"quizzes": [0,75,78],
"tests": [100,100]
}
def average(numList):
sum = 0
for number in numList:
sum += number
return (float(sum)/len(numList))
def getAverage(studDict):
homeworkAve = average(studDict['homework'])
quizAve = average(studDict['quizzes'])
testAve = average(studDict['tests'])
weightedAve = (0.1*homeworkAve)+(0.3*quizAve)+(0.6*testAve)
return weightedAve
def get_letter_grade(score):
if score >= 90:
return "A"
elif score < 90 and score >=80:
return "B"
elif score < 80 and score >=70:
return "C"
elif score < 70 and score >=60:
return "D"
elif score < 60:
return "F"
print get_letter_grade(getAverage(Lloyd))
Codecademy: Just Weight and See
#sample solution
Lloyd = {
"name":"Lloyd",
"homework": [90,97,75,92],
"quizzes": [ 88,40,94],
"tests": [ 75,90]
}
Alice = {
"name":"Alice",
"homework": [100,92,98,100],
"quizzes": [82,83,91],
"tests": [89,97]
}
Tyler = {
"name":"Tyler",
"homework": [0,87,75,22],
"quizzes": [0,75,78],
"tests": [100,100]
}
def average(numList):
sum = 0
for number in numList:
sum += number
return (sum/len(numList))
def getAverage(studDict):
homeworkAve = average(studDict['homework'])
quizAve = average(studDict['quizzes'])
testAve = average(studDict['tests'])
weightedAve = (0.1*homeworkAve)+(0.3*quizAve)+(0.6*testAve)
return weightedAve
print getAverage(Alice)
Lloyd = {
"name":"Lloyd",
"homework": [90,97,75,92],
"quizzes": [ 88,40,94],
"tests": [ 75,90]
}
Alice = {
"name":"Alice",
"homework": [100,92,98,100],
"quizzes": [82,83,91],
"tests": [89,97]
}
Tyler = {
"name":"Tyler",
"homework": [0,87,75,22],
"quizzes": [0,75,78],
"tests": [100,100]
}
def average(numList):
sum = 0
for number in numList:
sum += number
return (sum/len(numList))
def getAverage(studDict):
homeworkAve = average(studDict['homework'])
quizAve = average(studDict['quizzes'])
testAve = average(studDict['tests'])
weightedAve = (0.1*homeworkAve)+(0.3*quizAve)+(0.6*testAve)
return weightedAve
print getAverage(Alice)
Codecademy: It's Okay to be Average
#sample solution
Lloyd = {
"name":"Lloyd",
"homework": [90,97,75,92],
"quizzes": [ 88,40,94],
"tests": [ 75,90]
}
Alice = {
"name":"Alice",
"homework": [100,92,98,100],
"quizzes": [82,83,91],
"tests": [89,97]
}
Tyler = {
"name":"Tyler",
"homework": [0,87,75,22],
"quizzes": [0,75,78],
"tests": [100,99.5,99.7]
}
def average(numList):
sum = 0
for number in numList:
sum += number
return (float(sum)/len(numList))
print average(Tyler['tests'])
Lloyd = {
"name":"Lloyd",
"homework": [90,97,75,92],
"quizzes": [ 88,40,94],
"tests": [ 75,90]
}
Alice = {
"name":"Alice",
"homework": [100,92,98,100],
"quizzes": [82,83,91],
"tests": [89,97]
}
Tyler = {
"name":"Tyler",
"homework": [0,87,75,22],
"quizzes": [0,75,78],
"tests": [100,99.5,99.7]
}
def average(numList):
sum = 0
for number in numList:
sum += number
return (float(sum)/len(numList))
print average(Tyler['tests'])
Codecademy: For the Record
#sample solution
Lloyd = {
"name":"Lloyd",
"homework": [90, 97, 75, 92],
"quizzes": [88, 40, 94],
"tests": [75, 90]
}
Alice = {
"name":"Alice",
"homework": [100,92,98,100],
"quizzes": [82,83,91],
"tests": [89,97]
}
Tyler = {
"name":"Tyler",
"homework": [0,87,75,22],
"quizzes": [0,75,78],
"tests": [100,100]
}
students = [Lloyd, Alice, Tyler]
for student in students:
print student['name']
print student['homework']
print student['quizzes']
print student['tests']
Lloyd = {
"name":"Lloyd",
"homework": [90, 97, 75, 92],
"quizzes": [88, 40, 94],
"tests": [75, 90]
}
Alice = {
"name":"Alice",
"homework": [100,92,98,100],
"quizzes": [82,83,91],
"tests": [89,97]
}
Tyler = {
"name":"Tyler",
"homework": [0,87,75,22],
"quizzes": [0,75,78],
"tests": [100,100]
}
students = [Lloyd, Alice, Tyler]
for student in students:
print student['name']
print student['homework']
print student['quizzes']
print student['tests']
Codecademy: Put It Together
#sample solution
Lloyd = {
"name":"Lloyd",
"homework": [90, 97, 75, 92],
"quizzes": [88, 40, 94],
"tests": [75, 90]
}
Alice = {
"name":"Alice",
"homework": [100,92,98,100],
"quizzes": [82,83,91],
"tests": [89,97]
}
Tyler = {
"name":"Tyler",
"homework": [0,87,75,22],
"quizzes": [0,75,78],
"tests": [100,100]
}
students = [Lloyd, Alice, Tyler]
Lloyd = {
"name":"Lloyd",
"homework": [90, 97, 75, 92],
"quizzes": [88, 40, 94],
"tests": [75, 90]
}
Alice = {
"name":"Alice",
"homework": [100,92,98,100],
"quizzes": [82,83,91],
"tests": [89,97]
}
Tyler = {
"name":"Tyler",
"homework": [0,87,75,22],
"quizzes": [0,75,78],
"tests": [100,100]
}
students = [Lloyd, Alice, Tyler]
Codecademy: What's the Score?
#sample solution
Lloyd = {
"name":"Lloyd",
"homework": [90, 97, 75, 92],
"quizzes": [88, 40, 94],
"tests": [75, 90]
}
Alice = {
"name":"Alice",
"homework": [100,92,98,100],
"quizzes": [82,83,91],
"tests": [89,97]
}
Tyler = {
"name":"Tyler",
"homework": [0,87,75,22],
"quizzes": [0,75,78],
"tests": [100,100]
}
Lloyd = {
"name":"Lloyd",
"homework": [90, 97, 75, 92],
"quizzes": [88, 40, 94],
"tests": [75, 90]
}
Alice = {
"name":"Alice",
"homework": [100,92,98,100],
"quizzes": [82,83,91],
"tests": [89,97]
}
Tyler = {
"name":"Tyler",
"homework": [0,87,75,22],
"quizzes": [0,75,78],
"tests": [100,100]
}
Codecademy: Lesson Number One
#sample solution
Lloyd = {"name":"Lloyd","homework":[],"quizzes":[],"tests":[]}
Alice = {"name":"Alice","homework":[],"quizzes":[],"tests":[]}
Tyler = {"name":"Tyler","homework":[],"quizzes":[],"tests":[]}
Lloyd = {"name":"Lloyd","homework":[],"quizzes":[],"tests":[]}
Alice = {"name":"Alice","homework":[],"quizzes":[],"tests":[]}
Tyler = {"name":"Tyler","homework":[],"quizzes":[],"tests":[]}
Codecademy: Stocking Out
#sample solution
groceries = ["banana", "orange","apple"]
stock = {"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
def computeBill(groceries):
bill = 0
for fruit in groceries:
if stock[fruit] != 0:
bill += prices[fruit]
stock[fruit] -= 1
return bill
groceries = ["banana", "orange","apple"]
stock = {"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
def computeBill(groceries):
bill = 0
for fruit in groceries:
if stock[fruit] != 0:
bill += prices[fruit]
stock[fruit] -= 1
return bill
Codecademy: Making a Purchase
#sample solution
groceries = ["banana", "orange","apple"]
stock = {"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
def computeBill(groceries):
bill = 0
for fruit in groceries:
bill = bill + prices[fruit]
return bill
print computeBill(groceries)
groceries = ["banana", "orange","apple"]
stock = {"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
def computeBill(groceries):
bill = 0
for fruit in groceries:
bill = bill + prices[fruit]
return bill
print computeBill(groceries)
Codecademy: Shopping at the Market
#sample solution
groceries = ["banana", "orange", "apple"]
groceries = ["banana", "orange", "apple"]
Codecademy: Something of Value
#sample solution
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
totalValue = 0
for key in prices:
addedValue = prices[key] * stock[key]
totalValue = totalValue + addedValue
print totalValue
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
totalValue = 0
for key in prices:
addedValue = prices[key] * stock[key]
totalValue = totalValue + addedValue
print totalValue
Codecademy: Keeping Track of the Produce
#sample solution
prices = {"banana":4, "apple":2, "orange":1.5, "pear":3}
stock = {"banana":6, "apple":0, "orange":32, "pear":15}
for key in prices:
print key
print "price: " + str(prices[key])
print "stock: " + str(stock[key])
prices = {"banana":4, "apple":2, "orange":1.5, "pear":3}
stock = {"banana":6, "apple":0, "orange":32, "pear":15}
for key in prices:
print key
print "price: " + str(prices[key])
print "stock: " + str(stock[key])
Codecademy: Investing in Stock
#sample solution
prices = {"banana":4, "apple":2, "orange":1.5, "pear":3}
stock = {"banana":6, "apple":0, "orange":32, "pear":15}
prices = {"banana":4, "apple":2, "orange":1.5, "pear":3}
stock = {"banana":6, "apple":0, "orange":32, "pear":15}
Codecademy: Your Own Store!
#sample solution
prices = {"banana":4, "apple":2, "orange":1.5, "pear":3}
prices = {"banana":4, "apple":2, "orange":1.5, "pear":3}
Codecademy: Lists + Functions
#sample solution
def fizzCount(somelist):
count = 0
for item in somelist:
if item == 'fizz':
count = count + 1
return count
def fizzCount(somelist):
count = 0
for item in somelist:
if item == 'fizz':
count = count + 1
return count
Codecademy: Control Flow and Looping
#sample solution
A = [0,1,2,3,4,5,6,7,8,9,10,11,12,13]
for number in A:
if number % 2 == 0:
print number
A = [0,1,2,3,4,5,6,7,8,9,10,11,12,13]
for number in A:
if number % 2 == 0:
print number
Codecademy: This is KEY!
#sample solution
Webster = {
"Aardvark" : "A star of a popular children's cartoon show.",
"Baa" : "The sound a goat makes.",
"Carpet": "Goes on the Floor.",
"Dab": "A small amount."
}
for key in Webster:
print Webster[key]
Webster = {
"Aardvark" : "A star of a popular children's cartoon show.",
"Baa" : "The sound a goat makes.",
"Carpet": "Goes on the Floor.",
"Dab": "A small amount."
}
for key in Webster:
print Webster[key]
Codecademy: "BeFOR We Begin"
#sample solution
names = ["Adam","Alex","Mariah","Martine","Columbus"]
for name in names:
print name
names = ["Adam","Alex","Mariah","Martine","Columbus"]
for name in names:
print name
Codecademy: It's Dangerous To Go Alone!...
#sample solution
inventory = {'gold' : 500,
'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']}
# Adding a key 'burlap bag' and assigning a list to it
inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']
# Sorting the list found under the key 'pouch'
inventory['pouch'].sort()
# Here the dictionary access expression takes the place of a list name
# Your code here
inventory['pocket'] = ['seashell', 'strange berry', 'lint']
inventory['backpack'].sort()
inventory['backpack'].remove('dagger')
inventory['gold'] = inventory['gold'] + 50
print inventory
inventory = {'gold' : 500,
'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']}
# Adding a key 'burlap bag' and assigning a list to it
inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']
# Sorting the list found under the key 'pouch'
inventory['pouch'].sort()
# Here the dictionary access expression takes the place of a list name
# Your code here
inventory['pocket'] = ['seashell', 'strange berry', 'lint']
inventory['backpack'].sort()
inventory['backpack'].remove('dagger')
inventory['gold'] = inventory['gold'] + 50
print inventory
Codecademy: "Changing Your Mind"
#sample solution
# key - animal_name : value - location
zoo_animals = { 'Unicorn' : 'Cotton Candy House',
'Sloth' : 'Rainforest Exhibit',
'Bengal Tiger' : 'Jungle House',
'Atlantic Puffin' : 'Arctic Exhibit',
'Rockhopper Penguin' : 'Arctic Exhibit'}
# A dictionary (or list) declaration may break across multiple lines
# Removing the 'Unicorn' entry. (Unicorns are incredibly expensive.)
del zoo_animals['Unicorn']
# Your code here
del zoo_animals['Sloth']
del zoo_animals['Bengal Tiger']
zoo_animals['Rockhopper Penguin'] = 'Anything other than Arctic Exhibit'
print zoo_animals
# key - animal_name : value - location
zoo_animals = { 'Unicorn' : 'Cotton Candy House',
'Sloth' : 'Rainforest Exhibit',
'Bengal Tiger' : 'Jungle House',
'Atlantic Puffin' : 'Arctic Exhibit',
'Rockhopper Penguin' : 'Arctic Exhibit'}
# A dictionary (or list) declaration may break across multiple lines
# Removing the 'Unicorn' entry. (Unicorns are incredibly expensive.)
del zoo_animals['Unicorn']
# Your code here
del zoo_animals['Sloth']
del zoo_animals['Bengal Tiger']
zoo_animals['Rockhopper Penguin'] = 'Anything other than Arctic Exhibit'
print zoo_animals
Codecademy: "New Entries"
#sample solution
menu = {} # Empty dictionary
menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair
print menu['Chicken Alfredo']
# Your code here: Add some dish-price pairs to 'menu'
menu['Water'] = 1.50
menu['Dessert'] = 4.50
menu['Bread'] = 2.50
print "There are " + str(len(menu)) + " items on the menu."
print menu
menu = {} # Empty dictionary
menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair
print menu['Chicken Alfredo']
# Your code here: Add some dish-price pairs to 'menu'
menu['Water'] = 1.50
menu['Dessert'] = 4.50
menu['Bread'] = 2.50
print "There are " + str(len(menu)) + " items on the menu."
print menu
Codecademy: "The Next Part is Key"
#sample solution
# Assigning a dictionary with three key-value pairs to `residents`
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}
print residents['Puffin'] # Prints Puffin's room number
# Your code here
print residents['Sloth']
print residents['Burmese Python']
# Assigning a dictionary with three key-value pairs to `residents`
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}
print residents['Puffin'] # Prints Puffin's room number
# Your code here
print residents['Sloth']
print residents['Burmese Python']
Codecademy: More With 'for'
#sample solution
start_list = [5, 3, 1, 2, 4]
square_list = []
# Your code here
for number in start_list:
square_list.append(number**2)
square_list.sort()
print square_list
start_list = [5, 3, 1, 2, 4]
square_list = []
# Your code here
for number in start_list:
square_list.append(number**2)
square_list.sort()
print square_list
Codecademy: "For One and All"
#sample solution
my_list = [1,9,3,8,5,7]
for number in my_list:
# Your code here
print 2 * number
my_list = [1,9,3,8,5,7]
for number in my_list:
# Your code here
print 2 * number
Codecademy: "Maintaining Order"
#sample solution
animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck") # `index()` to find "duck"
# Your code here
animals.insert(duck_index,"cobra")
print animals # Observe what prints after the insert operation
animals = ["aardvark", "badger", "duck", "emu", "fennec fox"]
duck_index = animals.index("duck") # `index()` to find "duck"
# Your code here
animals.insert(duck_index,"cobra")
print animals # Observe what prints after the insert operation
Codecademy: "Slicing Lists and Strings"
#sample solution
animals = "catdogfrog"
cat = animals[:3]# The first three characters [:3] of `animals`
dog = animals[3:6]# The fouth through sixth characters
frog = animals[6:] # From the seventh character to the end
animals = "catdogfrog"
cat = animals[:3]# The first three characters [:3] of `animals`
dog = animals[3:6]# The fouth through sixth characters
frog = animals[6:] # From the seventh character to the end
Codecademy: "List Slicing"
#sample solution
suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]
first = suitcase[0:2] # the first two items
middle = suitcase[2:4] # third and fourth items
last = suitcase[4:6] # the last two items
suitcase = ["sunglasses", "hat", "passport", "laptop", "suit", "shoes"]
first = suitcase[0:2] # the first two items
middle = suitcase[2:4] # third and fourth items
last = suitcase[4:6] # the last two items
Tuesday, November 27, 2012
Codecademy: Late Arrivals & List Length
#sample solution
suitcase = []
suitcase.append("sunglasses")
# Your code here
suitcase.append("ball")
suitcase.append("towel")
suitcase.append("book")
list_length = len(suitcase) # length of `suitcase`
print "There are " + str(list_length) + " items in the suitcase."
print suitcase
suitcase = []
suitcase.append("sunglasses")
# Your code here
suitcase.append("ball")
suitcase.append("towel")
suitcase.append("book")
list_length = len(suitcase) # length of `suitcase`
print "There are " + str(list_length) + " items in the suitcase."
print suitcase
Codecademy: "New Neighbors"
#sample solution
zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"]
# Last night our zoo's sloth brutally attacked the poor tiger and ate it whole.
# The ferocious sloth has been replaced by a friendly hyena.
zoo_animals[2] = "hyena"
# What shall fill the void left by our dear departed tiger?
# Your code here.
zoo_animals[3] = "puma"
zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"]
# Last night our zoo's sloth brutally attacked the poor tiger and ate it whole.
# The ferocious sloth has been replaced by a friendly hyena.
zoo_animals[2] = "hyena"
# What shall fill the void left by our dear departed tiger?
# Your code here.
zoo_animals[3] = "puma"
Codecademy: "Access by Index"
#sample solution
numbers = [5, 6, 7, 8]
print "Adding the numbers at indices 0 and 2..."
print numbers[0] + numbers[2]
print "Adding the numbers at indices 1 and 3"
# Your code here
print numbers[1] + numbers[3]
numbers = [5, 6, 7, 8]
print "Adding the numbers at indices 0 and 2..."
print numbers[0] + numbers[2]
print "Adding the numbers at indices 1 and 3"
# Your code here
print numbers[1] + numbers[3]
Codecademy: "Introduction to Lists"
#sample solution
zoo_animals = [ "pangolin", "cassowary", "sloth", "elephant"]
# One animal is missing!
print zoo_animals
if len(zoo_animals) > 3:
print "The first animal at the zoo is the " + zoo_animals[0]
print "The second animal at the zoo is the " + zoo_animals[1]
print "The third animal at the zoo is the " + zoo_animals[2]
print "The fourth animal at the zoo is the " + str(zoo_animals[3])
zoo_animals = [ "pangolin", "cassowary", "sloth", "elephant"]
# One animal is missing!
print zoo_animals
if len(zoo_animals) > 3:
print "The first animal at the zoo is the " + zoo_animals[0]
print "The second animal at the zoo is the " + zoo_animals[1]
print "The third animal at the zoo is the " + zoo_animals[2]
print "The fourth animal at the zoo is the " + str(zoo_animals[3])
Codecademy: "Check Yourself"
#sample solution
#print "Welcome to the English to Pig Latin translator!"
original="";
def check_string(original):
size = len(original)
if size != 0:
print original
else:
print "empty"
check_string("A string!")
check_string("")
#print "Welcome to the English to Pig Latin translator!"
original="";
def check_string(original):
size = len(original)
if size != 0:
print original
else:
print "empty"
check_string("A string!")
check_string("")
Codecademy: "Paying Up"
#sample solution
def hotelCost(days):
return 140*days
bill = hotelCost(5)
print "Bill cost is " + str(bill)
def addMonthlyInterest(balance):
return balance * (1 + (0.15 / 12) )
def makePayment(payment,balance):
adjustedBalance = balance - payment
newBalance = addMonthlyInterest(adjustedBalance)
return "You Still Owe: " + str(newBalance)
print makePayment(350,bill)
def hotelCost(days):
return 140*days
bill = hotelCost(5)
print "Bill cost is " + str(bill)
def addMonthlyInterest(balance):
return balance * (1 + (0.15 / 12) )
def makePayment(payment,balance):
adjustedBalance = balance - payment
newBalance = addMonthlyInterest(adjustedBalance)
return "You Still Owe: " + str(newBalance)
print makePayment(350,bill)
Codecademy: "Something of Interest
#sample solution
def hotelCost(days):
return 140*days
bill = hotelCost(5)
def getMin(balance, rate):
minimumPayment = rate * balance
return minimumPayment
print getMin(bill, 0.02)
def addMonthlyInterest(balance):
#since APR is an annual percentage, divide it by 12 to get the
#monthly percentage
APR = 0.15 / 12
interest = balance * APR
return balance + interest
print addMonthlyInterest(100)
print addMonthlyInterest(bill)
def hotelCost(days):
return 140*days
bill = hotelCost(5)
def getMin(balance, rate):
minimumPayment = rate * balance
return minimumPayment
print getMin(bill, 0.02)
def addMonthlyInterest(balance):
#since APR is an annual percentage, divide it by 12 to get the
#monthly percentage
APR = 0.15 / 12
interest = balance * APR
return balance + interest
print addMonthlyInterest(100)
print addMonthlyInterest(bill)
Codecademy: At A Bare Minimum
#sample solution
def hotelCost(days):
return 140*days
bill = hotelCost(5)
def getMin(balance, rate):
minimumPayment = rate * balance
return minimumPayment
print getMin(bill, 0.02)
def hotelCost(days):
return 140*days
bill = hotelCost(5)
def getMin(balance, rate):
minimumPayment = rate * balance
return minimumPayment
print getMin(bill, 0.02)
Codecademy: "Gotta Give Me Some Credit"
#sample solution
def hotelCost(days):
return 140*days
bill = hotelCost(5)
def hotelCost(days):
return 140*days
bill = hotelCost(5)
Codecademy: Coming Back Home
#sample solution
def hotelCost(days):
return 140*days
def planeRideCost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "Los Angeles":
return 475
def rentalCarCost(days):
cost = days*40
if days >= 7:
cost -= 50
elif days >= 3:
cost -= 20
return cost
def tripCost(city,days,cash=0):
return cash+\
rentalCarCost(days)+\
hotelCost(days)+\
planeRideCost(city)
# You were planning on taking a trip to LA for 5 days
# with $600 of spending money.
print tripCost("Los Angeles",5,600)
actualCost = 2734.23
overBudget = actualCost - tripCost("Los Angeles",5,600)
print overBudget
def hotelCost(days):
return 140*days
def planeRideCost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "Los Angeles":
return 475
def rentalCarCost(days):
cost = days*40
if days >= 7:
cost -= 50
elif days >= 3:
cost -= 20
return cost
def tripCost(city,days,cash=0):
return cash+\
rentalCarCost(days)+\
hotelCost(days)+\
planeRideCost(city)
# You were planning on taking a trip to LA for 5 days
# with $600 of spending money.
print tripCost("Los Angeles",5,600)
actualCost = 2734.23
overBudget = actualCost - tripCost("Los Angeles",5,600)
print overBudget
Codecademy: Pull It All Together
#sample solution
def hotelCost(days):
return 140*days
def planeRideCost(city):
if city == "Charlotte":
return 183
if city == "Tampa":
return 220
if city == "Pittsburgh":
return 222
if city == "Los Angeles":
return 475
def rentalCarCost(days):
cost = days*40
if days >= 7:
cost -= 50
elif days >= 3:
cost -= 20
return cost
def tripCost(city,days):
return rentalCarCost(days) + planeRideCost(city) + hotelCost(days)
def hotelCost(days):
return 140*days
def planeRideCost(city):
if city == "Charlotte":
return 183
if city == "Tampa":
return 220
if city == "Pittsburgh":
return 222
if city == "Los Angeles":
return 475
def rentalCarCost(days):
cost = days*40
if days >= 7:
cost -= 50
elif days >= 3:
cost -= 20
return cost
def tripCost(city,days):
return rentalCarCost(days) + planeRideCost(city) + hotelCost(days)
Codecademy: Transportation
#sample solution
def hotelCost(days):
return days * 140
def planeRideCost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "Los Angeles":
return 475
else:
return "Unknown destination"
def rentalCarCost(days):
totalCarCost = days * 40
if days < 3:
return totalCarCost
elif days >= 3 and days < 7:
return totalCarCost - 20
elif days >= 7:
return totalCarCost - 50
def hotelCost(days):
return days * 140
def planeRideCost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "Los Angeles":
return 475
else:
return "Unknown destination"
def rentalCarCost(days):
totalCarCost = days * 40
if days < 3:
return totalCarCost
elif days >= 3 and days < 7:
return totalCarCost - 20
elif days >= 7:
return totalCarCost - 50
Codecademy: "Getting There"
#sample solution
def hotelCost(days):
return days * 140
def planeRideCost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "Los Angeles":
return 475
else:
return "Unknown destination"
def hotelCost(days):
return days * 140
def planeRideCost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "Los Angeles":
return 475
else:
return "Unknown destination"
Codecademy: "Planning Your Trip"
#sample solution
def hotelCost(days):
return days * 140
def hotelCost(days):
return days * 140
Codecademy: "Problem Solvers"
//sample solution
import math
def areaOfCircle(radius):
return math.pi * radius * radius
import math
def areaOfCircle(radius):
return math.pi * radius * radius
Codecademy: "Function and Control Flow"
//sample solution
def isEven(x):
if(x % 2 == 0):
return "yep"
else:
return "nope"
def isEven(x):
if(x % 2 == 0):
return "yep"
else:
return "nope"
Codecademy: "Call Me Maybe"
//sample solution
def cube(x):
return x**3
print cube(27)
def cube(x):
return x**3
print cube(27)
Codecademy: "Finding Your Identity"
//sample solution
def identity(x):
return x
def identity(x):
return x
Codecademy: "Before We Begin"
//sample solution
def answer():
return 42
answer()
Codecademy: "Review: Built-in Functions"
//sample solution
def distance_from_zero(param):
if (type(param) is int) or (type(param) is float):
return abs(param)
else:
return "This isn't an integer or a float!"
print distance_from_zero(-1)
print distance_from_zero(-2.13)
print distance_from_zero("A string.")
def distance_from_zero(param):
if (type(param) is int) or (type(param) is float):
return abs(param)
else:
return "This isn't an integer or a float!"
print distance_from_zero(-1)
print distance_from_zero(-2.13)
print distance_from_zero("A string.")
Codecademy: "Review: Modules"
//sample solution
from math import sqrt
val = sqrt(13689)
print val
from math import sqrt
val = sqrt(13689)
print val
Codecademy: "Extracting Information"
//sample solution
from datetime import datetime
now = datetime.now()
print "%2s" % (now.month)
print "%2s" % (now.day)
print "%2s" % (now.year)
from datetime import datetime
now = datetime.now()
print "%2s" % (now.month)
print "%2s" % (now.day)
print "%2s" % (now.year)
Codecademy: "The second 'if statement"
//sample solution
var slaying = true;
var youHit = Math.floor(Math.random() * 2);
console.log("youHit is " + youHit);
var damageThisRound = Math.floor(Math.random() * 5 + 1);
console.log("The amount of damage dealt this round is " + damageThisRound);
var totalDamage = 0;
console.log("The total damage received is " + totalDamage);
while(slaying){
if(youHit){
totalDamage = totalDamage + damageThisRound;
console.log("The total damage received is " + totalDamage);
if(totalDamage >= 4){
console.log("Congratulations! You've slayed the dragon.");
slaying = false;
}
else{
youHit = Math.floor(Math.random() * 1);
}
}
else{
console.log("The dragon defeated you!");
slaying = false;
}
}
var slaying = true;
var youHit = Math.floor(Math.random() * 2);
console.log("youHit is " + youHit);
var damageThisRound = Math.floor(Math.random() * 5 + 1);
console.log("The amount of damage dealt this round is " + damageThisRound);
var totalDamage = 0;
console.log("The total damage received is " + totalDamage);
while(slaying){
if(youHit){
totalDamage = totalDamage + damageThisRound;
console.log("The total damage received is " + totalDamage);
if(totalDamage >= 4){
console.log("Congratulations! You've slayed the dragon.");
slaying = false;
}
else{
youHit = Math.floor(Math.random() * 1);
}
}
else{
console.log("The dragon defeated you!");
slaying = false;
}
}
Codecademy: "To learn it, you gotta 'do' it"
//sample solution
getToDaChoppa(){
var test = 1;
do{
console.log("Print!");
test--;
} while(test>=0);
}
getToDaChoppa();
getToDaChoppa(){
var test = 1;
do{
console.log("Print!");
test--;
} while(test>=0);
}
getToDaChoppa();
Codecademy: "Break Out Your .accordion()"
//sample solution to script.js
$(document).ready(function(){
$('#menu').accordion();
});
$(document).ready(function(){
$('#menu').accordion();
});
Codecademy: "jQuery UI, is There Anything..."
<!-- sample solution to index.html-->
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel='stylesheet' type='text/css' href='http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css'/>
<script type='text/javascript' src='script.js'></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
</head>
<body>
<div id="menu">
<h3>Section 1</h3>
<div>
<p>I'm the first section!</p>
</div>
<!--Add two more sections below!-->
<h3>Section 2</h3>
<div>
<p>I'm the second section!</p>
</div>
<h3>Section 3</h3>
<div>
<p>I'm the third section!</p>
</div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel='stylesheet' type='text/css' href='http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css'/>
<script type='text/javascript' src='script.js'></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
</head>
<body>
<div id="menu">
<h3>Section 1</h3>
<div>
<p>I'm the first section!</p>
</div>
<!--Add two more sections below!-->
<h3>Section 2</h3>
<div>
<p>I'm the second section!</p>
</div>
<h3>Section 3</h3>
<div>
<p>I'm the third section!</p>
</div>
</div>
</body>
</html>
Codecademy: "Let's Sort Things Out"
//sample solution
$(document).ready(function(){
$('ol').sortable();
});
$(document).ready(function(){
$('ol').sortable();
});
Codecademy: "A Greater Selection"
//sample solution to script.js
$(document).ready(function(){
$('ol').selectable();
});
$(document).ready(function(){
$('ol').selectable();
});
Codecademy: "One Resize Fits All"
//sample solution to script.js
$(document).ready(function(){
$('div').resizable();
});
$(document).ready(function(){
$('div').resizable();
});
Codecademy: "Drag Racing"
//sample solution to script.js
$(document).ready(function(){
$('#car').draggable();
});
$(document).ready(function(){
$('#car').draggable();
});
Codecademy: ".slide()"
//sample solution to script.js
$(document).ready(function(){
$('div').click(function(){
$(this).effect('slide');
});
});
$(document).ready(function(){
$('div').click(function(){
$(this).effect('slide');
});
});
Codecademy: ".bounce()"
//sample solution
$(document).ready(function(){
$('div').click(function(){
$(this).effect('bounce',{times:3},500);
});
});
$(document).ready(function(){
$('div').click(function(){
$(this).effect('bounce',{times:3},500);
});
});
Codecademy: "Introducing jQuery UI"
//sample solution
$(document).ready(function(){
$('div').click(function(){
$(this).effect('explode');
});
});
$(document).ready(function(){
$('div').click(function(){
$(this).effect('explode');
});
});
Monday, November 26, 2012
Codecademy: "More Practice With .animate()"
//sample solution
$(document).ready(function(){
$('img').animate({top:'+=100px'},1000);
});
$(document).ready(function(){
$('img').animate({top:'+=100px'},1000);
});
Codecademy: "You Know This!"
//sample solution
$(document).ready(function(){
$('div').hide();
});
$(document).ready(function(){
$('div').hide();
});
Codecademy: "Filling Out the Cases"
//sample solution to script.js
$(document).ready(function() {
$(document).keydown(function(key) {
switch(parseInt(key.which,10)) {
case 65://left
$('img').animate({left: "-=10px"}, 'fast');
break;
case 83://down
$('img').animate({top: "+=10px"}, 'fast');
break;
case 87://up
$('img').animate({top: "-=10px"}, 'fast');
break;
case 68:
$('img').animate({left: "+=10px"}, 'fast');
break;
default:
break;
}
});
});
$(document).ready(function() {
$(document).keydown(function(key) {
switch(parseInt(key.which,10)) {
case 65://left
$('img').animate({left: "-=10px"}, 'fast');
break;
case 83://down
$('img').animate({top: "+=10px"}, 'fast');
break;
case 87://up
$('img').animate({top: "-=10px"}, 'fast');
break;
case 68:
$('img').animate({left: "+=10px"}, 'fast');
break;
default:
break;
}
});
});
Codecademy: "Using .keydown()"
//sample solution to script.js
$(document).ready(function(){
$(document).keydown(function(key){
});
});
$(document).ready(function(){
$(document).keydown(function(key){
});
});
Codecademy: "The .keydown() Event"
//sample solution to script.js
$(document).ready(function(){
//remember to click on the element when testing
$(document).keydown(function(){
$('div').animate({left:'+=10px'},500);
});
});
Codecademy: "Let's .focus()!"
//sample solution
$(document).ready(function(){
$('input').focus(function(){
$(this).css('outline-color','#FF0000');
});
});
$(document).ready(function(){
$('input').focus(function(){
$(this).css('outline-color','#FF0000');
});
});
Codecademy ".mouseenter() and .mouseleave()"
//sample solution
$(document).ready(function(){
$('div').mouseenter(function(){
$(this).fadeTo('fast',1);
});
$('div').mouseleave(function(){
$(this).fadeTo('fast',0.25);
});
});
$(document).ready(function(){
$('div').mouseenter(function(){
$(this).fadeTo('fast',1);
});
$('div').mouseleave(function(){
$(this).fadeTo('fast',0.25);
});
});
Codecademy: "The .dblclick() Event"
//sample solution
$(document).ready(function(){
$('div').dblclick(function(){
$(this).fadeOut('fast');
});
});
$(document).ready(function(){
$('div').dblclick(function(){
$(this).fadeOut('fast');
});
});
Codecademy: "Combining click() and hover()"
//sample solution to script.js
$(document).ready(function(){
$('div').click(function(){
$(this).fadeOut('fast');
});
$('div').hover(function(){
$(this).addClass('red');
});
});
$(document).ready(function(){
$('div').click(function(){
$(this).fadeOut('fast');
});
$('div').hover(function(){
$(this).addClass('red');
});
});
Codecademy: "Adding an Event Handler"
//sample solution to script.js
$(document).ready(function(){
$('div').click(function(){
$(this).fadeOut('fast');
});
});
$(document).ready(function(){
$('div').click(function(){
$(this).fadeOut('fast');
});
});
Codecademy: "Cutting to the Chase"
//sample solution to script.js
$(document).ready(function(){
$('div').fadeOut('fast');
});
$(document).ready(function(){
$('div').fadeOut('fast');
});
Codecademy: "$p vs $('p')"
//sample solution to script.js
// Write your jQuery code below!
var $div;
$(document).ready(function(){
$div = $('div');
});
// Write your jQuery code below!
var $div;
$(document).ready(function(){
$div = $('div');
});
Codecademy: "Creating HTML Elements"
//sample solution to script.js
var $h1;
$(document).ready(function(){
$h1 = $("<h1>Hello</h1>");
});
var $h1;
$(document).ready(function(){
$h1 = $("<h1>Hello</h1>");
});
Codecademy: "Remove What's Been Clicked"
//sample solution to script.js
$(document).ready(function(){
$('#button').click(function(){
var toAdd = $('input[name=checkListItem]').val();
//remember to click on the Add button when testing
$('.list').append("<div class='item'>" + toAdd + "</div>");
});
$(document).on('click','.item',function(){
$(this).remove();
});
});
$(document).ready(function(){
$('#button').click(function(){
var toAdd = $('input[name=checkListItem]').val();
//remember to click on the Add button when testing
$('.list').append("<div class='item'>" + toAdd + "</div>");
});
$(document).on('click','.item',function(){
$(this).remove();
});
});
Codecademy: "Append To Body"
//sample solution
$(document).ready(function(){
$('#button').click(function(){
var toAdd = $('input[name=checkListItem]').val();
//remember to add content to the input box and click on the Add button when testing
//$('.list').append('div').addClass('item').html(toAdd); //this should work too
$('.list').append("<div class='item'>" + toAdd + "</div>");
});
});
$(document).ready(function(){
$('#button').click(function(){
var toAdd = $('input[name=checkListItem]').val();
//remember to add content to the input box and click on the Add button when testing
//$('.list').append('div').addClass('item').html(toAdd); //this should work too
$('.list').append("<div class='item'>" + toAdd + "</div>");
});
});
Codecademy: "Click Da Button!"
//sample solution to script.js
$(document).ready(function(){
$('#button').click(function(){
var toAdd = $('input[name=checkListItem]').val();
});
});
$(document).ready(function(){
$('#button').click(function(){
var toAdd = $('input[name=checkListItem]').val();
});
});
Codecademy: "Modifying Content"
//sample solution to script.js
$(document).ready(function(){
$('p').html("jQuery magic in action!");
});
$(document).ready(function(){
$('p').html("jQuery magic in action!");
});
Codecademy: "Changing Your Style"
//sample solution to script.js
$(document).ready(function(){
$('div').height('200px').width('200px').css('border-radius','10px');
});
$(document).ready(function(){
$('div').height('200px').width('200px').css('border-radius','10px');
});
Codecademy: "Toggling Classes"
//sample solution to script.js
$(document).ready(function(){
$('#text').click(function(){
$(this).toggleClass('highlighted');
});
});
$(document).ready(function(){
$('#text').click(function(){
$(this).toggleClass('highlighted');
});
});
Codecademy: "Adding and Removing Classes"
//sample solution to script.js
$(document).ready(function(){
$('#text').click(function(){
$(this).addClass('highlighted');
});
});
$(document).ready(function(){
$('#text').click(function(){
$(this).addClass('highlighted');
});
});
Codecademy: "Removing Elements"
//sample solution to script.js
$(document).ready(function(){
$('#two').after("<p>I'm a paragraph!</p>");
$('p').remove();
});
$(document).ready(function(){
$('#two').after("<p>I'm a paragraph!</p>");
$('p').remove();
});
Codecademy: "Moving Elements Around"
//sample solution to script.js
$(document).ready(function(){
$('#two').after("<p>I'm a paragraph!</p>");
});
$(document).ready(function(){
$('#two').after("<p>I'm a paragraph!</p>");
});
Codecademy: "Before and After"
//sample solution to script.js
$(document).ready(function(){
$('#one').after("<p>I'm a paragraph!</p>");
});
$(document).ready(function(){
$('#one').after("<p>I'm a paragraph!</p>");
});
Codecademy: "Inserting Elements"
//sample solution to script.js
$(document).ready(function(){
$('body').append("<p>I'm a paragraph!</p>");
});
$(document).ready(function(){
$('body').append("<p>I'm a paragraph!</p>");
});
Codecademy: "Toggling Our Panel"
//sample solution to script.js
$(document).ready(function(){
$('.pull-me').click(function(){
$('.panel').slideToggle('slow');
});
});
$(document).ready(function(){
$('.pull-me').click(function(){
$('.panel').slideToggle('slow');
});
});
Codecademy: "Click and Pull"
//sample solution to script.js
$(document).ready(function(){
$('.pull-me').click(function(){
});
});
$(document).ready(function(){
$('.pull-me').click(function(){
});
});
Codecademy: "Flexible Selections"
//sample solution to script.js
$(document).ready(function(){
$(".pink, .red").fadeTo('slow',0);
});
//YAY
$(document).ready(function(){
$(".pink, .red").fadeTo('slow',0);
});
//YAY
Codecademy: "Selecting by ID"
//sample solution to script.js
$(document).ready(function() {
$('button').click(function() {
$('#blue').fadeOut('slow');
});
});
$(document).ready(function() {
$('button').click(function() {
$('#blue').fadeOut('slow');
});
});
Codecademy: "Selecting by Class"
//sample solution to script.js
$(document).ready(function() {
$('button').click(function() {
$('.vanish').fadeOut('slow');
});
});
$(document).ready(function() {
$('button').click(function() {
$('.vanish').fadeOut('slow');
});
});
Codecademy: "Using Functions to Select HTML Elements"
//sample solution to script.js
$(document).ready(function(){
$('div').fadeIn('slow');
});
$(document).ready(function(){
$('div').fadeIn('slow');
});
Codecademy: "Assigning Values"
//sample solution
// Write your jQuery code on line 3!
$(document).ready(function() {
var $target = $("li:nth-child(4)");
$target.fadeOut('fast');
});
// Write your jQuery code on line 3!
$(document).ready(function() {
var $target = $("li:nth-child(4)");
$target.fadeOut('fast');
});
Codecademy: "Functions, Part II:..."
//sample solution to script.js
$(document).ready(function() {
$('div').click(function() {
$('div').fadeOut('slow');
});
});
$(document).ready(function() {
$('div').click(function() {
$('div').fadeOut('slow');
});
});
Codecademy: "Functions, Part I:..."
//sample solution to script.js
$(document).ready(function(){
$('div').hide();
});
$(document).ready(function(){
$('div').hide();
});
Codecademy: "...and Get Yourself Out!"
//sample solution to script.js
$(document).ready(function(){
$('div').mouseenter(function(){
$('div').fadeTo('fast',1);
});
$('div').mouseleave(function(){
$('div').fadeTo('fast',0.5);
});
});
$(document).ready(function(){
$('div').mouseenter(function(){
$('div').fadeTo('fast',1);
});
$('div').mouseleave(function(){
$('div').fadeTo('fast',0.5);
});
});
Codecademy: "Get Yourself In..."
//sample solution to script.js
$(document).ready(function(){
$('div').mouseenter(function(){
$('div').fadeTo('fast',1);
});
});
$(document).ready(function(){
$('div').mouseenter(function(){
$('div').fadeTo('fast',1);
});
});
Codecademy: "Electr(on)ic Slide"
//sample solution to script.js
$(document).ready(function() {
$("div").slideDown('slow');
});
$(document).ready(function() {
$("div").slideDown('slow');
});
Codecademy: "The Functional Approach"
//sample solution to script.js
$(document).ready(function(){
});
$(document).ready(function(){
});
Subscribe to:
Posts (Atom)
This is an example of scrolling text using Javascript.
Popular Posts
-
//Sample Solution for MainController.js app.controller('MainController', ['$scope', function($scope) { $scope.title = ...
-
Question: What current is required for full scale deflection of a galvanometer having a current sensitivity of 50 micro-amperes per scale di...
-
Answer: This is the type of injury when a blow to the forehead causes a contusion of the eyeball due to the fracture of the bone at the r...
-
This is caused by the entrance of water into the air sacs which makes the lungs doughy, readily pits on pressure, exuding water and froth
-
var my_canvas=document.getElementById('canvas'); var context=my_canvas.getContext('2d');
-
#Sample Solution --- title: "Data Cleaning in R" output: html_notebook --- ```{r message=FALSE, warning=FALSE} # load libra...
-
# Update data types year_1_str = str(year_1) revenue_1_str = str(revenue_1) # Create a complete sentence combining only the string d...
-
//Sample Solution const gameState = {} function preload() { this.load.image('codey', 'https://s3.amazonaws.com/codecademy-...
-
Question: How do I startup Blend for Visual Studio once it has been installed? Answer: Click on the Windows button at the bottom left co...
-
Instructions: Count the number of rows from the flights table, where arr_time is not null and the destination is ATL. Sample Solution: S...