Ejemplo n.º 1
0
        ) == vector.to_tuple()

    def _ijk(self, vector):
        i = self.y * vector.z - self.z * vector.y
        j = self.z * vector.x - self.x * vector.z
        k = self.x * vector.y - self.y * vector.x
        return (i, j, k)

    def cross(self, vector):
        return Vector(self._ijk(vector))

    def dot(self, vector):
        return self.x * vector.x + self.y * vector.y + self.z * vector.z


test.describe("Basic tests")

examples = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

test.it("Both initializiations should result in the same vector")
test.assert_equals(Vector(examples[0]), Vector(*examples[0]))
test.it("Should correctly display coordinates")
v = Vector(examples[1])
test.assert_equals(v.x, 4)
test.assert_equals(v.y, 5)
test.assert_equals(v.z, 6)
# test.it("Should correctly calculate magnitude")
# test.assert_approx_equals(Vector(examples[0]).magnitude, 3.741, 0.001)
test.it("Should handle array representation")
test.assert_equals(Vector(examples[2]).to_tuple(), tuple(examples[2]))
test.it("Should handle string representation")
Ejemplo n.º 2
0
                val = sol.pop()
                puzzle[r][c] = val
                row_remains[r].remove(val)
                col_remains[c].remove(val)
                box_remains[3 * (r // 3) + c // 3].remove(val)
                unknown.remove((r, c))
                found = True
        assert found, "Deduction failed"

    return puzzle


if __name__ == '__main__':
    from test import Test

    Test.describe('Sudoku')

    puzzle = [[5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0],
              [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3],
              [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6],
              [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5],
              [0, 0, 0, 0, 8, 0, 0, 7, 9]]

    solution = [[5, 3, 4, 6, 7, 8, 9, 1, 2], [6, 7, 2, 1, 9, 5, 3, 4, 8],
                [1, 9, 8, 3, 4, 2, 5, 6, 7], [8, 5, 9, 7, 6, 1, 4, 2, 3],
                [4, 2, 6, 8, 5, 3, 7, 9, 1], [7, 1, 3, 9, 2, 4, 8, 5, 6],
                [9, 6, 1, 5, 3, 7, 2, 8, 4], [2, 8, 7, 4, 1, 9, 6, 3, 5],
                [3, 4, 5, 2, 8, 6, 1, 7, 9]]

    Test.it('Puzzle 1')
    Test.assert_equals(
Ejemplo n.º 3
0
    for r in range(rows):
        for c in range(columns):
            edges = []
            for dr, dc in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
                new_r, new_c = r + dr, c + dc
                if 0 <= new_r < rows and 0 <= new_c < columns and is_connected(r, c, new_r, new_c):
                    edges.append(new_r * columns + new_c)
            res.append(edges)

    return res


if __name__ == '__main__':
    from test import Test as test

    test.describe('Example Test Cases')
    test.assert_equals(components('''\
    +--+--+--+
    |  |  |  |
    +--+--+--+
    |  |  |  |
    +--+--+--+'''), [(1, 6)])

    test.assert_equals(components('''\
    +--+--+--+
    |  |     |
    +  +  +--+
    |  |  |  |
    +--+--+--+'''), [(3, 1), (2, 1), (1, 1)])

    test.assert_equals(components('''\
Ejemplo n.º 4
0
        result.add(string[1] + string[0])

    elif len(string) > 2:
        for i, c in enumerate(string):
            for s in permutations(string[:i] + string[i + 1:]):
                result.add(c + s)

    return list(result)


"""
Unit Test
"""
from test import Test

Test.describe('Basic tests')
Test.it('unique letters')
Test.assert_equals(sorted(permutations('a')), ['a'])
Test.assert_equals(sorted(permutations('ab')), ['ab', 'ba'])
Test.assert_equals(sorted(permutations('abc')),
                   ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'])

abcd = [
    'abcd', 'abdc', 'acbd', 'acdb', 'adbc', 'adcb', 'bacd', 'badc', 'bcad',
    'bcda', 'bdac', 'bdca', 'cabd', 'cadb', 'cbad', 'cbda', 'cdab', 'cdba',
    'dabc', 'dacb', 'dbac', 'dbca', 'dcab', 'dcba'
]
Test.assert_equals(sorted(permutations('abcd')), abcd)
Test.assert_equals(sorted(permutations('bcad')), abcd)
Test.assert_equals(sorted(permutations('dcba')), abcd)
Test.it('duplicate letters')
Ejemplo n.º 5
0
def update_state(state: State, change: Change):
    for (r, c), val in change.items():
        if state.board[r][c] == 0:
            state.board[r][c] = val
            state.remaining[('r', r)].remove(val)
            state.remaining[('c', c)].remove(val)


def revert_state(state, change: Change):
    for (r, c), val in change.items():
        state.board[r][c] = 0
        state.remaining[('r', r)].add(val)
        state.remaining[('c', c)].add(val)


if __name__ == '__main__':
    from test import Test as test

    clues = ((2, 2, 1, 3, 2, 2, 3, 1, 1, 2, 2, 3, 3, 2, 1, 3),
             (0, 0, 1, 2, 0, 2, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0))

    outcomes = (((1, 3, 4, 2), (4, 2, 1, 3), (3, 4, 2, 1), (2, 1, 3, 4)),
                ((2, 1, 4, 3), (3, 4, 1, 2), (4, 2, 3, 1), (1, 3, 2, 4)))

    test.describe("4 by 4 skyscrapers")
    test.it("should pass all the tests provided")

    test.assert_equals(solve_puzzle(clues[0]), outcomes[0])
    test.assert_equals(solve_puzzle(clues[1]), outcomes[1])
Ejemplo n.º 6
0
        return ''

    reverse_code = {code: letter for letter, code in freqs_to_code(freqs)}
    res = []
    i = 0
    for j in range(1, len(bits) + 1):
        if bits[i:j] in reverse_code:
            res.append(reverse_code[bits[i:j]])
            i = j
    return ''.join(res)


if __name__ == '__main__':
    from test import Test as test

    test.describe("basic tests")
    fs = frequencies("aaaabcc")
    test.it("aaaabcc encoded should have length 10")

    def test_len(res):
        test.assert_not_equals(res, None)
        test.assert_equals(len(res), 10)

    test_len(encode(fs, "aaaabcc"))

    test.it("empty list encode")
    test.assert_equals(encode(fs, []), '')

    test.it("empty list decode")
    test.assert_equals(decode(fs, []), '')
Ejemplo n.º 7
0
# https://www.codewars.com/kata/5270d0d18625160ada0000e4/train/python
from test import Test


def score(dice):
    counts = {x: 0 for x in range(1, 7)}
    result = 0

    for n in dice:
        counts[n] += 1
    for x, n in counts.items():
        if n >= 3 and x == 1:
            result += 1000
            result += (n - 3) * 100
        elif n >= 3:
            result += x * 100
            if x == 5:
                result += (n - 3) * 50
        elif x == 1:
            result += n * 100
        elif x == 5:
            result += n * 50
    return result


Test.describe("Example Tests")
Test.it("Example Case")
Test.assert_equals(score([2, 3, 4, 6, 2]), 0)
Test.assert_equals(score([4, 4, 4, 3, 3]), 400)
Test.assert_equals(score([2, 4, 4, 5, 4]), 450)
Ejemplo n.º 8
0
# https://www.codewars.com/kata/54521e9ec8e60bc4de000d6c/train/python

from test import Test


def max_sequence(param):
    maxl = 0
    maxg = 0
    for n in param:
        maxl = max(0, maxl + n)
        maxg = max(maxg, maxl)
    return maxg


Test.describe("Tests")
Test.it('should work on an empty array')
Test.assert_equals(max_sequence([]), 0)
Test.it('should work on the example')
Test.assert_equals(max_sequence([-2, 1, -3, 4, -1, 2, 1, -5, 4]), 6)
Ejemplo n.º 9
0
# https://www.codewars.com/kata/58708934a44cfccca60000c4/train/python
from test import Test
import re


def highlight(code):
    code = re.sub(r"(F+)", '<span style="color: pink">\g<1></span>', code)
    code = re.sub(r"(L+)", '<span style="color: red">\g<1></span>', code)
    code = re.sub(r"(R+)", '<span style="color: green">\g<1></span>', code)
    code = re.sub(r"(\d+)", '<span style="color: orange">\g<1></span>', code)
    return code


Test.describe("Your Syntax Highlighter")
Test.it("should work for the examples provided in the description")
print("Code without syntax highlighting: F3RF5LF7")
print("Your code with syntax highlighting: " + highlight("F3RF5LF7"))
print(
    'Expected syntax highlighting: <span style="color: pink">F</span><span style="color: orange">3</span><span style="color: green">R</span><span style="color: pink">F</span><span style="color: orange">5</span><span style="color: red">L</span><span style="color: pink">F</span><span style="color: orange">7</span>'
)
Test.assert_equals(
    highlight("F3RF5LF7"),
    '<span style="color: pink">F</span><span style="color: orange">3</span><span style="color: green">R</span><span style="color: pink">F</span><span style="color: orange">5</span><span style="color: red">L</span><span style="color: pink">F</span><span style="color: orange">7</span>'
)
print("Code without syntax highlighting: FFFR345F2LL")
print("Your code with syntax highlighting: " + highlight("FFFR345F2LL"))
print(
    'Expected syntax highlighting: <span style="color: pink">FFF</span><span style="color: green">R</span><span style="color: orange">345</span><span style="color: pink">F</span><span style="color: orange">2</span><span style="color: red">LL</span>'
)
Test.assert_equals(
    highlight("FFFR345F2LL"),
Ejemplo n.º 10
0
individual integers
or a range of integers denoted by the starting integer separated from the end integer in the range by a dash, '-'. The range includes all integers in the interval including both endpoints. It is not considered a range unless it spans at least 3 numbers. For example ("12, 13, 15-17")
Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format.

Example:

solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20])
# returns "-6,-3-1,3-5,7-11,14,15,17-20"
"""


def solution(args):
    return ''


"""
Unit Test
"""
from test import Test

Test.describe("Sample Test Cases")

Test.it("Simple Tests")
Test.assert_equals(
    solution([
        -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20
    ]), '-6,-3-1,3-5,7-11,14,15,17-20')
Test.assert_equals(solution([-3, -2, -1, 2, 10, 15, 16, 18, 19, 20]),
                   '-3--1,2,10,15,16,18-20')
# https://www.codewars.com/kata/52f787eb172a8b4ae1000a34/train/python
from math import log

from test import Test


def zeros(n):
    if n == 0:
        return 0

    count = 0
    for i in range(int(log(n, 5))):
        count += n // 5**(i + 1)
    return count


Test.describe("Sample Tests")
Test.it("Should pass sample tests")
Test.assert_equals(zeros(0), 0, "Testing with n = 0")
Test.assert_equals(zeros(6), 1, "Testing with n = 6")
Test.assert_equals(zeros(30), 7, "Testing with n = 30")
Ejemplo n.º 12
0
        return Getattr(update)

    def __getattr__(self, item):
        if item.startswith("is_a_"):
            return item[len("is_a_"):] in self._is
        elif item.startswith("is_"):
            return item[len("is_"):] == self.name
        elif item in self._has:
            return self._has[item]


if __name__ == '__main__':
    from test import Test as test

    jane = Thing('Jane')
    test.describe('jane =  Thing("Jane")')
    test.describe('jane.name')
    test.it('should be "Jane"')
    test.assert_equals(jane.name, 'Jane')

    test.describe('#is_a')
    test.describe('is_a.woman (dynamic key)')
    jane.is_a.woman
    test.it('jane.is_a_woman should return true')
    test.assert_equals(jane.is_a_woman, True)

    test.describe('#is_not_a')
    test.describe('is_not_a.man (dynamic key)')
    jane.is_not_a.man
    test.it('jane.is_a_man should return false')
    test.assert_equals(jane.is_a_man, False)
Ejemplo n.º 13
0
            break
        else:
            seen.add(pos)
            if all(p in floor for p in pos):
                for move in "RDLU":
                    new_pos = move_pos(pos, move)
                    if new_pos not in seen:
                        q.append((new_pos, moves + move))

    return res


if __name__ == '__main__':
    from test import Test as test

    test.describe('Example Tests')
    example_tests = [[
        '1110000000', '1B11110000', '1111111110', '0111111111', '0000011X11',
        '0000001110'
    ],
                     [
                         '000000111111100', '111100111001100',
                         '111111111001111', '1B11000000011X1',
                         '111100000001111', '000000000000111'
                     ],
                     [
                         '00011111110000', '00011111110000', '11110000011100',
                         '11100000001100', '11100000001100', '1B100111111111',
                         '11100111111111', '000001X1001111', '00000111001111'
                     ],
                     [
Ejemplo n.º 14
0
            state.remaining[('r', r)].remove(val)
            state.remaining[('c', c)].remove(val)


def revert_state(state, change: Change):
    for (r, c), val in change.items():
        state.board[r][c] = 0
        state.remaining[('r', r)].add(val)
        state.remaining[('c', c)].add(val)


if __name__ == '__main__':
    from test import Test
    import time

    Test.describe("Skyscrapers")
    Test.it("can solve 6x6 puzzle 1")
    clues = (3, 2, 2, 3, 2, 1, 1, 2, 3, 3, 2, 2, 5, 1, 2, 2, 4, 3, 3, 2, 1, 2,
             2, 4)

    expected = ((2, 1, 4, 3, 5, 6), (1, 6, 3, 2, 4, 5), (4, 3, 6, 5, 1, 2),
                (6, 5, 2, 1, 3, 4), (5, 4, 1, 6, 2, 3), (3, 2, 5, 4, 6, 1))

    start = time.time()
    actual = solve_puzzle(clues)
    duration = time.time() - start
    print(duration)
    Test.assert_equals(actual, expected)

    Test.it("can solve 6x6 puzzle 2")
    clues = (0, 0, 0, 2, 2, 0, 0, 0, 0, 6, 3, 0, 0, 4, 0, 0, 0, 0, 4, 4, 0, 3,