Beispiel #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)
Beispiel #2
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)
Beispiel #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),
Beispiel #6
0
    if (len(s) == 0): return l
    if (len(s) == 1):
        single = s + "_"
        l.append(single)
        return l
    if ((len(s) % 2) == 0): return re.findall('..', s)
    else:
        s = re.findall('..?', s)
        odd = s.pop()
        underscoreMe = odd + "_"
        s.append(underscoreMe)
        return s
    return len(s)


test.describe("Basic Tests")

tests = (
    ("asdfadsf", ['as', 'df', 'ad', 'sf']),
    ("asdfads", ['as', 'df', 'ad', 's_']),
    ("", []),
    ("x", ["x_"]),
)

for inp, exp in tests:
    test.assert_equals(solution(inp), exp)

test.describe("Random Tests")

from random import randint, choice
from string import ascii_lowercase
Beispiel #7
0

# ---------------  SOLUTION ---------------
def torrent(files):
    # create list (film_name, time_to_download)
    lst = [(file['name'], file["size_GB"] / file["speed_Mbps"] * 1000 * 8) for file in files]
    # sort list by time_to_download first, then by film_name
    lst = sorted(lst, key=lambda k: (k[1], k[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))
Beispiel #8
0
# Friend or Foe?  Unit Tests

from main import friend
import codewars_test as Test

Test.describe("Fixed Tests")

Test.assert_equals(friend([
    "Ryan",
    "Kieran",
    "Mark",
]), ["Ryan", "Mark"])
Test.assert_equals(friend(["Ryan", "Jimmy", "123", "4", "Cool Man"]), ["Ryan"])
Test.assert_equals(
    friend(["Jimm", "Cari", "aret", "truehdnviegkwgvke", "sixtyiscooooool"]),
    ["Jimm", "Cari", "aret"])
Test.assert_equals(friend(["Love", "Your", "Face", "1"]),
                   ["Love", "Your", "Face"])
Test.assert_equals(friend(["Hell", "Is", "a", "badd", "word"]),
                   ["Hell", "badd", "word"])
Test.assert_equals(friend(["Issa", "Issac", "Issacs", "ISISS"]), ["Issa"])
Test.assert_equals(friend(["Robot", "Your", "MOMOMOMO"]), ["Your"])
Test.assert_equals(friend(["Your", "BUTT"]), ["Your", "BUTT"])
Test.assert_equals(friend(["Hello", "I", "AM", "Sanjay", "Gupt"]), ["Gupt"])
Test.assert_equals(friend(["This", "IS", "enough", "TEst", "CaSe"]),
                   ["This", "TEst", "CaSe"])
Test.assert_equals(friend([]), [])

Test.describe("Random Tests")

from random import choice, randint
For every good kata idea there seem to be quite a few bad ones!

In this kata you need to check the provided array (x) for good ideas 'good' and bad ideas 'bad'. If there are one or two
good ideas, return 'Publish!', if there are more than 2 return 'I smell a series!'. If there are no good ideas, as is
often the case, return 'Fail!'.

"""

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


def well(x):
    gi = x.count("good")
    if gi > 2:
        return "I smell a series!"
    elif 1 <= gi <= 2:
        return "Publish!"
    else:
        return "Fail!"


# ---------------  TEST CASES ---------------
test.describe("Static Cases")
test.assert_equals(well(['bad', 'bad', 'bad']), 'Fail!')
test.assert_equals(well(['good', 'bad', 'bad', 'bad', 'bad']), 'Publish!')
test.assert_equals(
    well(['good', 'bad', 'bad', 'bad', 'bad', 'good', 'bad', 'bad', 'good']),
    'I smell a series!')
Beispiel #10
0
# ------------  KATA DESCRIPTION ------------
"""
https://www.codewars.com/kata/55edaba99da3a9c84000003b

8 kyu - Find numbers which are divisible by given number

Complete the function which takes two arguments and returns all numbers which are divisible by the given divisor. First
argument is an array of numbers and the second is the divisor.
Example
divisible_by([1, 2, 3, 4, 5, 6], 2) == [2, 4, 6]

"""

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


def divisible_by(numbers, divisor):
    return [x for x in numbers if not x % divisor]


# ---------------  TEST CASES ---------------
test.describe("Fixed tests")
test.assert_equals(divisible_by([1, 2, 3, 4, 5, 6], 2), [2, 4, 6])
test.assert_equals(divisible_by([1, 2, 3, 4, 5, 6], 3), [3, 6])
test.assert_equals(divisible_by([0, 1, 2, 3, 4, 5, 6], 4), [0, 4])
test.assert_equals(divisible_by([0], 4), [0])
test.assert_equals(divisible_by([1, 3, 5], 2), [])
Beispiel #11
0
    # find left_hand (lh) and right_hand (rh) groups
    pattern = r"101(\d{42})01010(\d{42})101$"
    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(
Beispiel #12
0
                return [ints[j], ints[i + j]]

    return None


# ---------------  TEST CASES ---------------
l1 = [1, 4, 8, 7, 3, 15]
l2 = [1, -2, 3, 0, -6, 1]
l3 = [20, -13, 40]
l4 = [1, 2, 3, 4, 1, 0]
l5 = [10, 5, 2, 3, 7, 5]
l6 = [4, -2, 3, 3, 4]
l7 = [0, 2, 0]
l8 = [5, 9, 13, -3]

test.describe("Testing For Sum of Pairs")
test.expect(
    sum_pairs(l1, 8) == [1, 7],
    "Basic: %s should return [1, 7] for sum = 8" % l1)
test.expect(
    sum_pairs(l2, -6) == [0, -6],
    "Negatives: %s should return [0, -6] for sum = -6" % l2)
test.expect(
    sum_pairs(l3, -7) == None,
    "No Match: %s should return None for sum = -7" % l3)
test.expect(
    sum_pairs(l4, 2) == [1, 1],
    "First Match From Left: %s should return [1, 1] for sum = 2 " % l4)
test.expect(
    sum_pairs(l5, 10) == [3, 7],
    "First Match From Left REDUX!: %s should return [3, 7] for sum = 10 " % l5)
Beispiel #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')
2 and 3 are factors of 6 because: 2 * 3 = 6

You can find a factor by dividing numbers. If the remainder is 0 then the number is a factor.
You can use the mod operator (%) in most languages to check for a remainder

For example 2 is not a factor of 7 because: 7 % 2 = 1
Note: base is a non-negative number, factor is a positive number.

"""

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


def check_for_factor(base, factor):
    return not base % factor


# ---------------  TEST CASES ---------------
test.describe("Should return True")
test.assert_equals(check_for_factor(10, 2), True)
test.assert_equals(check_for_factor(63, 7), True)
test.assert_equals(check_for_factor(2450, 5), True)
test.assert_equals(check_for_factor(24612, 3), True)

test.describe("Should return False")
test.assert_equals(check_for_factor(9, 2), False)
test.assert_equals(check_for_factor(653, 7), False)
test.assert_equals(check_for_factor(2453, 5), False)
test.assert_equals(check_for_factor(24617, 3), False)
Beispiel #15
0
    # 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)
    #-----------------
    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)
    test.assert_equals(persistence(444), 3)

    test.describe("Random tests")
    for _ in range(50):
        n = randint(1, 500000)
        test.it("Testing for: " + str(n))  
        test.assert_equals(persistence(n), soluce(n))
['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')
Beispiel #17
0
    op = "times"
    return (op, val)


def divided_by(func):
    op, val = func
    op = "divide"
    return (op, math.floor(val / 1))


print(seven(times(five())))
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)
Beispiel #18
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)
    contains an uppercase letter
    contains a number

Valid passwords will only be alphanumeric characters.

"""

# ---------------  SOLUTION ---------------
regex = "[0-9a-zA-Z]{6,}"


# ---------------  TEST CASES ---------------
import codewars_test as Test
from re import search

Test.describe("Basic tests")
Test.assert_equals(bool(search(regex, 'fjd3IR9')), True)
Test.assert_equals(bool(search(regex, 'ghdfj32')), False)
Test.assert_equals(bool(search(regex, 'DSJKHD23')), False)
Test.assert_equals(bool(search(regex, 'dsF43')), False)
Test.assert_equals(bool(search(regex, '4fdg5Fj3')), True)
Test.assert_equals(bool(search(regex, 'DHSJdhjsU')), False)
Test.assert_equals(bool(search(regex, 'fjd3IR9.;')), False)
Test.assert_equals(bool(search(regex, 'fjd3  IR9')), False)
Test.assert_equals(bool(search(regex, 'djI38D55')), True)
Test.assert_equals(bool(search(regex, 'a2.d412')), False)
Test.assert_equals(bool(search(regex, 'JHD5FJ53')), False)
Test.assert_equals(bool(search(regex, '!fdjn345')), False)
Test.assert_equals(bool(search(regex, 'jfkdfj3j')), False)
Test.assert_equals(bool(search(regex, '123')), False)
Test.assert_equals(bool(search(regex, 'abc')), False)
Beispiel #20
0
# ------------  KATA DESCRIPTION ------------
"""
6 kyu - Find the odd int

Given an array, find the int that appears an odd number of times.

There will always be only one integer that appears an odd number of times.

"""

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


def find_it(seq):
    for item in set(seq):
        if seq.count(item) % 2 == 1:
            return item


# ---------------  TEST CASES ---------------
test.describe("Example")
test.assert_equals(
    find_it([20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5]), 5)
Beispiel #21
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>'
    )
Beispiel #22
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')
class Foo(object, metaclass = Meta):
    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')
Beispiel #24
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)
Beispiel #25
0
# imports
import os
import sys
from solution import solution

# 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("Example Tests")

tests = (
    ("asdfadsf", ['as', 'df', 'ad', 'sf']),
    ("asdfads", ['as', 'df', 'ad', 's_']),
    ("", []),
    ("x", ["x_"]),
)

for inp, exp in tests:
    test.assert_equals(solution(inp), exp)
Beispiel #26
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!")
is_uppercase("c") == False
is_uppercase("C") == True
is_uppercase("hello I AM DONALD") == False
is_uppercase("HELLO I AM DONALD") == True
is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False
is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True

In this Kata, a string is said to be in ALL CAPS whenever it does not contain any lowercase letter so any string
containing no letters at all is trivially considered to be in ALL CAPS.
"""

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


def is_uppercase(inp):
    return True if inp.isupper() else False


# ---------------  TEST CASES ---------------
def gen_test_case(inp, res):
    test.assert_equals(is_uppercase(inp), res, inp)


test.describe("Basic Tests")

gen_test_case("c", False)
gen_test_case("C", True)
gen_test_case("hello I AM DONALD", False)
gen_test_case("HELLO I AM DONALD", True)
Beispiel #28
0
    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')
    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.describe('Random tests')
    for _ in range(50):
        test_string = _random_string()
        Test.it("Testing for: " + test_string)
        Test.assert_equals(count_letters_and_digits(test_string),
                           _inner_solution(test_string))
Beispiel #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")
def basic_tests():
    test.describe("Basic test")
    test.assert_equals(Invert.reverse_letter("krishan"), "nahsirk")
    test.assert_equals(Invert.reverse_letter("ultr53o?n"), "nortlu")
    test.assert_equals(Invert.reverse_letter("ab23c"), "cba")
    test.assert_equals(Invert.reverse_letter("krish21an"), "nahsirk")