Ejemplo n.º 1
0
def testsuite():
    # test(merge_1([1, 3, 4, 5, 5], [1, 2, 4, 5, 6]) == [1, 4, 5])
    # test(merge_1([1, 2, 5, 5, 8], [2, 8, 11]) == [2, 8])
    # test(merge_1([10], [9]) == [])
    # test(merge_1([-4, -3, 3, 4], [-4, -3, 0, 7, 9]) == [-4, -3])
    # test(merge_1([1], [0, 3, 5, 7, 9]) == [])
    # test(merge_2([10, 9, 8, 7], [6, 5, 4, 3]) == [10, 9, 8, 7])
    # test(merge_3([10, 9, 8, 7], [6, 5, 4, 3]) == [6, 5, 4, 3])
    # test(merge_4([1, 2, 3, 4, 5, 6], [1, 2, 3, 5, 7, 9]) == [4, 6, 7, 9])
    # test(merge_5([5, 7, 11, 11, 11, 12, 13], [7, 8, 11]) == [5, 11, 11, 12, 13])
    # test(not share_diagonal(5, 2, 2, 0))
    # test(share_diagonal(5, 2, 3, 0))
    # test(share_diagonal(5, 2, 4, 3))
    # test(share_diagonal(5, 2, 4, 1))
    # test(not col_clashes([6, 4, 2, 0, 5], 4))
    # test(not col_clashes([6, 4, 2, 0, 5, 7, 1, 3], 7))
    # test(col_clashes([0, 1], 1))
    # test(col_clashes([5, 6], 1))
    # test(col_clashes([6, 5], 1))
    # test(col_clashes([0, 6, 4, 3], 3))
    # test(col_clashes([5, 0, 7], 2))
    # test(not col_clashes([2, 0, 1, 3], 1))
    # test(col_clashes([2, 0, 1, 3], 2))
    # test(not has_clashes([6, 4, 2, 0, 5, 7, 1, 3]))  # Solution from above
    # test(has_clashes([4, 6, 2, 0, 5, 7, 1, 3]))  # Swap rows of first two
    # test(has_clashes([0, 1, 2, 3]))  # Try small 4x4 board
    # test(not has_clashes([2, 0, 3, 1]))
    # test(lotto_check([42, 4, 7, 11, 1, 13], [2, 5, 7, 11, 13, 17]) == 3)
    # test(lotto_check2(my_tickets, [2, 5, 7, 11, 13, 17]) == [2, 3, 6, 2])
    # test(return_prime([42, 4, 7, 11, 1, 13]) == 3)
    # test(prime_discover([[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43], [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43]], prime_nums) == [[47]])
    test(lotto_check3(my_tickets) == 4)
def main():
    test(flatten([2, 9, [2, 1, 13, 2], 8, [2, 6]]), [2, 9, 2, 1, 13, 2, 8, 2, 6])
    test(flatten([[9, [7, 1, 13, 2], 8], [7, 6]]), [9, 7, 1, 13, 2, 8, 7, 6])
    test(flatten([[9, [7, 1, 13, 2], 8], [2, 6]]), [9, 7, 1, 13, 2, 8, 2, 6])
    test(flatten([['this', ['a', ['thing'], 'a'], 'is'], ['a', 'easy']]),
         ['this', 'a', 'thing', 'a', 'is', 'a', 'easy'])
    test(flatten([]), [])
Ejemplo n.º 3
0
def testsuite():
    # test(search_linear(friends, "Zoe") == 1)
    # test(search_linear(friends, "Joe") == 0)
    # test(search_linear(friends, "Paris") == 6)
    # test(search_linear(friends, "Bill") == -1)
    # test(find_unknown_words(vocab, book_words) == ["from", "to"])
    # test(find_unknown_words([], book_words) == book_words)
    # test(find_unknown_words(vocab, ["the", "boy", "fell"]) == [])
    # test(text_to_words("My name is Earl!") == ["my", "name", "is", "earl"])
    # test(text_to_words('"Well, I never!", said Alice.') == ["well", "i", "never", "said", "alice"])
    # test(search_binary(xs, 20) == -1)
    # test(search_binary(xs, 99) == -1)
    # test(search_binary(xs, 1) == -1)
    # for (i, v) in enumerate(xs):
    #     test(search_binary(xs, v) == i)
    # test(remove_adjacent_dups([1, 2, 3, 3, 3, 3, 5, 6, 9, 9]) == [1, 2, 3, 5, 6, 9])
    # test(remove_adjacent_dups([]) == [])
    # test(remove_adjacent_dups(["a", "big", "big", "bite", "dog"]) ==
    #      ["a", "big", "bite", "dog"])
    # test(merge(xs2, []) == xs2)
    # test(merge([], ys) == ys)
    # test(merge([], []) == [])
    # test(merge(xs, ys) == zs)
    # test(merge([1, 2, 3], [3, 4, 5]) == [1, 2, 3, 3, 4, 5])
    test(
        merge(["a", "big", "cat"], ["big", "bite", "dog"]) ==
        ["a", "big", "big", "bite", "cat", "dog"])
Ejemplo n.º 4
0
def test_suite():
    test(
        exer_7(",", ";", "this,that,andsomeotherthing") ==
        "this;that;andsomeotherthing")
    test(
        exer_7(" ", "**", "Words will now        be separated by stars.") ==
        "Words**will**now**be**separated**by**stars.")
def main():
    test(flatten([2, 9, [2, 1, 13, 2], 8, [2, 6]]),
         [2, 9, 2, 1, 13, 2, 8, 2, 6])
    test(flatten([[9, [7, 1, 13, 2], 8], [7, 6]]), [9, 7, 1, 13, 2, 8, 7, 6])
    test(flatten([[9, [7, 1, 13, 2], 8], [2, 6]]), [9, 7, 1, 13, 2, 8, 2, 6])
    test(flatten([['this', ['a', ['thing'], 'a'], 'is'], ['a', 'easy']]),
         ['this', 'a', 'thing', 'a', 'is', 'a', 'easy'])
    test(flatten([]), [])
Ejemplo n.º 6
0
def test_suite():
    # test(square_roote(25) == 5)
    test(
        myreplace(",", ";", "this, that, and some other thing") ==
        "this; that; and some other thing")
    test(
        myreplace(" ", "**", "Words will now be separated by stars.") ==
        "Words**will**now**be**separated**by**stars.")
Ejemplo n.º 7
0
def test_suite():
    test(lotto_match([42, 4, 7, 11, 1, 13], [2, 5, 7, 11, 13, 17]) == 3)

    test(lotto_matches([42, 4, 7, 11, 1, 13], my_tickets) == [1, 2, 3, 1])

    test(prime_in([42, 4, 7, 11, 1, 13]) == 3)

    test(prime_misses(my_tickets) == [3, 29, 47])
Ejemplo n.º 8
0
def test_suit():
    new_inventory = {}
    add_fruit(new_inventory, "strawberries", 10)
    test("strawberries" in new_inventory)
    test(new_inventory["strawberries"] == 10)

    add_fruit(new_inventory, "strawberries", 25)
    test(new_inventory["strawberries"] == 35)
from unit_tester import test


def add_fruit(inventory, fruit, quantity=0):
    inventory[fruit] = inventory.get(fruit, 0) + quantity
    return


# Make these tests work...
new_inventory = {}
add_fruit(new_inventory, "strawberries", 10)
test("strawberries" in new_inventory, True)
test(new_inventory["strawberries"], 10)
add_fruit(new_inventory, "strawberries", 25)
test(new_inventory["strawberries"], 35)
Ejemplo n.º 10
0
import math


def r_max(num_list):
    largest = -math.inf
    for item in num_list:
        if type(item) == list:
            largest = max(largest, r_max(item))
        else:
            largest = max(item, largest)
    return largest


from unit_tester import test

test(r_max([2, 9, [1, 13], 8, 6]) == 13)
test(r_max([2, [[100, 7], 90], [1, 13], 8, 6]) == 100)
test(r_max([[[13, 7], 90], 2, [1, 100], 8, 6]) == 100)
# test(r_max(["joe", ["sam", "ben"]]) == "sam")


def fib(num):
    if num <= 1:
        return num
    else:
        result = fib(num - 1) + fib(num - 2)
    return result


# import time
# t0 = time.clock()
        """ Create a new point at the origin """
        self.x = x
        self.y = y

    def distance_from_origin(self):
        """ Compute my distance from the origin """
        return ((self.x**2) + (self.y**2))**0.5

    def __str__(self):  # All we have done is renamed the method
        return "({0}, {1})".format(self.x, self.y)

    def halfway(self, target):
        """ Return the halfway point between myself and the target """
        mx = (self.x + target.x) / 2
        my = (self.y + target.y) / 2
        return Point(mx, my)

    def distance(self, target):
        dx = target.x - self.x
        dy = target.y - self.y
        dsquared = dx * dx + dy * dy
        result = dsquared**0.5
        return result

    def reflect_x(self):
        ry = self.y * -1
        return Point(self.x, ry)


test(Point(3, 5).reflect_x(), (3, -5))
Ejemplo n.º 12
0
    lb = 0
    ub = len(xs)
    while True:
        if lb == ub:  # If region of interest (ROI) becomes empty
            return -1

        # Next probe should be in the middle of the ROI
        mid_index = (lb + ub) // 2

        # Fetch the item at that position
        item_at_mid = xs[mid_index]

        # print("ROI[{0}:{1}](size={2}), probed='{3}', target='{4}'".format(lb, ub, ub-lb, item_at_mid, target))

        # How does the probed item compare to the target?
        if item_at_mid == target:
            return mid_index  # Found it!
        if item_at_mid < target:
            lb = mid_index + 1  # Use upper half of ROI next time
        else:
            ub = mid_index  # Use lower half of ROI next time


# Main
xs = [2, 3, 5, 7, 11, 13, 17, 23, 29, 31, 37, 43, 47, 53]
test(search_binary(xs, 20), -1)  # Looks at the boundary conditions of the search
test(search_binary(xs, 99), -1)
test(search_binary(xs, 1), -1)
for (i, v) in enumerate(xs):
    test(search_binary(xs, v), i)
Ejemplo n.º 13
0
from unit_tester import test


def search_linear(xs, target):
    """ Find and return the index of target in sequence xs """
    for (i, v) in enumerate(xs):
        if v == target:
            return i
    return -1


friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]
test(search_linear(friends, "Zoe") == 1)
test(search_linear(friends, "Joe") == 0)
test(search_linear(friends, "Paris") == 6)
test(search_linear(friends, "Bill") == -1)

vocab = ["apple", "boy", "dog", "down", "fell", "girl", "grass", "the", "tree"]
book_words = "the apple fell from the tree to the grass".split()


def find_unknown_words(vocab, wds):
    """ Return a list of words in wds that do not occur in vocab """
    result = []
    for w in wds:
        if (search_linear(vocab, w) < 0):
            result.append(w)
    return result


def load_words_from_file(filename):
Ejemplo n.º 14
0
from unit_tester import test
from wordtools import *

test(cleanword("what?")=="what")
test(cleanword("'now!")=="now")
test(cleanword("?+='w-o-r-d!,@$()'")=="word")

test(has_dashdash("distance--but"))
test(not has_dashdash("several"))
test(has_dashdash("spoke--"))
test(has_dashdash("distance--but"))
test(not has_dashdash("-yo-yo-"))

test(extract_words("Now is the time! 'Now', is the time? Yes, now.")==
['now','is','the','time','now','is','the','time','yes','now'])
test(extract_words("she tried to curtsey as she spoke--fancy")==
['she','tried','to','curtsey','as','she','spoke','fancy'])

test(wordcount("now",["now","is","time","is","now","is","is"])==2)
test(wordcount("is",["now","is","time","is","now","the","is"])==3)
test(wordcount("time",["now","is","time","is","now","is","is"])==1)
test(wordcount("frog",["now","is","time","is","now","is","is"])==0)

test(wordset(["now","is","time","is","now","is","is"])==["is","now","time"])
test(wordset(["I","a","a","is","a","is","I","am"])==["I","a","am","is"])
test(wordset(["or","a","am","is","are","be","but","am"])==["a","am","are","be","but","is","or"])

test(longestword(["a","apple","pear","grape"])==5)
test(longestword(["a","am","I","be"])==2)
test(longestword(["this","supercalifragilisticexpialidocious"])==34)
test(longestword([])==0)
Ejemplo n.º 15
0
        return (x, mr, mt, mrx, mry, mtx, mty)


class Rectangle:
    """ A class to manufacture rectangle objects """
    def __init__(self, posn, w, h):
        """ Initialize rectangle at posn, with width w, height h """
        self.corner = posn
        self.width = w
        self.height = h

    def __str__(self):
        return "({0}, {1}, {2})".format(self.corner, self.width, self.height)

    def grow(self, delta_width, delta_height):
        """ Grow (or shrink) this object by the deltas """
        self.width += delta_width
        self.height += delta_height

    def move(self, dx, dy):
        """ Move this object by the deltas """
        self.corner.x += dx
        self.corner.y += dy

    def area(self):
        return self.width * self.height


r = Rectangle(Point(), 10, 5)
test(r.area(), 50)
        return result


#### Test 1 #####
#  0 1 2 3 4 5 6 7 8 9
# 0. . . . . . . . . .
# 1. . . . . . . . . .
# 2. . . . . . . . . .
# 3. . . b - - - - - +
# 4a - - | - +       |
# 5|     |   |       |
# 6|     + - - - - - +
# 7+ - - - - + . . . .
a = Rectangle(Point(0, 4), 5, 3)
b = Rectangle(Point(3, 3), 5, 3)
test(a.collision(b), True)
#### Test 2 #####
#  0 1 2 3 4 5 6 7
# 0. . . . . . . .
# 1. . . . . . . .
# 2. . b - + . . .
# 3. a |   | - + .
# 4. | + - +   + .
# 5. + - - - - + .
# 6. . . . . . . .
# 7. . . . . . . .
a = Rectangle(Point(1, 3), 4, 2)
b = Rectangle(Point(2, 2), 2, 2)
test(a.collision(b), True)
#### Test 3 #####
#  0 1 2 3 4 5 6 7
    :return: Return items that are present in either the first or the second list
    """
    result = []
    xi = 0
    yi = 0

    while True:
        if xi >= len(xs):
            result.extend(ys[yi:])
            return result

        if yi >= len(ys):
            result.extend(xs[xi:])
            return result

        if xs[xi] == ys[yi]:
            xi += 1
        elif xs[xi] <= ys[yi]:
            result.append(xs[xi])
            xi += 1
        else:
            result.append(ys[yi])
            yi += 1
    return result

test(in_both_lists([1, 2, 3, 4], [2, 5, 6, 8]), [1, 2, 3, 4, 5, 6, 8])
test(in_both_lists([2, 5, 6, 8], [1, 2, 3, 4]), [1, 2, 3, 4, 5, 6, 8])
test(in_both_lists([2, 5, 6, 8], [1, 4]), [1, 2, 4, 5, 6, 8])
test(in_both_lists([2, 5, 6, 8], []), [2, 5, 6, 8])
test(in_both_lists([], [2, 5, 6, 8]), [2, 5, 6, 8])
test(in_both_lists([], []), [])
            self.seconds -= 60
            self.minutes += 1

        while self.minutes >= 60:
            self.minutes -= 60
            self.hours += 1

    def to_seconds(self):
        """
        :return: the number of seconds represented by this instance
        """
        return self.hours * 3600 + self.minutes * 60 + self.seconds

    def after(self, time2):
        """Return True if I am strictly greather than time2"""
        return self.to_seconds() > time2.to_seconds()


def between(obj, t1, t2):
    return t1.to_seconds() <= obj.to_seconds() < t2.to_seconds()


t1 = MyTime(2, 34, 14)
t2 = MyTime(14, 32, 12)

test(between(MyTime(5, 34, 23), t1, t2), True)
test(between(MyTime(2, 34, 13), t1, t2), False)
test(between(MyTime(2, 34, 15), t1, t2), True)
test(between(MyTime(14, 32, 12), t1, t2), False)
test(between(MyTime(14, 32, 11), t1, t2), True)
        """ Create a new point at the origin """
        self.x = x
        self.y = y

    def distance_from_origin(self):
        """ Compute my distance from the origin """
        return ((self.x ** 2) + (self.y ** 2)) ** 0.5

    def __str__(self):  # All we have done is renamed the method
        return "({0}, {1})".format(self.x, self.y)

    def halfway(self, target):
        """ Return the halfway point between myself and the target """
        mx = (self.x + target.x) / 2
        my = (self.y + target.y) / 2
        return Point(mx, my)

    def distance(self, target):
        dx = target.x - self.x
        dy = target.y - self.y
        dsquared = dx * dx + dy * dy
        result = dsquared ** 0.5
        return result

    def reflect_x(self):
        ry = self.y * -1
        return Point(self.x, ry)


test(Point(3, 5).reflect_x(), (3, -5))
# 5. Write a function, recursive_min, that returns the smallest value in a nested number
# list. Assume there are no empty lists or sublists:
from unit_tester import test


def recursive_min(list):
    smallest = None
    first_time = True
    for n in list:
        if isinstance(n, type([])):
            val = recursive_min(n)
        else:
            val = n

        if first_time or val < smallest:
            smallest = val
            first_time = False
    return smallest


test(recursive_min([2, 9, [1, 13], 8, 6]), 1)
test(recursive_min([2, [[100, 1], 90], [10, 13], 8, 6]), 1)
test(recursive_min([2, [[13, -7], 90], [1, 100], 8, 6]), -7)
test(recursive_min([[[-13, 7], 90], 2, [1, 100], 8, 6]), -13)
# a. Return only those items that are present in both lists.
from unit_tester import test


def both_inlists(xs, ys):
    """ a. Return only those items that are present in both lists. """
    result = []
    xi = 0
    yi = 0

    while True:
        if xi >= len(xs):
            return result

        if yi >= len(ys):
            return result

        if xs[xi] == ys[yi]:  # found a match append it
            result.append(xs[xi])
            yi += 1
        elif xs[xi] < ys[yi]:  # move past this item
            xi += 1
        else:
            yi += 1


test(both_inlists([1, 2, 3, 4, 5, 12, 15, 20], [2, 5, 6, 7, 8, 9, 12]), [2, 5, 12])
test(both_inlists([1, 2, 3], [2, 5, 6, 7, 8, 9, 12]), [2])
test(both_inlists([1, 2, 3, 4, 5, 12, 15, 20], [2, 5]), [2, 5])
test(both_inlists([1, 2], []), [])
        while self.seconds >= 60:
            self.seconds -= 60
            self.minutes += 1

        while self.minutes >= 60:
            self.minutes -= 60
            self.hours += 1

    def to_seconds(self):
        """
        :return: the number of seconds represented by this instance
        """
        return self.hours * 3600 + self.minutes * 60 + self.seconds

    def after(self, time2):
        """Return True if I am strictly greater than time2"""
        return self.to_seconds() > time2.to_seconds()

    def between(self, t1, t2):
        return t1.to_seconds() <= self.to_seconds() < t2.to_seconds()


t1 = MyTime(2, 34, 14)
t2 = MyTime(14, 32, 12)

test(MyTime(5, 34, 23).between(t1, t2), True)
test(MyTime(2, 34, 13).between(t1, t2), False)
test(MyTime(2, 34, 15).between(t1, t2), True)
test(MyTime(14, 32, 12).between(t1, t2), False)
test(MyTime(14, 32, 11).between(t1, t2), True)
Ejemplo n.º 23
0
# Write a function flatten that returns a simple list containing all the values in a nested list:

from unit_tester import test


def flatten(data):
    flatlist = []
    for e in data:
        if type(e) == list:
            flatlist += (flatten(e))
        else:
            flatlist.append(e)
    return flatlist


test(flatten([2, 9, [2, 1, 13, 2], 8, [2, 6]]) == [2, 9, 2, 1, 13, 2, 8, 2, 6])
test(flatten([[9, [7, 1, 13, 2], 8], [7, 6]]) == [9, 7, 1, 13, 2, 8, 7, 6])
test(flatten([[9, [7, 1, 13, 2], 8], [2, 6]]) == [9, 7, 1, 13, 2, 8, 2, 6])
test(
    flatten([["this", ["a", ["thing"], "a"], "is"], ["a", "easy"]]) ==
    ["this", "a", "thing", "a", "is", "a", "easy"])
test(flatten([]) == [])
    def __str__(self):
        return "({0}, {1}, {2})".format(self.corner, self.width, self.height)

    def grow(self, delta_width, delta_height):
        """ Grow (or shrink) this object by the deltas """
        self.width += delta_width
        self.height += delta_height

    def move(self, dx, dy):
        """ Move this object by the deltas """
        self.corner.x += dx
        self.corner.y += dy

    def area(self):
        return self.width * self.height

    def perimeter(self):
        return (self.width * 2) + (self.height * 2)


box = Rectangle(Point(0, 0), 100, 200)
bomb = Rectangle(Point(100, 80), 5, 10)
# in my video game
print("box: ", box)
print("bomb: ", bomb)

r = Rectangle(Point(), 10, 5)
test(r.area(), 50)
test(r.perimeter(), 30)
Ejemplo n.º 25
0
    yeah = []
    for i in a:
        if i not in yeah:
            yeah.append(i)
        pass
    yeah.sort()
    return yeah

def longestword(a):
    count = 0
    for i in a:
        if len(i) > count:
            count = len(i)
    return count

unit_tester.test(cleanword("what?") == "what")
unit_tester.test(cleanword("'now!'") == "now")
unit_tester.test(cleanword("?+='w-o-r-d!,@$()'") ==  "word")

unit_tester.test(has_dashdash("distance--but"))
unit_tester.test(not has_dashdash("several"))
unit_tester.test(has_dashdash("spoke--"))
unit_tester.test(has_dashdash("distance--but"))
unit_tester.test(not has_dashdash("-yo-yo-"))

unit_tester.test(extract_words("Now is the time!  'Now', is the time? Yes, now.") ==
      ['now','is','the','time','now','is','the','time','yes','now'])
unit_tester.test(extract_words("she tried to curtsey as she spoke--fancy") ==
      ['she','tried','to','curtsey','as','she','spoke','fancy'])

unit_tester.test(wordcount("now", ["now","is","time","is","now","is","is"]) == 2)
Ejemplo n.º 26
0
    """ merge sorted lists xs and ys. Return a sorted result """
    result = []
    xi = 0
    yi = 0

    while True:
        if xi >= len(xs):
            result.extend(ys[yi:])
            return result

        if yi >= len(ys):
            result.extend(xs[xi:])
            return result

        if xs[xi] <= ys[yi]:
            result.append(xs[xi])
            xi += 1
        else:
            result.append(ys[yi])
            yi += 1

xs = [1,3,5,7,9,11,13,15,17,19]
ys = [4,8,12,16,20,24]
zs = xs+ys
zs.sort()
test(merge(xs, []) == xs)
test(merge([], ys) == ys)
test(merge([], []) == [])
test(merge(xs, ys) == zs)
test(merge([1,2,3], [3,4,5]) == [1,2,3,3,4,5])
test(merge(["a", "big", "cat"], ["big", "bite", "dog"]) == ["a", "big", "big", "bite", "cat", "dog"])
    yi = 0

    while True:
        if xi >= len(xs):
            return result

        if yi >= len(ys):           # we have come to the end of the second list.
            result.extend(xs[xi:])  # dump the rest of the array, since we know it's not in the second list.
            return result

        if xs[xi] not in ys:        # its not in the second list
            result.append(xs[xi])
        else:
            yi += 1

        xi += 1

def insecondlist(xs, ys):
    """
    c. Return only those items that are present in the second list, but not in the first.
    :param xs: First List
    :param ys: Second List
    :return: Return only those items that are present in the second list, but not in the first.
    """
    return infirstlist(ys, xs)     # Cause really, I am lazy :P


test(insecondlist([1, 2, 3, 4, 5, 12, 15, 20], [2, 5, 6, 7, 8, 9, 12]), [6, 7, 8, 9])
test(insecondlist([1, 2, 3], [2, 5, 6, 7, 8, 9, 12]), [5, 6, 7, 8, 9, 12])
test(insecondlist([1, 2, 3, 4, 5, 12, 15, 20], [2, 5]), [])
test(infirstlist([], []), [])
Ejemplo n.º 28
0
#
#
# xs = make_random_ints_no_dups(10, 1, 6)
# print(xs)

# def do_my_sum(xs):
#     sum = 0
#     for v in xs:
#         sum += v
#     return sum
#
# sz = 10000000        # Lets have 10 million elements in the list
# testdata = range(sz)
#
# t0 = time.process_time()
# my_result = do_my_sum(testdata)
# t1 = time.process_time()
# print("my_result    = {0} (time taken = {1:.4f} seconds)"
#         .format(my_result, t1-t0))
#
# t2 = time.process_time()
# their_result = sum(testdata)
# t3 = time.process_time()
# print("their_result = {0} (time taken = {1:.4f} seconds)"
#         .format(their_result, t3-t2))

s = "A string"
unit_tester.test(seqtools.remove_at(4, s) == "A sting")

cal = calendar.TextCalendar()  # Create an instance
cal.pryear(2012)
Ejemplo n.º 29
0
    return tot


def r_max(nxs):
    """
        Find the maximum in a recursive structure of lists within other lists.
        Precondition: No lists or sublists are empty.
    :param nxs: list
    :return:
    """
    largest = None
    first_time = True
    for e in nxs:
        if type(e) == type([]):
            val = r_max(e)
        else:
            val = e

        if first_time or val > largest:
            largest = val
            first_time = False
    return largest


print(r_sum([1, 2, 3, [11, 13], 8]))

test(r_max([2, 9, [1, 13], 8, 6]), 13)
test(r_max([2, [[100, 7], 90], [1, 13], 8, 6]), 100)
test(r_max([[[13, 7], 90], 2, [1, 100], 8, 6]), 100)
test(r_max(["joe", ["sam", "ben"]]), "sam")
Ejemplo n.º 30
0
        self.messages.append( (False, from_number, time_arrived, text_of_sms) )

    def message_count(self):
        return len(self.messages)

    def get_unread_indexes(self):
        indexlist = []
        for i in self.messages:
            if i[0] is False:
                indexlist.append(self.messages[i])
        return indexlist

    def get_message(self, i):
        message = self.messages[i]
        readmessage = (True, message[1], message[2], message[3])
        self.messages[i] = readmessage
        return message

    def delete(self, i):
        self.messages.remove(self.messages[i])
        return self.messages

    def clear(self):
        self.messages = []
        return self.messages


my_inbox = SMS_store()
my_inbox.add_new_arrival(12345, "12:00", "Hello World!")
test(my_inbox.message_count()==1)
print(my_inbox.get_message(0))

def between(t1, t2, s):
    t1seconds = t1.to_seconds()
    t2seconds = t2.to_seconds()
    Aseconds = s.to_seconds()
    if t1seconds <= Aseconds < t2seconds:
        return True
    return False


time1 = MyTime(1, 1, 1)
time2 = MyTime(10, 10, 10)
time3 = MyTime(5, 5, 5)
t3 = time2 > time1
print(t3)

# Ex 5

time2.increment(-120)
test((time2.minutes) == 8)
time2.increment(120)
test((time2.minutes) == 10)
time2.increment(-36610)  # All the time in seconds
test((time2.hours) == 0)
time2.increment(-36611)  # Here we are trying to substract with 1 second more.
test((time2.hours) == time2.to_seconds())

# print(between(time1, time2, time3))
# print(time3.between(time1, time2))
Ejemplo n.º 32
0

book_words = get_words_in_book("alice_in_wonderland.txt")
print("There are {0} words in the book, the first 100 are\n{1}".format(
    len(book_words), book_words[:100]))

#missing_words = find_unknown_words(bigger_vocab, book_words)

t0 = time.clock()
missing_words = find_unknown_words(bigger_vocab, book_words)
t1 = time.clock()
print("There are {0} unknown words.".format(len(missing_words)))
print("That took {0:.4f} seconds.".format(t1 - t0))

print(missing_words)
test(search_linear(friends, "Zoe") == 1)
test(search_linear(friends, "Joe") == 0)
test(search_linear(friends, "Paris") == 6)
test(search_linear(friends, "Bill") == -1)

vocab = ["apple", "boy", "dog", "down", "fell", "girl", "grass", "the", "tree"]
book_words = "the apple fell from the tree to the grass".split()
test(find_unknown_words(vocab, book_words) == ["from", "to"])
test(find_unknown_words([], book_words) == book_words)
test(find_unknown_words(vocab, ["the", "boy", "fell"]) == [])

test(text_to_words("My name is Earl!") == ["my", "name", "is", "earl"])
test(
    text_to_words('"Well, I never!", said Alice.') ==
    ["well", "i", "never", "said", "alice"])
def longestword(sentence):
    """
    Finds the longest word and returns the length of that word
    :param sentence: array of words to search through
    :return: length of the largest word
    """
    lword = 0

    for word in sentence:
        if len(word) > lword:
            lword = len(word)

    return lword

test(cleanword("what?"),  "what")
test(cleanword("'now!'"), "now")
test(cleanword("?+='w-o-r-d!,@$()'"),  "word")

test(has_dashdash("distance--but"), True)
test(has_dashdash("several"), False)
test(has_dashdash("spoke--"), True)
test(has_dashdash("distance--but"), True)
test(has_dashdash("-yo-yo-"), False)

test(extract_words("Now is the time!  'Now', is the time? Yes, now."),
     ['now','is','the','time','now','is','the','time','yes','now'])
test(extract_words("she tried to curtsy as she spoke--fancy"),
     ['she','tried','to','curtsy','as','she','spoke','fancy'])

test(wordcount("now", ["now","is","time","is","now","is","is"]), 2)
    yi = 0

    while True:
        if xi >= len(xs):
            result.extend(ys[yi:])
            return result

        if yi >= len(ys):
            result.extend(xs[xi:])
            return result

        if xs[xi] == ys[yi]:
            xi += 1
            yi += 1
        elif xs[xi] < ys[yi]:
            result.append(xs[xi])
            xi += 1
        else:
            yi += 1






test(items_present_in_both(xs, ys) == bs)
test(items_present_in_both(xs, qs) == cs)
test(items_present_in_first_by_not_second_list(xs, ys) == ds)
test(items_present_in_first_by_not_second_list(xs, qs) == es)
test(bagdiff([5,7,11,11,11,12,13], [7,8,11]) == [5,11,11,12,13])
Ejemplo n.º 35
0
    for (i, v) in enumerate(xs):
        if v == target:
            return i
    return -1


def load_words_from_file(filename):
    """ Read words from filename, return list of words. """
    f = open(filename, "r")
    file_content = f.read()
    f.close()
    wds = file_content.split()
    return wds


test(text_to_words("My name is Earl") == ["my", "name", "is", "earl"])
test(
    text_to_words('"Well, I never!", said Alice.') ==
    ["well", "i", "never", "said", "alice"])

book_words = get_words_in_the_book("alice_in_wonderland.txt")
print("There are {0} words in the book, the first 100 words are\n {1}".format(
    len(book_words), book_words[:100]))

bigger_vocab = load_words_from_file("vocab.txt")
t0 = time.clock()
missing_words = find_unknown_words(bigger_vocab, book_words)
t1 = time.clock()
print("There are {0} unknown words.".format(len(missing_words)))
print("That took {0:.4f} seconds".format(t1 - t0))
#print("There are {0} missing words, which are\n {1}".format(len(missing_words), missing_words))
from unit_tester import test
from queens_functions import *

# 7|_|_|_|_|_|X|_|_|
# 6|X|_|_|_|_|_|_|_|
# 5|_|_|_|_|X|_|_|_|
# 4|_|X|_|_|_|_|_|_|
# 3|_|_|_|_|_|_|_|X|
# 2|_|_|X|_|_|_|_|_|
# 1|_|_|_|_|_|_|X|_|
# 0|_|_|_|X|_|_|_|_|
# _|0|1|2|3|4|5|6|7|
test(has_clashes([6, 4, 2, 0, 5, 7, 1, 3]), False)  # Solution from above

# 7|_|_|_|_|_|X|_|_|
# 6|_|X|_|_|_|_|_|_|
# 5|_|_|_|_|X|_|_|_|
# 4|X|_|_|_|_|_|_|_|
# 3|_|_|_|_|_|_|_|X|
# 2|_|_|X|_|_|_|_|_|
# 1|_|_|_|_|_|_|X|_|
# 0|_|_|_|X|_|_|_|_|
# _|0|1|2|3|4|5|6|7|
test(has_clashes([4, 6, 2, 0, 5, 7, 1, 3]), True)  # Swap rows of first two

# 3|_|_|_|X|
# 2|_|_|X|_|
# 1|_|X|_|_|
# 0|X|_|_|_|
# _|0|1|2|3|
test(has_clashes([0, 1, 2, 3]), True)  # Try small 4x4 board
Ejemplo n.º 37
0
    for i in range(c):  # Look at all columns to the left of c.
        if share_diagonal(i, bs[i], c, bs[c]):
            return True
    return False        # No clashes - col c has a safe placement.

def has_clashes(the_board):
    """ Determine whether we have any queens clashing on the diagonals.
        We're assuming here that the_board is a permutation of column
        numbers, so we're not explicitly checking row or column clashes.
    """
    for col in range(1, len(the_board)):
        if col_clashes(the_board, col):
            return True
    return False

test(not share_diagonal(5,2,2,0))
test(share_diagonal(5,2,3,0))
test(share_diagonal(5,2,4,3))
test(share_diagonal(5,2,4,1))

# Solutions cases that should not have any clashes
test(not col_clashes([6,4,2,0,5], 4))
test(not col_clashes([6,4,2,0,5,7,1,3], 7))

# More test cases that should mostly clash
test(col_clashes([0,1], 1))
test(col_clashes([5,6], 1))
test(col_clashes([6,5], 1))
test(col_clashes([0,6,4,3], 3))
test(col_clashes([5,0,7], 2))
test(not col_clashes([2,0,1,3], 1))
def test_suit():
    test(not share_diagonal(5, 2, 2, 0))
    test(share_diagonal(5, 2, 3, 0))
    test(share_diagonal(5, 2, 4, 3))
    test(share_diagonal(5, 2, 4, 1))

    test(not col_clashes([6, 4, 2, 0, 5], 4))
    test(not col_clashes([6, 4, 2, 0, 5, 7, 1, 3], 7))

    test(col_clashes([0, 1], 1))
    test(col_clashes([5, 6], 1))
    test(col_clashes([6, 5], 1))
    test(col_clashes([0, 6, 4, 3], 3))
    test(col_clashes([5, 0, 7], 2))
    test(not col_clashes([2, 0, 1, 3], 1))
    test(col_clashes([2, 0, 1, 3], 2))

    test(not has_clashes([6, 4, 2, 0, 5, 7, 1, 3]))
    test(has_clashes([4, 6, 2, 0, 5, 7, 1, 3]))
    test(has_clashes([0, 1, 2, 3]))
    test(not has_clashes([2, 0, 3, 1]))
    test(has_clashes([3, 2, 4, 0, 6, 1, 5, 7]))

    test(mirror_x_axis([6, 4, 2, 0, 5, 7, 1, 3]) == [1, 3, 5, 7, 2, 0, 6, 4])
    test(mirror_x_axis([1, 3, 0, 2]) == [2, 0, 3, 1])

    test(mirror_y_axis([6, 4, 2, 0, 5, 7, 1, 3]) == [3, 1, 7, 5, 0, 2, 4, 6])
    test(mirror_y_axis([1, 3, 0, 2]) == [2, 0, 3, 1])

    test(rotate_90_degrees([1, 3, 0, 2]) == [1, 3, 0, 2])
    test(
        rotate_90_degrees([6, 4, 2, 0, 5, 7, 1, 3]) ==
        [4, 1, 5, 0, 6, 3, 7, 2])

    test(rotate_180_degrees([1, 3, 0, 2]) == [1, 3, 0, 2])
    test(
        rotate_180_degrees([6, 4, 2, 0, 5, 7, 1, 3]) ==
        [4, 6, 0, 2, 7, 5, 3, 1])

    test(rotate_270_degrees([1, 3, 0, 2]) == [1, 3, 0, 2])
    test(
        rotate_270_degrees([6, 4, 2, 0, 5, 7, 1, 3]) ==
        [5, 0, 4, 1, 7, 2, 6, 3])

    test(
        family_of_symmetries([0, 4, 7, 5, 2, 6, 1, 3]) ==
        [[0, 4, 7, 5, 2, 6, 1, 3], [7, 1, 3, 0, 6, 4, 2, 5],
         [4, 6, 1, 5, 2, 0, 3, 7], [2, 5, 3, 1, 7, 4, 6, 0],
         [3, 1, 6, 2, 5, 7, 4, 0], [0, 6, 4, 7, 1, 3, 5, 2],
         [7, 3, 0, 2, 5, 1, 6, 4], [5, 2, 4, 6, 0, 3, 1, 7]])
Ejemplo n.º 39
0
#    print(result)
    return result

def search_linear(xs, target):
    """ Find and return the index of target in sequence xs """
    for (i, v) in enumerate(xs):
        if v == target:
            return i
    return -1

def load_words_from_file(filename):
    """ Read words from filename, return list of words. """
    f = open(filename, "r")
    file_content = f.read()
    f.close()
    wds = file_content.split()
    return wds

test(text_to_words("My name is Earl") == ["my", "name", "is", "earl"])
test(text_to_words('"Well, I never!", said Alice.') == ["well", "i", "never", "said", "alice"])

book_words = get_words_in_the_book("alice_in_wonderland.txt")
print("There are {0} words in the book, the first 100 words are\n {1}".format(len(book_words), book_words[:100]))

bigger_vocab = load_words_from_file("vocab.txt")
t0 = time.clock()
missing_words = find_unknown_words(bigger_vocab, book_words)
t1 = time.clock()
print("There are {0} unknown words.".format(len(missing_words)))
print("That took {0:.4f} seconds".format(t1 - t0))
#print("There are {0} missing words, which are\n {1}".format(len(missing_words), missing_words))
        Original code before I compressed it:
        cx = self.corner.x
        cy = self.corner.y
        ex = float(pt.x)
        ey = float(pt.y)

        if cx <= ex < self.width:
            x = True
        else:
            x = False

        if cy <= ey < self.height:
            y = True
        else:
            y = False
        return x and y
        :param pt: Point to check
        :return: if its within the rectangle
        """
        return (self.corner.x <= float(pt.x) < self.width) \
               and (self.corner.y <= float(pt.y) < self.height)


r = Rectangle(Point(), 10, 5)
test(r.contains(Point(0, 0)), True)
test(r.contains(Point(3, 3)), True)
test(r.contains(Point(3, 7)), False)
test(r.contains(Point(3, 5)), False)
test(r.contains(Point(3, 4.99999)), True)
test(r.contains(Point(-3, -3)), False)
def count(search_obj, list):
    counter = 0

    for item in list:
        # Recursive Case - Want to first check if the item is a list
        if isinstance(item, type([])):
            counter += count(search_obj, item)
        else:  # Ok its not a list lets check if it the search object matches
            # Base Case - Does not CALL it's self
            if item == search_obj:
                counter += 1
    return counter


def stdCount(obj, list):
    counter = 0
    for item in list:
        if item == obj:
            counter += 1
    return counter


# test(stdCount(7, [9, 7, 1, 13, 2, 8, 7, 6]), 2)

test(count(2, []), 0)
test(count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]]), 4)
test(count(7, [[9, [7, 1, 13, 2], 8], [7, 6]]), 2)
test(count(15, [[9, [7, 1, 13, 2], 8], [2, 6]]), 0)
test(count(5, [[5, [5, [1, 5], 5], 5], [5, 6]]), 6)
test(count('a', [['this', ['a', ['thing', 'a'], 'a'], ' is '], ['a', 'easy']]), 4)
Ejemplo n.º 42
0
'''
12.11.7
'''

import unit_tester

def myreplace(old, new, s):
    """ Replace all occurrences of old with new in s. """
    return new.join(s.split(old))


unit_tester.test(myreplace(",", ";", "this, that, and some other thing") ==
                         "this; that; and some other thing")
unit_tester.test(myreplace(" ", "**",
                 "Words will now be separated by stars.") ==
                 "Words**will**now**be**separated**by**stars.")
        for match in lotto_matches(lotto_draw(), tickets):
            if match >= match_number:
                matches += 1
        number_of_draws += 1

    return number_of_draws


def avg_draws(n):
    draw_list = []
    average_draw_list = 0
    for i in range(20):
        draw_list.append(weeky_draw(my_tickets, n))
        average_draw_list = statistics.mean(draw_list)
        print(".")
    print("On {0} matches the number of average draws needed: {1}".format(n, average_draw_list))


my_tickets = [[7, 17, 37, 19, 23, 43],
              [7, 2, 13, 41, 31, 43],
              [2, 5, 7, 11, 13, 17],
              [13, 17, 37, 19, 23, 43]]

test(lotto_match([42, 4, 7, 11, 1, 13], [2, 5, 7, 11, 13, 17]), 3)
test(lotto_matches([42, 4, 7, 11, 1, 13], my_tickets), [1, 2, 3, 1])
test(primes_in([42, 4, 7, 11, 1, 13]), 3)
test(prime_misses(my_tickets), [3, 29, 47])

avg_draws(3)
avg_draws(4)
avg_draws(5)
Ejemplo n.º 44
0
        while self.seconds >= 60:
            self.seconds -= 60
            self.minutes += 1

        while self.minutes >= 60:
            self.minutes -= 60
            self.hours += 1

    def to_seconds(self):
        """
        :return: the number of seconds represented by this instance
        """
        return self.hours * 3600 + self.minutes * 60 + self.seconds

    def after(self, time2):
        """Return True if I am strictly greater than time2"""
        return self.to_seconds() > time2.to_seconds()

    def between(self, t1, t2):
        return t1.to_seconds() <= self.to_seconds() < t2.to_seconds()


t1 = MyTime(2, 34, 14)
t2 = MyTime(14, 32, 12)

test(MyTime(5, 34, 23).between(t1, t2), True)
test(MyTime(2, 34, 13).between(t1, t2), False)
test(MyTime(2, 34, 15).between(t1, t2), True)
test(MyTime(14, 32, 12).between(t1, t2), False)
test(MyTime(14, 32, 11).between(t1, t2), True)

class Rectangle:
    """ A class to manufacture rectangle objects """

    def __init__(self, posn, w, h):
        """ Initialize rectangle at posn, with width w, height h """
        self.corner = posn
        self.width = w
        self.height = h

    def __str__(self):
        return "({0}, {1}, {2})".format(self.corner, self.width, self.height)

    def grow(self, delta_width, delta_height):
        """ Grow (or shrink) this object by the deltas """
        self.width += delta_width
        self.height += delta_height

    def move(self, dx, dy):
        """ Move this object by the deltas """
        self.corner.x += dx
        self.corner.y += dy

    def area(self):
        return self.width * self.height


r = Rectangle(Point(), 10, 5)
test(r.area(), 50)
def infirstlist(xs, ys):
    """
    b. Return only those items that are present in the first list, but not in the second.
    :param xs: Sorted list A
    :param ys: Sorted List B
    :return: Return only those items that are present in the first list, but not in the second.
    """
    result = []
    xi = 0
    yi = 0

    while True:
        if xi >= len(xs):
            return result

        if yi >= len(ys):           # we have come to the end of the second list.
            result.extend(xs[xi:])  # dump the rest of the array, since we know it's not in the second list.
            return result

        if xs[xi] not in ys:        # its not in the second list
            result.append(xs[xi])
        else:
            yi += 1

        xi += 1

test(infirstlist([1, 2, 3, 4], [2, 4, 6, 8]), [1, 3])
test(infirstlist([1, 2, 3, 4, 5, 6, 7], [2]), [1, 3, 4, 5, 6, 7])
test(infirstlist([1, 2, 3, 4, 5, 6, 7], []), [1, 2, 3, 4, 5, 6, 7])
test(infirstlist([], []), [])
from unit_tester import test
from list_functions import *

# Test cases

test(remove_adjacent_dups([1,2,3,3,3,3,5,6,9,9]), [1,2,3,5,6,9])
test(remove_adjacent_dups([]), [])
test(remove_adjacent_dups(["a", "big", "big", "bite", "dog"]), ["a", "big", "bite", "dog"])

all_words = get_words_in_book("alice_in_wonderland.txt")
all_words.sort()
book_words = remove_adjacent_dups(all_words)
print("There are {0} words in the book. Only {1} are unique.".format(len(all_words), len(book_words)))
print("The first 100 words are\n{0}".format(book_words[:100]))
Ejemplo n.º 48
0
# fill in the body of the function below using the split and join methods of str objects. Tests should pass.

from unit_tester import test


def myreplace(old, new, s):
    """ Replace all occurrences of old with new in s. """
    s = " ".join(s.split())
    return new.join(s.split(old))


test(
    myreplace(",", ";", "this, that, and some other thing") ==
    "this; that; and some other thing")
test(
    myreplace(" ", "**", "Words will now      be  separated by stars.") ==
    "Words**will**now**be**separated**by**stars.")
    """ Point class represents and manipulates x,y coords. """

    def __init__(self, x=0, y=0):
        """ Create a new point at the origin """
        self.x = x
        self.y = y

    def distance_from_origin(self):
        """ Compute my distance from the origin """
        return ((self.x ** 2) + (self.y ** 2)) ** 0.5

    def __str__(self):  # All we have done is renamed the method
        return "({0}, {1})".format(self.x, self.y)

    def halfway(self, target):
        """ Return the halfway point between myself and the target """
        mx = (self.x + target.x) / 2
        my = (self.y + target.y) / 2
        return Point(mx, my)

    def distance(self, target):
        dx = target.x - self.x
        dy = target.y - self.y
        dsquared = dx * dx + dy * dy
        result = dsquared ** 0.5
        return result


test(Point(1, 2).distance(Point(4, 6)), 5.0)

from unit_tester import test
from queens_functions import *

# 5_|_|_|_|_|_|
# 4_|_|_|_|_|_|
# 3_|_|_|_|_|_|
# 2_|_|_|_|_|X|
# 1_|_|_|_|_|_|
# 0_|_|X|_|_|_|
# _0|1|2|3|4|5|
test(share_diagonal(5, 2, 2, 0), False)

# 5_|_|_|_|_|_|
# 4_|_|_|_|_|_|
# 3_|_|_|_|_|_|
# 2_|_|_|_|_|X|
# 1_|_|_|_|_|_|
# 0_|_|_|X|_|_|
# _0|1|2|3|4|5|
test(share_diagonal(5, 2, 3, 0), True)

# 5_|_|_|_|_|_|
# 4_|_|_|_|_|_|
# 3_|_|_|_|X|_|
# 2_|_|_|_|_|X|
# 1_|_|_|_|_|_|
# 0_|_|_|_|_|_|
# _0|1|2|3|4|5|
test(share_diagonal(5, 2, 4, 3), True)

# 5_|_|_|_|_|_|
Ejemplo n.º 51
0
from unit_tester import test


def extract(s):
    extracted_list = []
    for i in s:
        if type(i) == list or type(i) == tuple:
            extracted_list.extend(extract(i))
        else:
            extracted_list.append(i)
    return extracted_list


def count(target, nxs):
    return extract(nxs).count(target)


test(count(2, []) == 0)
test(count(2, [2, 9, [2, 1, 13, 2], 8, [2, 6]]) == 4)
test(count(7, [[9, [7, 1, 13, 2], 8], [7, 6]]) == 2)
test(count(15, [[9, [7, 1, 13, 2], 8], [2, 6]]) == 0)
test(count(5, [[5, [5, [1, 5], 5], 5], [5, 6]]) == 6)
test(count("a",
           [["this", ["a", ["thing", "a"], "a"], "is"], ["a", "easy"]]) == 4)
Ejemplo n.º 52
0
from unit_tester import test


def share_diagonal(x0, y0, x1, y1):
    """ Is (x0, y0) on a shared diagonal with (x1, y1)? """
    dy = abs(y1 - y0)        # Calc the absolute y distance
    dx = abs(x1 - x0)        # CXalc the absolute x distance
    return dx == dy          # They clash if dx == dy


test(not share_diagonal(5,2,2,0))
test(share_diagonal(5,2,3,0))
test(share_diagonal(5,2,4,3))
test(share_diagonal(5,2,4,1))


def col_clashes(bs, c):
    """ Return True if the queen at column c clashes
         with any queen to its left.
    """
    for i in range(c):     # Look at all columns to the left of c
          if share_diagonal(i, bs[i], c, bs[c]):
              return True

    return False           # No clashes - col c has a safe placement.

# Solutions cases that should not have any clashes


test(not col_clashes([6,4,2,0,5], 4))
test(not col_clashes([6,4,2,0,5,7,1,3], 7))
Ejemplo n.º 53
0
def bagdiff(xs, ys):
    """ merge sorted lists xs and ys. Return a sorted result """
    result = []
    xi = 0
    yi = 0

    while True:
        if xi >= len(xs):
            result.extend(ys[yi:])
            return result

        if yi >= len(ys):
            result.extend(xs[xi:])
            return result

        if xs[xi] < ys[yi]:
            result.append(xs[xi])
            xi += 1
        elif xs[xi] > ys[yi]:
            yi += 1
        else:
            xi += 1
            yi += 1


print(bagdiff([5, 7, 11, 11, 11, 12, 13], [7, 8, 11]))
from unit_tester import test

test(bagdiff())
Ejemplo n.º 54
0
bigger_vocab = load_words_from_file("vocab.txt")
print("There are {0} words in the vocab, starting with\n {1} ".format(
    len(bigger_vocab), bigger_vocab[:6]))

book_words = get_words_in_book("alice_in_wonderland.txt")
print("There are {0} words in the book, the first 100 are\n{1}".format(
    len(book_words), book_words[:100]))

# t0 = time.clock()
# missing_words = find_unknown_words(bigger_vocab, book_words)
# t1 = time.clock()
# print("There are {0} unknown words.".format(len(missing_words)))
# print("That took {0:.4f} seconds.".format(t1-t0))

xs = [2, 3, 5, 7, 11, 13, 17, 23, 29, 31, 37, 43, 47, 53]
test(search_binary(xs, 20) == -1)
test(search_binary(xs, 99) == -1)
test(search_binary(xs, 1) == -1)
for (i, v) in enumerate(xs):
    test(search_binary(xs, v) == i)

t0 = time.clock()
missing_words = find_unknown_words(bigger_vocab, book_words)
t1 = time.clock()
print("There are {0} unknown words.".format(len(missing_words)))
print("That took {0:.4f} seconds.".format(t1 - t0))

test(
    remove_adjacent_dups([1, 2, 3, 3, 3, 3, 5, 6, 9, 9]) == [1, 2, 3, 5, 6, 9])
test(remove_adjacent_dups([]) == [])
test(
    """ A class to manufacture rectangle objects """

    def __init__(self, posn, w, h):
        """ Initialize rectangle at posn, with width w, height h """
        self.corner = posn
        self.width = w
        self.height = h

    def __str__(self):
        return "({0}, {1}, {2})".format(self.corner, self.width, self.height)

    def grow(self, delta_width, delta_height):
        """ Grow (or shrink) this object by the deltas """
        self.width += delta_width
        self.height += delta_height

    def move(self, dx, dy):
        """ Move this object by the deltas """
        self.corner.x += dx
        self.corner.y += dy

    def area(self):
        return self.width * self.height

    def perimeter(self):
        return (self.width * 2) + (self.height * 2)


r = Rectangle(Point(), 10, 5)
test(r.perimeter(), 30)
Ejemplo n.º 56
0
import calendar
import copy

#import os, sys
#sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) #adds parent folder to our path
import unit_tester

unit_tester.test(1 == 8)
x = 27
y = copy.deepcopy(x)
y += 1
print(y, x)
Ejemplo n.º 57
0
from unit_tester import test

def find_unknown_words(vocab, wds):
    """ Return a list of words in wds that do not occur in vocab """
    result = []
    for w in wds:
        if (search_linear(vocab, w) < 0):
            result.append(w)
#    print(result)
    return result

def search_linear(xs, target):
    """ Find and return the index of target in sequence xs """
    for (i, v) in enumerate(xs):
        if v == target:
            return i
    return -1

vocab = ["apple", "boy", "dog", "down", "fell", "girl", "grass", "the", "tree"]
#used split to create our list of words - it is easier than typing out the list, and very convenient if you want to input a sentence into the program and turn it into a list of words.
book_words = "the apple fell from the tree to the grass".split()

test(find_unknown_words(vocab, book_words) == ["from", "to"])
test(find_unknown_words([], book_words) == book_words)
test(find_unknown_words(vocab, ["the", "boy", "fell"]) == [])