Ejemplo n.º 1
5
sample = open('samplepost.txt').read()  #reading the dictionary from the samplepost.txt file, and storing it to the variable sample
sample_post_dict = json.loads(sample)  #this is taking the sample variable from above, taking it from JSON formatted string to a python dictionary.
p = Post(sample_post_dict)  #passing the dictionary we created into the class Post above, so we can perform operations on the dictionary so we can get information.

# 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
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)        
    
Ejemplo n.º 2
0
from test import testEqual

class Point:

    def __init__(self, init_x, init_y):
        """ Create a new point at the given coordinates. """
        self.x = init_x
        self.y = init_y

    def get_x(self):
        return self.x

    def get_y(self):
        return self.y

    def distance_from_origin(self):
        return ((self.x ** 2) + (self.y ** 2)) ** 0.5

    def __repr__(self):
        return "x=" + str(self.x) + ", y=" + str(self.y)


r = Rectangle(Point(0, 0), 10, 5)
testEqual(r.contains(Point(0, 0)), True)
testEqual(r.contains(Point(3, 3)), True)
testEqual(r.contains(Point(3, 7)), False)
testEqual(r.contains(Point(3, 5)), False)
testEqual(r.contains(Point(3, 4.99999)), True)
testEqual(r.contains(Point(-3, -3)), False)
Ejemplo n.º 3
0
    # Bonus: your code here
    count = 0
    for roll in double_list:
        if (same_roll(roll)):
            count += 1
    return count


def same_roll(throw):
    is_same = True
    val = throw[0]
    for i in range(1, len(throw)):
        if (throw[i] != val):
            is_same = False

    return is_same


# To play, yo'd do something like this
# dice = input("How many dice?")
# rolls = input("What is the number of rolls?")
# list = roll_dice(dice, rolls)
# print("Sum of roll:", sum_of_roll(list))

print("Testing sum_of_roll...")
testEqual(sum_of_roll([[4, 5, 2], [6, 2, 1], [4, 4, 4]]), [11, 9, 12])
testEqual(sum_of_roll([[3, 4, 6], [2, 6, 1], [3, 4, 3]]), [13, 9, 10])
print("Testing yahtzee...")
testEqual(yahtzee([[4, 5, 2], [6, 2, 1], [4, 4, 4]]), 1)
testEqual(yahtzee([[3, 4, 6], [2, 6, 1], [3, 4, 3]]), 0)
Ejemplo n.º 4
0
#         return final_r + [new_row]

# Modify recursive tree
# Fractal Mountain
# Hilbert Curve
# Koch Snowflake

# Tower of Hanoi
# Cannibal Puzzle
# Die Hard Jug Puzzle

#   base case
#   change state, move towards base case
#   call itself

testEqual(reverse("hello"), "olleh")
testEqual(reverse("l"), "l")
testEqual(reverse("follow"), "wollof")
testEqual(reverse(""), "")
testEqual(is_palindrome("hello"), False)
testEqual(is_palindrome("aibohphobia"), True)

print(alpha_only("Cage! Match!"))

s = "madam i'm adam"
print(is_palindrome(s))

print(factorial(5))

alist = [1, 2, 3, 4, 5]
print(reverse_list(alist))
Ejemplo n.º 5
0
from test import testEqual


def is_rightangled(a, b, c):
    rightangled = False

    if a > b and a > c:
        rightangled = abs(b**2 + c**2 - a**2) < 0.001
    elif b > a and b > c:
        rightangled = abs(a**2 + c**2 - b**2) < 0.001
    else:
        rightangled = abs(a**2 + b**2 - c**2) < 0.001
    return rightangled


testEqual(is_rightangled(1.5, 2.0, 2.5), True)
testEqual(is_rightangled(4.0, 8.0, 16.0), False)
testEqual(is_rightangled(4.1, 8.2, 9.1678787077), True)
testEqual(is_rightangled(4.1, 8.2, 9.16787), True)
testEqual(is_rightangled(4.1, 8.2, 9.168), False)
testEqual(is_rightangled(0.5, 0.4, 0.64031), True)
Ejemplo n.º 6
0
    one = [a.replace("ebook", "") for a in x]
    two = [a.replace("Novel", "") for a in one]
    three = [a.replace("book", "") for a in two]
    four = [a.replace("Book", "") for a in three]
    five = [a.lower() for a in four]
    list_novels = [a.replace("-", " ") for a in five]
    return list_novels


novellist2 = (fix_data(hardcovernonfiction_booknames))
print "Here's the best seller list of the top 10 hardcover non fiction books"
print pretty(novellist2)

print "Tests"
try:
    test.testEqual(type(novellist2), type([]))
    test.testEqual(len(novellist2), 10)
except:
    print "Check that you are performing the list comprehensions correctly in order to collect the names of only ten novels in an iterable list"

#Steps 11-15 repeat same process but with third list
d = {}
d['api-key'] = '678eeafb3f2b698e01865592a3de62ab:7:70254372'
d['list-name'] = 'e-book-fiction'
d['date'] = '2014-12-07'
e = urllib.urlencode(d)
param_str = e

baseurl = "http://api.nytimes.com/svc/books/v3/lists"
nyt_request = baseurl + "?" + param_str
Ejemplo n.º 7
0
#========================INTRODUCTION TO TEST CASES==============================
#================================================================================
def square(x):
    return x * x


import test

print('TESTING SQUARE FUNCTION')
test.testEqual(square(10), 100)
Ejemplo n.º 8
0
from test import testEqual


def remove_all(substr, theStr):
    occur = theStr.count(substr)
    for i in range(occur):
        theStr = theStr.replace(substr, "")
    return theStr
    # your code here


testEqual(remove_all('an', 'banana'), 'ba')
testEqual(remove_all('cyc', 'bicycle'), 'bile')
testEqual(remove_all('iss', 'Mississippi'), 'Mippi')
testEqual(remove_all('eggs', 'bicycle'), 'bicycle')
Ejemplo n.º 9
0
Reversing a string using the Stack data structure.
O(n) running time.
"""

from test import testEqual
from pythonds.basic.stack import Stack

# My implementation:
def revstring_mine(mystr):
    s = Stack()
    for char in mystr:
        s.push(char)
    rev_chars = [s.pop() for i in range(len(mystr))]
    return ''.join(l)


# Example given in the book:
def revstring_mine(mystr):
    s = Stack()
    for char in mystr:
        s.push(char)
    revstr = ''
    while not s.isEmpty():
        revstr += s.pop()
    return revstr


testEqual(revstring('apple'),'elppa')
testEqual(revstring('x'),'x')
testEqual(revstring('1234567890'),'0987654321')
Ejemplo n.º 10
0
from test import testEqual

def findHypot(a,b):
    hypotenuse=(a**2+b**2)**0.5
    print(hypotenuse)
    return hypotenuse

testEqual(findHypot(12.0, 5.0), 13.0)
testEqual(findHypot(14.0, 48.0), 50.0)
testEqual(findHypot(21.0, 72.0), 75.0)
testEqual(findHypot(1, 1.73205), 1.999999)
Ejemplo n.º 11
0
from test import testEqual

def reverse(astring):
    j=""
    s=len(astring)
    for i in range(s):
        j=astring[i]+j
    return j
 

testEqual(reverse("happy"), "yppah")
testEqual(reverse("Python"), "nohtyP")
testEqual(reverse(""), "")
Ejemplo n.º 12
0
def fix_data(x):
    one = [a.replace("ebook", "") for a in x]
    two= [a.replace("Novel", "") for a in one]
    three= [a.replace("book", "") for a in two]
    four= [a.replace("Book", "") for a in three]
    five = [a.lower() for a in four]
    list_novels = [a.replace("-", " ") for a in five]
    return list_novels 
novellist2 = (fix_data(hardcovernonfiction_booknames))
print "Here's the best seller list of the top 10 hardcover non fiction books"
print pretty(novellist2)

print "Tests"
try:
    test.testEqual(type(novellist2), type([]))
    test.testEqual(len(novellist2), 10)
except:
    print "Check that you are performing the list comprehensions correctly in order to collect the names of only ten novels in an iterable list"
    
#Steps 11-15 repeat same process but with third list of fictional ebooks
d = {}
d['api-key'] = '678eeafb3f2b698e01865592a3de62ab:7:70254372'
d['list-name'] = 'e-book-fiction'
d['date'] = '2014-12-07'
e =  urllib.urlencode(d)
param_str = e

baseurl = "http://api.nytimes.com/svc/books/v3/lists"
nyt_request = baseurl + "?" + param_str
Ejemplo n.º 13
0
from test import testEqual

def buildTree():
    pass

ttree = buildTree()

testEqual(ttree.getRightChild().getRootVal(),'c')
testEqual(ttree.getLeftChild().getRightChild().getRootVal(),'d')
testEqual(ttree.getRightChild().getLeftChild().getRootVal(),'e')
Ejemplo n.º 14
0
from test import testEqual

def isLeap(year):
    if year%100==0:
        if year%400==0:
            return True
        else: 
            return False
    else:
        if year%4==0:
            return True
        else:
            return False    

testEqual(isLeap(1944), True)
testEqual(isLeap(2011), False)
testEqual(isLeap(1986), False)
testEqual(isLeap(1800), False)
testEqual(isLeap(1900), False)
testEqual(isLeap(2000), True)
testEqual(isLeap(2056), True)
Ejemplo n.º 15
0
from test import testEqual

def remove_letter(theLetter, theString):
    s=len(theString)
    j=""
    for i in theString:
        if i!=theLetter:
            j=j+i    
    return j

testEqual(remove_letter('a', 'apple'), 'pple')
testEqual(remove_letter('a', 'banana'), 'bnn')
testEqual(remove_letter('z', 'banana'), 'banana')
Ejemplo n.º 16
0
class Point:
    def __init__(self, init_x, init_y):
        """ Create a new point at the given coordinates. """
        self.x = init_x
        self.y = init_y

    def get_x(self):
        return self.x

    def get_y(self):
        return self.y

    def distance_from_origin(self):
        return ((self.x**2) + (self.y**2))**0.5

    def __repr__(self):
        return "x=" + str(self.x) + ", y=" + str(self.y)


from test import testEqual

r = Rectangle(Point(0, 0), 10, 5)
testEqual(r.perimeter(), 30)
from test import testEqual

def remove(substr,theStr):
    index = theStr.find(substr)
    if index < 0: # substr doesn't exist in theStr
        return theStr
    return_str = theStr[:index] + theStr[index+len(substr):]
    return return_str

testEqual(remove('an', 'banana'), 'bana')
testEqual(remove('cyc', 'bicycle'), 'bile')
testEqual(remove('iss', 'Mississippi'), 'Missippi')
testEqual(remove('egg', 'bicycle'), 'bicycle')
def get_country_codes(prices):
    new_prices = prices.split()

    new_list = []
    for codes in new_prices:
        new_list.append(codes[0:2])

    return (', '.join(new_list))


# don't include these tests in Vocareum
from test import testEqual

testEqual(get_country_codes("NZ$300, KR$1200, DK$5"), "NZ, KR, DK")
testEqual(get_country_codes("US$40, AU$89, JP$200"), "US, AU, JP")
testEqual(get_country_codes("AU$23, NG$900, MX$200, BG$790, ES$2"),
          "AU, NG, MX, BG, ES")
testEqual(get_country_codes("CA$40"), "CA")
Ejemplo n.º 19
0
# 	for x in list:
# 		s=x.split()
# 		first=s[0]
# 		newlist=newlist.append(first)
# 	return newlist
# 
# words= ['Amazing', 'corny', 'zany']
# print f(words)

def interp(x, y):

	mystr = 'That is %d in a row, %s. Congratulations!' %(x,y)
	return mystr

print interp(5,'sir')
test.testEqual(interp(5, "sir"), "That is 5 in a row, sir. Congratulations!")
test.testEqual(interp(6, "your highness"), "That is 6 in a row, your highness. Congratulations!")

def h(x=1,y=3 ,z=4):

    return[x, y, z]
print h()

def enum(L):
    res = []
    n = 1
    for item in L:
        res.append((n, item))
        n = n + 1
    return res
print enum(["a", "b", "c"])
Ejemplo n.º 20
0
from test import testEqual
import math

def findHypot(a,b):
    #math.hypot(x,Y)
    length = math.hypot(a,b)
    return length

#print  (findHypot (3,4)) 
testEqual(findHypot(12.0, 5.0), 13.0)
testEqual(findHypot(14.0, 48.0), 50.0)
testEqual(findHypot(21.0, 72.0), 75.0)
testEqual(findHypot(1, 1.73205), 1.999999)
Ejemplo n.º 21
0
# put your code here -- you just need to change what's in the param_str variable.
d = {}
d['format'] = 'json'
param_str = urllib.urlencode(d)

# (1b) Add (concatenate) the airport and the param_str to the base URL, which is:
#        http://services.faa.gov/airport/status/
#      Store the string in a variable called airport_request.
print '---------------'
baseurl = 'http://services.faa.gov/airport/status/'
airport = 'DTW'
airport_request = baseurl + airport + '?' + param_str # change this line of code so airport_request equals the whole request
# Again, simple -- we're doing this step by step.

## Testing problem 1
test.testEqual(param_str, "format=json", "testing correct output for 1(a)")
test.testEqual(airport_request,"http://services.faa.gov/airport/status/DTW?format=json", "testing correct output for 1(b)")


# [PROBLEM 2]
## Grabbing data off the web
# (2)  Use urllib2.urlopen() to retrieve data from the airport_request address.
# You did a similar thing last week -- but now we're going to move toward getting data 
# and using it.
#      Store the data, in one long string, in a variable called airport_json_str.
print '---------------'

try:
    result = urllib2.urlopen(airport_request)
    airport_json_str = urllib2.urlopen("http://services.faa.gov/airport/status/DTW?format=json").read() # change this line of code
__author__ = 'ada'

from test import testEqual
from Pythonds.basic.stack import Stack

def revstring(original_string):

    myStack = Stack()
    for each_char in original_string:
        myStack.push(each_char) #=> creeaza a stack with the letters in the original original_string
    # create the reversed string by taking the element from the top of the stack(last inserted, first taken) and insering it into the string

    reversed_string = ""
    while not myStack.isEmpty():
        reversed_string += myStack.pop()

    return reversed_string

testEqual(revstring("caracao"), "oacarac")



Ejemplo n.º 23
0
# input format: a: [[start1,end1,val1],[start2,end2,val2]...]
# first break the input into two parts
def interval_max(a):
    pair = []
    one = []
    length = len(a)
    for i in range(length):
        one = []
        one.append(a[i][0])
        one.append(a[i][2])
        pair.append(one)
        one = []
        one.append(a[i][1])
        one.append(-a[i][2])
        pair.append(one)
        
    pair.sort()
    max_sum = 0
    cur = pair[0][1]
    for i in range(2*length):
        max_sum = max_sum+pair[i][1]
        if (max_sum > cur):
            cur = max_sum 
            
    return cur              


test.testEqual(interval_max([[1,3,100],[2,4,200],[5,6,300]]),300)


Ejemplo n.º 24
0
#    percent = num_e / num_char
#    percent = str(percent)
#    percent = str("num_e" + "percent")

#    print("The text contains" + num_char " alphabetic characters, of which " 105 (43.75%)" + " are 'e'.")

# Don't copy these tests into Vocareum!
# Note that depending on whether you use str.format or string concatenation
# your code will pass different tests. As long as your code passes either
# tests 1-3 OR tests 4-6, it should pass in Vocareum. See below for more details.
from test import testEqual

# Tests 1-3: solutions using string concatenation should pass these
text1 = "Eeeee"
answer1 = "The text contains 5 alphabetic characters, of which 5 (100.0%) are 'e'."
testEqual(analyze_text(text1), answer1)

text2 = "Blueberries are tasteee!"
answer2 = "The text contains 21 alphabetic characters, of which 7 (33.3333333333%) are 'e'."
testEqual(analyze_text(text2), answer2)

text3 = "Wright's book, Gadsby, contains a total of 0 of that most common symbol ;)"
answer3 = "The text contains 55 alphabetic characters, of which 0 (0.0%) are 'e'."
testEqual(analyze_text(text3), answer3)

# Tests 4-6: solutions using str.format should pass these
text4 = "Eeeee"
answer4 = "The text contains 5 alphabetic characters, of which 5 (100%) are 'e'."
testEqual(analyze_text(text4), answer4)

text5 = "Blueberries are tasteee!"
Ejemplo n.º 25
0
from test import testEqual

def is_even(n):
    return n % 2 == 0
        
testEqual(is_even(10), True)
testEqual(is_even(5), False)
testEqual(is_even(1), False)
testEqual(is_even(0), True)
Ejemplo n.º 26
0
'''import math

def calculate_area(radius):
    return math.pi * radius ** 2
    '''
'''import math
def area_of_circle(radius):
    return math.pi*radius**2
    print (area_of_circle(1))
    '''
''''(GRADED) Write a function areaOfCircle(r) which returns the area of a circle of radius r.
 Make sure you use the math module in your solution.'''

from test import testEqual
import math


# TODO: use def to define a function called areaOfCircle which takes an argument called r
# TODO implment your function to return the area of a circle whose radius is r
def areaOfCircle(r):
    return math.pi * r**2


t = areaOfCircle(0)
testEqual(t, 0)
t = areaOfCircle(1)
testEqual(t, math.pi)
t = areaOfCircle(100)
testEqual(t, 31415.926535897932)
Ejemplo n.º 27
0
    while i < len(original_string):
        #print("At the start of the loop, i is:", i, "and the string is:", new_str)
        if (original_string[i:i+len(substr)] == substr) and (found == False):
            i += len(substr)
            #print("yes")
            found = True
        else:
            new_str += original_string[i]
            #print("no")
            i += 1
        #print("At the end of the loop, i is:", i, "and the string is:", new_str)
            
    
    return new_str

testEqual(remove('an', 'banana'), 'bana')
testEqual(remove('cyc', 'bicycle'), 'bile')
testEqual(remove('iss', 'Mississippi'), 'Missippi')
testEqual(remove('egg', 'bicycle'), 'bicycle')
testEqual(remove('oo', 'Yahoohoo'), 'Yahhoo')

#4. Write a function reverse that receives a string argument, and returns a reversed version of the string.
from test import testEqual

def reverse(text):
    # your code here
    new_str = ""
    
    for char in text:
        new_str = char + new_str
        
            return True
    print('\tTest Failed: expected {} but got {}'.format(expected, actual))
    return False


print("\n------Begin Unit Testing------")
import test


def square(x):
    '''raise x to the second power'''
    return x * x


print('testing square function')
test.testEqual(square(10), 100)


def power_of_3(x):
    # To the third power
    return x * x * x


print('\ntesting cube function')
test.testEqual(power_of_3(2), 8)


def doubling(x):
    return x * 2

Ejemplo n.º 29
0
    You are the bouncer outside the door of a seniors only bar.
     People must be 70 or older, otherwise they are not allowed in.
     When a group of friends arrives, your job is to determine whether to accept or reject the group.
     The function below, check_group, is supposed to return a boolean indicating whether or not the group is allowed inside.
     But it’s not working!

'''


# return True if every member of the group is at least 70, otherwise return False
def check_group(ages):
    for age in ages:
        if age < 70:
            return False
    return True


from test import testEqual

# this group should not be allowed inside the bar
group = [78, 71, 25, 84]
testEqual(check_group(group), False)

# this group should also not be allowed inside the bar
group2 = [2, 99]
testEqual(check_group(group2), False)

# this loner is allowed
group3 = [99]
testEqual(check_group(group3), True)
Ejemplo n.º 30
0
#
# def remove(substr,theStr):
#     # your code here
#     strIndex=theStr.find(substr)
#     if strIndex<0:
#         return theStr
#     else:
#         newstring=theStr[:strIndex]+theStr[strIndex+len(substr):]
#         return newstring
#
#
# testEqual(remove('an', 'banana'), 'bana')
# testEqual(remove('cyc', 'bicycle'), 'bile')
# testEqual(remove('iss', 'Mississippi'), 'Missippi')
# testEqual(remove('egg', 'bicycle'), 'bicycle')
# testEqual(remove('oo', 'Yahoohoo'), 'Yahhoo')
# ///////////////////////////////////////
from test import testEqual


def reverse(text):
    w = ''
    for x in text:
        w = x + w
    return w


testEqual(reverse("happy"), "yppah")
testEqual(reverse("Python"), "nohtyP")
testEqual(reverse(""), "")
Ejemplo n.º 31
0
    wn.exitonclick()

if __name__ == "__main__":
    main()

"""5. Write a function called is_even(n) that takes an integer as an argument and returns True if the argument is an even number and False if it is odd. Note that instead of printing out the results we are using test statements. The goal is to pass all the tests that are listed underneath the function you will write. You do not need to add a main function to this code to run it."""
from test import testEqual

def is_even(n):
    # your code here
    if (n % 2) == 0:
        return True
    else:
        return False

testEqual(is_even(10), True)
testEqual(is_even(5), False)
testEqual(is_even(1), False)
testEqual(is_even(0), True)

#6. Now write the function is_odd(n) that returns True when n is odd and False otherwise.
from test import testEqual

def is_odd(n):
    # Your code here
     # your code here
    if (n % 2) != 0:
        return True
    else:
        return False
Ejemplo n.º 32
0
from test import testEqual


def reverse(s):
    y = ""
    w = len(s)
    for x in range(len(s)):
        y += s[w - 1]
        w -= 1
    return y


testEqual(reverse("hello"), "olleh")
testEqual(reverse("l"), "l")
testEqual(reverse("follow"), "wollof")
testEqual(reverse(""), "")
Ejemplo n.º 33
0
# TODO: use def to define a function called areaOfCircle which takes an argument called r
import math


# TODO implement your function to return the area of a circle whose radius is r
def areaOfCircle(r):
    a = r**2 * math.pi
    return a


# Below are some tests which can give you an indication that your code seems to be correct.
# IMPORTANT: You should NOT include this part when you submit in Vocareum.
# When you submit, only include the function above.
from test import testEqual

t = areaOfCircle(0)
testEqual(t, 0)
t = areaOfCircle(1)
testEqual(t, math.pi)
t = areaOfCircle(100)
testEqual(t, 31415.926535897932)
t = areaOfCircle(-1)
testEqual(t, math.pi)
t = areaOfCircle(-5)
testEqual(t, 25 * math.pi)
t = areaOfCircle(2.3)
testEqual(t, 16.61902513749)
Ejemplo n.º 34
0
		return self.time
		
	def militaryto12(self):
		time1 = self.time[11:]
		time2 = int(time1[:2])
		if time2 > 12:
			return str(time2-12)+':'+time1[3:]+' PM'
		
		
newdlist = []
for x in dlist:
	one = DateTime(str(x))
	print one
	newdlist.append(one.militaryto12())

test.testEqual(one.militaryto12(), '6:30:00 PM')	

strlist = []
for x in biglist:
	date2 = x['datetime_local']
	address = x['venue']['address']
	location2 = x['venue']['display_location']
	venue = x['venue']['name']
#	for d in newdlist:
		#date1 = d
	date3 = DateTime(str(date2))
	for y in x['performers']:
		name = y['name']
		if name in blist:
			strings = "%s is coming to %s on %s at %s at %s at %s." % (name, location2, date2[:10], date3.militaryto12(), venue, address)
			strlist.append(str(strings))
Ejemplo n.º 35
0
		return self.time

	def militaryto12(self):
		time1 = self.time[11:]
		time2 = int(time1[:2])
		if time2 > 12:
			return str(time2-12)+':'+time1[3:]+' PM'


newdlist = []
for x in dlist:
	one = DateTime(str(x))
	print(one)
	newdlist.append(one.militaryto12())

test.testEqual(one.militaryto12(), '6:30:00 PM')

strlist = []
for x in biglist:
	date2 = x['datetime_local']
	address = x['venue']['address']
	location2 = x['venue']['display_location']
	venue = x['venue']['name']
#	for d in newdlist:
		#date1 = d
	date3 = DateTime(str(date2))
	for y in x['performers']:
		name = y['name']
		if name in blist:
			strings = "%s is coming to %s on %s at %s at %s at %s." % (name, location2, date2[:10], date3.militaryto12(), venue, address)
			strlist.append(str(strings))
    """ Point class for representing and manipulating x,y coordinates. """
    def __init__(self, initX, initY):

        self.x = initX
        self.y = initY

    def distanceFromOrigin(self):
        return ((self.x**2) + (self.y**2))**0.5

    def move(self, dx, dy):
        self.x = self.x + dx
        self.y = self.y + dy


import test

#testing instance variables x and y
p = Point(3, 4)
test.testEqual(p.y, 4)
test.testEqual(p.x, 3)

#testing the distance method
p = Point(3, 4)
test.testEqual(p.distanceFromOrigin(), 5.0)

#testing the move method
p = Point(3, 4)
p.move(-2, 3)
test.testEqual(p.x, 1)
test.testEqual(p.y, 7)
Ejemplo n.º 37
0
#1
from test import testEqual

testEqual('Python'[1], 'y')
testEqual('Strings are sequences of characters.'[5], 'g')
testEqual(len('wonderful'), 9)
testEqual('Mystery'[:4], 'Myst')
testEqual('p' in 'Pineapple', True)
testEqual('apple' in 'Pineapple', True)
testEqual('pear' not in 'Pineapple', True)
testEqual('apple' > 'pineapple', False)
testEqual('pineapple' < 'Peach', False)


#2
def num_digits(n):
    n_str = str(n)
    return len(n_str)


def main():
    print(num_digits(50))
    print(num_digits(20000))
    print(num_digits(1))


if __name__ == "__main__":
    main()

#3
from test import testEqual
Ejemplo n.º 38
0
        sorted_contact_list.append(contact)

    return sorted_contact_list


#if __name__ == "__main__":
#    main()

# The code below is just for your testing purposes. Make sure you pass all the tests.
# In Vocareum, only put code for the sort_contacts function above
from test import testEqual

testEqual(
    sort_contacts({
        "Horney, Karen": ("1-541-656-3010", "*****@*****.**"),
        "Welles, Orson": ("1-312-720-8888", "*****@*****.**"),
        "Freud, Anna": ("1-541-754-3010", "*****@*****.**")
    }), [('Freud, Anna', '1-541-754-3010', '*****@*****.**'),
         ('Horney, Karen', '1-541-656-3010', '*****@*****.**'),
         ('Welles, Orson', '1-312-720-8888', '*****@*****.**')])
#testEqual(sort_contacts({"Summitt, Pat": ("1-865-355-4320", "*****@*****.**"),
#    "Rudolph, Wilma": ("1-410-5313-584", "*****@*****.**")}),
#    [('Rudolph, Wilma', '1-410-5313-584', '*****@*****.**'),
#    ('Summitt, Pat', '1-865-355-4320', '*****@*****.**')])
#testEqual(sort_contacts({"Dinesen, Isak": ("1-718-939-2548", "*****@*****.**")}),
#    [('Dinesen, Isak', '1-718-939-2548', '*****@*****.**')])
#testEqual(sort_contacts({"Rimbaud, Arthur": ("1-636-555-5555", "*****@*****.**"),
#    "Swinton, Tilda": ("1-917-222-2222", "*****@*****.**"),
#    "Almodovar, Pedro": ("1-990-622-3892", "*****@*****.**"), "Kandinsky, Wassily":
#    ("1-333-555-9999", "*****@*****.**")}), [('Almodovar, Pedro', '1-990-622-3892',
#    '*****@*****.**'), ('Kandinsky, Wassily', '1-333-555-9999', '*****@*****.**'),
#    ('Rimbaud, Arthur', '1-636-555-5555', '*****@*****.**'), ('Swinton, Tilda',
Ejemplo n.º 39
0
    # Your code here
    count = 0
    i = 0
    d = {}
    while i < len(l):
        first = l[i]
        j = i + 1
        while j < len(l):
            second = l[j]
            if second % first == 0:
                mid_count = d.get((j, second), -1)
                if mid_count == -1:
                    mid_count = 0
                    k = j + 1
                    while k < len(l):
                        third = l[k]
                        if third % second == 0:
                            mid_count += 1
                        k += 1
                    d[(j, second)] = mid_count
                count += mid_count
            j += 1
        i += 1
    
    return count

test.testEqual(solution([1, 1, 1]), 1)
test.testEqual(solution([1, 2, 3, 4, 5, 6]), 3)
test.testEqual(solution([1, 2, 4, 8, 16, 5, 10, 15]), 13)

from test import testEqual


def removeWhite(s):
    s.replace(" ", "")
    s.replace("‘", "")
    return s


def isPal(s):
    if len(s) == 1 or len(s) == 0:
        return True

    for i in range(len(s) // 2):
        if s[i] == s[-1 - i]:
            return True
        else:
            return False


testEqual(isPal(removeWhite("x")), True)
testEqual(isPal(removeWhite("radar")), True)
testEqual(isPal(removeWhite("hello")), False)
testEqual(isPal(removeWhite("")), True)
testEqual(isPal(removeWhite("hannah")), True)
testEqual(isPal(removeWhite("madam i'm adam")), True)
Ejemplo n.º 41
0
# from test import testEqual
# import math
#
# def findHypot(a,b):
#     return math.sqrt( (a**2) + (b**2) )
#
# testEqual(findHypot(12.0, 5.0), 13.0)
# testEqual(findHypot(14.0, 48.0), 50.0)
# testEqual(findHypot(21.0, 72.0), 75.0)
# testEqual(findHypot(1, 1.73205), 1.999999)
from test import testEqual

def is_odd(n):
    # Your code here
    if n%2 !=0:
        return True
    else:
        return False

testEqual(is_odd(10), False)
testEqual(is_odd(5), True)
testEqual(is_odd(1), True)
testEqual(is_odd(0), False)
Ejemplo n.º 42
0
def sum_all(nums):
    # your code here
    found_first = False
    total = 0

    for n in nums:
        if not found_first and n % 2 == 0:
            found_first = True
            continue

        total += n

    return total


print(sum_all([1, 2, 3, 4]))

from test import testEqual

testEqual(sum_of_initial_odds([1, 3, 1, 4, 3, 8]), 5)
testEqual(sum_of_initial_odds([6, 1, 3, 5, 7]), 0)
testEqual(sum_of_initial_odds([1, -7, 10, 23]), -6)
testEqual(sum_of_initial_odds(range(1, 555, 2)), 76729)
Ejemplo n.º 43
0
import test

test.testEqual(sorted([1, 7, 4]), [1, 4, 7])
test.testEqual(sorted([1, 7, 4], reverse=True), [7, 4, 1])
Ejemplo n.º 44
0
bubble_sort(lst1)
bubble_sort(lst2)
print(lst1)
print(lst2)

#方法2


def bubble_sort(alist):
    exchanges = True
    passnum = len(alist) - 1
    while passnum > 0 and exchanges:
        exchanges = False
        for i in range(passnum):
            if alist[i] > alist[i + 1]:
                exchanges = True
                temp = alist[i]
                alist[i] = alist[i + 1]
                alist[i + 1] = temp
        passnum = passnum - 1
    return alist


from test import testEqual

testEqual(bubble_sort([0]), [0])  # Sorts a single element, returns same list
testEqual(bubble_sort([1, 2, 3, 4, 5]),
          [1, 2, 3, 4, 5])  # Sorted list is the same
testEqual(bubble_sort([5, 4, 3, 2, 1]), [1, 2, 3, 4, 5])
testEqual(bubble_sort([4, 5, 3, 1, 2]), [1, 2, 3, 4, 5])
Ejemplo n.º 45
0
from test import testEqual

def is_odd(n):
    if n%2!=0:
        return True
    else:
        return False

testEqual(is_odd(10), False)
testEqual(is_odd(5), True)
testEqual(is_odd(1), True)
testEqual(is_odd(0), False)