예제 #1
0
def basic_tests():
    tests = [
        (True, ([66, 101], 66)),
        (False, ([78, 117, 110, 99, 104, 117, 107, 115], 8)),
        (True, ([101, 45, 75, 105, 99, 107], 107)),
        (True, ([80, 117, 115, 104, 45, 85, 112, 115], 45)),
        (True, (['t', 'e', 's', 't'], 'e')),
        (False, (["what", "a", "great", "kata"], "kat")),
        (True, ([66, "codewars", 11,
                 "alex loves pushups"], "alex loves pushups")),
        (False, (["come", "on", 110, "2500", 10, '!', 7, 15], "Come")),
        (True, (["when's", "the", "next", "Katathon?", 9, 7], "Katathon?")),
        (False, ([8, 7, 5, "bored", "of", "writing", "tests", 115], 45)),
        (True, (["anyone", "want", "to", "hire", "me?"], "me?")),
    ]

    for exp, inp in tests:
        test.assert_equals(check(*inp), exp)
예제 #2
0
        return eval(f'9 {i[0]}')
    return 9

def plus(j): return f'+ {j}'
def minus(j): return f'- {j}'
def times(j): return f'* {j}'
def divided_by(j): return f'// {j}'


# Top solution
def zero(f = None): return 0 if not f else f(0)
def one(f = None): return 1 if not f else f(1)
def two(f = None): return 2 if not f else f(2)
def three(f = None): return 3 if not f else f(3)
def four(f = None): return 4 if not f else f(4)
def five(f = None): return 5 if not f else f(5)
def six(f = None): return 6 if not f else f(6)
def seven(f = None): return 7 if not f else f(7)
def eight(f = None): return 8 if not f else f(8)
def nine(f = None): return 9 if not f else f(9)

def plus(y): return lambda x: x+y
def minus(y): return lambda x: x-y
def times(y): return lambda  x: x*y
def divided_by(y): return lambda  x: x/y


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)
예제 #3
0

# Other interesting solution, seems awkward but easily readable
def tickets(a):
    n25 = n50 = n100 = 0
    for e in a:
        if e == 25: n25 += 1
        elif e == 50:
            n25 -= 1
            n50 += 1
        elif e == 100 and n50 > 0:
            n25 -= 1
            n50 -= 1
        elif e == 100 and n50 == 0:
            n25 -= 3
        if n25 < 0 or n50 < 0:
            return 'NO'
    return 'YES'


test.assert_equals(tickets([25, 25, 50]), "YES")
test.assert_equals(tickets([25, 100]), "NO")
test.assert_equals(tickets([25, 25, 50, 50, 100]), "NO")
test.assert_equals(tickets([50, 100, 100]), "NO")
test.assert_equals(tickets([100, 25, 100]), "NO")
test.assert_equals(tickets([25, 50, 50, 100]), "NO")
test.assert_equals(
    tickets([25, 50, 25, 25, 50, 25, 25, 25, 100, 25, 25, 25, 25, 25, 50,
             100]), "YES")
test.assert_equals(tickets([25, 25, 50]), "YES")
예제 #4
0
    for i in x:
        if int(i) < 5:
            output += '0'
        else:
            output += '1'
    return output


# Nice one
def fake_bin(s):
    return s.translate(string.maketrans('0123456789', '0000011111'))


# Nice, but not as readable
def fake_bin(x):
    return ''.join('0' if c < '5' else '1' for c in x)


test.describe("Example Tests")
tests = [
    # [expected, input]
    ["01011110001100111", "45385593107843568"],
    ["101000111101101", "509321967506747"],
    ["011011110000101010000011011", "366058562030849490134388085"],
    ["01111100", "15889923"],
    ["100111001111", "800857237867"],
]

for exp, inp in tests:
    test.assert_equals(fake_bin(inp), exp)
예제 #5
0
def count_positives_sum_negatives(arr):
    if not arr: return []
    pos = 0
    neg = 0
    for x in arr:
        if x > 0:
            pos += 1
        if x < 0:
            neg += x
    return [pos, neg]


# Other different, nice
def count_positives_sum_negatives(arr):
    pos = sum(1 for x in arr if x > 0)
    neg = sum(x for x in arr if x < 0)
    return [pos, neg] if len(arr) else []


Test.describe("Basic tests")
Test.assert_equals(
    count_positives_sum_negatives(
        [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15]), [10, -65])
Test.assert_equals(
    count_positives_sum_negatives(
        [0, 2, 3, 0, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14]), [8, -50])
Test.assert_equals(count_positives_sum_negatives([1]), [1, 0])
Test.assert_equals(count_positives_sum_negatives([-1]), [0, -1])
Test.assert_equals(count_positives_sum_negatives([0, 0, 0, 0, 0, 0, 0, 0, 0]),
                   [0, 0])
Test.assert_equals(count_positives_sum_negatives([]), [])
예제 #6
0
from Test import Test, Test as test
'''
Given an array of integers your solution should find the smallest integer.

For example:

Given [34, 15, 88, 2] your solution will return 2
Given [34, -345, -1, 100] your solution will return -345
You can assume, for the purpose of this kata, that the supplied array will not be empty.
'''


def find_smallest_int(arr):
    return min(arr)


test.assert_equals(find_smallest_int([78, 56, 232, 12, 11, 43]), 11)
test.assert_equals(find_smallest_int([78, 56, -2, 12, 8, -33]), -33)
test.assert_equals(find_smallest_int([0, 1 - 2**64, 2**64]), 1 - 2**64)
예제 #7
0
maskify(               "1") ==                "1"
maskify(                "") ==                 ""

# "What was the name of your first pet?"
maskify("Skippy")                                   == "##ippy"
maskify("Nananananananananananananananana Batman!") == "####################################man!"
'''


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


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')
예제 #8
0
No Story

No Description

Only by Thinking and Testing

Look at the result of testcase, guess the code!
'''


def test_it(a, b):
    return sum([int(x) for x in str(a)]) * sum([int(y) for y in str(b)])


# Hmm.. 0 * 1 = 0
test.assert_equals(test_it(0, 1), 0)

# Yes, 1 * 2 = 2
test.assert_equals(test_it(1, 2), 2)

# I know, 5 * 6 = 30
test.assert_equals(test_it(5, 6), 30)

# What? 10 * 10 = 1 ?
test.assert_equals(test_it(10, 10), 1)

# Damn.. 200 * 200 = 4, 0 was omitted ?
test.assert_equals(test_it(200, 200), 4)

# Discover the mysteries of it ;-)
test.assert_equals(test_it(12, 34), 21)
예제 #9
0
from Test import Test, Test as test
'''
Timmy & Sarah think they are in love, but around where they live, they will only know once they pick a flower each. If one of the flowers has an even number of petals and the other has an odd number of petals it means they are in love.

Write a function that will take the number of petals of each flower and return true if they are in love and false if they aren't.
'''


def lovefunc(flower1, flower2):
    if (flower1 % 2 == 0 and flower2 % 2 == 1) or (flower1 % 2 == 1
                                                   and flower2 % 2 == 0):
        return True
    return False


test.assert_equals(lovefunc(1, 4), True)
test.assert_equals(lovefunc(2, 2), False)
test.assert_equals(lovefunc(0, 1), True)
test.assert_equals(lovefunc(0, 0), False)
예제 #10
0
from Test import Test, Test as test
'''
Check to see if a string has the same amount of 'x's and 'o's. The method must return a boolean and be case insensitive. The string can contain any char.

Examples input/output:

XO("ooxx") => true
XO("xooxx") => false
XO("ooxXm") => true
XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true
XO("zzoo") => false
'''


def xo(s):
    return s.lower().count('x') == s.lower().count('o')


test.assert_equals(xo('xo'), True)
test.assert_equals(xo('xo0'), True)
test.assert_equals(xo('xxxoo'), False)
예제 #11
0
    if fighter1.name == first_attacker:
        hitter = fighter1
        victim = fighter2
    else:
        hitter = fighter2
        victim = fighter1

    while True:
        victim.health -= hitter.damage_per_attack
        if victim.health <= 0:
            return hitter.name
        hitter, victim = victim, hitter


test.assert_equals(
    declare_winner(Fighter("Lew", 10, 2), Fighter("Harry", 5, 4), "Lew"),
    "Lew")
test.assert_equals(
    declare_winner(Fighter("Lew", 10, 2), Fighter("Harry", 5, 4), "Harry"),
    "Harry")
test.assert_equals(
    declare_winner(Fighter("Harald", 20, 5), Fighter("Harry", 5, 4), "Harry"),
    "Harald")
test.assert_equals(
    declare_winner(Fighter("Harald", 20, 5), Fighter("Harry", 5, 4), "Harald"),
    "Harald")
test.assert_equals(
    declare_winner(Fighter("Jerry", 30, 3), Fighter("Harald", 20, 5), "Jerry"),
    "Harald")
test.assert_equals(
    declare_winner(Fighter("Jerry", 30, 3), Fighter("Harald", 20, 5),
예제 #12
0
from Test import Test, Test as test
'''
Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.

Example: The binary representation of 1234 is 10011010010, so the function should return 5 in this case
'''


def countBits(n):
    return bin(n).count('1')


test.assert_equals(countBits(0), 0)
test.assert_equals(countBits(4), 1)
test.assert_equals(countBits(7), 3)
test.assert_equals(countBits(9), 2)
test.assert_equals(countBits(10), 2)
예제 #13
0
    return total


# Using length of list
def duplicate_count(text):
    output = []
    input = text.lower()
    for letter in input:
        if input.count(letter) > 1 and letter not in output:
            output.append(letter)
    return len(output)


# Create dictionary, which will not allow duplicates
# Return length of dictionary
def duplicate_count(text):
    x = text.lower()
    return len({y for y in x if x.count(y) > 1})


# Better, use set(), in which every value is unique
# Loop through the set so only going through each item once
# But get count from full item
def duplicate_count(text):
    return len({y for y in set(text.lower()) if text.lower().count(y) > 1})


test.assert_equals(duplicate_count("abcde"), 0)
test.assert_equals(duplicate_count("abcdea"), 1)
test.assert_equals(duplicate_count("indivisibility"), 1)
예제 #14
0
    length = len(names)
    # d[min(4, length)] insures that the appropriate string is called from the dictionary
    # and subsequently returned. Min is necessary as len(names) may be > 4

    # The * in *names ensures that the list names is blown up and that format is called
    # as if each item in names was passed to format individually, i. e.
    # format(names[0], names[1], .... , names[n], others = length - 2
    return d[min(4, length)].format(*names, others=length - 2)


# My own practice
def likes(names):
    n = len(names)
    d = {
        0: 'no one likes this',
        1: '{} likes this',
        2: '{} and {} like this',
        3: '{}, {} and {} like this',
        4: '{}, {} and {o} others like this'
    }
    return d[min(4, n)].format(*names, o=n - 2)


Test.assert_equals(likes([]), 'no one likes this')
Test.assert_equals(likes(['Peter']), 'Peter likes this')
Test.assert_equals(likes(['Jacob', 'Alex']), 'Jacob and Alex like this')
Test.assert_equals(likes(['Max', 'John', 'Mark']),
                   'Max, John and Mark like this')
Test.assert_equals(likes(['Alex', 'Jacob', 'Mark', 'Max']),
                   'Alex, Jacob and 2 others like this')
예제 #15
0
def is_triangle(a, b, c):
    return (a<b+c) and (b<a+c) and (c<a+b)

def is_triangle(a, b, c):
    return (a + b) > c and (a + c) > b and (b + c) > a

def is_triangle(a, b, c):
    a, b, c = sorted([a, b, c])
    return a + b > c



Test.describe('is_triangle')

Test.it("works for some examples")
Test.assert_equals(is_triangle(1, 2, 2), True, "didn't work when sides were 1, 2, 2")
Test.assert_equals(is_triangle(7, 2, 2), False, "didn't work when sides were 7, 2, 2")
Test.assert_equals(is_triangle(1, 2, 3), False, "didn't work when sides were 1, 2, 3")
Test.assert_equals(is_triangle(1, 3, 2), False, "didn't work when sides were 1, 3, 2")
Test.assert_equals(is_triangle(3, 1, 2), False, "didn't work when sides were 3, 1, 2")
Test.assert_equals(is_triangle(5, 1, 2), False, "didn't work when sides were 5, 1, 2")
Test.assert_equals(is_triangle(1, 2, 5), False, "didn't work when sides were 1, 2, 5")
Test.assert_equals(is_triangle(2, 5, 1), False, "didn't work when sides were 2, 5, 1")
Test.assert_equals(is_triangle(4, 2, 3), True, "didn't work when sides were 4, 2, 3")
Test.assert_equals(is_triangle(5, 1, 5), True, "didn't work when sides were 5, 1, 5")
Test.assert_equals(is_triangle(2, 2, 2), True, "didn't work when sides were 2, 2, 2")
Test.assert_equals(is_triangle(-1, 2, 3), False, "didn't work when sides were -1, 2, 3")
Test.assert_equals(is_triangle(1, -2, 3), False, "didn't work when sides were 1, -2, 3")
Test.assert_equals(is_triangle(1, 2, -3), False, "didn't work when sides were 1, 2, -3")
Test.assert_equals(is_triangle(0, 2, 3), False, "didn't work when sides were 0, 2, 3")
예제 #16
0
from Test import Test
'''
Create a function that returns the sum of the two lowest positive numbers given an array of minimum 4 positive integers. No floats or non-positive integers will be passed.

For example, when an array is passed like [19, 5, 42, 2, 77], the output should be 7.

[10, 343445353, 3453445, 3453545353453] should return 3453455.
'''


def sum_two_smallest_numbers(n):
    return sorted(n)[0] + sorted(n)[1]


# Top one, clever
def sum_two_smallest_numbers(n):
    return sum(sorted(n)[:2])


Test.describe("Basic tests")
Test.assert_equals(sum_two_smallest_numbers([5, 8, 12, 18, 22]), 13)
Test.assert_equals(sum_two_smallest_numbers([7, 15, 12, 18, 22]), 19)
Test.assert_equals(sum_two_smallest_numbers([25, 42, 12, 18, 22]), 30)
'''


def points(games):
    score = 0
    for g in games:
        x, y = g.split(':')
        if x > y:
            score += 3
        elif x == y:
            score += 1
    return score


Test.assert_equals(
    points(
        ['1:0', '2:0', '3:0', '4:0', '2:1', '3:1', '4:1', '3:2', '4:2',
         '4:3']), 30)
Test.assert_equals(
    points(
        ['1:1', '2:2', '3:3', '4:4', '2:2', '3:3', '4:4', '3:3', '4:4',
         '4:4']), 10)
Test.assert_equals(
    points(
        ['0:1', '0:2', '0:3', '0:4', '1:2', '1:3', '1:4', '2:3', '2:4',
         '3:4']), 0)
Test.assert_equals(
    points(
        ['1:0', '2:0', '3:0', '4:0', '2:1', '1:3', '1:4', '2:3', '2:4',
         '3:4']), 15)
Test.assert_equals(
    points(
예제 #18
0
from Test import Test, Test as test
'''
Complete the square sum function so that it squares each number passed into it and then sums the results together.

For example, for [1, 2, 2] it should return 9 because 1^2 + 2^2 + 2^2 = 9.
'''


def square_sum(numbers):
    return sum(i * i for i in numbers)


Test.assert_equals(square_sum([1, 2]), 5)
Test.assert_equals(square_sum([0, 3, 4, 5]), 50)
예제 #19
0
from Test import Test, Test as test
'''
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.
'''


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


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)
예제 #20
0
from Test import Test, Test as test
'''
Simple, remove the spaces from the string, then return the resultant string.
'''


def no_space(x):
    return x.replace(' ', '')


Test.describe("Basic tests")
Test.assert_equals(no_space('8 j 8   mBliB8g  imjB8B8  jl  B'),
                   '8j8mBliB8gimjB8B8jlB')
Test.assert_equals(no_space('8 8 Bi fk8h B 8 BB8B B B  B888 c hl8 BhB fd'),
                   '88Bifk8hB8BB8BBBB888chl8BhBfd')
Test.assert_equals(no_space('8aaaaa dddd r     '), '8aaaaaddddr')
Test.assert_equals(no_space('jfBm  gk lf8hg  88lbe8 '), 'jfBmgklf8hg88lbe8')
Test.assert_equals(no_space('8j aam'), '8jaam')
There is a bus moving in the city, and it takes and drop some people in each bus stop.

You are provided with a list (or array) of integer arrays (or tuples). Each integer array has two items which represent number of people get into bus (The first item) and number of people get off the bus (The second item) in a bus stop.

Your task is to return number of people who are still in the bus after the last bus station (after the last array). Even though it is the last bus stop, the bus is not empty and some people are still in the bus, and they are probably sleeping there :D

Take a look on the test cases.

Please keep in mind that the test cases ensure that the number of people in the bus is always >= 0. So the return integer can't be negative.

The second value in the first integer array is 0, since the bus is empty in the first bus stop.
'''


def number(bus_stops):
    left = 0
    for stop in bus_stops:
        left += stop[0] - stop[1]
    return left


def number(bus_stops):
    return sum([s[0] - s[1] for s in bus_stops])


test.assert_equals(number([[10, 0], [3, 5], [5, 8]]), 5)
test.assert_equals(number([[3, 0], [9, 1], [4, 10], [12, 2], [6, 1], [7, 10]]),
                   17)
test.assert_equals(number([[3, 0], [9, 1], [4, 8], [12, 2], [6, 1], [7, 8]]),
                   21)
예제 #22
0
Give your answer as a string matching "odd" or "even".

If the input array is empty consider it as: [0] (array with a zero).

Example:
odd_or_even([0])          ==  "even"
odd_or_even([0, 1, 4])    ==  "odd"
odd_or_even([0, -1, -5])  ==  "even"
'''


def odd_or_even(arr):
    if sum(arr) % 2:
        return 'odd'
    return 'even'


# Top solution
def oddOrEven(arr):
    return 'even' if sum(arr) % 2 == 0 else 'odd'


# interesting, indexing tuple
def oddOrEven(arr):
    return ('even', 'odd')[sum(arr) % 2]


test.assert_equals(odd_or_even([0, 1, 2]), "odd")
test.assert_equals(odd_or_even([0, 1, 3]), "even")
test.assert_equals(odd_or_even([1023, 1, 2]), "even")
예제 #23
0
from Test import Test, Test as test
'''
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.

Note: If the number is a multiple of both 3 and 5, only count it once.
'''


def solution(number):
    l = []
    for x in range(3, number):
        if x % 3 == 0 or x % 5 == 0:
            l.append(x)
    print(l)
    return sum(l)


def solution(number):
    return sum([x for x in range(3, number) if x % 3 == 0 or x % 5 == 0])


test.assert_equals(solution(10), 23)
예제 #24
0
            for n in list(range(1, 10)):
                if n not in [
                        board[x + a][y + b] for a in range(3) for b in range(3)
                ]:
                    return False
    return True


try:
    valid_solution = validSolution
except NameError:
    pass

test.assert_equals(
    valid_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]]), True)

test.assert_equals(
    valid_solution([[5, 3, 4, 6, 7, 8, 9, 1, 2], [6, 7, 2, 1, 9, 0, 3, 4, 9],
                    [1, 0, 0, 3, 4, 2, 5, 6, 0], [8, 5, 9, 7, 6, 1, 0, 2, 0],
                    [4, 2, 6, 8, 5, 3, 7, 9, 1], [7, 1, 3, 9, 2, 4, 8, 5, 6],
                    [9, 0, 1, 5, 3, 7, 2, 1, 4], [2, 8, 7, 4, 1, 9, 6, 3, 5],
                    [3, 0, 0, 4, 8, 1, 1, 7, 9]]), False)

test.assert_equals(
    valid_solution([[1, 2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 4, 5, 6, 7, 8, 9, 1],
                    [3, 4, 5, 6, 7, 8, 9, 1, 2], [4, 5, 6, 7, 8, 9, 1, 2, 3],
                    [5, 6, 7, 8, 9, 1, 2, 3, 4], [6, 7, 8, 9, 1, 2, 3, 4, 5],
                    [7, 8, 9, 1, 2, 3, 4, 5, 6], [8, 9, 1, 2, 3, 4, 5, 6, 7],
예제 #25
0
from Test import Test, Test as test

'''
Write a function that takes an array of numbers and returns the sum of the numbers. The numbers can be negative or non-integer. If the array does not contain any numbers then you should return 0.

Examples
Input: [1, 5.2, 4, 0, -1]
Output: 9.2

Input: []
Output: 0

Input: [-2.398]
Output: -2.398
'''

def sum_array(a):
    return sum(a)

test.assert_equals(sum_array([]), 0)
test.assert_equals(sum_array([1, 2, 3]), 6)
test.assert_equals(sum_array([1.1, 2.2, 3.3]), 6.6)
test.assert_equals(sum_array([4, 5, 6]), 15)
test.assert_equals(sum_array(range(101)), 5050)
예제 #26
0
            return True
    return False


def group_cities(seq):
    out = []
    for city in seq:
        l = sorted({c for c in seq if check_rotate(city, c)})
        if l not in out:
            out.append(l)
    out.sort()
    out.sort(key=len, reverse=True)
    return out


test.assert_equals(
    group_cities(
        ['Tokyo', 'London', 'Rome', 'Donlon', 'Kyoto', 'Paris', 'Okyot']),
    [['Kyoto', 'Okyot', 'Tokyo'], ['Donlon', 'London'], ['Paris'], ['Rome']])

test.assert_equals(group_cities(['Tokyo', 'London', 'Rome', 'Donlon']),
                   [['Donlon', 'London'], ['Rome'], ['Tokyo']])

test.assert_equals(group_cities(['Aab', 'Baa', 'Abbc', 'Cbba', 'Ba']),
                   [['Aab', 'Baa'], ['Abbc'], ['Ba'], ['Cbba']])

test.assert_equals(group_cities(['Rome', 'Rome', 'Rome', 'Donlon', 'London']),
                   [['Donlon', 'London'], ['Rome']])
test.assert_equals(group_cities(['Ab', 'Aa']), [['Aa'], ['Ab']])
test.assert_equals(group_cities([]), [])
예제 #27
0
The goal of this exercise is to convert a string to a new string where each character in the new string is "(" if that character appears only once in the original string, or ")" if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate.
'''


def duplicate_encode(word):
    o = ''
    for l in word:
        if word.lower().count(l.lower()) == 1:
            o = o + '('
        else:
            o = o + ')'
    return o


# One liner, but not readable
def duplicate_encode(word):
    return ''.join(
        ['(' if word.lower().count(l.lower()) == 1 else ')' for l in word])


# Two liner, more readable, cleaner
def duplicate_encode(word):
    w = word.lower()
    return ''.join(['(' if w.count(l) == 1 else ')' for l in w])


Test.assert_equals(duplicate_encode("din"), "(((")
Test.assert_equals(duplicate_encode("recede"), "()()()")
Test.assert_equals(duplicate_encode("Success"), ")())())")
Test.assert_equals(duplicate_encode("(( @"), "))((")
예제 #28
0
from Test import Test, Test as test

'''
A hero is on his way to the castle to complete his mission. However, he's been told that the castle is surrounded with a couple of powerful dragons! each dragon takes 2 bullets to be defeated, our hero has no idea how many bullets he should carry.. Assuming he's gonna grab a specific given number of bullets and move forward to fight another specific given number of dragons, will he survive?

Return True if yes, False otherwise :)
'''

def hero(bullets, dragons):
    if bullets / dragons < 2 or dragons == 0:
        return False
    return True

# Top solution
def hero(bullets, dragons):
    return bullets >= dragons * 2


test.assert_equals(hero(10, 5), True)
test.assert_equals(hero(7, 4), False)
test.assert_equals(hero(4, 5), False)
test.assert_equals(hero(100, 40), True)
test.assert_equals(hero(1500, 751), False)
test.assert_equals(hero(0, 1), False)
예제 #29
0
For example, given the input [2, 1, 2], we can hold 1 unit of water in the middle.

Given the input [3, 0, 1, 3, 0, 5], we can hold 3 units in the first index, 2 in the second, and 3 in the fourth index (we cannot hold 5 since it would run off to the left), so we can trap 8 units of water.
'''

# Some ideas
# 1. Find all peaks
# 1a. Save as sub-lists
# 2. Fill in water


def check_answer(arr):
    high_start = arr[0]
    high_end = 0
    in_valley = False

    peaks = []

    for i in arr[1:]:
        # New start
        if i > high_start:
            high_start = i
            pass
        elif i < high_start:
            pass
        total += i - min_val
    return total


Test.assert_equals(check_answer([3, 0, 1, 3, 0, 5]), 8)
예제 #30
0
from Test import Test, Test as test
'''
It's the academic year's end, fateful moment of your school report. The averages must be calculated. All the students come to you and entreat you to calculate their average for them. Easy ! You just need to write a script.

Return the average of the given array rounded down to its nearest integer.

The array will never be empty.
'''

import math


def get_average(marks):
    return math.floor(sum(marks) / len(marks))


# Top solution
def get_average(marks):
    return sum(marks) // len(marks)


test.assert_equals(get_average([2, 2, 2, 2]), 2,
                   "didn't work for [2, 2, 2, 2]")
test.assert_equals(get_average([1, 5, 87, 45, 8, 8]), 25,
                   "didn't work for [1, 5, 87, 45, 8, 8]")
test.assert_equals(get_average([2, 5, 13, 20, 16, 16, 10]), 11,
                   "didn't work for [2,5,13,20,16,16,10]")
test.assert_equals(
    get_average([1, 2, 15, 15, 17, 11, 12, 17, 17, 14, 13, 15, 6, 11, 8, 7]),
    11, "didn't work for [1,2,15,15,17,11,12,17,17,14,13,15,6,11,8,7]")