예제 #1
0
def oper_array(fct, arr, init):
    # your code

# ---------------  TEST CASES ---------------
    def testing(actual, expected):
        Test.assert_equals(actual, expected)

    Test.describe("oper_array")
    Test.it("Basic tests 1 : gcdi, lcmu, som, mini, maxi")
    a = [18, 69, -90, -78, 65, 40]

    r = [18, 3, 3, 3, 1, 1]
    op = oper_array(gcdi, a, a[0])
    testing(op, r)
    r = [18, 414, 2070, 26910, 26910, 107640]
    op = oper_array(lcmu, a, a[0])
    testing(op, r)
    r = [18, 87, -3, -81, -16, 24]
    op = oper_array(som, a, 0)
    testing(op, r)
    r = [18, 18, -90, -90, -90, -90]
    op = oper_array(mini, a, a[0])
    testing(op, r)
    r = [18, 69, 69, 69, 69, 69]
    op = oper_array(maxi, a, a[0])
    testing(op, r)
예제 #2
0
    # Custom 
    Test.assert_equals(tribonacci([14, 9, 3], 1), [14])

    # Test Cases
    Test.describe("Basic tests")
    Test.assert_equals(tribonacci([1,1,1],10),[1,1,1,3,5,9,17,31,57,105])
    Test.assert_equals(tribonacci([0,0,1],10),[0,0,1,1,2,4,7,13,24,44])
    Test.assert_equals(tribonacci([0,1,1],10),[0,1,1,2,4,7,13,24,44,81])
    Test.assert_equals(tribonacci([1,0,0],10),[1,0,0,1,1,2,4,7,13,24])
    Test.assert_equals(tribonacci([0,0,0],10),[0,0,0,0,0,0,0,0,0,0])
    Test.assert_equals(tribonacci([1,2,3],10),[1,2,3,6,11,20,37,68,125,230])
    Test.assert_equals(tribonacci([3,2,1],10),[3,2,1,6,9,16,31,56,103,190])
    Test.assert_equals(tribonacci([1,1,1],1),[1])
    Test.assert_equals(tribonacci([300,200,100],0),[])
    Test.assert_equals(tribonacci([0.5,0.5,0.5],30),[0.5,0.5,0.5,1.5,2.5,4.5,8.5,15.5,28.5,52.5,96.5,177.5,326.5,600.5,1104.5,2031.5,3736.5,6872.5,12640.5,23249.5,42762.5,78652.5,144664.5,266079.5,489396.5,900140.5,1655616.5,3045153.5,5600910.5,10301680.5])

    Test.describe("Random tests")
    from random import randint
    def soluzionacci(sign,n):
        seq=sign[:]
        while len(seq)<n:
            seq+=[seq[-3]+seq[-2]+seq[-1]]
        return seq[:n]

    for i in range(40):
        sign=[randint(0,20),randint(0,20),randint(0,20)]
        n=randint(0,50)
        Test.it("Testing for signature: "+str(sign)+" and n: "+str(n))
        Test.assert_equals(tribonacci(sign[:], n), soluzionacci(sign,n), "It should work with random inputs too")
예제 #3
0
"""

# ---------------  SOLUTION ---------------
import codewars_test as test


def cakes(recipe, available):

    mn = float(
        'inf')  # used to store minimum, initialized with positive infinity

    for ing in recipe:
        if ing in available:  # find how many cakes you can bake for that ingredient and save minimum amount
            mn = min(mn, available[ing] // recipe[ing])
        else:
            return 0  # if there is no ingredient available no cakes can be baked

    return mn


# ---------------  TEST CASES ---------------
test.describe('Testing Pete, the Baker')
test.it('gives us the right number of cakes')

recipe = {"flour": 500, "sugar": 200, "eggs": 1}
available = {"flour": 1200, "sugar": 1200, "eggs": 5, "milk": 200}
test.assert_equals(cakes(recipe, available), 2, 'Wrong result for example #1')

recipe = {"apples": 3, "flour": 300, "sugar": 150, "milk": 100, "oil": 100}
available = {"sugar": 500, "flour": 2000, "milk": 2000}
test.assert_equals(cakes(recipe, available), 0, 'Wrong result for example #2')
ENJOY LEARNING !!
Zizou

"""

# ---------------  SOLUTION ---------------
import codewars_test as test


def array_leaders(numbers):
    result = list()
    for i, num in enumerate(numbers, 1):
        if num > sum(numbers[i:]):
            result.append(num)
    return result


# ---------------  TEST CASES ---------------
test.describe("Sample Tests")
test.it("Positive Values")
test.assert_equals(array_leaders([1, 2, 3, 4, 0]), [4])
test.assert_equals(array_leaders([16, 17, 4, 3, 5, 2]), [17, 5, 2])

test.it("Negative Values")
test.assert_equals(array_leaders([-1, -29, -26, -2]), [-1])
test.assert_equals(array_leaders([-36, -12, -27]), [-36, -12])

test.it("Mixed Values")
test.assert_equals(array_leaders([5, 2]), [5, 2])
test.assert_equals(array_leaders([0, -1, -29, 3, 2]), [0, -1, 3, 2])
Input is always going to be valid/reasonable: ie: a non negative number;
extra cookie for not using a loop to compute square-by-square (at least not directly) and instead trying a smarter
approach [hint: some peculiar operator]; a trick converting the number might also work: impress me!
"""

# ---------------  SOLUTION ---------------
import codewars_test as Test


def squares_needed(grains):
    return 0 if grains == 0 else len(bin(grains)) - 2


# ---------------  TEST CASES ---------------
Test.describe("Basic tests")
Test.assert_equals(squares_needed(0), 0)
Test.assert_equals(squares_needed(1), 1)
Test.assert_equals(squares_needed(2), 2)
Test.assert_equals(squares_needed(3), 2)
Test.assert_equals(squares_needed(4), 3)
print("<COMPLETEDIN::>")

Test.describe("Random tests")
from random import randint
sol = lambda n: 1 + sol(n >> 1) if n else n

for _ in range(40):
    n = randint(1, 10**randint(1, 15))
    Test.it("Testing for " + str(n))
    Test.assert_equals(squares_needed(n), sol(n),
                       "It should work for random inputs too")
예제 #6
0
import re
import codewars_test as Test


def highlight(code):
    ret = code
    ret = re.sub(r"(F+)", '<span style="color: pink">\\1</span>', ret)
    ret = re.sub(r"(L+)", '<span style="color: red">\\1</span>', ret)
    ret = re.sub(r"(R+)", '<span style="color: green">\\1</span>', ret)
    ret = re.sub(r"([0-9]+)", '<span style="color: orange">\\1</span>', ret)
    return ret


if __name__ == "__main__":
    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(
예제 #7
0
    # return list of film_name's and time of last item of list
    return [f[0] for f in lst], lst[-1:][0][1]


# ---------------  TEST CASES ---------------
import codewars_test as test

test.describe("Computer problem series #2: uTorrent download")

file_1 = {"name": "alien", "size_GB": 38, "speed_Mbps": 38}
file_2 = {"name": "predator", "size_GB": 38, "speed_Mbps": 2}
file_3 = {"name": "terminator", "size_GB": 5, "speed_Mbps": 25}
file_4 = {"name": "zombieland", "size_GB": 38, "speed_Mbps": 38}

# Basic
test.it("Basic tests")
files = [file_1, file_2, file_3]
test.assert_equals(torrent(files), (["terminator", "alien", "predator"], 152000))

# Order by name in case of a tie
test.it("Tie tests")
files = [file_1, file_4]
test.assert_equals(torrent(files), (["alien", "zombieland"], 8000))

files = [file_4, file_1]
test.assert_equals(torrent(files), (["alien", "zombieland"], 8000))

# import random
from random import randint, sample, choice

# tie tests: high probability of same size and speed between 2 o more films
예제 #8
0
    result = functools.reduce(mul, numbers)
    return calculate(result, multiplicative+1)


def persistence(n):
    if len(str(n)) == 1: return 0
    n, m = calculate(n, 0)
    return m



if __name__== "__main__":
    import codewars_test as test

    # Sample Tests
    test.it("Basic tests")
    test.assert_equals(persistence(39), 3) # 3*9=27 - 2*7=14 - 1*4=4
    test.assert_equals(persistence(4), 0)
    test.assert_equals(persistence(25), 2)
    test.assert_equals(persistence(999), 4)

    # Test Cases
    from functools import reduce
    from random import randint
    #-----------------
    def soluce(n):
            digits = [int(d) for d in str(n)]
            if (len(digits) == 1):
                return 0
            p = reduce(lambda x, y : x * y, digits, 1)
            return 1 + soluce(p)
예제 #9
0
What could be easier than comparing integer numbers? However, the given piece of code doesn't recognize some of the
special numbers for a reason to be found. Your task is to find the bug and eliminate it.

"""

# ---------------  SOLUTION ---------------
import codewars_test as Test


def what_is(x):
    if x == 42:
        return 'everything'
    elif x == 42 * 42:
        return 'everything squared'
    else:
        return 'nothing'


# ---------------  TEST CASES ---------------
Test.describe('what_is')
Test.it('should work correctly')
tests = [
    (0, 'nothing'),
    (123, 'nothing'),
    (-1, 'nothing'),
    (42, 'everything'),
    (42 * 42, 'everything squared'),
]
for x, answer in tests:
    Test.assert_equals(what_is(x), answer)
예제 #10
0
['a','b','c','d','f'] -> 'e'
['O','Q','R','S'] -> 'P'

(Use the English alphabet with 26 letters!)

Have fun coding it and please don't forget to vote and rank this kata! :-)

I have also created other katas. Take a look if you enjoyed this kata!
"""

# ---------------  SOLUTION ---------------
import codewars_test as test
from string import ascii_letters


def find_missing_letter(chars):

    start = ascii_letters.index(chars[0])

    for i in range(len(chars)):
        if chars[i] != ascii_letters[start + i]:
            return ascii_letters[start + i]


# ---------------  TEST CASES ---------------
test.describe("kata tests")
test.it("example tests")
test.assert_equals(find_missing_letter(['a', 'b', 'c', 'd', 'f']), 'e')
test.assert_equals(find_missing_letter(['O', 'Q', 'R', 'S']), 'P')
예제 #11
0
    x = re.search(pattern, barcode)
    lh = re.findall(r'\d{7}', x.group(1))
    rh = re.findall(r'\d{7}', x.group(2))

    # convert binary to int digits
    lh = [str(LEFT_HAND[p]) for p in lh]
    rh = [str(RIGHT_HAND[p]) for p in rh]

    # format and return the result
    return f"{lh[0]} {''.join(lh[1:])} {''.join(rh[:-1])} {rh[-1]}"


# ---------------  TEST CASES ---------------
test.describe('should convert barcode to digits')

test.it("Campbell's Chicken Noodle Soup")
test.assert_equals(
    read_barcode(
        '▍ ▍   ▍▍ ▍ ▍▍   ▍  ▍▍  ▍   ▍▍ ▍   ▍▍ ▍   ▍▍ ▍ ▍ ▍ ▍▍▍  ▍ ▍▍  ▍▍ ▍▍ ▍▍  ▍  ▍▍▍ ▍▍  ▍▍ ▍   ▍  ▍ ▍'
    ), '0 51000 01251 7')

test.it("Hershey's Natural Unsweetened Cocoa")
test.assert_equals(
    read_barcode(
        '▍ ▍   ▍▍ ▍ ▍▍▍▍ ▍ ▍   ▍▍   ▍▍ ▍   ▍▍ ▍   ▍▍ ▍ ▍ ▍ ▍▍▍  ▍ ▍  ▍▍▍ ▍▍ ▍▍  ▍▍▍  ▍ ▍▍▍  ▍ ▍ ▍▍▍  ▍ ▍'
    ), '0 34000 05200 4')

test.it("Bob's Red Mill Corn Grits")
test.assert_equals(
    read_barcode(
        '▍ ▍   ▍▍ ▍ ▍▍▍▍ ▍   ▍ ▍▍   ▍ ▍▍ ▍▍▍ ▍▍ ▍▍ ▍▍▍ ▍ ▍ ▍▍▍  ▍ ▍▍▍  ▍ ▍▍  ▍▍ ▍▍ ▍▍  ▍  ▍▍▍ ▍▍ ▍▍  ▍ ▍'
예제 #12
0
파일: test.py 프로젝트: fernandoe/study
import codewars_test as test
from code import countOnes

# Sample Tests
test.describe("Sample Tests")
test.it('Easy')
test.assert_equals(countOnes(5, 7), 7)
test.assert_equals(countOnes(12, 29), 51)

# Test Cases
예제 #13
0
#!/usr/bin/env python

# imports
import os
import sys
from solution import to_weird_case

# Module "Global" Variables
location = os.path.abspath(__file__)
here = os.path.abspath(
    os.path.dirname(__file__)
)  # Get the absolute path for the directory where this file is located "here"
project_root = os.path.abspath(os.path.join(
    here, ".."))  # Get the absolute path for the project / repository root
sys.path.insert(
    0, project_root
)  # Extend the system path to include the project root and import the test module

# relative imports
import codewars_test as test

test.describe('to_weird_case')

test.it('should return the correct value for a single word')
test.assert_equals(to_weird_case('This'), 'ThIs')
test.assert_equals(to_weird_case('is'), 'Is')

test.it('should return the correct value for multiple words')
test.assert_equals(to_weird_case('This is a test'), 'ThIs Is A TeSt')
예제 #14
0
파일: test.py 프로젝트: fernandoe/study
import codewars_test as test
from code import max_sequence

# Sample Tests
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)

# Test Cases
try:
    # backwards compatibility
    max_sequence = maxSequence
except NameError:
    pass

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)
test.it('should work on the example with negative numbers')
test.assert_equals(max_sequence([-2, -1, -3, -4, -1, -2, -1, -5, -4]), 0)
test.it('should work on random arrays')
from random import randint


def randomArray(size):
    return [randint(-30, 30) for i in range(0, size)]
예제 #15
0
# ------------  KATA DESCRIPTION ------------
"""
https://www.codewars.com/kata/523b4ff7adca849afe000035

8 kyu - Function 1 - hello world

Description:
Make a simple function called greet that returns the most-famous "hello world!".
Style Points
Sure, this is about as easy as it gets. But how clever can you be to create the most creative hello world you can think
of? What is a "hello world" solution you would want to show your friends?
"""

# ---------------  SOLUTION ---------------
import codewars_test as test


def greet():
    return "hello world!"


# ---------------  TEST CASES ---------------
test.describe("Greet function")
test.it("Making sure greet exists")
test.assert_equals(greet(), "hello world!",
                   "Greet doesn't return hello world!")
예제 #16
0
def do():
    def testing(act, exp):
        Test.expect(
            abs(act - exp) < 1e-6, "{} should equal {}".format(act, exp))

    Test.it("Fixed tests")
    tests = [["2 + 3 * 4 / 3 - 6 / 3 * 3 + 8", 8], ["1 + 2 * 3 * 3 - 8", 11],
             ["1 + 2 * 3 * (5 - 2) - 8", 11],
             ["1 + 2 * 3 * (5 - (3 - 1)) - 8", 11], ["4 + -(1)", 3],
             ["4 - -(1)", 5], ["4 * -(1)", -4], ["4 / -(1)", -4], ["-1", -1],
             ["-(-1)", 1], ["-(-(-1))", -1], ["-(-(-(-1)))", 1],
             ["(((((-1)))))", -1], ["5 - 1", 4], ["5- 1", 4], ["5 -1", 4]]

    try:
        if calc("'x'") == "x": Test.expect(False, "Trying to use eval?")
    except:
        pass

    for test in tests:
        testing(calc(test[0]), test[1])

    Test.it("Random tests")
    for i in range(100):
        try:
            expression = "{}{} {} {}{} {} {}{} {} {}{} {} {}{} {} {}{} {} {}{} {} {}{}".format(
                random.choice(["-", ""]), random.randint(1, 100),
                random.choice(["+", "-", "*", "/"]), random.choice(["-", ""]),
                random.randint(1, 100), random.choice(["+", "-", "*", "/"]),
                random.choice(["-", ""]), random.randint(1, 100),
                random.choice(["+", "-", "*", "/"]), random.choice(["-", ""]),
                random.randint(1, 100), random.choice(["+", "-", "*", "/"]),
                random.choice(["-", ""]), random.randint(1, 100),
                random.choice(["+", "-", "*", "/"]), random.choice(["-", ""]),
                random.randint(1, 100), random.choice(["+", "-", "*", "/"]),
                random.choice(["-", ""]), random.randint(1, 100),
                random.choice(["+", "-", "*", "/"]), random.choice(["-", ""]),
                random.randint(1, 100))
            testing(calc(expression), eval(expression))
        except ZeroDivisionError:
            pass

    for i in range(100):
        try:
            expression = "{}({}{}) {} ({}{} {} {}{} {} {}({})) {} ({}{} {} {}((({}({}{} {} {}{})))) {} {}{})".format(
                random.choice(["-", ""]), random.choice(["-", ""]),
                random.randint(1, 100), random.choice(["+", "-", "*", "/"]),
                random.choice(["-", ""]), random.randint(1, 100),
                random.choice(["+", "-", "*", "/"]), random.choice(["-", ""]),
                random.randint(1, 100), random.choice(["+", "-", "*", "/"]),
                random.choice(["-", ""]), random.randint(1, 100),
                random.choice(["+", "-", "*", "/"]), random.choice(["-", ""]),
                random.randint(1, 100), random.choice(["+", "-", "*", "/"]),
                random.choice(["-", ""]), random.choice(["-", ""]),
                random.choice(["-", ""]), random.randint(1, 100),
                random.choice(["+", "-", "*", "/"]), random.choice(["-", ""]),
                random.randint(1, 100), random.choice(["+", "-", "*", "/"]),
                random.choice(["-", ""]), random.randint(1, 100))
            testing(calc(expression), eval(expression))
        except ZeroDivisionError:
            pass

    for i in range(100):
        expression = "{}{}- {}{}- {}{}- {}{}".format(random.choice(["-", ""]),
                                                     random.randint(1, 100),
                                                     random.choice(["-", ""]),
                                                     random.randint(1, 100),
                                                     random.choice(["-", ""]),
                                                     random.randint(1, 100),
                                                     random.choice(["-", ""]),
                                                     random.randint(1, 100))
        testing(calc(expression), eval(expression))
예제 #17
0
파일: code.py 프로젝트: fernandoe/study
def count_letters_and_digits(s):
    counter = 0
    for c in s:
        if c.isalpha() or c.isnumeric():
            counter += 1
    return counter


if __name__ == "__main__":
    import codewars_test as Test

    # Sample tests
    Test.it('Basic tests')
    Test.assert_equals(count_letters_and_digits('n!!ice!!123'), 7)
    Test.assert_equals(count_letters_and_digits('de?=?=tttes!!t'), 8)
    Test.assert_equals(count_letters_and_digits(''), 0)
    Test.assert_equals(count_letters_and_digits('!@#$%^&`~.'), 0)
    Test.assert_equals(count_letters_and_digits('u_n_d_e_r__S_C_O_R_E'), 10)

    # Test Cases
    from string import ascii_letters, digits, printable
    from random import choices, randint

    def _inner_solution(s):
        return len(list(filter(lambda x: x in ascii_letters + digits,
                               s))) if type(s) is str else 0

    def _random_string(_min=30, _max=100):
        return ''.join(choices(printable, k=randint(_min, _max)))

    Test.it('Basic tests')
예제 #18
0
Note:
Your points are not included in the array of your class's points. For calculating the average point you may add your
point to the given array!
"""

# ---------------  SOLUTION ---------------
import codewars_test as test


def better_than_average(class_points, your_points):
    return your_points > sum(class_points) / len(class_points)


# ---------------  TEST CASES ---------------
test.describe("Basic Tests")

test.it("better_than_average([2, 3], 5) should return True")
test.assert_equals(better_than_average([2, 3], 5), True)

test.it(
    "better_than_average([100, 40, 34, 57, 29, 72, 57, 88], 75) should return True"
)
test.assert_equals(better_than_average([100, 40, 34, 57, 29, 72, 57, 88], 75),
                   True)

test.it(
    "better_than_average([12, 23, 34, 45, 56, 67, 78, 89, 90], 69) should return True"
)
test.assert_equals(
    better_than_average([12, 23, 34, 45, 56, 67, 78, 89, 90], 69), True)
예제 #19
0
파일: main.py 프로젝트: ksbeasle/dev
print(four(plus(nine())))
print(eight(minus(three())))
print(six(divided_by(two())))

test.describe('Basic Tests')
test.assert_equals(seven(times(five())), 35)
test.assert_equals(four(plus(nine())), 13)
test.assert_equals(eight(minus(three())), 5)
test.assert_equals(six(divided_by(two())), 3)

test.describe('Random Tests')

base = [
    "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
    "nine"
]
basef = [zero, one, two, three, four, five, six, seven, eight, nine]

for _ in range(40):
    a, b = randint(0, 9), randint(0, 9)
    test.it("Testing for %s(plus(%s()))" % (base[a], base[b]))
    test.assert_equals(basef[a](plus(basef[b]())), a + b)
    a, b = randint(0, 9), randint(0, 9)
    test.it("Testing for %s(minus(%s()))" % (base[a], base[b]))
    test.assert_equals(basef[a](minus(basef[b]())), a - b)
    a, b = randint(0, 9), randint(0, 9)
    test.it("Testing for %s(times(%s()))" % (base[a], base[b]))
    test.assert_equals(basef[a](times(basef[b]())), a * b)
    a, b = randint(0, 9), randint(1, 9)
    test.it("Testing for %s(divided_by(%s()))" % (base[a], base[b]))
    test.assert_equals(basef[a](divided_by(basef[b]())), a // b)
    C++: unsigned long;

You have to return the digits of this number within an array in reverse order.
Example:

348597 => [7,9,5,8,4,3]
"""

# ---------------  SOLUTION ---------------
import codewars_test as Test


def digitize(n):
    return [int(i) for i in reversed(str(n))]


# ---------------  TEST CASES ---------------
Test.assert_equals(digitize(35231), [1, 3, 2, 5, 3])
Test.assert_equals(digitize(23582357), [7, 5, 3, 2, 8, 5, 3, 2])
Test.assert_equals(digitize(984764738), [8, 3, 7, 4, 6, 7, 4, 8, 9])
Test.assert_equals(digitize(45762893920), [0, 2, 9, 3, 9, 8, 2, 6, 7, 5, 4])
Test.assert_equals(digitize(548702838394),
                   [4, 9, 3, 8, 3, 8, 2, 0, 7, 8, 4, 5])

Test.describe('Random tests')
from random import randint
for x in range(37):
    y = randint(10, 99 * 2**x)
    Test.it('Testing %s' % y)
    Test.assert_equals(digitize(y), list(map(int, list(str(y)[::-1]))))
예제 #21
0
#!/usr/bin/env python

import codewars_test as test
from calc import Calculator

test.it("Tests")
for key, val in {
        "127": 127,
        "2 + 3": 5,
        "2 - 3 - 4": -5,
        "10 * 5 / 2": 25,
        "2 / 2 + 3 * 4 - 6": 7,
        "2 + 3 * 4 / 3 - 6 / 3 * 3 + 8": 8,
        "1.1 + 2.2 + 3.3": 6.6,
        "1.1 * 2.2 * 3.3": 7.986
}.items():
    actual = Calculator().evaluate(key)
    test.expect(isinstance(actual, (float, int)),
                "Your result should be a number, not: " + str(type(actual)))
    test.expect(
        abs(actual - val) < 1e-12,
        "Expected %s == %s, but got %s" % (key, val, actual))
예제 #22
0
#!/usr/bin/env python

# imports
import os
import sys
from solution import persistence

# Module "Global" Variables
location = os.path.abspath(__file__)
here = os.path.abspath(
    os.path.dirname(__file__)
)  # Get the absolute path for the directory where this file is located "here"
project_root = os.path.abspath(os.path.join(
    here, ".."))  # Get the absolute path for the project / repository root
sys.path.insert(
    0, project_root
)  # Extend the system path to include the project root and import the test module

# relative imports
import codewars_test as test

test.it("Basic tests")
test.assert_equals(persistence(39), 3)
test.assert_equals(persistence(4), 0)
test.assert_equals(persistence(25), 2)
test.assert_equals(persistence(999), 4)
예제 #23
0
    def __init__(self, x):
        self.x = x

    def bar(self, v):
        return (self.x, v)

a = Foo(1)
a.bar(2)

calls = Debugger.method_calls

test.assert_equals(len(calls), 2)

test.describe("Test collected method calls")

test.it("Call to init should be collected")
test.assert_equals(calls[0]['args'], (a, 1))

test.it("Call to bar should be collected")
test.assert_equals(calls[1]['args'], (a, 2))

test.describe("Test collected attribute accesses")
accesses = Debugger.attribute_accesses
print(Debugger.method_calls)

test.assert_equals(len(accesses), 3)

test.it("Attribute set in init should be collected")
test.assert_equals(accesses[0]['action'], 'set')
test.assert_equals(accesses[0]['attribute'], 'x')
test.assert_equals(accesses[0]['value'], 1)
예제 #24
0
maskify("Nananananananananananananananana Batman!") == "####################################man!"
"""

# ---------------  SOLUTION ---------------
import codewars_test as test


# return masked string
def maskify(cc):
    return "#" * (len(cc) - 4) + cc[-4:]


# ---------------  TEST CASES ---------------
cc = ''
r = maskify(cc)
test.describe("masking: {0}".format(cc))
test.it("{0}  matches  {1}".format(cc, r))
test.assert_equals(r, cc)

cc = '123'
r = maskify(cc)
test.describe("masking: {0}".format(cc))
test.it("{0}  matches  {1}".format(cc, r))
test.assert_equals(r, cc)

cc = 'SF$SDfgsd2eA'
r = maskify(cc)
test.describe("masking: {0}".format(cc))
test.it("{0}  matches  {1}".format('########d2eA', r))
test.assert_equals(r, '########d2eA')
예제 #25
0
# ------------  KATA DESCRIPTION ------------
"""
8 kyu
Array plus array

I'm new to coding and now I want to get the sum of two arrays...actually the sum of all their elements. I'll appreciate for your help.

P.S. Each array includes only integer numbers. Output is a number too.
"""

# ---------------  SOLUTION ---------------
import codewars_test as Test


def array_plus_array(arr1, arr2):
    return sum(arr1) + sum(arr2)


# ---------------  TEST CASES ---------------
Test.it("Basic test")
Test.assert_equals(array_plus_array([1, 2, 3], [4, 5, 6]), 21)
Test.assert_equals(array_plus_array([-1, -2, -3], [-4, -5, -6]), -21)
Test.assert_equals(array_plus_array([0, 0, 0], [4, 5, 6]), 15)
Test.assert_equals(array_plus_array([100, 200, 300], [400, 500, 600]), 2100)
예제 #26
0
Maximum subarray sum

The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers:

maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4])
# should be 6: [4, -1, 2, 1]

Easy case is when the list is made up of only positive numbers and the maximum sum is the sum of the whole array. If the list is made up of only negative numbers, return 0 instead.

Empty list is considered to have zero greatest sum. Note that the empty list or array is also a valid sublist/subarray.
"""

# ---------------  SOLUTION ---------------
import codewars_test as test


def maxSequence(arr):
    max_sum = 0
    for i in range(len(arr)):
        for j in range(len(arr)-i):
            sm = sum(arr[i:len(arr)-j])
            max_sum = sm if sm > max_sum else max_sum
    return max_sum


# ---------------  TEST CASES ---------------
test.describe("Tests")
test.it('should work on an empty array')
test.assert_equals(maxSequence([]), 0)
test.it('should work on the example')
test.assert_equals(maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4]), 6)
예제 #27
0
def second_example_test_case():
    for nmbr in range(1, 9):
        a = nmbr ** nmbr
        test.it("Testing %d and %d" % (a, 0))
        test.assert_equals(last_digit(a, 0), 1, "x ** 0 must return 1")
import codewars_test as Test
import Context
import Operations

Test.it("Basic tests")
Test.assert_equals(Operations.sumar(1, 2), 3)
Test.assert_equals(Operations.sumar(2, 2), 4)
Test.assert_equals(Operations.restar(1, 2), -1)
Test.assert_equals(Operations.restar(1, 7), -6)
예제 #29
0
            char)  # counts number of "chars" in s1 and s2 strings

        if l1 > 1 or l2 > 1:

            if l1 == l2:
                mas.append((l1, "=:" + str(char) * l1))

            elif l1 != l2:
                mas.append((max(l1, l2), ("1" if l1 > l2 else "2") + ":" +
                            str(char) * max(l1, l2)))

    mas.sort(key=lambda row: row[1])
    mas.sort(key=lambda row: row[0], reverse=True)

    return '/'.join([item[1] for item in mas])


# ---------------  TEST CASES ---------------
Test.describe("Mix")
Test.it("Basic Tests")
Test.assert_equals(mix("Are they here", "yes, they are here"),
                   "2:eeeee/2:yy/=:hh/=:rr")
Test.assert_equals(
    mix("looping is fun but dangerous", "less dangerous than coding"),
    "1:ooo/1:uuu/2:sss/=:nnn/1:ii/2:aa/2:dd/2:ee/=:gg")
Test.assert_equals(mix(" In many languages", " there's a pair of functions"),
                   "1:aaa/1:nnn/1:gg/2:ee/2:ff/2:ii/2:oo/2:rr/2:ss/2:tt")
Test.assert_equals(mix("Lords of the Fallen", "gamekult"), "1:ee/1:ll/1:oo")
Test.assert_equals(mix("codewars", "codewars"), "")
Test.assert_equals(mix("A generation must confront the looming ", "codewarrs"),
                   "1:nnnnn/1:ooooo/1:tttt/1:eee/1:gg/1:ii/1:mm/=:rr")
예제 #30
0
# ------------  KATA DESCRIPTION ------------
"""
8 kyu - Sum of positive

You get an array of numbers, return the sum of all of the positives ones.
Example [1,-4,7,12] => 1 + 7 + 12 = 20
Note: if there is nothing to sum, the sum is default to 0.
"""

# ---------------  SOLUTION ---------------
import codewars_test as test


def positive_sum(arr):
    return sum(x for x in arr if x > 0)


# ---------------  TEST CASES ---------------
test.describe("positive_sum")

test.it("works for some examples")
test.assert_equals(positive_sum([1, 2, 3, 4, 5]), 15)
test.assert_equals(positive_sum([1, -2, 3, 4, 5]), 13)
test.assert_equals(positive_sum([-1, 2, 3, 4, -5]), 9)

test.it("returns 0 when array is empty")
test.assert_equals(positive_sum([]), 0)

test.it("returns 0 when all elements are negative")
test.assert_equals(positive_sum([-1, -2, -3, -4, -5]), 0)