def test___init__(self): ut.test(isinstance(ArgumentError('function', 'parameter', tuple), ArgumentError)) argumenterror1 = ArgumentError('test', 'expression', bool) ut.test(argumenterror1.function_name == 'test') ut.test(argumenterror1.parameter_name == 'expression') ut.test(argumenterror1.acceptable_types == bool) ut.test(argumenterror1.error_message == ('test requires bool for ' 'expression.'))
elif rec1.contains(Point(right_x, bottom_y)): return True else: return False def same_coordinates(p1, p2): return (p1.x == p2.x) and (p1.y == p2.y) box = Rectangle(Point(0, 0), 100, 200) bomb = Rectangle(Point(100, 80), 5, 10) print("box: ", box) print("bomb: ", bomb) r = Rectangle(Point(0, 0), 10, 5) test(r.area(), 50) test(r.perimeter(), 30) test((r.width == 10 and r.height == 5), True) r.flip() test((r.width == 5 and r.height == 10), True) r = Rectangle(Point(0, 0), 10, 5) test(r.contains(Point(0, 0)), True) test(r.contains(Point(3, 3)), True) test(not r.contains(Point(3, 7)), True) test(not r.contains(Point(3, 5)), True) test(r.contains(Point(3, 4.999999)), True) test(not r.contains(Point(-3, -3)), True) # small box inside large box rec1 = Rectangle(Point(1, 1), 4, 3) rec2 = Rectangle(Point(3, 2), 1, 1)
from unit_testing import test def myreplace(old, new, s): """ Replace all occurences of old with new in s. """ s = s.split() s = " ".join(s) 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.")
""" For given solution returns family of symmetries for that solution """ new_board = board[:] solutions_family = [] solutions_family.append(new_board) solutions_family.append(rotate_left_90(new_board)) solutions_family.append(rotate_left_180(new_board)) solutions_family.append(rotate_left_270(new_board)) solutions_family.append(mirror_y(new_board)) solutions_family.append(mirror_y(rotate_left_270(new_board))) solutions_family.append(mirror_x(new_board)) solutions_family.append(mirror_y(rotate_left_90(new_board))) return solutions_family test(not share_diagonal(5, 2, 2, 0), True) test(share_diagonal(5, 2, 3, 0), True) test(share_diagonal(5, 2, 4, 3), True) test(share_diagonal(5, 2, 4, 1), True) # Solutions cases that should not have any clashes test(not col_clashes([6, 4, 2, 0, 5], 4), True) test(not col_clashes([6, 4, 2, 0, 5, 7, 1, 3], 7), True) # More test cases that should mostly clash test(col_clashes([0, 1], 1), True) test(col_clashes([5, 6], 1), True) test(col_clashes([6, 5], 1), True) test(col_clashes([0, 6, 4, 3], 3), True) test(col_clashes([5, 0, 7], 2), True) test(not col_clashes([2, 0, 1, 3], 1), True)
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 100 are\n{1}".format( len(book_words), book_words[:100])) friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"] ##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(search_linear(friends, "Zoe"), 1) test(search_linear(friends, "Joe"), 0) test(search_linear(friends, "Paris"), 6) test(search_linear(friends, "Bill"), -1) 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"]) ##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]
def solution(digits): """Return the largest 5 digit number in a string of digits :type digits: str """ # check the largest possible number starting from all numbers beginning at 9 largest = 0 check_num = 9 ix = 0 while check_num > 0: while ix != -1: ix = digits.find(str(check_num), ix) if ix != -1: sub = int(digits[ix:ix+5]) # decrementing function for inner loop ix += 1 if sub > largest: largest = sub # here we have to check if early termination is possible else: if largest > 0 and len(str(largest)) == 5: return largest # decrementing function for main loop check_num = check_num - 1 if largest > 0 and len(str(largest)) == 5: return largest test(solution('1234567898765'), 98765)
from unit_testing import test def recursive_min(nested_list): """ Returns the smallest value in a nested list """ minimum = None first_run = True for item in nested_list: if type(item) == type([]): val = recursive_min(item) else: val = item if first_run or val < minimum: minimum = val first_run = False return minimum 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)
from unit_testing import test def longest_palindrome(s): """ Find longest possible substring that is a palindrome """ """ have to check from first index to last and reversing after increasing the index """ """ then increase the first index and check till end again """ ix1 = 0 ix2 = 1 substring = "" while True: sub = s[ix1:ix2] if sub == sub[::-1]: if len(sub) > len(substring): substring = sub if ix2 < (len(s)): ix2 += 1 continue else: if ix1 < (len(s) - 2): ix1 += 1 ix2 = ix1 + 1 continue return len(substring) test(longest_palindrome("baablkj12345432133d"), 9)
def test_check_output_type(): ut.test(check_output_type(5, int) == None) ut.test(check_output_type('', str) == None) ut.test(check_output_type('', (list, str, int)) == None) errors = 0 try: ut.test(check_output_type('', int) == None) except OutputError: errors += 1 try: ut.test(check_output_type('', list) == None) except OutputError: errors += 1 try: ut.test(check_output_type(8.7, (list, str, tuple)) == None) except OutputError: errors += 1 ut.test(errors == 3)
def test_check_arg_type(): ut.test(check_arg_type(1, 'num', (int, float)) == None) ut.test(check_arg_type('', 'string', str) == None) ut.test(check_arg_type([], 'data', (str, int, list, tuple)) == None) errors = 0 try: ut.test(check_arg_type(1, 'string', str) == None) except ArgumentError: errors += 1 try: ut.test(check_arg_type('', 'num', (int, float)) == None) except ArgumentError: errors += 1 try: ut.test(check_arg_type(1.5, 'parameter', (int, str, tuple, list, bool)) == None) except ArgumentError: errors += 1 ut.test(errors == 3)
def test___init__(self): ut.test(isinstance(OutputError('hi'), OutputError)) outputerror1 = OutputError('Function should return int.') ut.test(outputerror1.error_message == 'Function should return int.')
from unit_testing import test def flatten(nested_list): """ Returns a simple list with all elements of the nested_list """ new_list = [] for item in nested_list: if type(item) == type([]): new_list.extend(flatten(item)) else: new_list.append(item) return new_list 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([]), [])
from unit_testing import test def add_fruit(inventory: dict, fruit, quantity=0): """Adds quantity of fruit to the inventory""" inventory[fruit] = inventory.get(fruit, 0) + quantity 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)
from unit_testing import test def tribonacci(signature, n): trib_dict = {number: signature[number - 1] for number in range(1, 4)} if n == 0: return [] for pos in range(4, n + 1): trib_dict[pos] = trib_dict[pos - 3] + trib_dict[pos - 2] + trib_dict[pos - 1] return [trib_dict[key] for key in range(1, n + 1)] test(tribonacci([1, 1, 1], 10), [1, 1, 1, 3, 5, 9, 17, 31, 57, 105])
""" def auto_draw(tries, correct_picks): """ Repeatedly makes a new draw and compares to my_tickets Return average num_of_draws when my_tickets has 3 correct picks Will try 20 times and calculate the average """ sum_num_of_draws = 0 for i in range(1, tries + 1): draw = [] num_of_draws = 0 while max(lotto_matches(draw, my_tickets)) < correct_picks: draw = lotto_draw() num_of_draws += 1 if num_of_draws % 20 == 0: print(".", end="") if num_of_draws % 1000 == 0: print("1000 draws checked") sum_num_of_draws += num_of_draws return (sum_num_of_draws / tries) print(lotto_draw()) 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]) print(prime_misses(my_tickets)) print(auto_draw(20, 3))
from unit_testing import test def count(target, nested_list): """ Return number of occurences of target in nested_list """ occurences = 0 for item in nested_list: if type(item) == type([]): occurences += count(target, item) else: if item == target: occurences += 1 return occurences 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)
def longestword(word_list): """ Returns the lenght of a longest word in the word_list. """ longest = 0 for word in word_list: if len(word) > longest: longest = len(word) return longest 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.") test(cleanword("what?"), "what") test(cleanword("'now!'"), "now") test(cleanword("?+='w-o-r-d!,@$()'"), "word") test(has_dashdash("distance--but"), True) test(not has_dashdash("several"), True) test(has_dashdash("spoke--"), True) test(has_dashdash("distance--but"), True) test(not has_dashdash("-yo-yo-"), True) test(extract_words("Now is the time! 'Now', is the time? Yes, now."), ['now', 'is', 'the', 'time', 'now', 'is', 'the', 'time', 'yes', 'now'])
book_words = get_words_in_book("alice_in_wonderland.txt") print("There are {0} words in the book, the 100 are\n{1}".format(len(book_words), book_words[:100])) friends = ["Joe", "Zoe", "Brad", "Angelina", "Zuki", "Thandi", "Paris"] ##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(search_linear(friends, "Zoe"), 1) test(search_linear(friends, "Joe"), 0) test(search_linear(friends, "Paris"), 6) test(search_linear(friends, "Bill"), -1) 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"]) ##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)
also change state to has been viewed. If there is no message at postition index return None.""" SMS_store.msg_list[index] = (True, ) + SMS_store.msg_list[index][1:] return SMS_store.msg_list[index][1:] def delete(self, index): """ Deletes the message at index """ del (SMS_store.msg_list[index]) SMS_store.msg_count -= 1 def clear(self): """ Deletes all messages from the inbox """ SMS_store.msg_list = [] SMS_store.msg_count = 0 my_inbox = SMS_store() time = datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S") my_inbox.add_new_arrival("00447403344912", time, "test sms message") test(my_inbox.message_count(), 1) my_inbox.add_new_arrival("00481234567865", time, "message from Poland") test(my_inbox.message_count(), 2) my_inbox.add_new_arrival("+4434563342344", time, "wiadomosc dnia") test(my_inbox.message_count(), 3) test(my_inbox.get_unread_indexes(), [0, 1, 2]) test(my_inbox.get_message(0), ("00447403344912", time, "test sms message")) test(my_inbox.get_unread_indexes(), [1, 2]) test(my_inbox.delete(0), )
def is_opposite(item1, item2): if (item1 == "NORTH" and item2 == "SOUTH"): return True elif (item1 == "SOUTH" and item2 == "NORTH"): return True elif (item1 == "WEST" and item2 == "EAST"): return True elif (item1 == "EAST" and item2 == "WEST"): return True else: return False first_element = None second_element = None ix = 0 while len(arr) > 1: if ix > len(arr) - 2: break first_element = arr[ix] second_element = arr[ix + 1] if is_opposite(first_element, second_element): arr = arr[0:ix] + arr[ix + 2:] ix = 0 else: ix += 1 return arr test(dirReduc(["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]), ["WEST"])
from unit_testing import test def r_max(nxs): """Find the maximum in a recursive structure of lists within other lists. Precondition: no lists or sublists are empty.""" 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 test(r_max([2, 9, [1, 13], 8, 6]), 13)