Exemple #1
0
    return False

# others
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")
Exemple #2
0
                                f'{other} already played with {player}, return False'
                            )
                            return False
                        else:
                            player_stats[player]['with'].append(other)

    # Check if each player golfed every day
    for player in player_stats:
        if len(player_stats[player]['played']) != len(a):
            print(f'{player} did NOT play all {len(a)} days')
            return False

    return True


test.describe("Simple Positive Tests")

# Satisfying the following case is optional; uncomment it if you like.
#test.it("accepts having no golfers at all")
#for s in ([], [[]], [[],[]], [[],[],[]]):
#    test.assert_equals(valid(s), True, "There are no conflicts with zero golfers")

test.it("can handle the two-player case")
s = [["AB"]]
test.assert_equals(valid(s), True, "Two player, one day works")

test.it("can handle a four-player case")
s = [["AB", "CD"], ["AD", "BC"], ["BD", "AC"]]
test.assert_equals(valid(s), True, "Four players, three days works")

test.it("can handle the case from Wolfram MathWorld")
  '     *     ',
  '    ***    ',
  '   *****   ',
  '  *******  ',
  ' ********* ',
  '***********'
]
'''

# Initial
def tower_builder(n_floors):
    total_len = n_floors * 2 - 1
    l = []
    for x in range(1, n_floors+1):
        a = '*' * (x * 2 - 1)
        a = a.center(total_len, ' ')
        l.append(a)
    return l

# Condensed
def tower_builder(n_floors):
    return [('*' * (x*2-1)).center(n_floors*2-1) for x in range(1, n_floors+1)]



test.describe("Tests")
test.it("Basic Tests")
test.assert_equals(tower_builder(1), ['*', ])
test.assert_equals(tower_builder(2), [' * ', '***'])
test.assert_equals(tower_builder(3), ['  *  ', ' *** ', '*****'])
from Test import Test, Test as test
'''
Jenny has written a function that returns a greeting for a user. However, she's in love with Johnny, and would like to greet him slightly different. She added a special case to her function, but she made a mistake.

Can you help her?
'''


def greet(name):
    if name == "Johnny":
        return "Hello, my love!"
    return f"Hello, {name}!"


Test.describe("Jenny's greeting function")
Test.it("should greet some people normally")
Test.assert_equals(greet("James"), "Hello, James!")
Test.assert_equals(greet("Jane"), "Hello, Jane!")
Test.assert_equals(greet("Jim"), "Hello, Jim!")

Test.it("should greet Johnny a little bit more special")
Test.assert_equals(greet("Johnny"), "Hello, my love!")
Example:

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


def solution(args):
    s = ''
    for i in args:
        if len(s) == 0:
            s = str(i)
        elif i - 1 in args and i + 1 in args:
            if s[-1] != '-':
                s += '-'
        elif s[-1] == '-':
            s += str(i)
        else:
            s += ',' + str(i)
    return s


Test.describe("Sample Test Cases")
Test.it("Simple Tests")
Test.assert_equals(
    solution([
        -6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20
    ]), '-6,-3-1,3-5,7-11,14,15,17-20')
Test.assert_equals(solution([-3, -2, -1, 2, 10, 15, 16, 18, 19, 20]),
                   '-3--1,2,10,15,16,18-20')
Exemple #6
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([]), [])
Exemple #7
0
    elif p[p.index(p1)-1] == p2:
        return "Player 1 won!"
    return "Player 2 won!"

# Top solution - more readable
def rps(p1, p2):
    beats = {'rock': 'scissors', 'scissors': 'paper', 'paper': 'rock'}
    if beats[p1] == p2:
        return "Player 1 won!"
    elif beats[p2] == p1:
        return "Player 2 won!"
    return "Draw!"




Test.describe('rock paper scissors')
Test.it('player 1 win')
Test.assert_equals(rps('rock', 'scissors'), "Player 1 won!")
Test.assert_equals(rps('scissors', 'paper'), "Player 1 won!")
Test.assert_equals(rps('paper', 'rock'), "Player 1 won!")

Test.it('player 2 win')
Test.assert_equals(rps('scissors', 'rock'), "Player 2 won!")
Test.assert_equals(rps('paper', 'scissors'), "Player 2 won!")
Test.assert_equals(rps('rock', 'paper'), "Player 2 won!")

Test.it('draw')
Test.assert_equals(rps('rock', 'rock'), 'Draw!')
Test.assert_equals(rps('scissors', 'scissors'), 'Draw!')
Test.assert_equals(rps('paper', 'paper'), 'Draw!')
Exemple #8
0
from Test import Test
'''
Given an array of ones and zeroes, convert the equivalent binary value to an integer.

Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1.
'''


def binary_array_to_number(arr):
    total = 0
    step = 1
    arr.reverse()
    for digit in arr:
        if digit == 1:
            total += step
        step *= 2
    return total


Test.describe("One's and Zero's")
Test.it("Example tests")
Test.assert_equals(binary_array_to_number([0, 0, 0, 1]), 1)
Test.assert_equals(binary_array_to_number([0, 0, 1, 0]), 2)
Test.assert_equals(binary_array_to_number([1, 1, 1, 1]), 15)
Test.assert_equals(binary_array_to_number([0, 1, 1, 0]), 6)
Exemple #9
0
error_printer(s) => "0/14"

s="aaaxbbbbyyhwawiwjjjwwm"
error_printer(s) => "8/22"
'''


def printer_error(s):
    return f"{len([x for x in s if x in 'nopqrstuvwxyz'])}/{len(s)}"


# Top one
from re import sub


def printer_error(s):
    return "{}/{}".format(len(sub("[a-m]", '', s)), len(s))


import re


def printer_error(s):
    return '{}/{}'.format(len(re.findall('[n-z]', s)), len(s))


Test.describe("printer_error")
Test.it("Basic tests")
s = "aaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbmmmmmmmmmmmmmmmmmmmxyz"
Test.assert_equals(printer_error(s), "3/56")
from Test import Test, Test as test
'''
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.
'''


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


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)
# https://www.codewars.com/kata/58acfe4ae0201e1708000075/train/python

from Test import Test


def invite_more_women(arr):
    return False if sum(arr) <= 0 else True


# best solution
def invite_more_women_best(arr):
    return sum(arr) > 0


# Nice Solurion
def invite_more_women_nice(arr):
    return arr.count(1) > arr.count(-1)


testing = Test()

testing.describe("Basic Tests")
testing.assert_equals(invite_more_women([1, -1, 1]), True)
testing.assert_equals(invite_more_women([-1, -1, -1]), False)
testing.assert_equals(invite_more_women([1, -1]), False)
testing.assert_equals(invite_more_women([1, 1, 1]), True)
testing.assert_equals(invite_more_women([]), False)

testing.report()
from Test import Test, Test as test
'''
Given an array of integers, return a new array with each value doubled.

For example:

[1, 2, 3] --> [2, 4, 6]

For the beginner, try to use the map method - it comes in very handy quite a lot so is a good one to know.
'''


def maps(a):
    return [i * 2 for i in a]


test.describe("Sample tests")
test.assert_equals(maps([1, 2, 3]), [2, 4, 6])
test.assert_equals(maps([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),
                   [0, 2, 4, 6, 8, 10, 12, 14, 16, 18])
test.assert_equals(maps([]), [])
Exemple #13
0
    l = []
    for n, i in enumerate(s, start=1):
        l.append((i * n).title())
    return '-'.join(l)


def accum(s):
    return '-'.join([(i * n).title() for n, i in enumerate(s, start=1)])


# Top solution, nice thinking
def accum(s):
    return '-'.join(c.upper() + c.lower() * i for i, c in enumerate(s))


Test.describe("accum")
Test.it("Basic tests")
Test.assert_equals(
    accum("ZpglnRxqenU"),
    "Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu"
)
Test.assert_equals(
    accum("NyffsGeyylB"),
    "N-Yy-Fff-Ffff-Sssss-Gggggg-Eeeeeee-Yyyyyyyy-Yyyyyyyyy-Llllllllll-Bbbbbbbbbbb"
)
Test.assert_equals(
    accum("MjtkuBovqrU"),
    "M-Jj-Ttt-Kkkk-Uuuuu-Bbbbbb-Ooooooo-Vvvvvvvv-Qqqqqqqqq-Rrrrrrrrrr-Uuuuuuuuuuu"
)
Test.assert_equals(
    accum("EvidjUnokmM"),
For example:

time = 3 ----> litres = 1

time = 6.7---> litres = 3

time = 11.8--> litres = 5
'''

import math


def litres(time):
    return math.floor(time * 0.5)


# top
def litres(time):
    return time // 2


test.describe('Fixed tests')
test.it('Tests')
test.assert_equals(litres(2), 1, 'should return 1 litre')
test.assert_equals(litres(1.4), 0, 'should return 0 litres')
test.assert_equals(litres(12.3), 6, 'should return 6 litres')
test.assert_equals(litres(0.82), 0, 'should return 0 litres')
test.assert_equals(litres(11.8), 5, 'should return 5 litres')
test.assert_equals(litres(1787), 893, 'should return 893 litres')
test.assert_equals(litres(0), 0, 'should return 0 litres')
Exemple #15
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)
from case_sensitive import case_sensitive
from Test import Test
import unittest

# Using built-in Test.py class: $ python test_case_sensitive
test = Test()

test.describe("Basic Tests")
test.it("Sample Tests")
test.assert_equals(case_sensitive('asd'), [True, []])
test.assert_equals(case_sensitive('cellS'), [False, ['S']])
test.assert_equals(case_sensitive('z'), [True, []])
test.assert_equals(case_sensitive(''), [True, []])


# Using pytest: $ pytest -v test_case_sensitive
def test_basic_tests():
    assert case_sensitive('asd') == [True, []]
    assert case_sensitive('cellS') == [False, ['S']]
    assert case_sensitive('z') == [True, []]
    assert case_sensitive('') == [True, []]


# Using unittest: $ python -m unittest -v test_case_sensitive.Testing
class Testing(unittest.TestCase):
    def test_string(self):
        a = 'some'
        b = 'some'
        self.assertEqual(a, b)

    def test_boolean(self):
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')
from Test import Test, Test as test
'''
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?
'''


def greet():
    return ''.join(
        ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!'])


test.describe("Greet function")
test.it("Making sure greet exists")
test.assert_equals(greet(), "hello world!",
                   "Greet doesn't return hello world!")
Exemple #19
0
    output = ''
    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)
from Test import Test, Test as test
'''
It's pretty straightforward. Your goal is to create a function that removes the first and last characters of a string. You're given one parameter, the original string. You don't have to worry with strings with less than two characters.
'''


def remove_char(s):
    return s[1:-1]


Test.describe("Tests")
Test.assert_equals(remove_char('eloquent'), 'loquen')
Test.assert_equals(remove_char('country'), 'ountr')
Test.assert_equals(remove_char('person'), 'erso')
Test.assert_equals(remove_char('place'), 'lac')
Test.assert_equals(remove_char('ok'), '')