Example #1
0
def test_wild_lt():
    """
    Tests that __lt__ works properly for WildCard.
    """
    import wild

    card1 = wild.WildCard(code='QD')
    card2 = wild.WildCard(code='QS')
    introcs.assert_true(card1 < card2)
    introcs.assert_false(card2 < card1)

    card1 = wild.WildCard(code='JD')
    card2 = wild.WildCard(code='QD')
    introcs.assert_true(card1 < card2)
    introcs.assert_false(card2 < card1)

    card1 = wild.WildCard(code='2C')
    card2 = wild.WildCard(code='AS')
    introcs.assert_true(card1 < card2)
    introcs.assert_false(card2 < card1)

    card3 = wild.WildCard(code='WC')
    introcs.assert_true(card3 < card2)
    introcs.assert_false(card2 < card3)
    introcs.assert_true(card1 < card3)
    introcs.assert_false(card3 < card1)

    print('The wild __lt__ tests passed')
def test_circ_area():
    """
    Test procedure for function circ_area().
    """
    print('Testing circ_area()')

    result = func.circ_area(radius=3)
    introcs.assert_floats_equal(28.27433, result)

    result = func.circ_area(radius=2)
    introcs.assert_floats_equal(12.56637, result)

    result = func.circ_area(diameter=4)
    introcs.assert_floats_equal(12.56637, result)

    # Test for crashes
    try:
        func.circ_area()
        introcs.assert_true(False)  # We should never reach this line!
    except:
        pass

    try:
        func.circ_area(radius=3, diameter=6)
        introcs.assert_true(False)  # We should never reach this line!
    except:
        pass

    # Add a test with additional arguments
    dict1 = {'radius': 3, 'foo': 20, 'bar': 10}
    result = func.circ_area(**dict1)
    introcs.assert_floats_equal(28.274333882308138, result)
Example #3
0
def test_wild_deck():
    """
    Tests that the classmethod deck works properly for WildCard.
    """
    import wild

    deck1 = card.Card.deck()
    deck2 = wild.WildCard.deck()

    introcs.assert_equals(len(deck1) + 2, len(deck2))
    for pos in range(len(deck1)):
        introcs.assert_equals(deck1[pos].getSuit(), deck2[pos].getSuit())
        introcs.assert_equals(deck1[pos].getRank(), deck2[pos].getRank())
        introcs.assert_false(deck2[pos].isWild())

    rdjoker = deck2[-2]
    introcs.assert_equals(2, rdjoker.getSuit())
    introcs.assert_equals(1, rdjoker.getRank())
    introcs.assert_true(rdjoker.isWild())

    bkjoker = deck2[-1]
    introcs.assert_equals(3, bkjoker.getSuit())
    introcs.assert_equals(1, bkjoker.getRank())
    introcs.assert_true(bkjoker.isWild())

    print('The wild deck tests passed')
Example #4
0
def test_asserts():
    """
    This is a simple test procedure to help you understand how assert works
    """
    print('Testing the introcs asserts')
    introcs.assert_equals('b c', 'ab cd'[1:4])
    #introcs.assert_equals('b c', 'ab cd'[1:3])     # UNCOMMENT ONLY WHEN DIRECTED

    introcs.assert_true(3 < 4)
    introcs.assert_equals(3, 1 + 2)

    introcs.assert_equals(3.0, 1.0 + 2.0)
Example #5
0
def test_asserts():
    """
    This is a simple test procedure to help you understand how assert works
    """
    print('Testing the introcs asserts')
    introcs.assert_equals('b c', 'ab cd'[1:4])
    #introcs.assert_equals('b c', 'ab cd'[1:3])

    introcs.assert_true(3 < 4)
    introcs.assert_equals(3, 1 + 2)

    introcs.assert_equals(3.0, 1.0 + 2.0)
    introcs.assert_floats_equal(6.3, 3.1 + 3.2)
Example #6
0
def test_encode():
    """
    Tests the method encode in class Encoder
    """
    print('Testing method encode')
    
    # This is not a lot we can test without decode.  Just True or False
    image = load_image('blocks')
    encoder = a6encode.Encoder(image)
    
    encoder.increment()
    result = encoder.encode('')
    introcs.assert_true(result)
    
    encoder.undo()
    encoder.increment()
    result = encoder.encode('Hello World')
    introcs.assert_true(result)
    
    encoder.undo()
    encoder.increment()
    result = encoder.encode('Hello 😊')
    introcs.assert_true(result)
    
    text = load_text('doi')
    encoder.undo()
    encoder.increment()
    result = encoder.encode(text)
    introcs.assert_false(result)
    
    encoder.undo()
    encoder.increment()
    result = encoder.encode(text[len(image)-10])
    introcs.assert_true(result)
Example #7
0
def test_write_json():
    """
    Test procedure for the function write_json()
    """
    print('Testing write_json()')

    # Access the file relative to this one, not the user's terminal
    parent = os.path.split(__file__)[0]

    # First test (erase any existing file)
    fpath  = os.path.join(parent,'files','temp1.json')
    open(fpath,'w').close()
    funcs.write_json(FILE1,fpath)

    # Check file was created
    introcs.assert_true(os.path.exists(fpath))

    file = open(fpath)
    actual  =  file.read()
    file.close()

    file = open(os.path.join(parent,'files','readjson1.json'))
    correct = file.read()
    file.close()

    # Check to see if they are the same WITHOUT indentation
    introcs.assert_equals(unindent_json(correct),unindent_json(actual))
    # Check to see if they are the same WITH indentation
    introcs.assert_equals(correct,actual)

    # Second test (erase any existing file)
    fpath  = os.path.join(parent,'files','temp2.json')
    open(fpath,'w').close()
    funcs.write_json(FILE2,fpath)

    # Check file was created
    introcs.assert_true(os.path.exists(fpath))

    file = open(fpath)
    actual  =  file.read()
    file.close()

    file = open(os.path.join(parent,'files','readjson2.json'))
    correct = file.read()
    file.close()

    # Check to see if they are the same WITHOUT indentation
    introcs.assert_equals(unindent_json(correct),unindent_json(actual))
    # Check to see if they are the same WITH indentation
    introcs.assert_equals(correct,actual)
Example #8
0
def test_algorithm_a():
    """
    Tests Part A of the Algorithm class.
    """
    print('  Testing Part A of class Algorithm')

    # A dataset with four points almost in a square
    items = [[0., 0.], [10., 1.], [10., 10.], [0., 9.]]
    dset = a6dataset.Dataset(2, items)

    # Test creating a clustering with random seeds
    km = a6algorithm.Algorithm(dset, 3)
    # Should have 3 clusters
    introcs.assert_equals(len(km.getClusters()), 3)

    for clust in km.getClusters():
        print(clust.getCentroid)
        # cluster centroids should have been chosen from items
        introcs.assert_true(clust.getCentroid() in items)
        # cluster centroids should be distinct (since items are)
        for clust2 in km.getClusters():
            if clust2 is not clust:
                introcs.assert_float_lists_not_equal(clust.getCentroid(),
                                                     clust2.getCentroid())

    print('    Random Algorithm initialization looks okay')

    # Clusterings of that dataset, with two and three deterministic clusters
    km = a6algorithm.Algorithm(dset, 2, [0, 2])
    introcs.assert_equals(items[0], km.getClusters()[0].getCentroid())
    introcs.assert_equals(items[2], km.getClusters()[1].getCentroid())
    km = a6algorithm.Algorithm(dset, 3, [0, 2, 3])
    introcs.assert_equals(items[0], km.getClusters()[0].getCentroid())
    introcs.assert_equals(items[2], km.getClusters()[1].getCentroid())
    introcs.assert_equals(items[3], km.getClusters()[2].getCentroid())

    # Try it on a file
    file = os.path.join(os.path.split(__file__)[0], TEST_FILE)
    data = a6dataset.Dataset(4, tools.data_for_file(file))
    km2 = a6algorithm.Algorithm(data, 3, [23, 54, 36])
    introcs.assert_equals([0.38, 0.94, 0.53, 0.07],
                          km2.getClusters()[0].getCentroid())
    introcs.assert_equals([0.84, 0.88, 0.04, 0.86],
                          km2.getClusters()[1].getCentroid())
    introcs.assert_equals([0.8, 0.4, 0.23, 0.33],
                          km2.getClusters()[2].getCentroid())

    print('    Seeded Algorithm initialization looks okay')
    print('  Part A of class Algorithm appears correct')
    print()
Example #9
0
def testD():
    """
    Test for part D
    """
    #-----------tests for iscurrency------------------------------------------------
    value1 = pro.iscurrency('USD')
    introcs.assert_true(value1)

    value2 = pro.iscurrency('GHS')
    introcs.assert_true(value2)

    value3 = pro.iscurrency('EUR')
    introcs.assert_true(value3)

    value4 = pro.iscurrency('CAD')
    introcs.assert_true(value4)

    #--------------------tests for exchange-----------------------------------------

    compare1 = pro.exchange('USD', 'GHS', 256.84)
    introcs.assert_floats_equal(compare1, 1279.0632)

    compare2 = pro.exchange('EUR', 'CAD', -0.96)
    introcs.assert_floats_equal(compare2, -1.4492613128365)

    compare3 = pro.exchange('CAD', 'GHS', 1200.01)
    introcs.assert_floats_equal(compare3, 4543.3533104394)

    compare4 = pro.exchange('EUR', 'USD', 780.98)
    introcs.assert_floats_equal(compare4, 896.35012033895)
Example #10
0
def test_read_csv():
    """
    Test procedure for the function read_csv()
    """
    print('Testing read_csv()')

    # Access the file relative to this one, not the user's terminal
    parent = os.path.split(__file__)[0]

    # First test
    fpath = os.path.join(parent, 'files', 'readcsv1.csv')
    table = func.read_csv(fpath)

    introcs.assert_equals(type(table), list)
    introcs.assert_true(len(table) > 0 and type(table[0]) == list)
    introcs.assert_true(len(table[0]) > 0 and type(table[0][0]) == str)
    introcs.assert_equals(table, FILE1)

    # Second test
    fpath = os.path.join(parent, 'files', 'readcsv2.csv')
    table = func.read_csv(fpath)

    introcs.assert_equals(type(table), list)
    introcs.assert_true(len(table) > 0 and type(table[0]) == list)
    introcs.assert_true(len(table[0]) > 0 and type(table[0][0]) == str)
    introcs.assert_equals(table, FILE2)
Example #11
0
def test_pixel_list():
    """
    Tests the precondition helper _is_pixel_list
    """
    print('Testing helper _is_pixel_list')
    introcs.assert_false(a6image._is_pixel_list('a'))
    introcs.assert_false(a6image._is_pixel_list((0,244,255)))
    introcs.assert_false(a6image._is_pixel_list(['a']))
    introcs.assert_true(a6image._is_pixel_list([(0,244,255)]))
    introcs.assert_false(a6image._is_pixel_list([[(0,244,255)]]))
    introcs.assert_false(a6image._is_pixel_list([(304,244,255)]))
    introcs.assert_true(a6image._is_pixel_list([(0,244,255),(100,64,255),(50,3,250)]))
    introcs.assert_false(a6image._is_pixel_list([(0,244,255),(100,'64',255),(50,3,250)]))
    introcs.assert_false(a6image._is_pixel_list([(0,244,255),(100,-64,255),(50,3,250)]))
Example #12
0
def test_files_to_dictionary():
    """
    Test loading function files_to_dictionary
    """
    files = ['colorblind/normal.dat','colorblind/tritanomaly.dat']
    maps = a2.files_to_dictionary(files)

    introcs.assert_equals(2,len(maps))
    introcs.assert_true('Normal' in maps)
    introcs.assert_true('Tritanomaly' in maps)
    introcs.assert_float_lists_equal([1,0,0],maps['Normal'][0])
    introcs.assert_float_lists_equal([0,1,0],maps['Normal'][1])
    introcs.assert_float_lists_equal([0,0,1],maps['Normal'][2])
    introcs.assert_float_lists_equal([0.967, 0.033, 0],maps['Tritanomaly'][0])
    introcs.assert_float_lists_equal([0, 0.733, 0.267],maps['Tritanomaly'][1])
    introcs.assert_float_lists_equal([0, 0.183, 0.817],maps['Tritanomaly'][2])
Example #13
0
def test_wild_init():
    """
    Tests the initializer for the WildCard objects

    This test does not require that setCode support the 'WC' code.  This is
    an optional exercise.
    """
    import wild

    # This will create an empty card if the initializer is not defined
    card = wild.WildCard(1, 12)
    introcs.assert_equals(1, card.getSuit())
    introcs.assert_equals(12, card.getRank())
    introcs.assert_equals('QD', card.getCode())
    introcs.assert_false(card.isWild())

    card = wild.WildCard(2, 11, True)
    introcs.assert_equals(2, card.getSuit())
    introcs.assert_equals(11, card.getRank())
    introcs.assert_true(card.isWild())

    card = wild.WildCard(2, 11, True, 'AS')
    introcs.assert_equals(3, card.getSuit())
    introcs.assert_equals(1, card.getRank())
    introcs.assert_false(card.isWild())

    try:
        card = wild.WildCard(5, 11, True)
        introcs.quit_with_error('initializer does not enforce preconditions')
    except:
        pass

    try:
        card = wild.WildCard(2, 0, True)
        introcs.quit_with_error('initializer does not enforce preconditions')
    except:
        pass

    try:
        card = wild.WildCard(2, 11, 3)
        introcs.quit_with_error('initializer does not enforce preconditions')
    except:
        pass

    print('The wild __init__ tests passed')
Example #14
0
def test_pair_sum():
    """
    Test procedure for the sum method in the Pair class
    """
    print('Testing class Pair (sum)')
    try:
        obj = pair.Pair(1,2)
    except:
        introcs.quit_with_error('The initializer for Pair has the wrong number of parameters')

    introcs.assert_true(hasattr(obj,'sum'))
    result = 0
    try:
        result = obj.sum()
    except:
        introcs.quit_with_error('The sum method has the wrong number of parameters')
    introcs.assert_equals(3,result)
    introcs.assert_equals(7,pair.Pair(3,4).sum())
Example #15
0
def test_pair_init():
    """
    Test procedure for the initializer in the Pair class
    """
    print('Testing class Pair (__init__)')
    try:
        result = pair.Pair(1,2)
    except:
        introcs.quit_with_error('The initializer for Pair has the wrong number of parameters')

    introcs.assert_equals(pair.Pair, type(result))
    introcs.assert_true(hasattr(result,'first'))
    introcs.assert_true(hasattr(result,'second'))
    introcs.assert_equals(1, result.first )
    introcs.assert_equals(2, result.second)

    result = pair.Pair(3,5)
    introcs.assert_equals(pair.Pair, type(result))
    introcs.assert_equals(3, result.first )
    introcs.assert_equals(5, result.second)
def test_isnetid():
    """
    Test procedure for isnetid
    """
    print('Testing isnetid()')

    result = funcs.isnetid('wmw2')
    introcs.assert_true(result)

    result = funcs.isnetid('jrs1234')
    introcs.assert_true(result)

    result = funcs.isnetid('ww9999')
    introcs.assert_true(result)

    result = funcs.isnetid('Wmw2')
    introcs.assert_false(result)

    result = funcs.isnetid('wMw2')
    introcs.assert_false(result)

    result = funcs.isnetid('wmW2')
    introcs.assert_false(result)

    result = funcs.isnetid('ww99a99')
    introcs.assert_false(result)

    result = funcs.isnetid('#w999')
    introcs.assert_false(result)

    result = funcs.isnetid('w#w999')
    introcs.assert_false(result)

    result = funcs.isnetid('ww#999')
    introcs.assert_false(result)
Example #17
0
def testD():
    """
    Test functions iscurrency(), and exchange()
    """

    #test valid currency
    introcs.assert_true(a1.is_currency("USD"))

    #test invalid currency
    introcs.assert_equals(False, a1.is_currency("ABC"))

    #test invalid currency (>3 letters)
    introcs.assert_equals(False, a1.is_currency("invalid"))

    #test invalid currency (<3 letters)
    introcs.assert_equals(False, a1.is_currency("hi"))

    #testing a valid currency to a different valid currency
    introcs.assert_equals(64.375, a1.exchange("USD", "CUP", 2.5))

    #testing a valid to itself
    introcs.assert_equals(2.5, a1.exchange("USD", "USD", 2.5))
Example #18
0
def test_wild_setters():
    """
    Tests the setters for the WildCard objects

    This test does not require that the initializer work yet.  If you still
    have pass in the initilizer, these tests should be fine.

    This test does not require that setCode support the 'WC' code.  This is
    an optional exercise.
    """
    import wild

    # This will create an empty card if the initializer is not defined
    card = wild.WildCard()

    card.setSuit(1)
    introcs.assert_equals(1, card.getSuit())
    card.setRank(3)
    introcs.assert_equals(3, card.getRank())

    card.setWild(True)
    introcs.assert_true(card.isWild())
    card.setWild(False)
    introcs.assert_false(card.isWild())

    try:
        card.setWild(5)
        introcs.quit_with_error('setWild does not enforce preconditions')
    except:
        pass

    # Check that setCode works on codes OTHER than 'WC'
    card.setCode('AS')
    introcs.assert_equals(1, card.getRank())
    introcs.assert_equals(3, card.getSuit())
    introcs.assert_equals('AS', card.getCode())

    print('The wild setter tests passed')
Example #19
0
def test_wild_code():
    """
    Tests that setCode (and the initializer) works properly for WildCard.
    """
    import wild

    # This will create an empty card if the initializer is not defined
    card = wild.WildCard()
    card.setCode('QD')
    introcs.assert_equals(1, card.getSuit())
    introcs.assert_equals(12, card.getRank())
    introcs.assert_equals('QD', card.getCode())
    introcs.assert_false(card.isWild())

    card.setCode('WC')
    introcs.assert_equals(3, card.getSuit())
    introcs.assert_equals(1, card.getRank())
    introcs.assert_equals('WC', card.getCode())
    introcs.assert_true(card.isWild())

    try:
        card.setCode(23)
        introcs.quit_with_error('setCode does not enforce preconditions')
    except:
        pass

    try:
        card.setCode('WD')
        introcs.quit_with_error('setCode does not enforce preconditions')
    except:
        pass

    card = wild.WildCard(code='QD')
    introcs.assert_equals(1, card.getSuit())
    introcs.assert_equals(12, card.getRank())
    introcs.assert_equals('QD', card.getCode())
    introcs.assert_false(card.isWild())

    card = wild.WildCard(code='WC')
    introcs.assert_equals(3, card.getSuit())
    introcs.assert_equals(1, card.getRank())
    introcs.assert_equals('WC', card.getCode())
    introcs.assert_true(card.isWild())

    card = wild.WildCard(2, 11, True)
    introcs.assert_equals(2, card.getSuit())
    introcs.assert_equals(11, card.getRank())
    introcs.assert_equals('WC', card.getCode())
    introcs.assert_true(card.isWild())

    print('The wild setCode tests passed')
Example #20
0
def test_cluster_b():
    """
    Tests Part B of the Cluster class assignment.
    """
    print('  Testing Part B of class Cluster')

    # A dataset with four points
    items = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0],
             [0.0, 0.0, 1.0]]
    dset = a6dataset.Dataset(3, items)

    # Create some clusters
    cluster1 = a6cluster.Cluster(dset, [0.0, 0.0, 0.2])
    cluster2 = a6cluster.Cluster(dset, [0.5, 0.5, 0.0])
    cluster3 = a6cluster.Cluster(dset, [0.0, 0.0, 0.5])

    # TEST CASE 1 (distance)
    dist = cluster2.distance([1.0, 0.0, -1.0])
    introcs.assert_floats_equal(1.22474487139, dist)

    # TEST CASE 2 (distance)
    dist = cluster2.distance([0.5, 0.5, 0.0])
    introcs.assert_floats_equal(0.0, dist)

    # TEST CASE 3 (distance)
    dist = cluster3.distance([0.5, 0.0, 0.5])
    introcs.assert_floats_equal(0.5, dist)
    print('    Method Cluster.distance() looks okay')

    # Add some indices
    cluster1.addIndex(0)
    cluster1.addIndex(1)
    cluster2.addIndex(0)
    cluster2.addIndex(1)
    cluster3.addIndex(0)
    cluster3.addIndex(1)
    cluster3.addIndex(2)

    # TEST CASE 1 (radius)
    rads = cluster1.getRadius()
    introcs.assert_floats_equal(1.0198039, rads)

    # TEST CASE 2 (radius)
    rads = cluster2.getRadius()
    introcs.assert_floats_equal(0.7071068, rads)

    # TEST CASE 3 (radius)
    rads = cluster3.getRadius()
    introcs.assert_floats_equal(1.1180340, rads)
    print('    Method Cluster.getRadius() looks okay')

    # TEST CASE 1 (updateCentroid): centroid remains the same
    stable = cluster2.update()
    introcs.assert_float_lists_equal([0.5, 0.5, 0.0], cluster2.getCentroid())
    introcs.assert_true(stable)

    # TEST CASE 2 (updateCentroid): centroid changes
    cluster2.addIndex(2)
    cluster2.addIndex(3)
    stable = cluster2.update()
    introcs.assert_float_lists_equal([0.25, 0.25, 0.25],
                                     cluster2.getCentroid())
    introcs.assert_false(stable)
    # updating again without changing points: centroid stable
    stable = cluster2.update()
    introcs.assert_float_lists_equal([0.25, 0.25, 0.25],
                                     cluster2.getCentroid())
    introcs.assert_true(stable)

    print('    Method Cluster.update() looks okay')
    print('  Part B of class Cluster appears correct')
    print()
Example #21
0
def test_dealerBust():
    """
    Tests the dealerBust method for Blackjack objects
    """
    # get dummy deck
    deck = [
        card.Card(0, 12),
        card.Card(2, 9),
        card.Card(1, 10),
    ]
    game = bjack.Blackjack(deck)

    introcs.assert_true(not game.dealerBust())
    game.dealerHand = [card.Card(0, 1), card.Card(1, 10)]
    introcs.assert_true(not game.dealerBust())
    game.dealerHand = [card.Card(0, 1), card.Card(1, 10), card.Card(0, 2)]
    introcs.assert_true(game.dealerBust())
    game.dealerHand = [card.Card(0, 10), card.Card(1, 10), card.Card(0, 1)]
    introcs.assert_true(game.dealerBust())
    game.dealerHand = [card.Card(0, 11), card.Card(1, 10), card.Card(0, 1)]
    introcs.assert_true(game.dealerBust())
    game.playerHand = [
        card.Card(0, 11),
        card.Card(1, 10),
        card.Card(0, 1),
        card.Card(1, 1)
    ]
    introcs.assert_true(game.playerBust())

    print('The dealerBust tests passed')
Example #22
0
p = a1.Point(3, 4)
l = a1.Line(0, 1, 0)
a1.findMirrorPoint(p, l)
assert_equals(-3.0, p.x)
assert_equals(4.0, p.y)

p = a1.Point(1, -1)
l = a1.Line(1, -1, 0)
a1.findMirrorPoint(p, l)
assert_equals(-1.0, p.x)
assert_equals(1.0, p.y)

p1 = a1.Point(3, 4)
p2 = a1.Point(2, 0)
l = a1.Line(1, -1, 0)
assert_true(a1.checkSides(p1, p2, l, l))

p1 = a1.Point(0, 0)
p2 = a1.Point(2, 0)
l1 = a1.Line(1, -1, 0)
l2 = a1.Line(0, 1, 4)
assert_true(a1.checkSides(p1, p2, l1, l2))

c1 = a1.Circle(0, 0, 5)
c2 = a1.Circle(10, 0, 5)
assert_true(a1.checkIntersection(c1, c2))

c1 = a1.Circle(0, 0, 5)
c2 = a1.Circle(10, 0, 20)
assert_false(a1.checkIntersection(c1, c2))
Example #23
0
def test_write_numbers():
    """
    Test procedure for the function write_numbers()
    """
    print('Testing write_numbers()')

    # Find the directory with this file in it
    parent = os.path.split(__file__)[0]

    # Remaining files are in 'files' folder, relative to this one

    # TEST 1
    filepath = os.path.join(parent, 'files', 'tempfile.txt')
    funcs.write_numbers(filepath, 5)

    # Check file was created
    introcs.assert_true(os.path.exists(filepath))

    file = open(filepath)
    actual = file.read()
    file.close()

    file = open(os.path.join(parent, 'files', 'writefile1.txt'))
    correct = file.read()
    file.close()

    # Check to see if they are the same
    introcs.assert_equals(correct, actual)

    # TEST 2
    filepath = os.path.join(parent, 'files', 'tempfile.txt')
    funcs.write_numbers(filepath, 16)

    # Check file was created
    introcs.assert_true(os.path.exists(filepath))

    file = open(filepath)
    actual = file.read()
    file.close()

    file = open(os.path.join(parent, 'files', 'writefile2.txt'))
    correct = file.read()
    file.close()

    # Check to see if they are the same
    introcs.assert_equals(correct, actual)

    # TEST 3
    filepath = os.path.join(parent, 'files', 'tempfile.txt')
    funcs.write_numbers(filepath, 26)

    # Check file was created
    introcs.assert_true(os.path.exists(filepath))

    file = open(filepath)
    actual = file.read()
    file.close()

    file = open(os.path.join(parent, 'files', 'writefile3.txt'))
    correct = file.read()
    file.close()

    # Check to see if they are the same
    introcs.assert_equals(correct, actual)
Example #24
0
def test_algorithm_c():
    """
    Tests Part C of the Algorithm class.
    """
    print('  Testing Part C of class Algorithm')
    items = [[0., 0.], [10., 1.], [10., 10.], [0., 9.]]
    dset = a6dataset.Dataset(2, items)
    km1 = a6algorithm.Algorithm(dset, 2, [0, 2])
    km1._partition()

    # Test update()
    stable = km1._update()
    introcs.assert_float_lists_equal([0, 4.5],
                                     km1.getClusters()[0].getCentroid())
    introcs.assert_float_lists_equal([10.0, 5.5],
                                     km1.getClusters()[1].getCentroid())
    introcs.assert_false(stable)

    # updating again should not change anything, but should return stable
    stable = km1._update()
    introcs.assert_float_lists_equal([0, 4.5],
                                     km1.getClusters()[0].getCentroid())
    introcs.assert_float_lists_equal([10.0, 5.5],
                                     km1.getClusters()[1].getCentroid())
    introcs.assert_true(stable)

    print('    Method Algorithm._update() looks okay')

    # Now test the k-means process itself.

    # FOR ALL TEST CASES
    # Create and initialize a non-empty dataset
    items = [[0.5, 0.5, 0.5], [0.5, 0.6, 0.6], [0.6, 0.5, 0.6],
             [0.5, 0.6, 0.5], [0.5, 0.4, 0.5], [0.5, 0.4, 0.4]]
    dset = a6dataset.Dataset(3, items)

    # Create a clustering, providing non-random seed indices so the test is deterministic
    km2 = a6algorithm.Algorithm(dset, 2, [1, 3])

    # PRE-TEST: Check first cluster (should be okay if passed part D)
    cluster1 = km2.getClusters()[0]
    introcs.assert_float_lists_equal([0.5, 0.6, 0.6], cluster1.getCentroid())
    introcs.assert_equals(set([]), set(cluster1.getIndices()))

    # PRE-TEST: Check second cluster (should be okay if passed part D)
    cluster2 = km2.getClusters()[1]
    introcs.assert_float_lists_equal([0.5, 0.6, 0.5], cluster2.getCentroid())
    introcs.assert_equals(set([]), set(cluster2.getIndices()))

    # Make a fake cluster to test update_centroid() method
    clustertest = a6cluster.Cluster(dset, [0.5, 0.6, 0.6])
    for ind in [1, 2]:
        clustertest.addIndex(ind)

    # TEST CASE 1 (update)
    stable = clustertest.update()
    introcs.assert_float_lists_equal([0.55, 0.55, 0.6],
                                     clustertest.getCentroid())
    introcs.assert_false(stable)  # Not yet stable

    # TEST CASE 2 (update)
    stable = clustertest.update()
    introcs.assert_float_lists_equal([0.55, 0.55, 0.6],
                                     clustertest.getCentroid())
    introcs.assert_true(stable)  # Now it is stable

    # TEST CASE 3 (step)
    km2.step()

    # Check first cluster (WHICH HAS CHANGED!)
    cluster1 = km2.getClusters()[0]
    introcs.assert_float_lists_equal([0.55, 0.55, 0.6], cluster1.getCentroid())
    introcs.assert_equals(set([1, 2]), set(cluster1.getIndices()))

    # Check second cluster (WHICH HAS CHANGED!)
    cluster2 = km2.getClusters()[1]
    introcs.assert_float_lists_equal([0.5, 0.475, 0.475],
                                     cluster2.getCentroid())
    introcs.assert_equals(set([0, 3, 4, 5]), set(cluster2.getIndices()))

    # TEST CASE 3 (step)
    km2.step()

    # Check first cluster (WHICH HAS CHANGED!)
    cluster1 = km2.getClusters()[0]
    introcs.assert_float_lists_equal([8. / 15, 17. / 30, 17. / 30],
                                     cluster1.getCentroid())
    introcs.assert_equals(set([1, 2, 3]), set(cluster1.getIndices()))

    # Check second cluster (WHICH HAS CHANGED!)
    cluster2 = km2.getClusters()[1]
    introcs.assert_float_lists_equal([0.5, 13. / 30, 14. / 30],
                                     cluster2.getCentroid())
    introcs.assert_equals(set([0, 4, 5]), set(cluster2.getIndices()))

    # Try it on a file
    file = os.path.join(os.path.split(__file__)[0], TEST_FILE)
    data = a6dataset.Dataset(4, tools.data_for_file(file))
    km3 = a6algorithm.Algorithm(data, 3, [23, 54, 36])
    km3.step()

    # The actual results
    cluster0 = km3.getClusters()[0]
    cluster1 = km3.getClusters()[1]
    cluster2 = km3.getClusters()[2]

    # The "correct" answers
    contents0 = [[0.88, 0.84, 0.8, 0.3], [0.02, 0.67, 0.75, 0.61],
                 [0.2, 0.54, 0.73, 0.85], [0.62, 0.75, 0.65, 0.43],
                 [0.35, 0.63, 0.65, 0.12], [0.61, 0.85, 0.81, 0.44],
                 [0.95, 0.94, 0.98, 0.69], [0.04, 0.69, 0.38, 0.39],
                 [0.04, 0.52, 0.99, 0.75], [0.28, 0.91, 0.63, 0.08],
                 [0.14, 0.55, 0.67, 0.63], [0.38, 0.94, 0.53, 0.07],
                 [0.08, 0.62, 0.32, 0.27], [0.69, 0.82, 0.75, 0.65],
                 [0.84, 0.89, 0.91, 0.38], [0.22, 0.88, 0.39, 0.33],
                 [0.39, 0.38, 0.85, 0.32], [0.26, 0.39, 0.95, 0.63],
                 [0.15, 0.87, 0.62, 0.22], [0.65, 0.81, 0.69, 0.55],
                 [0.27, 0.63, 0.69, 0.39], [0.35, 0.7, 0.41, 0.15],
                 [0.2, 0.48, 0.98, 0.84], [0.76, 0.86, 0.74, 0.61],
                 [0.27, 0.65, 0.52, 0.28], [0.86, 0.91, 0.88, 0.62],
                 [0.1, 0.79, 0.5, 0.12], [0.09, 0.85, 0.55, 0.21],
                 [0.79, 0.94, 0.83, 0.48], [0.73, 0.92, 0.74, 0.39],
                 [0.31, 0.5, 0.87, 0.85], [0.39, 0.9, 0.52, 0.26],
                 [0.46, 0.35, 0.96, 0.05], [0.21, 0.62, 0.33, 0.09],
                 [0.58, 0.37, 0.9, 0.08], [0.54, 0.92, 0.36, 0.35],
                 [0.36, 0.64, 0.57, 0.26], [0.09, 0.47, 0.63, 0.8],
                 [0.4, 0.69, 0.74, 0.7]]
    contents1 = [[0.32, 0.87, 0.14, 0.68], [0.87, 0.99, 0.2, 0.8],
                 [0.86, 0.86, 0.32, 0.88], [0.81, 0.66, 0.26, 0.82],
                 [0.91, 0.98, 0.61, 0.58], [0.84, 0.88, 0.04, 0.86],
                 [0.8, 0.62, 0.09, 0.65], [0.72, 0.88, 0.02, 0.95],
                 [0.88, 0.96, 0.09, 0.88]]
    contents2 = [[0.4, 0.21, 0.78, 0.68], [0.54, 0.06, 0.81, 0.98],
                 [0.73, 0.31, 0.15, 0.08], [0.81, 0.69, 0.65, 0.65],
                 [0.14, 0.31, 0.86, 0.74], [0.77, 0.45, 0.31, 0.31],
                 [0.39, 0.14, 0.99, 0.24], [0.23, 0.32, 0.7, 0.75],
                 [0.65, 0.05, 0.39, 0.49], [0.96, 0.09, 0.49, 0.3],
                 [0.86, 0.03, 0.3, 0.39], [0.5, 0.2, 0.69, 0.95],
                 [0.79, 0.09, 0.41, 0.69], [0.4, 0.3, 0.78, 0.74],
                 [0.65, 0.24, 0.63, 0.27], [0.35, 0.3, 0.94, 0.92],
                 [0.71, 0.78, 0.64, 0.57], [0.8, 0.4, 0.23, 0.33],
                 [0.38, 0.07, 0.82, 0.01], [0.66, 0.09, 0.69, 0.46],
                 [0.54, 0.06, 0.74, 0.86], [0.95, 0.62, 0.28, 0.01],
                 [0.35, 0.71, 0.01, 0.32], [0.62, 0.24, 0.77, 0.17],
                 [0.73, 0.65, 0.23, 0.02], [0.27, 0.38, 0.76, 0.63],
                 [0.9, 0.63, 0.83, 0.6], [0.7, 0.04, 0.7, 0.82],
                 [0.95, 0.83, 0.64, 0.5], [0.41, 0.11, 0.61, 0.78],
                 [0.22, 0.44, 0.67, 0.99], [0.51, 0.05, 0.95, 0.66],
                 [0.99, 0.68, 0.8, 0.42], [0.72, 0.55, 0.1, 0.17],
                 [0.44, 0.1, 0.61, 0.98], [0.31, 0.16, 0.95, 0.9],
                 [0.61, 0.42, 0.24, 0.33], [0.89, 0.72, 0.78, 0.38],
                 [0.5, 0.09, 0.84, 0.78], [0.62, 0.01, 0.88, 0.1],
                 [0.44, 0.28, 0.88, 0.99], [0.57, 0.23, 0.6, 0.85],
                 [0.9, 0.05, 0.34, 0.41], [0.9, 0.41, 0.27, 0.36],
                 [0.67, 0.32, 0.66, 0.2], [0.72, 0.14, 0.63, 0.37],
                 [0.39, 0.08, 0.77, 0.96], [0.9, 0.7, 0.74, 0.63],
                 [0.63, 0.05, 0.52, 0.63], [0.62, 0.27, 0.67, 0.77],
                 [0.35, 0.04, 0.85, 0.86], [0.36, 0.34, 0.75, 0.37]]
    centroid0 = [
        0.3987179487179487, 0.7097435897435899, 0.6864102564102561,
        0.4164102564102565
    ]
    centroid1 = [
        0.7788888888888889, 0.8555555555555555, 0.19666666666666668,
        0.788888888888889
    ]
    centroid2 = [
        0.6038461538461538, 0.29865384615384616, 0.6217307692307692,
        0.5455769230769231
    ]

    introcs.assert_float_lists_equal(centroid0, cluster0.getCentroid())
    introcs.assert_float_lists_equal(centroid1, cluster1.getCentroid())
    introcs.assert_float_lists_equal(centroid2, cluster2.getCentroid())
    assert_point_sets_equal(contents0, cluster0.getContents())
    assert_point_sets_equal(contents1, cluster1.getContents())
    assert_point_sets_equal(contents2, cluster2.getContents())

    print('    Method Algorithm.step looks okay')
    print('  Part C of class Algorithm appears correct')
    print()
Example #25
0
def test_algorithm_b():
    """
    Tests Part B of the Algorithm class.
    s"""
    # This function tests the methods _nearest and _partition, both of which are hidden
    # methods.  Normally it's not good form to directly call these methods from outside
    # the class, but we make an exception for testing code, which often has to be more
    # tightly integrated with the implementation of a class than other code that just
    # uses the class.
    print('  Testing Part B of class Algorithm')
    # Reinitialize data set
    items = [[0., 0.], [10., 1.], [10., 10.], [0., 9.]]
    dset = a6dataset.Dataset(2, items)
    km1 = a6algorithm.Algorithm(dset, 2, [0, 2])
    km2 = a6algorithm.Algorithm(dset, 3, [0, 2, 3])

    nearest = km1._nearest([1., 1.])
    introcs.assert_true(nearest is km1.getClusters()[0])

    nearest = km1._nearest([1., 10.])
    introcs.assert_true(nearest is km1.getClusters()[1])

    nearest = km2._nearest([1., 1.])
    introcs.assert_true(nearest is km2.getClusters()[0])

    nearest = km2._nearest([1., 10.])
    introcs.assert_true(nearest is km2.getClusters()[2])
    print('    Method Algorithm._nearest() looks okay')

    # Testing partition()
    # For this example points 0 and 3 are closer, as are 1 and 2
    km1._partition()
    introcs.assert_equals(set([0, 3]), set(km1.getClusters()[0].getIndices()))
    introcs.assert_equals(set([1, 2]), set(km1.getClusters()[1].getIndices()))
    # partition and repeat -- should not change clusters.
    km1._partition()
    introcs.assert_equals(set([0, 3]), set(km1.getClusters()[0].getIndices()))
    introcs.assert_equals(set([1, 2]), set(km1.getClusters()[1].getIndices()))

    # Reset the cluster centroids; now it changes
    cluster = km1.getClusters()
    cluster[0]._centroid = [5.0, 10.0]
    cluster[1]._centroid = [0.0, 2.0]
    km1._partition()
    introcs.assert_equals(set([2, 3]), set(km1.getClusters()[0].getIndices()))
    introcs.assert_equals(set([0, 1]), set(km1.getClusters()[1].getIndices()))

    # Try it on a file
    index1 = [
        2, 3, 5, 9, 11, 15, 16, 18, 19, 20, 22, 23, 29, 30, 32, 33, 37, 40, 41,
        42, 44, 45, 50, 60, 61, 62, 64, 69, 71, 73, 75, 76, 78, 80, 85, 88, 90,
        94, 97
    ]
    index2 = [0, 34, 8, 43, 66, 46, 77, 84, 54]
    index3 = [
        1, 4, 6, 7, 10, 12, 13, 14, 17, 21, 24, 25, 26, 27, 28, 31, 35, 36, 38,
        39, 47, 48, 49, 51, 52, 53, 55, 56, 57, 58, 59, 63, 65, 67, 68, 70, 72,
        74, 79, 81, 82, 83, 86, 87, 89, 91, 92, 93, 95, 96, 98, 99
    ]

    file = os.path.join(os.path.split(__file__)[0], TEST_FILE)
    data = a6dataset.Dataset(4, tools.data_for_file(file))
    km3 = a6algorithm.Algorithm(data, 3, [23, 54, 36])
    km3._partition()
    introcs.assert_equals(set(index1), set(km3.getClusters()[0].getIndices()))
    introcs.assert_equals(set(index2), set(km3.getClusters()[1].getIndices()))
    introcs.assert_equals(set(index3), set(km3.getClusters()[2].getIndices()))

    print('    Method Algorithm._partition() looks okay')
    print('  Part B of class Algorithm appears correct')
    print()