Пример #1
0
            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('''\
    +--+--+--+
    |  |     |
    +  +  +--+
    |        |
Пример #2
0
        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")
test.assert_equals(str(Vector(examples[1])), "<4, 5, 6>")
test.it("Should handle addition")
test.assert_equals(Vector(examples[0]) + Vector(*examples[1]), Vector(5, 7, 9))
test.it("Should handle subtraction")
test.assert_equals(
    def __getitem__(self, item):
        return self.values.pop(item)

    def __len__(self):
        return len(self.values)

    def __repr__(self):
        return self._print()

    def __str__(self):
        return self._print()

    def _print(self):
        values = self.values
        self.values = []
        return f"[{', '.join(map(str, values))}]"


base = [1, 2, 3, 4]
a = SecureList(base)

Test.assert_equals(a[0], base[0], "List returned wrong value.")
Test.assert_equals(a[0], base[1], "List returned wrong value.")
Test.assert_equals(len(a), 2, "List hasn't deleted it's items once accessed")
print("current List: %s" % a)
Test.assert_equals(len(a), 0, "List Should be empty after printing")
a = SecureList(base)
print("current List: %r" % a)
Test.assert_equals(len(a), 0,
                   "List Should be empty after printing a representation")
Пример #4
0
foo0042 -> foo0043

foo9 -> foo10

foo099 -> foo100
"""

import re


def increment_string(strng):
    if re.findall(r'\d+', strng):
        num = re.findall(r'\d+', strng)[-1]
        return strng.split(num)[0] + str(int(num) + 1).zfill(len(num))
    else:
        return strng + '1'


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

Test.assert_equals(increment_string("foo"), "foo1")
Test.assert_equals(increment_string("foobar001"), "foobar002")
Test.assert_equals(increment_string("foobar1"), "foobar2")
Test.assert_equals(increment_string("foobar00"), "foobar01")
Test.assert_equals(increment_string("foobar99"), "foobar100")
Test.assert_equals(increment_string("foobar099"), "foobar100")
Test.assert_equals(increment_string(""), "1")
"abcde" -> 0 # no characters repeats more than once
"aabbcde" -> 2 # 'a' and 'b'
"aabbcdeB" -> 2 # 'a' and 'b'
"indivisibility" -> 1 # 'i'
"Indivisibilities" -> 2 # 'i' and 's'
'''


# first attempt
def duplicate_count2(text):
    k = 0
    for c in set(text.lower()):
        if text.lower().count(c) > 1:
            k += 1
    return k


# refined
def duplicate_count(text):
    return len([c for c in set(text.lower()) if text.lower().count(c) > 1])


test = Test()
test.assert_equals(duplicate_count("abcde"), 0)
test.assert_equals(duplicate_count("abcdea"), 1)
test.assert_equals(duplicate_count("indivisibility"), 1)
test.assert_equals(duplicate_count("Indivisibilities"), 2)
test.assert_equals(duplicate_count("Doggydog"), 3)
test.report()
# https://www.codewars.com/kata/58ab2ed1acbab2eacc00010e/train/python
import re
from urllib.request import urlopen

from bs4 import BeautifulSoup

from test import Test


def get_member_since(username: str) -> str:
    response = urlopen(f'https://www.codewars.com/users/{username}')
    soup = BeautifulSoup(response.read(), 'html.parser')
    since = soup.select_one(
        'div.flex-box > div:nth-of-type(2) > div:nth-of-type(1)').text
    since = re.findall(r':([\w\s]+)$', since)
    return since[0]


Test.assert_equals(get_member_since('jhoffner'), 'Oct 2012')
Пример #7
0
# https://www.codewars.com/kata/550f22f4d758534c1100025a/train/python
from test import Test


def dirReduc(arr):
    compass = ['NORTH', 'EAST', 'SOUTH', 'WEST']
    stack = []
    for direction in arr:
        reversed_direction = compass[compass.index(direction) - 2]
        if stack and stack[-1] == reversed_direction:
            stack.pop(-1)
        else:
            stack.append(direction)
    return stack


a = ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"]
Test.assert_equals(dirReduc(a), ['WEST'])
u = ["NORTH", "WEST", "SOUTH", "EAST"]
Test.assert_equals(dirReduc(u), ["NORTH", "WEST", "SOUTH", "EAST"])
Пример #8
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])
Пример #9
0
 def test_len(res):
     test.assert_not_equals(res, None)
     test.assert_equals(len(res), 10)
Пример #10
0
    def test_enc_len(fs, strs, lens):
        def enc_len(s):
            return len(encode(fs, s))

        test.assert_equals(list(map(enc_len, strs)), lens)
Пример #11
0
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, []), '')

    def test_enc_len(fs, strs, lens):
        def enc_len(s):
            return len(encode(fs, s))

        test.assert_equals(list(map(enc_len, strs)), lens)

    test.describe("length")
    test.it(
        "equal lengths with same frequencies if alphabet size is a power of two"
    )
    test_enc_len([('a', 1), ('b', 1)], ["a", "b"], [1, 1])
Пример #12
0
from test import Test
'''
Description:

Trolls are attacking your comment section!

A common way to deal with this situation is to remove all of the vowels from the trolls' comments, neutralizing the threat.

Your task is to write a function that takes a string and return a new string with all vowels removed.

For example, the string "This website is for losers LOL!" would become "Ths wbst s fr lsrs LL!".
'''


# Refined solution
def disemvowel(string):
    return ''.join([letter for letter in string if letter.lower() not in 'aeiou'])


test = Test()
test.assert_equals(disemvowel("This website is for losers LOL!"), "Ths wbst s fr lsrs LL!",)
test.report()
Пример #13
0

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"),
    '<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>'
)
Пример #14
0
# https://www.codewars.com/kata/the-hashtag-generator/train/python
from test import Test


def generate_hashtag(s):
    words = s.split()
    result = f'#{"".join([word.capitalize() for word in words])}'
    if 1 < len(result) <= 140:
        return result
    else:
        return False


Test.describe("Basic tests")
Test.assert_equals(generate_hashtag(''), False,
                   'Expected an empty string to return False')
Test.assert_equals(
    generate_hashtag('Do We have A Hashtag')[0], '#',
    'Expeted a Hashtag (#) at the beginning.')
Test.assert_equals(generate_hashtag('Codewars'), '#Codewars',
                   'Should handle a single word.')
Test.assert_equals(generate_hashtag('Codewars      '), '#Codewars',
                   'Should handle trailing whitespace.')
Test.assert_equals(generate_hashtag('Codewars Is Nice'), '#CodewarsIsNice',
                   'Should remove spaces.')
Test.assert_equals(generate_hashtag('codewars is nice'), '#CodewarsIsNice',
                   'Should capitalize first letters of words.')
Test.assert_equals(
    generate_hashtag('CodeWars is nice'), '#CodewarsIsNice',
    'Should capitalize all letters of words - all lower case but the first.')
Test.assert_equals(
Пример #15
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)
Пример #16
0
# https://www.codewars.com/kata/520b9d2ad5c005041100000f/train/python
from test import Test


def pig_it(text: str):
    result = []
    words = text.split()
    for word in words:
        if word.isalpha():
            result.append(f'{word[1:]}{word[0]}ay')
        else:
            result.append(word)
    return ' '.join(result)


Test.assert_equals(pig_it('Pig latin is cool'), 'igPay atinlay siay oolcay')
Test.assert_equals(pig_it('This is my string'), 'hisTay siay ymay tringsay')
Test.assert_equals(pig_it('Hello world !'), 'elloHay orldway !')
Пример #17
0
# https://www.codewars.com/kata/5390bac347d09b7da40006f6/train/python

from test import Test


def to_jaden_case(string):
    return ' '.join(map(str.capitalize, string.split()))



quote = "How can mirrors be real if our eyes aren't real"
Test.assert_equals(to_jaden_case(quote), "How Can Mirrors Be Real If Our Eyes Aren't Real")
Пример #18
0
                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(
        sudoku(puzzle), solution,
        "Incorrect solution for the following puzzle: " + str(puzzle))
Пример #19
0
        elif not c.isspace():  # Paren or letter
            if not q and c != ')':
                q.append('1')

            if q:
                if not q[-1].isnumeric():
                    q.append('1')
                yield int(''.join(q))
                q.clear()

            yield c


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

    examples = [["a + a = b", "b - d = c", "a + b = d"],
                ["a + 3g = k", "-70a = g"], ["-j -j -j + j = b"]]
    formula = ["c + a + b", "-k + a", "-j - b"]
    answer = ["2a", "210a", "1j"]

    for i in range(len(answer)):
        print('examples:' + str(examples[i]))
        print('formula:' + str(formula[i]))
        print('expected answer:' + str(answer[i]))
        Test.assert_equals(simplify(examples[i], formula[i]), answer[i])

    Test.assert_equals(
        simplify(['(-3f + q) + r = l', '4f + q = r', '-10f = q'],
                 '20l + 20(q - 200f)'), '-4580f')
Пример #20
0
# https://www.codewars.com/kata/5254ca2719453dcc0b00027d/train/python
import itertools

from test import Test


def permutations(string: str) -> map:
    return map(''.join, set(itertools.permutations(string)))


Test.assert_equals(sorted(permutations('a')), ['a'])
Test.assert_equals(sorted(permutations('ab')), ['ab', 'ba'])
Test.assert_equals(sorted(permutations('aabb')),
                   ['aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa'])
    res = []
    if len(cards) == 2 and cards[0].suit == cards[1].suit:
        min_rank = min(cards[0].rank, cards[1].rank)
        max_rank = max(cards[0].rank, cards[1].rank)
        if max_rank - min_rank == 0:
            res.append(Card(min_rank, cards[0].suit))
        elif cards[0].suit != 'z' and max_rank - min_rank == 1:
            res.append(Card(min_rank - 1, cards[0].suit))
            res.append(Card(max_rank + 1, cards[0].suit))
        elif cards[0].suit != 'z' and max_rank - min_rank == 2:
            res.append(Card(min_rank + 1, cards[0].suit))
    return res


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

    # You may add more custom tests here :)
    cases = [
        ('2p 2p 3p 3p 4p 4p 5p 5p 7m 7m 8m 8m 8m', '2p 5p 7m 8m'),
        ('1p 1p 3p 3p 4p 4p 5p 5p 6p 6p 7p 7p 9p', '9p'),
        ('2p 2p 3p 3p 4p 4p 5p 5p 5p 5p 7p 7p 9p', '9p'),
        ('2p 2p 2p 3p 3p 3p 4p 4p 4p 5p 5p 6p 8p', '7p'),
        ('2p 2p 2p 3p 3p 3p 4p 4p 4p 5p 5p 7p 8p', '6p 9p'),
        ('2p 2p 2p 3p 3p 3p 4p 4p 4p 5p 5p 6m 7m', '5m 8m'),
        ('2p 2p 2p 3p 3p 3p 4p 4p 4p 5p 5p 6p 7p', '2p 3p 4p 5p 6p 8p'),
    ]

    for hand, expected in cases:
        test.assert_equals(solution(hand), expected)
Пример #22
0
# https://www.codewars.com/kata/52685f7382004e774f0001f7/train/python
from test import Test


def make_readable(seconds):
    h = seconds // 3600
    m = (seconds % 3600) // 60
    s = (seconds % 3600) % 60

    return '{:02d}:{:02d}:{:02d}'.format(h, m, s)


Test.assert_equals(make_readable(0), "00:00:00")
Test.assert_equals(make_readable(5), "00:00:05")
Test.assert_equals(make_readable(60), "00:01:00")
Test.assert_equals(make_readable(86399), "23:59:59")
Test.assert_equals(make_readable(359999), "99:59:59")
Пример #23
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')
Test.assert_equals(sorted(permutations('aa')), ['aa'])
Test.assert_equals(sorted(permutations('aabb')),
Пример #24
0
                                         math.factorial(n - i))
        coefficient = binomial * a**i * b**(n - i)
        if coefficient != 0:
            sign = '-' if coefficient < 0 else ('+' if terms else '')
            c_str = str(
                abs(coefficient)) if abs(coefficient) != 1 or i == 0 else ''
            exp_str = '' if i == 0 else x + (f"^{str(i)}" if i > 1 else "")
            terms.append(sign + c_str + exp_str)

    return ''.join(terms)


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

    Test.assert_equals(expand("(x+1)^0"), "1")
    Test.assert_equals(expand("(x+1)^1"), "x+1")
    Test.assert_equals(expand("(x+1)^2"), "x^2+2x+1")

    Test.assert_equals(expand("(x-1)^0"), "1")
    Test.assert_equals(expand("(x-1)^1"), "x-1")
    Test.assert_equals(expand("(x-1)^2"), "x^2-2x+1")

    Test.assert_equals(expand("(5m+3)^4"), "625m^4+1500m^3+1350m^2+540m+81")
    Test.assert_equals(expand("(2x-3)^3"), "8x^3-36x^2+54x-27")
    Test.assert_equals(expand("(7x-7)^0"), "1")

    Test.assert_equals(expand("(-5m+3)^4"), "625m^4-1500m^3+1350m^2-540m+81")
    Test.assert_equals(expand("(-2k-3)^3"), "-8k^3-36k^2-54k-27")
    Test.assert_equals(expand("(-7x-7)^0"), "1")
# https://www.codewars.com/kata/where-my-anagrams-at/train/python
from test import Test


def anagrams(word, words):
    word = sorted(word)
    return [v for v in words if sorted(v) == word]


Test.assert_equals(anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']),
                   ['aabb', 'bbaa'])
Test.assert_equals(
    anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']),
    ['carer', 'racer'])
        every_months_buyers = every_months_buyers & set(buyers)

    for buyer in every_months_buyers:
        result[summary.count(buyer)].append(buyer)
    return sorted(
        [[count, sorted(value)] for count, value in result.items()],
        reverse=True,
    )


test.describe("Basic Tests")

a1 = ['A042', 'B004', 'A025', 'A042', 'C025']
a2 = ['B009', 'B040', 'B004', 'A042', 'A025', 'A042']
a3 = ['A042', 'A025', 'B004']
test.assert_equals(id_best_users(a1, a2, a3),
                   [[5, ['A042']], [3, ['A025', 'B004']]])

a1 = ['A043', 'B004', 'A025', 'A042', 'C025']
a2 = ['B009', 'B040', 'B003', 'A042', 'A027', 'A044']
a3 = ['A041', 'A026', 'B005']
test.assert_equals(id_best_users(a1, a2, a3), [])

a1 = ['A042', 'B004', 'A025', 'A042', 'C025']
a2 = ['B009', 'B040', 'B004', 'A042', 'A025', 'A042']
a3 = [
    'A042', 'B004', 'A025', 'A042', 'C025', 'B009', 'B040', 'B004', 'A042',
    'A025', 'A042'
]
a4 = ['A042', 'A025', 'B004']
test.assert_equals(id_best_users(a1, a2, a3, a4),
                   [[9, ['A042']], [5, ['A025', 'B004']]])
there exist natural numbers m > 1, and k > 1 such that mk = n.

Your task is to check whether a given integer is a perfect power. If it is a perfect
power, return a pair m and k with mk = n as a proof. Otherwise return Nothing, Nil,
null, None or your language's equivalent.

Note: For a perfect power, there might be several pairs. For example 81 = 3^4 = 9^2,
 so (3,4) and (9,2) are valid solutions. However, the tests take care of this, so if
  a number is a perfect power, return any pair that proves it.
'''


def isPP(n):
    i, k = 2, 2
    while i**k <= n:
        while i**k <= n:
            if i**k == n:
                return [i, k]
            k += 1
        k = 2
        i += 1
    return


test = Test()
test.assert_equals(isPP(4), [2,2], "4 = 2^2")
test.assert_equals(isPP(4), [2,2], "4 = 2^2")
test.assert_equals(isPP(9), [3,2], "9 = 3^2")
test.assert_equals(isPP(5), None, "5 isn't a perfect power")
test.report()
Пример #28
0
# https://www.codewars.com/kata/55ddb0ea5a133623b6000043/train/python
import re

from test import Test as test


def class_name_changer(cls, new_name):
    if re.match(r'^[A-Z][\w]+$', new_name):
        cls.__name__ = new_name
    else:
        raise


class MyClass:
    pass


myObject = MyClass()
test.assert_equals(MyClass.__name__, "MyClass")

class_name_changer(MyClass, "UsefulClass")
test.assert_equals(MyClass.__name__, "UsefulClass")

class_name_changer(MyClass, "SecondUsefulClass")
test.assert_equals(MyClass.__name__, "SecondUsefulClass")
Пример #29
0
        else:
            raise

    @classmethod
    def __str__(cls):
        return f'Class name is: {cls.__name__}'


class MyClass(ReNameAbleClass):
    pass


myObject = MyClass()
test.assert_equals(
    str(myObject),
    "Class name is: MyClass",
    "Original class name shouldn't be changed yet...",
)

myObject.change_class_name("UsefulClass")
test.assert_equals(
    str(myObject),
    "Class name is: UsefulClass",
    "New class name should be as boss wanted to!",
)

myObject.change_class_name("SecondUsefulClass")
test.assert_equals(
    str(myObject),
    "Class name is: SecondUsefulClass",
    "New class name should be as boss wanted to!",
# https://www.codewars.com/kata/5552101f47fc5178b1000050/train/python
from test import Test


def dig_pow(n, p):
    summary = 0
    for x in str(n):
        summary += int(x)**p
        p += 1
    result = summary / n
    if result.is_integer():
        return result
    return -1


Test.assert_equals(dig_pow(89, 1), 1)
Test.assert_equals(dig_pow(92, 1), -1)
Test.assert_equals(dig_pow(46288, 3), 51)
Пример #31
0
"""


def move_zeros(array):
    result = [i for i in array if isinstance(i, bool) or i != 0]
    result.extend([0] * (len(array) - len(result)))
    return result


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

Test.describe("Basic tests")
Test.assert_equals(move_zeros([1, 2, 0, 1, 0, 1, 0, 3, 0, 1]),
                   [1, 2, 1, 1, 3, 1, 0, 0, 0, 0])
Test.assert_equals(
    move_zeros(
        [9, 0.0, 0, 9, 1, 2, 0, 1, 0, 1, 0.0, 3, 0, 1, 9, 0, 0, 0, 0, 9]),
    [9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
Test.assert_equals(
    move_zeros(
        ["a", 0, 0, "b", "c", "d", 0, 1, 0, 1, 0, 3, 0, 1, 9, 0, 0, 0, 0, 9]),
    ["a", "b", "c", "d", 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
Test.assert_equals(
    move_zeros([
        "a", 0, 0, "b", None, "c", "d", 0, 1, False, 0, 1, 0, 3, [], 0, 1, 9,
        0, 0, {}, 0, 0, 9
    ]), [
        "a", "b", None, "c", "d", 1, False, 1, 3, [], 1, 9, {}, 9, 0, 0, 0, 0,
        0, 0, 0, 0, 0, 0