Beispiel #1
0
##   check_upper('A') => True
##   check_upper('after') => False
##   check_upper('After') => True


def check_upper(s):
    if s == '':
        return False
    elif s[0] in upper:
        return True
    else:
        return check_upper(s[1:])


## Tests:
check.expect("t1", check_upper(''), False)
check.expect("t2", check_upper('A'), True)
check.expect('t3', check_upper('after'), False)
check.expect('t4', check_upper('Af ter'), True)
check.expect('t5', check_upper('CHEN'), True)

## helper function to check lower-cased words
## check_lower(s) returns True if there is at least one lower-cased letter
##   in the string s; returns False otherwise
## check_lower: Str -> Bool
## Examples:
##   check_lower('') => False
##   check_lower('A') => False
##   check_lower('a') => True
##   check_lower('AFTER') => False
##   check_lower('After') => True
        print('The password ("' + password + '") failed a basic test')
        return False
    if len(password) < 5:
        strength_points = strength_points - 10
    if len(password) > 8:
        strength_points = strength_points + 10
    if password.lower() != password and has_digit(password):
        strength_points = strength_points + 10
    specials = num_of_sp(password, "")
    if specials > 0:
        strength_points = strength_points + (20 + (5 * (specials - 1)))
    return strength_points

# Q1 Test 1: Empty string
check.set_screen('The password ("") failed a basic test')
check.expect("T1", password_strength(""), False)

# Q1 Test 2: lower case password
check.set_screen('The password ("PaSSword") failed a basic test')
check.expect("T2", password_strength("PaSSword"), False)

# Q1 Test 3: only lower case
check.set_screen('The password ("newpassword") failed a basic test')
check.expect("T3", password_strength("newpassword"), False)

# Q1 Test 4: only upper case
check.set_screen('The password ("ASDF") failed a basic test')
check.expect("T4", password_strength("ASDF"), False)

# Q1 Test 5: all digits
check.set_screen('The password ("9876") failed a basic test')
Beispiel #3
0
#           smallest_power(4) => -26
#           smallest_power(124223) => -3
#
# Note: Your solution on your computer may be different, but we will be
# running everyone's solutions on the same system and checking the answers
# for that system.
def smallest_power(b):
    p = -1
    done = False  # to signal when the right exponent p is found
    while done == False:
        if (1 + math.pow(b, p)) == 1.0:  # checking for equality with float 1
            done = True
            return p + 1  # if (1+b^p) == 1.0 => p +1 is the required p
        p -= 1


## Testing:
print "Testing smallest_power"

# Test 1: Smallest int >1 = 2
check.expect("Question 1 Test 1", smallest_power(2), -52)

# Test 2: Large integer >1 = 124223
check.expect("Question 1 Test 2", smallest_power(124223), -3)

# Test 3: General case
check.expect("Question 1 Test 3", smallest_power(4), -26)


# check.withinconsumesfourvalues:astring(alabelofthetest,suchasÒQuestion1 Test 6Ó), a value to test, an expected value, and a tolerance.
Beispiel #4
0
# card('diamonds',6)]

def go_fish(hand, v):
    count = 0
    for card in hand:
        if card.value == v:
            hand.remove(card)
            count = count + 1
    if count == 0:
        print output_string

# Tests
## base case: given list is an empty list
L = []
check.set_screen(output_string)
check.expect('q2t1a', go_fish(L,2), None)
check.expect('q2t1b', L, L)
## case when there is no card with the given integer
L = [card('spades',8),card('hearts',5),card('diamonds',6),card('clubs',5)]
check.set_screen(output_string)
check.expect('q2t2a', go_fish(L,9), None)
check.expect('q2t2b', L, L)
## case when the given list is mutated
L = [card('spades',8),card('hearts',5),card('diamonds',6),card('clubs',5)]
new_list = [card('spades',8), card('diamonds',6)]
check.expect('q2t3a', go_fish(L,5), None)
check.expect('q2t3b', L, new_list)
## a longer list
## mutation
L = [card('hearts',6), card('spades',10), card('spades',2), card('clubs',8), \
     card('hearts',2), card('diamonds',3), card('clubs', 2), card('diamonds',2),\
Beispiel #5
0
        for i in temp_list:
            temp_list[i] = list(options[i])
        for letter in letters:
            for i in range(0,len(options)):
                if (letter in options[i] and letter in temp_list[i]):
                    temp_list[i].remove(letter)
                    loa[i] = letter + loa[i]
        for word in options:
            if len(loa[options.index(word)]) == len(word):
                word_list.append(word)
        return word_list
## Testing:
print "Testing find_words"

# Test 1: Empty string, empty list
check.expect("Question 4 Test 1", find_words("", []), [])

# Test 2: Empty string, options
check.expect("Question 4 Test 2", find_words("", ['goat','eggs','milk']), [])

# Test 3: Letters, empty list
check.expect("Question 4 Test 3", find_words("fgrwr", []), [])


# Test 4: Duplicate Letters, options
check.expect("Question 4 Test 4",\
             find_words("aabbcdd",['aabc','abcd','bbddc','dddd']), \
             ['aabc','abcd','bbddc'])

# Test 5: Letters, 3 letter words
check.expect("Question 4 Test 5", find_words("cat", ['act','cat','tac','tca'])\
Beispiel #6
0
# ["cust2", "cambridge", 5192345647), it produces None but all_records 
# becomes [["cust1", "kitchener", 5192345647], ["cust2", "cambridge", 5192345647]]

def add_record(all_records,cust_record):
	phone_record = map(lambda list: list[2], all_records)
	new_phone = cust_record[2]
	check_new = filter(lambda ph_num: ph_num == new_phone, phone_record)
	if check_new == []:
		return all_records.append(cust_record)
	else:
		print phone_str % new_phone

# Tests
## adding a phone number 
all_records = [["cust1","kitchener",5192345647]] 
check.expect("Q4t1", add_record(all_records,["cust2","cambridge",5193243456]), None)
check.set_screen([["cust1", "kitchener", 5192345647], \
                  ["cust2", "cambridge", 5192345647]])
## phone number already exists
all_records = [["cust1","kitchener",5192345647]]
check.expect("Q4t2", add_record(all_records, \
                                ["cust2","cambridge",5192345647]), None)
check.set_screen("Phone number 5192345647 is already in the exisiting customer records")

##**************************************************************************

# delete_record: customer_list phone -> None

# Purpose: produces none by consuming a listof customer_record (all_records)
# and a 10-digit phone number(phone)
Beispiel #7
0
# value of (total_cents)

# Effect: no effect since there is no mutation

# Examples: coin_change([1],20) => [[1,20]]
# coin_change([25,5,1],35) => [[25,1],[5,2]]
# coin_change([10,5,1],25) => [[10,2],[5,1]]
# coin_change([90,85,20,1],108) => [[90,1],[1,18]]

def coin_change(avail_change, total_cents):
        coin = avail_change[0]
        number = total_cents/coin
        if total_cents % coin == 0:
                return [[coin, number]]
        elif coin > total_cents:
                return coin_change(avail_change[1:], total_cents)
        else:
                left = total_cents - coin*number
                return [[coin,number]] + coin_change(avail_change[1:], left)

# Tests
## base case
check.expect("q3t1", coin_change([1],20), [[1,20]])
## case that only first coin value is used
check.expect("q3t2", coin_change([25,5,1],100), [[25,4]])
check.expect("q3t3", coin_change([50,25,10,5,1],200), [[50,4]])
## case that all coin values in the list are used
check.expect("q3t4", coin_change([50,5,1],108), [[50,2],[5,1],[1,3]])
## that some of the coin values are used
check.expect("q3t5", coin_change([10,5,1],25), [[10,2],[5,1]])
check.expect("q3t6", coin_change([90,85,20,1],108), [[90,1],[1,18]])
    """ Given an array of int, arr, find the subset of elements, s, 
    such that the sum of elements in s is maximed """

    if arr == []:
        return ([], 0)

    max_sum = arr[0]
    max_subsetsum_array = arr[0:1]

    for i in range(1, len(arr)):
        if ((arr[i] + max_sum) > max_sum and (arr[i] + max_sum) > arr[i]):
            max_sum = arr[i] + max_sum
            max_subsetsum_array.append(arr[i])

        if (arr[i] > max_sum and arr[i] > (max_sum + arr[i])):
            max_sum = arr[i]
            max_subsetsum_array = [arr[i]]

    return (max_subsetsum_array, max_sum)


# Tests
print(check.expect(([], 0), max_subsetsum_array([])))
print(check.expect(([2], 2), max_subsetsum_array([2])))
print(check.expect(([-1], -1), max_subsetsum_array([-1])))
print(check.expect(([1, 3, 5], 9), max_subsetsum_array([-2, 1, 0, 3, 5])))
print(check.expect(([1, 2, 3, 4, 5], 15), max_subsetsum_array([1, 2, 3, 4,
                                                               5])))
print(check.expect(([0], 0), max_subsetsum_array([-1, -2, -3, 0, -4])))
print(check.expect(([-1], -1), max_subsetsum_array([-5, -2, -3, -10, -1])))
print(check.expect(([1, 3, 5], 9), max_subsetsum_array([-2, 1, 3, -4, 5])))
# n is a natural number greater than 0
# Examples:
# make_poem("How many Lowes would Rob Lowe rob if Rob Lowe could rob Lowes", 3) 
#           will print:
#  How many Lowes
#  would Rob Lowe
#  rob if Rob
#  Lowe could rob
#  Lowes
def make_poem(s,n):
    k = space_position(s, n)
    if k >= len(s):
        print(s)
    else:
        print(s[0:k])
        make_poem(s[k+1:], n)

# Test Example, n = 3
check.set_screen("How many Lowes\nwould Rob Lowe\nrob if Rob\nLowe could rob\nLowes")
check.expect("Q4T1", make_poem("How many Lowes would Rob Lowe rob if Rob Lowe could rob Lowes", 3), 
             None)

# Test when n = 1
check.set_screen("abc\ndef\nhijk\nlmno\npQ")
check.expect("Q4T2", make_poem("abc def hijk lmno pQ",1), None)

# Test When n = 4
check.set_screen("my job is very\nawaresome and my dad\nis superman")
check.expect("Q4T3", make_poem("my job is very awaresome and my dad is superman", 4), None)

Beispiel #10
0
import check

# bin2nat(bistr) returns the decimal value of the binary number in the/
# string
# bin2nat: Str -> Nat
# Example: bin2nat("101") => 5


def bin2nat(bistr):
    if len(bistr) == 0:
        return 0
    else:
        return int(bistr[0:1]) * (2**(len(bistr) - 1)) + bin2nat(bistr[1:])


# Tests:
check.expect("Q2T1", bin2nat("1111"), 15)
check.expect("Q2T2", bin2nat("111"), 7)
check.expect("Q2T3", bin2nat("0"), 0)
check.expect("Q2T4", bin2nat("1"), 1)
check.expect("Q2T5", bin2nat("10"), 2)
check.expect("Q2T6", bin2nat("100"), 4)
Beispiel #11
0
    Examples: 
    is_prime(5,2) => True
    is_prime(6,2) => False
    '''
    if a == 1:
        return False
    elif a == b:
        return True
    elif a % b != 0:
        return is_prime(a, b - 1)
    else:
        return False


## Test
check.expect("Q4T1", is_prime(9, 2), False)
check.expect("Q4T2", is_prime(1, 2), False)
check.expect("Q4T3", is_prime(2, 2), True)


def is_prime_divisor(c, d):
    '''
    Returns the number of prime divisors from a range of 2 to d. 
    
    is_prime_divisor: Int Int => Nat
    
    requires:
    * c and d are both positive integers
    * to be a divisor then c%d == 0
    
    Examples: 
Beispiel #12
0
        j += 1
        index_L += 1
    return L

# merge3(L1,L2,L3) consumes three lists of natural numbers, L1, L2 & L3, and 
#   returns a new list contain L1 L2 and L3 in ascending order
# merge3: (listof Nat) (listof Nat) (listof Nat) -> (listof Nat)
# Examples:
# merge3([1, 5], [2, 7], [3, 4, 9]) =>[1, 2, 3, 4, 5, 7, 9]

def merge3(L1, L2, L3):
    return helper_merge3(helper_merge3(L1,L2),L3)

# Test:
# Test1: Examples Test
check.expect('PartaT1', merge3([1,5], [2,7], [3,4,9]), [1,2,3,4,5,7,9])
# Test2: Non empty order 
check.expect('PartaT2', merge3([1,7],[4,5,6], [8,9,16]),[1,4,5,6,7,8,9,16])
check.expect('PartaT3', merge3([1,9],[2,2,2], [9,9,9]),[1,2,2,2,9,9,9,9])
check.expect('PartaT4', merge3([2,13],[2,12],[2,11]),[2,2,2,11,12,13])
check.expect('PartaT5', merge3([3,10], [2,9], [1, 6]), [1,2,3,6,9,10])
# Test3: empty order
check.expect('PartaT6', merge3([1,7],[4,5,6],[]),[1,4,5,6,7])
check.expect('PartaT7', merge3([], [],[1,2]),[1,2])
check.expect('PartaT8', merge3([],[], []),[])

# Question 4 - part b
# mergesort3(L): consumes a list of natural number, L, and returns a list of
#   natural number in ascending order
# mergesort3: (listof Nat) -> (listof Nat)
# Examples:
Beispiel #13
0
    leader = max(c1, c2, c3)
    second = min(m12, m13, m23)
    leader_max = leader * 2
    second_max = second * 2
    if leader == second:
        return leader
    if second_max == leader:
        return 1
    if second == 0:
        return 0
    if second < leader:
        return leader_max + 1 - second_max


## Test1: leader = second
check.expect("Q3T1", final_jeopardy(500, 500, 10), 500)
check.expect("Q3T2", final_jeopardy(10, 200, 200), 200)
check.expect("Q3T3", final_jeopardy(200, 10, 200), 200)
## Test2: leader > second
check.expect("Q3T4", final_jeopardy(5000, 7500, 10000), 5001)
check.expect("Q3T5", final_jeopardy(10000, 7500, 5000), 5001)
check.expect("Q3T6", final_jeopardy(7500, 5000, 10000), 5001)
check.expect("Q3T7", final_jeopardy(7500, 0, 10000), 5001)
## Test3: second = 0
check.expect("Q3T8", final_jeopardy(0, 0, 10000), 0)
check.expect("Q3T9", final_jeopardy(0, 10000, 0), 0)
## Test4: second max bet = leader
check.expect("Q3T10", final_jeopardy(5000, 0, 10000), 1)
check.expect("Q3T11", final_jeopardy(0, 10000, 5000), 1)

print(final_jeopardy(100, 889, 890))
Beispiel #14
0
    '''
    s = s.lower()
    if len(s) == 0:
        return "" 
    elif not s[0].isalnum():
        return "" + removal(s[1:])
    elif s[0].isalpha():
        return s[0] + removal(s[1:])
    elif s[0].isdigit():
        return "" + removal(s[1:])
    else:
        return removal(s[1:])

## Upper and Lower Char
check.set_print_exact("mom")
check.expect("Q2T1:", print(removal("moM")), None)

## Not palindrome
check.set_print_exact("computers")
check.expect("Q2T2:", print(removal("computers")), None)

def reversal(s):
    '''
    Consumes a string and returns the string in reverse 
    
    reversal: Str -> Str
    
    Requires:
    * ignores non alphanumeric characters
    * reverses both numbers and alphabetic characters
    
    elif W[0] == '':
        return append_final_number(W[1:], group_names[1:], Z)
    else:
        return append_final_number(W[1:], group_names[1:], Z + \
                                   [W[0] + group_names[0]])


def spell_number(n, group_names):
    if n == 0:
        return "zero"
    else:
        return append_final_number(three_word_list(three_num_list \
                    (three_size_number(n,group_names),[]),[]),group_names,[])


check.expect("ex1", spell_number(0, [""]), "zero")

check.expect("ex2", spell_number(42, [""]), "forty  two")

check.expect("ex3", spell_number(900, [""]), "nine  hundred")

check.expect("ex4", spell_number(42713, ["thousand", ""]), "forty  two \
thousand  seven  hundred  thirteen")

check.expect("ex5", spell_number (4000000 , ["million", "thousand", "units"]), \
             "four  million")

check.expect("ex5", spell_number (8000010 , ["million", "thousand", ""]), \
             "eight  million  ten")

check.expect("ex6", spell_number (123456789 , ["billion", "million", \
# If the user input is ["40" "49" "39" "13" "10"], number_game() prints "Your 
#   original number is 10"
def number_game():
    mul_4 = int(input(step1_msg))
    my_num = mul_4/4
    subtract_ori = plus_9(mul_4)
    divide_3 = sub_ori(subtract_ori, my_num)
    subtract_3 = div_3(divide_3)
    final_num = sub_3(subtract_3)
    print(final_msg.format(final_num))
    

# original number = 10
check.set_input(["40", "49", "39", "13", "10"])
check.set_screen("Your original number is 10")
check.expect("original number = 10", number_game(), None)

# original number = 7
check.set_input(["28", "32", "37", "30", "10", "7"])
check.set_screen("Think of a number. Multiply your number by 4:"
                 "Add 9:"
                 "That is not correct"
                 "Subtract the original number:"
                 "Divide by 3:"
                 "Your original number is 7")
check.expect("original number = 7", number_game(), None)

# original number = 1
check.set_input(["4", "13", "12", "3", "4", "1"])
check.set_screen("Think of a number. Multiply your number by 4:"
                 "Add 9:"
# Q2
# bin2nat(bistr) returns a natural number representing the decimal value of 
#    bistr
# bin2nat: Str -> Nat
# Requires:
# Bistr is a non-empty string only contain "0" and "1"
# Examples:
# bin2nat("101") => 5
# bin2nat("1111") => 15

def bin2nat(bistr):
    mul_times = len(bistr) -1
    if mul_times == -1:
        return 0
    else:
        num = int(bistr[0:1])
    return num*(2**mul_times) + bin2nat(bistr[1:])

# Test1: all 0
check.expect("Q2Test1", bin2nat("000000"), 0)
# Test2: all 1
check.expect("Q2Test2", bin2nat("1"), 1)
check.expect("Q2Test3", bin2nat("11"), 3)
check.expect("Q2Test4", bin2nat("111"), 7)
check.expect("Q2Test5", bin2nat("1111"), 15)
# Test3: contain 1 and 0
check.expect("Q2Test6", bin2nat("101"), 5)
check.expect("Q2Test7", bin2nat("1011"), 11)
check.expect("Q2Test8", bin2nat("1010101"), 85)
# requires: grid and board have the same dimensions and are consistent
#           0 <= row < height of board
#           0 <= col < width  of board
# examples:
# count_mines(grid4x4,0,1) => 1
# count_mines(grid4x4,3,3) => 3
# count_mines(grid4x4,3,0) => 0
def count_mines(grid, row, col):
    if grid[row][col]:
        return 0
    else:
        return count_mines_no(grid, row, col)


# Test1 for helper function: No Mine surrounded
check.expect('Q3T1H', count_mines(grid3x3, 2, 0), 0)
check.expect('Q3T2H', count_mines(grid4x4, 0, 3), 0)
# Test2 for helper funciton: one Mine surrounded
check.expect('Q3T3H', count_mines(grid3x3, 1, 0), 1)
check.expect('Q3T4H', count_mines(grid4x4, 1, 0), 1)
check.expect('Q3T5H', count_mines(grid4x4, 2, 0), 1)
# Test3 for helper function: two or more Mine surrounded
check.expect('Q3T6H', count_mines(grid3x3, 1, 1), 2)
check.expect('Q3T7H', count_mines(grid4x4, 3, 1), 3)
check.expect('Q3T8H', count_mines(grid4x4, 3, 3), 3)
# Test4 for helper function: on Mine
check.expect('Q3T9H', count_mines(grid4x4, 0, 0), 0)
check.expect('Q3T10H', count_mines(grid4x4, 2, 2), 0)


# reveal(grid,board, row, col) reveals the tile at the given row and col(umn)
Beispiel #19
0
# Examples: rc_height(0,0,0) => 0
# rc_height(1,2,1) => 2
# rc_height(2,1,3) => 1
# rc_height(3,0,2) => 18

def rc_height(rc_h,x,h):
    comp = 1- 1.0/100000
    rc = 0.057
    if h >= rc_h:
        return x
    else:
        return rc_height (rc_h,x+1, (h + rc * comp**(x-1)))

# Test
check.expect("Q3HT1", rc_height(0,0,1), 0)
check.expect("Q3HT2", rc_height(1,2,1), 2)
check.expect("Q3HT3", rc_height(2,1,3), 1)
check.expect("Q3HT4", rc_height(3,0,2), 18)
check.expect("Q3HT5", rc_height(4.5,3,1.2), 61)

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

# get_numrc_a: (union int float) -> int

# Purpose: produces the number of rubik's cubes required to stack
# up to the number of given (height)

# Examples: get_numrc_a(0) => 0
# get_numrc_a(1) => 19
# get_numrc_a(11) => 194
Beispiel #20
0
    factor = [1, n]
    i = n - 1
    j = 2
    while i > j:
        if n % j == 0:
            factor.append(j)
            if j != int(n / j):
                factor.append(int(n / j))
            i = int(n / j)
        j += 1
    factor.sort()
    return factor


# Examples
check.expect('one', factors(1), [1])
check.expect('a prime', factors(3), [1, 3])
check.expect('composite with some prime factors', factors(24),
             [1, 2, 3, 4, 6, 8, 12, 24])

# Test
check.expect('composite and all factors primme', factors(10), [1, 2, 5, 10])
check.expect('square of a prime', factors(9), [1, 3, 9])
check.expect('at least 10 factors', factors(120),
             [1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120])


def new_word(s):
    '''
    Returns new string where each instance of s[2], not including s[2] itself, 
    is changed with a '#' symbol
Beispiel #21
0
# and odd value from the given list (hand)

# Effect: no effect since there is no mutation

# Examples: red_odd([]) => []
# red_odd([card1,card4]) => []
# red_odd([card1,card2,card3,card4]) => [card]

def red_odd(hand):
    new_list = filter(lambda c: c.value % 2 == 1 and \
                      (c.suit == "diamonds" or c.suit == "hearts"), hand)
    return new_list

# Tests
## base case
check.expect('q1at1', red_odd([]), [])
## case with only one element
## neither red suit or odd value
check.expect('q1at2', red_odd([card1]), [])
## red suit but not odd value
check.expect('q1at3', red_odd([card3]), [])
## odd value but not red suit
check.expect('q1at4', red_odd([card4]), [])
## both red suit and odd value
check.expect('q1at5', red_odd([card2]), [card2])
## more complex cases
check.expect('q1at6', red_odd([card1,card4]), [])
check.expect('q1at7', red_odd([card1,card2,card3,card4]), [card2])

##--------------------------------------------------------------------
Beispiel #22
0
## a
## b
## c
## done
##
## results in 'output.txt' containing the following three lines
##
## ccccccccccccccccccccccc
## bbbbbbbbbbbbbbbbbbbbbbb
## aaaaaaaaaaaaaaaaaaaaaaa
def silly():
	with open("output.txt",'w') as outFile :
		## silly_helper: None -> None
		##
		## Effects: Same as silly, but assumes the write file is already open
		def silly_helper() :
			nextLine = raw_input()
			if (nextLine == "done") :
				return
			silly_helper()
			outFile.write(nextLine*23)
			outFile.write("\n")
		silly_helper()

## Test by running function with varying number and types of input.

# Be sure to do lots more of your own testing!
check.set_input(['a','b','c','d','e',"done"])
check.set_file("output.txt","expected_output")
check.expect("Simple test",silly(),None)
Beispiel #23
0
import check

## fairy_distance: float float float float -> float
## Purpose: Consumes four floats d, the starting distance between the two
## unicorns (km), v1(km/hr), the velocity of the first unicorn, v2(km/hr), the 
## velocity of the second unicorn and f(km/hr), the velocity of the fairy and
## produces the float distance travelled by the fairy when the two unicorns
## meet and stop for tea with the fairy.
# Examples: fairy_distance(18.0, 2.5, 3.0, 15.0) => 49.090909 (approx)
#           fairy_distance(200.0,60.0,80.0,300.0) => 428.5714286 (approx)
#           fairy_distance(200.0,5.0,5.0,50.0) => 1000.0 
#           
def fairy_distance(d, v1, v2, f): 
    return(d / (v1 + v2))*f
## Testing:
print "Testing fairy_distance"

# Test 1: Example test
check.within("Question 3 Test 1", fairy_distance(18.0,2.5,3.0,15.0), \
             49.09090909090909093, 0.000001)

# Test 2: Fast fairy
check.within("Question 3 Test 2", fairy_distance(200.0,60.0,80.0,300.0)\
             , 428.5714286, 0.000001)

# Test 3: Slow unicorns
check.expect("Question 3 Test 3", fairy_distance(200.0,5.0,5.0,50.0),1000.0)

# Test 4: Small distance, slow fairy
check.within("Question 3 Test 4", fairy_distance(5.0,30.0,30.0,1.0)\
             , 0.083333333, 0.000001)
Beispiel #24
0
import check
def two_sum(array, num):
    if len(array) < 2:
        return False
    else:
        result = num - array[0]
        if result in array[1:]:
            return True
        else:
            return two_sum(array[1:], num)

s = [2, 5, 3, 1, 0, -6, -7, 9, 4]
p = [3]
check.expect("Test 1", two_sum(s, 5), True)
check.expect("Test 2", two_sum(p, 5), False)
check.expect("Test 3", two_sum(s, 0), False)
check.expect("Test 4", two_sum(s, 43), False)
check.expect("Test 5", two_sum(s, 13), True)
                print(" ", end = "")
            elif (c + r) % 2 != 0:
                print("#", end = "")
            if c == cols - 1:
                print("|")
        if r == rows - 1:
            for c in range(cols):
                if c == 0:
                    print("+", end = "")
                print("-", end = "")
                if c == cols - 1:
                    print("+")
                    
# Q2 Test 1: small even board - 2x2
check.set_screen("+--+\n| #|\n|# |\n+--+")
check.expect("T1", print_checkerboard(2,2), None)

# Q2 Test 2: small odd board - 3x3
check.set_screen("+---+\n| # |\n|# #|\n| # |\n+---+")
check.expect("T2", print_checkerboard(3,3), None)

# Q2 Test 3: small even/odd board - 2x3
check.set_screen("+---+\n| # |\n|# #|\n+---+")
check.expect("T3", print_checkerboard(2,3), None)

# Q2 Test 4: large even board - 10x12
check.set_screen("+------------+\n| # # # # # #|\n|# # # # # # |\n| # # # # # #|\n|# # # # # # |\n| # # # # # #|\n|# # # # # # |\n| # # # # # #|\n|# # # # # # |\n| # # # # # #|\n|# # # # # # |\n+------------+")
check.expect("T4", print_checkerboard(10,12), None)

# Q2 Test 5: large odd board - 7x7
check.set_screen("+-------+\n| # # # |\n|# # # #|\n| # # # |\n|# # # #|\n| # # # |\n|# # # #|\n| # # # |\n+-------+")
        return True
    elif  len(s) >= len(w) and s[:len(w)] == w:
        if s[len(w):] == "":
            return True
        elif s[len(w):2*len(w)] == w[::-1]:
            return is_alter(s[2*len(w):], w)
        else:
            return False
    else:
        return False

# alternating(s) checks to see if s is alternating or not and produces a boolean value
# alternating: Str -> Bool
# Examples:
# alternating("abccbaabc") => True
# alternating("dsqfgfh") => False

def alternating(s):
    new_w = find_w(s, 2)
    if new_w == False:
        return False
    elif is_alter(s, new_w):
        return True
    else:
        return False

check.expect("T1", alternating("abccbaabc"), True)
check.expect("T2", alternating("sdafghj"), False)
check.expect("T3", alternating("bobbob"), True)
check.expect("T4", alternating("abccbaabccba"), True)
check.expect("T5", alternating("abcabcabc"), False)
Beispiel #27
0
        if cmd == 'A':
            all_value = reduce(lambda x,y: x+y, D.values())
            count = len(D)
            outcome = float(all_value)/count
            print '%.2f' %outcome 
        cmd = raw_input(cmd_prompt)
    for key in sorted(D):
        value = str(D[key])
        print key, value
            
# Test
## average of the values in dictionary
D = {'mary':6,'bob':3}
check.set_input(['A'])
check.set_screen(4.50)
check.expect('q4t1a', memory(D), None)
check.expect('q4t1b', D, D)
## increse one of the value in dictionary by 1
check.set_input(['I', 'mary'])
check.expect('q4t2a', memory(D), None)
check.expect('q4t2b', D, {'mary':7,'bob':3})
## compare the two key values, G
check.set_input(['G', 'mary','bob'])
check.set_screen(True)
check.expect('q4t3a', memory(D), None)
check.expect('q4t3b', D, D)
## compare the two key values, L
check.set_input(['L', 'mary','bob'])
check.set_screen(False)
check.expect('q4t4a', memory(D), None)
check.expect('q4t4b', D, D)
        print("Enter 1 to take " + str(board[0]))
        print("Enter 2 to take " + str(board[1]))
        print("Enter 3 to take " + str(board[2]))
        print("Enter 4 to take " + str(board[3]))
        player_input = int(input(prompt))
        taken_row = board[player_input - 1]
        board[player_input - 1] = [card]
        return taken_row
    smallest_index = list_of_diff.index(min_diff)
    if len(board[smallest_index]) == full_row:
        old_row = board[smallest_index]
        board[smallest_index] = [card]
        return old_row
    else:
        board[smallest_index].append(card)
        return True
    
# Q4 Test 1 card smaller than all last elements:
check.set_screen('"Enter (row number) to take my_board[row number - 1]" for all 4 rows followed \
by "Enter choice: "')
check.set_input(["3"])
check.expect("T1", turn_6nimmt(my_board, 4), [8])
check.expect("T1{my_board}", my_board, [[67, 70], [9, 18, 19], [4], [13, 30, 50, 88, 93]])

# Q4 Test 2 card on full row
check.expect("T2", turn_6nimmt(my_board, 94), [13, 30, 50, 88, 93])
check.expect("T2{my_board}", my_board, [[67, 70], [9, 18, 19], [4], [94]])

# Q4 Test 3 card on not full row
check.expect("T3", turn_6nimmt(my_board, 20), True)
check.expect("T3{my_board}", my_board, [[67, 70], [9, 18, 19, 20], [4], [94]])
Beispiel #29
0
# Algorithm taken from en.wikipedia.org/wiki/Line-line-_intersection
# All code written by Joel Williamson

## intersection: Int Int Int Int  Int Int Int Int -> (union "parallel" (listof Int Int Int Int))
##
## Purpose: Treating the input as 4 pairs of integers, each representing the
##	endpoint of a line, returns the intersection of the two lines, or
##	"parallel" if they are parallel
##
## Effects:
##
## Example: intersection(-15,15,15,-15,-10,-10,10,10) => [0,1,0,1]
def intersection(x1, y1, x2, y2, x3, y3, x4, y4):
	x_numerator = ((x1*y2-y1*x2)*(x3-x4) - (x1-x2)*(x3*y4-y3*x4))
	denominator = (x1-x2)*(y3-y4)-(y1-y2)*(x3-x4)
	if (denominator == 0) :
		return "parallel"
	x_gcd = gcd(x_numerator,denominator)

	y_numerator = (x1*y2-y1*x2)*(y3-y4)-(y1-y2)*(x3*y4-y3*x4)
	y_gcd = gcd(y_numerator,denominator)

	return [x_numerator/x_gcd,denominator/x_gcd,
		y_numerator/y_gcd,denominator/y_gcd]

## Tests:
check.expect('Sample test', intersection(-15,15,15,-15,-10,-10,10,10), [0,1,0,1])
check.expect('Parallel', intersection(-10,-10,10,10,-20,-10,0,10),"parallel")

# Be sure to do lots more of your own testing!
def print_checkerboard(rows,cols):
    first_line = new_line(cols)
    second_line = alternate_line(cols)
    dashes = "-" * cols
    boundary = "+"+dashes+"+"
    print(boundary)
    while rows > 0:
        if rows%2 ==0:
            print("|"+second_line+"|")
            rows = rows - 1
        else:
            print("|"+first_line+"|")
            rows = rows - 1
    print(boundary)

#Tests:
check.set_screen("+--+\n|# |\n+--+")
check.expect("Q2T1", print_checkerboard(1,2), None)
check.set_screen("+---+\n| # |\n|# #|\n| # |\n+---+")
check.expect("Q2T2", print_checkerboard(3,3), None)
check.set_screen("+-+\n| |\n|#|\n| |\n|#|\n| |\n+-+")
check.expect("Q2T3", print_checkerboard(5,1), None)

check.set_screen("+----+\n|# # |\n| # #|\n|# # |\n+----+")
check.expect("Q2T3", print_checkerboard(3,4), None)

                 

    
    
Beispiel #31
0
## sieve: int[>1] -> (listof int[>=2])
## Purpose: Consumes an integer greater than 1, n, and produces a list of
## all prime numbers less than integer n using the sieve of Eratosthenes
## algorithm to mark non-primes in a list of natural numbers.
#
# Examples: sieve(2) => [2]
#           sieve(100) => [2,3,5,7,11,13,17,19,23,29,31,37,41,43, \
#                          47,53,59,61,67,71,73,79,83,89,97]
#           sieve(15) => [2,3,5,7,11,13]
def sieve(n):
    lon = range(2, n + 1) #list being examined
    lop = range(2, n + 1) #list being marked
    for num in lon: #to cover each 
        for mark in range(2*num,n+1,num): #marking each pth entry in list
            lop[mark-2] = False   
    return filter(lambda x: x != False,lop) #removing marked entries
## Testing:
print "Testing sieve"

# Test 1: Smallest case = 2
check.expect("Question 2 Test 1", sieve(2), [2])

# Test 2: Large case = 100
primes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]
check.expect("Question 2 Test 2", sieve(100), primes)

# Test 3: General case
check.expect("Question 2 Test 3", sieve(15), [2,3,5,7,11,13])
    
Beispiel #32
0
g.right = None
g.parent = c

b.left = d
b.right = e
b.parent = a

c.left = f
c.right = g
c.parent = a

a.left = b
a.right = c
a.parent = None

check.expect("Q1T0", get_successor(None), None)
t1 = Node(71)
check.expect("Q1T1", get_successor(a).key, t1.key)
t2 = Node(23)
check.expect("Q1T2", get_successor(b).key, t2.key)
t3 = Node(100)
check.expect("Q1T3", get_successor(c).key, t3.key)
check.expect("Q1T4", get_successor(d), None)
check.expect("Q1T5", get_successor(e), None)
t4 = Node(84)
check.expect("Q1T6", get_successor(f).key, t4.key)
check.expect("Q1T7", get_successor(g), None)
check.expect("Q1T8", get_successor(h), None)
t5 = Node(37)
check.expect("Q1T9", get_successor(i).key, t5.key)
check.expect("Q1T10", get_successor(j), None)
Beispiel #33
0
import check

# is_palidrome(s) returns if the given string s is in palidrome form
# is_palidrome: Str -> Bool
# Example: is_palindrome('aba') => True


def is_palindrome(s):
    if len(s) == 0 or len(s) == 1:
        return True
    while len(s) > 1:
        if s[0] == s[-1]:
            return True
        else:
            return False
        s = s[1:-1]


# Tests:
check.expect('Q3T1', is_palindrome(''), True)
check.expect('Q3T2', is_palindrome('a'), True)
check.expect('Q3T3', is_palindrome('aba'), True)
check.expect('Q3T4', is_palindrome('abc'), False)
check.expect('Q3T5', is_palindrome('abcba'), True)
        elif cos <1:
            if k in result[acute_cat]:
                None
            else:
                result[acute_cat].append(k)
    return result
                
# Test: 

a = [Vector(-4,0), Vector(-3,4), Vector(-6,-5)]
b = [Vector(-4,0), Vector(0,-7), Vector(10,5), Vector(-1,7),\
     Vector(-5,-3), Vector(4,-6), Vector(-1,7),Vector(-9,3)]
c = [Vector(1,1), Vector(2,2), Vector(-1,-1)]

# contain one of the keys in lov
check.expect('Acute', classify_angles(a, Vector(-1,1)),\
             {acute_cat: [Vector(-4,0), Vector(-3,4), Vector(-6,-5)], obtuse_cat: [], right_cat: [], par_cat: []})
check.expect('Vector', classify_angles(a, Vector(6,1)),\
             {acute_cat: [], obtuse_cat: [Vector(-4,0), Vector(-3,4), Vector(-6,-5)], right_cat: [], par_cat: []})
check.expect('Parallel', classify_angles(c, Vector(9,9)),\
             {acute_cat: [], obtuse_cat: [], right_cat: [], par_cat: [Vector(1,1), Vector(2,2), Vector(-1,-1)]})
check.expect('Right', classify_angles(c, Vector(-9,9)),\
             {acute_cat: [], obtuse_cat: [], right_cat: [Vector(1,1), Vector(2,2), Vector(-1,-1)], par_cat:[] })
# contain two of the keys in lov
check.expect('Right & Obtuse', classify_angles(a, Vector(4,3)),\
             {acute_cat: [], obtuse_cat: [Vector(-4,0), Vector(-6,-5)], right_cat: [Vector(-3,4)], par_cat: []})
# contain three of the keys in lov
check.expect('Acute, Obtuse and Parallel', classify_angles(b, Vector(-2,3)), \
             {'ACUTE': [Vector(-4,0), Vector(-1,7), Vector(-5,-3), Vector(-9,3)],
             'OBTUSE': [Vector(0,-7), Vector(10,5)], 'RIGHT': [],
             'PARALLEL': [Vector(4,-6)]})             
# contain all in lov
    '''
    consumes a string s and returns 1 if length of s is greater than 9
    else it returns 0.
    
    password_length: Str -> Nat
    
    Examples:
    password_length("titile") -> 0
    password_length('haramkhoriyaan1234') -> 1
    '''
    if len(s) > 9:
        return 1
    else :
        return 0
##Tests
check.expect("length less than 9", password_length("titile"), 0)
check.expect("length more than 9", password_length('haramkhoriyaan1234'), 1)
    
def least_one_upper(s) :
    '''
    consumes a string s and returns 1 if the string has atleast 1 uppercase
    alphabet else returns 0
    
    least_one_upper: Str -> Nat
    
    Examples:
    least_one_upper("dumb") -> 0
    least_one_upper("DUmb") -> 1
    least_one_upper("duMb1") -> 1
    '''
    if s == "" :
Beispiel #36
0
    second_half = all_lines[n:]
    p_board = []
    p_constraints = []

    for i in first_half:
        split = i.split()
        p_board.append(split)
    for i in second_half:
        split = i.split()
        p_constraints.append(split)
    for i in p_constraints:
        i[1] = int(i[1])
    return Puzzle(n, p_board, p_constraints)


check.expect("Ta1", read_puzzle("inp1.txt"), puzzle1)
check.expect("Ta2", read_puzzle("inp2.txt"), puzzle3)

###############################################################################
###############################################################################


def print_sol(puz, fname):
    '''
    prints the Puzzle puz in fname file
    
    print_sol: Puzzle Str -> None
    '''

    w_file = open(fname, 'w')
    for i in puz.board:
Beispiel #37
0
        return mid
    elif med1 > med2:
        if l1 % 2 == 1:
            lst1 = lst1[:l1/2+1]
            lst2 = lst2[l1/2:]
            return find_median(lst1,lst2)
        else:
            lst1 = lst1[:l1/2+1]
            lst2 = lst2[l1/2-1:]
    elif med1 < med2:
        if l1 % 2 == 1:
            lst1 = lst1[l1/2:]
            lst2 = lst2[:l1/2+1]
            return find_median(lst1,lst2)
        else:
            lst1 = lst1[l1/2-1:]
            lst2 = lst2[:l1/2+1]
            return find_median(lst1,lst2)
    else:
        return med1

# Tests
## base case: one element
check.expect("q4t1", find_median([4],[3]), 3)
## two elements
check.expect("q4t2", find_median([4,6],[3,4]), 4)
## longer lists
check.expect("q4t3", find_median([4,6,7],[3,4,5]), 4)
check.expect("q4t4", find_median([1,12,15,19],[2,13,17,19]), 14)
## much longer cases
check.expect("q4t5", find_median([1,2,3,4,5,6,7,8,9],[2,3,4,5,6,7,9,10,12]), 5)
Beispiel #38
0
## nat2bin(12)-> [1,1,0,0]
## nat2bin(0) -> [0]
## nat2bin(3) -> [1,1]


def nat2bin(n):
    q = [n % 2]
    while n // 2 != 0:
        n = n // 2
        q.extend([n % 2])

    q.reverse()
    return q


check.expect("Test1", nat2bin(0), [])
check.expect("Test2", nat2bin(2), [])
check.expect("Test3", nat2bin(3), [])
check.expect("Test4", nat2bin(5), [])
check.expect("Test5", nat2bin(8), [])
check.expect("Test6", nat2bin(17), [])


#b
def nat2base(n, base):
    q = [n % base]
    while n // base != 0:
        n = n // base
        q.extend([n % base])

    q.reverse()
Beispiel #39
0
# Purpose: produces a list of integers after a series of caculations
# from the given integer (n)

# Effect: no effect since there is no mutation

# Examples: collatz_list(1) => [1]
# collatz_list(2) => [2,1]
# collatz_list(3) => [3,10,5,16,8,4,2,1]
# collatz_list(8) => [8,4,2,1]

def collatz_list(n):
    initial = []
    while n > 1:
        initial = initial + [n]
        if n % 2 == 1:
            n = 3*n + 1
        else:
            n = n/2
    return initial+[1]

# Tests
## base case
check.expect('q2t1', collatz_list(1), [1])
## small numbers
check.expect('q2t2', collatz_list(2), [2,1])
check.expect('q2t3', collatz_list(3), [3,10,5,16,8,4,2,1])
check.expect('q2t4', collatz_list(4), [4,2,1])
check.expect('q2t5', collatz_list(6), [6,3,10,5,16,8,4,2,1])
## large number
check.expect('q2t6', collatz_list(25), [25,76,38,19,58,29,88,44,22,11,\
                                        34,17,52,26,13,40,20,10,5,16,8,4,2,1])
Beispiel #40
0
        return 2
    else:
        return 1


# * Points Nimmt Function *
# points_6nimmt(cards) Produces the total number of points earned by 'cards'
# points_6nimmt: (listof Int) -> Int
# Requires: 0 < entry in list < 105, no repeats
# Examples:
# points_6nimmt([]) => 0
# points_6nimmt([1,2,3,4,5]) => 6


def points_6nimmt(cards):
    if cards == []: return 0
    else:
        return sum(map(card_points, cards))


# Tests for points_6nimmt
check.expect('Q2T1', points_6nimmt([]), 0)
check.expect('Q2T2', points_6nimmt([1, 2, 3, 4, 5]), 6)
check.expect('Q2T3', points_6nimmt([55]), 7)
check.expect('Q2T4', points_6nimmt([66]), 5)
check.expect('Q2T5', points_6nimmt([70]), 3)
check.expect('Q2T6', points_6nimmt([35]), 2)
check.expect('Q2T7', points_6nimmt([101]), 1)
check.expect('Q2T8', points_6nimmt([55, 66, 70, 35, 101]), 18)
check.expect('Q2T9', points_6nimmt([4, 2, 100, 55, 44, 21]), 18)
check.expect('Q2T10', points_6nimmt([110, 55, 3, 8, 4, 83, 90, 95]), 21)
# Example: fib_rec(6) => 8
#          fib_rec(0) => 0

def fib_rec(n):
    def fib_acc(new_n,last_fib,prev_fib):
        if (new_n == n):
            return last_fib
        else:
            return fib_acc((1+new_n),(last_fib+prev_fib),last_fib)
    if (n == 0):
        return 0
    else:
        return fib_acc(1,1,0)

# Testing fib_rec:
check.expect("Test 1", fib_rec(10), 55)
check.expect("Test 2", fib_rec(65), 17167680177565)

# fib_approx(n) consumes a natural number (n) and produces a float that is approximately the nth position of the fibonnachi sequence
# fib_approx: Nat -> Approx
# Example: fib_approx(6) => 8.0
#          fib_approx(0) => 0

def fib_approx(n):
    phi = (1+(math.sqrt(5)))/2
    fib_final = ((phi ** n) - ((-phi) ** (-n)))/math.sqrt(5)
    return fib_final

# Testing fib_approx

check.within("Test 3", fib_approx(10), 55.0, 0.0001)
Beispiel #42
0
            val = self._theItems.dequeue()
            self.push(val)
        return val

    def pop(self):
        assert not self.isEmpty(), "Cannot pop from an empty stack"
        k = len(self._theItems) - 1
        for i in range(k):
            self.push(self._theItems.dequeue())
        return self._theItems.dequeue()

    def push(self, item):
        self._theItems.enqueue(item)


# Test 1: Normal use case
s = Stack()
s.push(12)
check.expect("Question 1 Test 1", s.isEmpty(), False)
s.push(98)
check.expect("Question 1 Test 1", s.peek(), 98)
s.push(14)
check.expect("Question 1 Test 1", s.pop(), 14)
check.expect("Question 1 Test 1", s.peek(), 98)
check.expect("Question 1 Test 1", len(s), 2)

# Test 2: Empty Stack
s1 = Stack()
check.expect("Question 1 Test 2", s1.isEmpty(), True)
check.expect("Question 1 Test 2", len(s1), 0)
Beispiel #43
0
    elif L1[i] < L2[j]:
        R.append(L1[i])
        merge(L1,L2,i+1,j,R)
    else:
        R.append(L2[j])
        merge(L1,L2,i,j+1,R)

# copy_values(to, original, pos) copies all the values from original to to when pos is 0
# copy_values: (listof Any) (listof Any) -> None
# Effects: Mutates to by setting each element equal to original
def copy_values(to,original,pos):
    if pos < len(original):
        to[pos] = original[pos]
        copy_values(to, original,pos+1)

# smallest_diff(numbers) produces the smallest difference between 2 adjacent integers
#  in the list numbers
# smallest_diff: (listof Int) ->  Int
# requires: numbers to be in non-decreasing order

# Examples:
# smallest_diff([1,2,3,4,5,6]) =>
# smallest_diff([1,2,445,5678,54332,53453243,43456455353]) => 1

def smallest_diff(numbers):
    list_diffs = list_of_diff([], numbers)
    return mergesort(list_diffs)[0]

check.expect("T1", smallest_diff([1,2,3,4,5,6]), 1)
check.expect("T2", smallest_diff([1,2,445,5678,54332,53453243,43456455353]), 1)
check.expect("T3", smallest_diff([1,22,445,5678,54332,54333]), 1)
        board[1] = [card]
        return old_row
    if card - last_card3 == row_to_enter and card > last_card3 and len(
            board[2]) == 5:
        old_row = board[2]
        board[2] = [card]
        return old_row
    if card - last_card4 == row_to_enter and card > last_card4 and len(
            board[3]) == 5:
        old_row = board[3]
        board[3] = [card]
        return old_row


# Tests for turn_6nimmt
check.expect('Q4T1a', turn_6nimmt(my_board, 71), True)
check.expect('Q4T1b', my_board,
             [[67, 70, 71], [9, 18, 19], [8], [13, 30, 50, 88, 93]])
check.expect('Q4T2a', turn_6nimmt(my_board, 94), [13, 30, 50, 88, 93])
check.expect('Q4T2b', my_board, [[67, 70, 71], [9, 18, 19], [8], [94]])
check.expect('Q4T3a', turn_6nimmt(my_board, 25), True)
check.expect('Q4T3b', my_board, [[67, 70, 71], [9, 18, 19, 25], [8], [94]])
check.set_input(['2'])
check.set_screen('Choose one of the rows')
check.expect('Q4T4a', turn_6nimmt(my_board, 5), [9, 18, 19, 25])
check.expect('Q4T4b', my_board, [[67, 70, 71], [5], [8], [94]])
check.expect('Q4T5a', turn_6nimmt(my_board, 9), True)
check.expect('Q4T5b', my_board, [[67, 70, 71], [5], [8, 9], [94]])
check.expect('Q4T6a', turn_6nimmt(my_board, 10), True)
check.expect('Q4T6b', my_board, [[67, 70, 71], [5], [8, 9, 10], [94]])
check.expect('Q4T7a', turn_6nimmt(my_board, 11), True)
        comp_ans_num = fib_rec(game_num) % 3
        if comp_ans_num == 0:
            comp_ans = "r"
        elif comp_ans_num == 1:
            comp_ans = "p"
        else:
            comp_ans = "s"
        if (player_ans == "r" and comp_ans == "p") or (player_ans == "p" and comp_ans == "s") or (player_ans == "s" and comp_ans == "r"):
            comp_wins = comp_wins + 1
            print("Player plays: " + player_ans + ". Computer plays: " + comp_ans + ". Computer won.")
        elif (player_ans == "p" and comp_ans == "r") or (player_ans == "s" and comp_ans == "p") or (player_ans == "r" and comp_ans == "s"):
            player_wins = player_wins + 1
            print("Player plays: " + player_ans + ". Computer plays: " + comp_ans + ". Player won.")
        elif player_ans == comp_ans:
            tied_games = tied_games + 1
            print("Player plays: " + player_ans + ". Computer plays: " + comp_ans + ". Tied.")
    print("Thank you for playing! Total game statistics:")
    print("Tied games: " + str(tied_games) + ".")
    print("Player won " + str(player_wins) + " times.")
    print("Computer won " + str(comp_wins) + " times.")
    
# Q4 Test 1: one response
check.set_screen("Welcome to the Rock-Paper-Scissors game!\nHow would you like to play next [r/p/s/q]?\nPlayer plays: r. \
Computer plays: p. Computer won.\nHow would you like to play next [r/p/s/q]?\nThank you for playing! Total game statistics:\nTied games 0.\nPlayer won 0 times.\nComputer won 1 times.")
check.set_input(["r","q"])
check.expect("T1", play_rps(), None)

# Q4 Test 2: many responses
check.set_screen("Welcome to the Rock-Paper-Scissors game!\nHow would you like to play next [r/p/s/q]?\nPlayer plays: r. Computer plays: p. Computer won.\nHow would you like to play next [r/p/s/q]?\nPlayer plays: s. Computer plays: p. Player won.\nHow would you like to play next [r/p/s/q]?\nPlayer plays: p. Computer plays: s. Computer won.\nHow would you like to play next [r/p/s/q]?\nPlayer plays: s. Computer plays: r. Computer won.\nHow would you like to play next [r/p/s/q]?\nThank you for playing! Total game statistics:\nTied games 0.\nPlayer won 1 times.\nComputer won 3 times.")
check.set_input(["r","s","p","s","q"])
check.expect("T2", play_rps(), None)
Beispiel #46
0
import check
import math

# how_many_phones(phone_length, distance) returns the exact number of
# phones with known length needed to cover a certain distance
# how_many_phones: Float Float -> Nat
# requires: phone_length is measured in centimeter and is not zero
#           distance is measured in kilometer
# Examples: how_many_phones(14.7, 1.6) => 10885


def how_many_phones(phone_length, distance):
    num = (1000 * distance) / (phone_length / 100)
    number_of_phone = math.ceil(num)
    return number_of_phone


# Tests:
check.expect("Q1T1", how_many_phones(1, 0), 0)
check.expect("Q1T2", how_many_phones(100, 23), 23000)
check.expect("Q1T3", how_many_phones(100, 2.3), 2300)
check.expect("Q1T4", how_many_phones(13.4, 2.7), 20150)
Beispiel #47
0
## Example: intersection(-15,15,15,-15,-10,-10,10,10) => [0,1,0,1]
def intersection(x1, y1, x2, y2, x3, y3, x4, y4):
        x_numerator = ((x1*y2-y1*x2)*(x3-x4) - (x1-x2)*(x3*y4-y3*x4))
        denominator = (x1-x2)*(y3-y4)-(y1-y2)*(x3-x4)
        if (denominator == 0) :
                return "parallel"
        x_gcd = gcd(x_numerator,denominator)

        y_numerator = (x1*y2-y1*x2)*(y3-y4)-(y1-y2)*(x3*y4-y3*x4)
        y_gcd = gcd(y_numerator,denominator)

        return (x_numerator/x_gcd,denominator/x_gcd,
                y_numerator/y_gcd,denominator/y_gcd)

## Tests:
check.expect('Sample test', intersection(-15,15,15,-15,-10,-10,10,10), (0,1,0,1))
check.expect('Parallel', intersection(-10,-10,10,10,-20,-10,0,10),"parallel")

## point_range: (listof Int) (listof Int) (listof Int) (listof Int)  (optional (tuple Int Int Int Int))
##	-> (iterable (tuple Int Int Int Int))
##
## Purpose: Merges four lists of equal length into an iterable of points,
##	optionally starting after the point specified by (init_x1,init_y1,initx2,inity2)
##
## Example: 	i_p = point_range([1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16])
## 		i_p.next() = (1,5,9,13)
##		i_p.next() = (2,6,10,14)
def point_range(X1,Y1,X2,Y2,(init_x1 ,init_y1, init_x2, init_y2 )= (None,None,None,None)) :
	if (init_x1 == None) : 
		started = True
	else :
## Conditions:
##     PRE: consumes four integers between 0 and 100.
##     POST: produced value <= 100.
## Purpose: Produces the integer grade in CS116 according to the
##          specified rules.
## Examples:
##     cs116_grade(80,90,75,77) => 78
##     cs116_grade(20,0,50,40)=> 37

def cs116_grade(assignments, clickers, midterm, exam):
    weighted_exam = (midterm * 0.3 + exam * 0.45)
    standard_calculation = midterm * 0.3 + exam * 0.45 \
    + assignments * 0.2 + clickers * 0.05
    if weighted_exam >= 37.5:
        return int(round(standard_calculation))
    else:
        return int(round(min(weighted_exam / 75 * 100, standard_calculation)))

## Tests for cs116_grade
## Test 1: Pass the weighted exam average(WEA) with at least 50%
check.expect("Q2T1", cs116_grade(80, 90, 75, 77), 78)
## Test 2: Fail the WEA and WEA is smaller than standard calculation(SC)
check.expect("Q2T2", cs116_grade(100, 100, 40, 40), 40)
## Test 3: Fail the WEA and SC is smaller than WEA
check.expect("Q2T3", cs116_grade(0, 0, 40, 40), 30)
## Test 4: General case 
check.expect("Q2T4", cs116_grade(20, 0, 50, 40), 37)
## Test 5: General case 
check.expect("Q2T5", cs116_grade(100, 95, 50, 75), 74)       
        
    
def points_6nimmt(cards):
    if cards == []:
        return 0
    elif cards[0] == 55:
        return 7 + points_6nimmt(cards[1:])
    elif cards[0] % 11 == 0:
        return 5 + points_6nimmt(cards[1:])
    elif cards[0] % 10 == 0:
        return 3 + points_6nimmt(cards[1:])
    elif cards[0] % 5 == 0:
        return 2 + points_6nimmt(cards[1:])
    else:
        return 1 + points_6nimmt(cards[1:])


# Q2 Test 1:
check.expect("T1", points_6nimmt([]), 0)

# Q2 Test 2:
check.expect("T2", points_6nimmt([1, 55, 2, 104]), 10)

# Q2 Test 3:
check.expect("T3", points_6nimmt([55]), 7)

# Q2 Test 4:
check.expect("T4", points_6nimmt([1, 55, 2, 104, 13, 12, 54, 16, 98, 85, 42, 53, 25]), 21)

# Q2 Test 5:
check.expect("T5", points_6nimmt([33, 55, 100, 75, 91]), 18)
Beispiel #50
0
    Examples: 
    is_prime(5,2) => True
    is_prime(6,2) => False
    '''
    if a == 1:
        return False
    elif a == b:
        return True
    elif a % b == 0:
        return False
    else:
        return is_prime(a, b + 1)


# Test
check.expect("Q2T1", is_prime(9, 2), False)
check.expect("Q2T2", is_prime(1, 2), False)
check.expect("Q2T3", is_prime(2, 2), True)


def next_prime(current_num):
    '''
    Takes into account what the current number which can either be be a prime 
    number or not. If the current number is a prime nummber, then it returns the 
    same number. If it is not a prime number, then the next prime number is 
    returned. 
    
    next_prime: Nat -> Nat
    
    examples:
    next_prime(1) -> 2
Beispiel #51
0
def test_calc_error():
    import check
    
    # test one_norm
    observed = np.array([10, 15])
    expected = np.array([12.5, 20])
    check.expect("", one_norm(observed, expected), 7.5)
    
    expected = np.random.rand(4)
    observed = expected + 3.0  # add 3 to all elements in the array
    check.expect("", one_norm(observed, expected), 4 * 3.0)
    
    check.expect("", one_norm(3, 2.7), 0.3)
    check.expect("", one_norm(3, 3.3), 0.3)
    
     # test two_norm
    observed = np.array([10, 15])
    expected = np.array([13, 19])
    check.expect("", two_norm(observed, expected), 5.0)
    
    expected = np.random.rand(4)
    observed = expected + 3.0  # add 3 to all elements in the array
    check.expect("", two_norm(observed, expected), np.sqrt(4) * 3.0 )
    
    check.expect("", two_norm(3, 2.7), 0.3)
    check.expect("", two_norm(3, 3.3), 0.3)
Beispiel #52
0
# -> (listof (listof str, int[>=0,<=100],(union 'A' 'B' 'C' 'D' 'E')))

# Purpose: produces a list of lists with mixed string and integer and symbols
# by consuming the name list (full_names) and grade list (percentages)

# Examples: student_grade([], []) => []
# student_grade(["Troy"], [89]) => [["Troy", 89, 'A']]
# student_grade(["Troy" , "Lori" , "Adriel"], [89,84,74]) => [["Troy", 89, 
# "A"], ["Lori", 84, "A"], ["Adriel", 74, "B"]]
# student_grade(["Rosina" , "Maheen" ,"Dan", "EDI"], [72,61,42,52]) 
# => ["Rosina", 72, "B"], ["Maheen", 61, "C"], ["Dan", 42, "E"], 
# ["EDI", 52, "D"]]

def student_grade(full_names,percentages):
    return grade_list(full_names, percentages, [])

# Tests
## base case
check.expect("Q2T1", student_grade([], []), [])
## Test for single element
check.expect("Q2T2", student_grade(["Troy"], [89]), [["Troy", 89, "A"]])
## Test for longer list
check.expect("Q2T3", student_grade(["Troy" , "Lori" , "Adriel"], [89,84,74]),\
             [["Troy", 89, "A"], ["Lori", 84, "A"], ["Adriel", 74, "B"]])
check.expect("Q2T4", student_grade(["Rosina" , "Maheen" ,"Dan", "EDI"], \
                                   [72,61,42,52]),\
             [["Rosina", 72, "B"], ["Maheen", 61, "C"], ["Dan", 42, "E"], ["EDI", 52, "D"]])
check.expect("Q2T5", student_grade (["Troy" , "Lori" , "Adriel", "Rosina" , "Maheen" ,"Dan", "EDI"], \
                                    [89,84,74,72,61,42,52]), \
             [["Troy", 89, "A"], ["Lori", 84, "A"], ["Adriel", 74, "B"], ["Rosina", 72,"B"], \
              ["Maheen", 61, "C"], ["Dan", 42, "E"], ["EDI", 52, "D"]])
Beispiel #53
0
# bhcs_game([["shoe","hat","hat","cupcake"], ["cupcake","hat","shoe","bear"]])
# => "Player 2 is the winner with 17 points"

def bhcs_game(die_rolls):
        point_roll = map(str_points, die_rolls)
        winner_points = max(point_roll)
        player = point_roll.index(winner_points) + 1
        check_tie = filter (lambda int: int == winner_points, point_roll)
        if len(check_tie) == 1:
                return winner_str % (player, winner_points)
        else:
                return tie_str
        
# Tests
## base case
check.expect("Q3T1", bhcs_game([["cupcake","hat","shoe","bear"]]), \
             "Player 1 is the winner with 17 points")
## tie 
check.expect("Q3T2", bhcs_game([["cupcake","hat","shoe","shoe"], \
                                ["shoe","hat","shoe","cupcake"]]), \
             "There is a tie")
check.expect("Q3T3", bhcs_game([["cupcake","hat","shoe","bear"], \
                                ["cupcake","hat","shoe","bear"], \
                                ["hat","cupcake","bear","shoe"]]), \
             "There is a tie") 
## other
check.expect("Q3T4", bhcs_game([["shoe","hat","hat","cupcake"], \
                                ["cupcake","hat","shoe","bear"]]),\
             "Player 2 is the winner with 17 points")
check.expect("Q3T5", bhcs_game([["bear","shoe","shoe","hat"], \
                                ["cupcake","bear","shoe", "hat"], \
                                ["bear","bear","bear","bear"], \
Beispiel #54
0
    elif need - correct >= incorrect:
        earned = correct * 2 + incorrect * 1
    else:
        earned = correct * 2 + need - correct * 1
    return 100 * ((earned) / total)


# Constant for tests
master1 = ['A', 'A', 'B', 'C', 'A', 'D', 'E', 'A', 'D', 'B']
master2 = ['A', 'A', 'B', 'C', 'A']
student1 = ['A', 'A', 'B', 'C', 'A', 'D', 'E', 'A', 'D', 'B']
student2 = ['A', 'A', 'B', 'C', 'D', 'E', 'A', 'E', 'B', ' ']
student3 = ['A', 'B', 'A', ' ', ' ', 'D', ' ', 'A', ' ', 'B']
student4 = ['E', 'E', ' ', ' ', ' ']
student5 = ['A', ' ', ' ', 'C', ' ']

# Tests1: contain only correct answers
check.expect("Q1T1", clicker_grade(master1, student1), 100.0)
# Tests2: contain correct and incorrect answers
check.within("Q1T2", clicker_grade(master1, student2), 78.57143, 0.00001)
# Tests3: contain all types of answers
check.within("Q1T3", clicker_grade(master1, student3), 71.42857, 0.00001)
# Tests4: contain only incorrect answers
check.expect("Q1T4", clicker_grade(['A', 'A'], ['B', 'C']), 50.0)
# Tests5: contain incorrect and unanswered answers
check.within("Q1T5", clicker_grade(master2, student4), 33.3333, 0.0001)
# Tests6: contain only unanswered answers
check.expect("Q1T6", clicker_grade(['A', 'C'], [' ', ' ']), 0.0)
# Tests7: contain only correct and unanswered answers
check.within("Q1T7", clicker_grade(master2, student5), 66.6666, 0.0001)
# rid_repeats: (listof Int) (listof Int) -> (listof Int)
# requires: new_list = []
#           old_list to be ordered from smallest to largest
def rid_repeats(new_list, old_list):
    if old_list == []:
        return new_list
    elif new_list == []:
        return rid_repeats([old_list[0]], old_list[1:])
    elif new_list[-1] == old_list[0]:
        return rid_repeats(new_list, old_list[1:])
    else:
        return rid_repeats(new_list + [old_list[0]], old_list[1:])


# singles(lst) produces an ordered list of all the unique integers in lst
# singles: (listof Int) -> (listof Int)

# Examples:
# singles([]) => []
# singles([4,4,9,8,3,4])

def singles(lst):
    sorted_list = sorted(lst)
    no_repeats = rid_repeats([], sorted_list)
    return no_repeats

check.expect("T1", singles([]), [])
check.expect("T2", singles([4,4,9,8,3,4]), [3,4,8,9])
check.expect("T3", singles([1,2,3,4,5,6,7,8,9]), [1,2,3,4,5,6,7,8,9])
check.expect("T4", singles([5,4,3,2,1]), [1,2,3,4,5])
check.expect("T5", singles([-4,4,9,-8,3,4]), [-8,-4,3,4,9])
Beispiel #56
0
# containing the highest temperature and the lowest temperature in the 
# given file

# Effect: reads from the file (day_temps)

# Example: get_low_high('') => []
# get_low_high('q1t2.txt') => [-8.89,-8.89]
# get_low_high('2003-Jan-17-temps.txt') => [-19.32,-8.68]

def get_low_high(day_temps):
    try:
        input_file = file(day_temps, 'r')
        lst = input_file.readlines()
        data = map(float, map(lambda item: item.split()[4], lst[1:]))
        input_file.close()
        return [min(data), max(data)]
    except:
        return []

# Tests:
## base case: no string input
check.expect('q1t1a', get_low_high(''), [])
## another base case: empty file
check.expect('q1t1b', get_low_high('q1t1'), [])
## case with one day of data in the file
check.expect('q1t2', get_low_high('q1t2.txt'), [-8.89,-8.89])
## case with a short entries of data
check.expect('q1t3', get_low_high('q1t3.txt'), [-15.61, -8.89])
check.expect('q1t4', get_low_high('q1t4.txt'), [-17.63, -15.35])
## case with multiple entries
check.expect('q1t5', get_low_high('2003-Jan-17-temps.txt'), [-19.32,-8.68])
Beispiel #57
0
def replace_str(base, target,rep):
        word = len(target)
        if word == 0:
                return base
        if len(base) < word:
                return base
        elif target in base:
                start = base.find(target)
                new_base = base[start+word:]
                new = base[:start] + rep + replace_str(new_base,target,rep)
                return new
        else:
                return base
        
# Tests
## base case
check.expect("q1t1", replace_str('','a','b'), '')
check.expect("q1t2", replace_str('','','a'), '')
check.expect("q1t3", replace_str('','a',''), '')
## single replacement
check.expect("q1t4", replace_str('fruit','f','t'), 'truit')
check.expect("q1t5", replace_str('This is my book','my','the'), \
             'This is the book')
## multiple replacement
check.expect("q1t6", replace_str('aaaaa','aa','x'), 'xxa')
check.expect("q1t7", replace_str('My brother reads books and sometimes he reads magazines', 'reads', 'likes'), \
             'My brother likes books and sometimes he likes magazines')
check.expect("q1t8", replace_str('I like this book','I','I'), 'I like this book')
## no replacement
check.expect("q1t9", replace_str('this is my book','a','the'), 'this is my book')
Beispiel #58
0
# count_mines(grid3x3,1,0) => 1
# count_mines(grid3x3,1,1) => 2

def count_mines(grid,row,col):
    if len(grid) == 1 and len(grid[0]) == 1:
        return 0
    elif len(grid) == 1:
        if col == 0: return int(grid[0][1])
        elif col == len(grid[0]) - 1: return int(grid[0][-2])
        else: return int(grid[0][col - 1]) + int(grid[0][col + 1])
    else:
        return len(list(filter(lambda x: x == True,count_mines_area\
                               (grid,row,col))))

# Tests:
check.expect("test1",count_mines(grid3x3,0,0),0)
check.expect("test2",count_mines(grid3x3,1,0),1)
check.expect("test3",count_mines(grid3x3,2,0),0)
check.expect("test4",count_mines(grid3x3,0,1),1)
check.expect("test5",count_mines(grid3x3,1,1),2)
check.expect("test6",count_mines(grid3x3,2,1),1)
check.expect("test7",count_mines(grid3x3,0,2),0)
check.expect("test8",count_mines(grid3x3,1,2),1)
check.expect("test9",count_mines(grid3x3,2,2),0)
check.expect("test10",count_mines(grid5x6,4,5),0)
check.expect("test11",count_mines(grid5x6,1,1),8)
check.expect("test12",count_mines(grid5x6,0,0),2)
check.expect("test13",count_mines(grid5x6,3,0),3)
check.expect("test14",count_mines(grid5x6,3,3),3)
check.expect("test15",count_mines(grid2x2,1,0),1)
check.expect("test16",count_mines(grid2x2,0,0),0)
Beispiel #59
0
    lst = infile.readlines()
    infile.close()
    
    ## taking the useful part of the file into file_list
    check = day_trans(day_of_week)
    program = map(lambda item: item.split(','), lst)[2:]
    file_list = []
    for shows in program:
        days = shows[3]
        if days[check-1] != '.':
            file_list.append(shows[:2])
    
    ## writing to a file
    filename = day_of_week + '-' + ratings_file
    output_file = file(filename, 'w')
    output_file.write(day_string % day_of_week)
    for seg in file_list:
        output_file.write(seg)
    output_file.close()

# Tests
## base case: the given file only contains the first two lines and
## there is no program data in the file
check.expect('q2t1', ratings_by_day('q2t1.txt', 'Sunday'), None)
check.set_file('Sunday-q2t1.txt', 'q2t1-check.txt')
## other case: the given file contains some of the program infomation
check.expect('q2t2', ratings_by_day('q2t2.txt', 'Tuesday'), None)
check.set_file('Tuesday-q2t2.txt', 'q2t2-check.txt')
## case that data in the given file has no programs on the given day
check.expect('q2t3', ratings_by_day('q2t3.txt', 'Sunday'), None)
check.set_file('Sunday-q2t3.txt', 'q2t3-check.txt')
Beispiel #60
0
                new_appt_time = float(details[4])
                appt_book.changeAppointment(appt_date, appt_time,
                                            new_appt_date, new_appt_time)
            else:
                continue

        except:
            continue

    f.close()
    return appt_book


# Test 1: empty text file
book1 = AppointmentBook()
check.expect("Q2T1", buildApptBook("q2_empty.txt"), book1)

# Test 2: text file with just a 'Make' command
book2 = AppointmentBook()
book2.makeAppointment(32, 12.0, "checkup")
check.expect("Q2T2", buildApptBook("q2_make.txt"), book2)

# Test 3: text file with just a 'Cancel' command
check.set_screen("There is no appointment at 9.5 on 10.")
check.expect("Q2T3", buildApptBook("q2_cancel.txt"), book1)

# Test 4: text file with just a 'Change' command
check.expect("Q2T4", buildApptBook("q2_change.txt"), book1)

# Test 5: text file with invalid inputs (values given are out of range)
check.expect("Q2T5", buildApptBook("q2_invalid.txt"), book1)