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 #2
0
    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")
s = [['ABCD', 'EFGH', 'IJKL', 'MNOP', 'QRST'],
     ['AEIM', 'BJOQ', 'CHNT', 'DGLS', 'FKPR'],
     ['AGKO', 'BIPT', 'CFMS', 'DHJR', 'ELNQ'],
     ['AHLP', 'BKNS', 'CEOR', 'DFIQ', 'GJMT'],
     ['AFJN', 'BLMR', 'CGPQ', 'DEKT', 'HIOS']]
test.assert_equals(valid(s), True, "Wolfram MathWorld case works")
Exemple #3
0
from Test import Test, Test as test
'''
Given a set of numbers, return the additive inverse of each. Each positive becomes negatives, and the negatives become positives.

invert([1,2,3,4,5]) == [-1,-2,-3,-4,-5]
invert([1,-2,3,-4,5]) == [-1,2,-3,4,-5]
invert([]) == []
You can assume that all values are integers. Do not mutate the input array/list.
'''


def invert(lst):
    return [-i for i in lst]


Test.it("Basic Tests")
Test.assert_equals(invert([1, 2, 3, 4, 5]), [-1, -2, -3, -4, -5])
Test.assert_equals(invert([1, -2, 3, -4, 5]), [-1, 2, -3, 4, -5])
Test.assert_equals(invert([]), [])
from Test import Test, Test as test

'''
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.
'''

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

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)
import sys
sys.path.append("..")

from Test import Test as test


def max_sumDig(nMax, maxSum):
    for nbr in range(1000, nMax):
        nbr = str(nbr)


test.describe("Example tests")
test.it("nMax = " + str(2000))
test.it("maxSum = " + str(3))
test.assert_equals(max_sumDig(2000, 3), [11, 1110, 12555])
test.it("nMax = " + str(2000))
test.it("maxSum = " + str(4))
test.assert_equals(max_sumDig(2000, 4), [21, 1120, 23665])
test.it("nMax = " + str(2000))
test.it("maxSum = " + str(7))
test.assert_equals(max_sumDig(2000, 7), [85, 1200, 99986])
test.it("nMax = " + str(3000))
test.it("maxSum = " + str(7))
test.assert_equals(max_sumDig(3000, 7), [141, 1600, 220756])
test.it("nMax = " + str(4000))
test.it("maxSum = " + str(4))
test.assert_equals(max_sumDig(4000, 4), [35, 2000, 58331])
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!")
Exemple #7
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")
Exemple #8
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)
Exemple #9
0
eg:

validate_pin("1234") == True
validate_pin("12345") == False
validate_pin("a234") == False
'''

def validate_pin(pin):
    return (len(pin) == 4 or len(pin) == 6) and pin.isnumeric()

# Top solution
def validate_pin(pin):
    return len(pin) in (4, 6) and pin.isdigit()

Test.it("should return False for pins with length other than 4 or 6")
Test.assert_equals(validate_pin("1"), False, "Wrong output for '1'")
Test.assert_equals(validate_pin("12"), False, "Wrong output for '12'")
Test.assert_equals(validate_pin("123"), False, "Wrong output for '123'")
Test.assert_equals(validate_pin("12345"), False, "Wrong output for '12345'")
Test.assert_equals(validate_pin("1234567"), False, "Wrong output for '1234567'")
Test.assert_equals(validate_pin("-1234"), False, "Wrong output for '-1234'")
Test.assert_equals(validate_pin("1.234"), False, "Wrong output for '1.234'")
Test.assert_equals(validate_pin("00000000"), False, "Wrong output for '00000000'")

Test.it("should return False for pins which contain characters other than digits")
Test.assert_equals(validate_pin("a234"), False, "Wrong output for 'a234'")
Test.assert_equals(validate_pin(".234"), False, "Wrong output for '.234'")
Test.assert_equals(validate_pin("-123"), False, "Wrong output for '-123'")
Test.assert_equals(validate_pin("-1.234"), False, "Wrong output for '-1.234'")
Exemple #10
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)
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)
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 #13
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 #14
0
  '     *     ',
  '    ***    ',
  '   *****   ',
  '  *******  ',
  ' ********* ',
  '***********'
]
'''

# 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 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):
Exemple #16
0
# 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")
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")
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!")
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')

# Top
def sum_array(arr):
    if arr == None or len(arr) < 3:
        return 0
    return sum(arr) - max(arr) - min(arr)


# Nice
def sum_array(arr):
    return 0 if arr == None else sum(sorted(arr)[1:-1])


Test.describe("Basic tests")
Test.it("None or Empty")
Test.assert_equals(sum_array(None), 0)
Test.assert_equals(sum_array([]), 0)

Test.it("Only one Element")
Test.assert_equals(sum_array([3]), 0)
Test.assert_equals(sum_array([-3]), 0)

Test.it("Only two Element")
Test.assert_equals(sum_array([3, 5]), 0)
Test.assert_equals(sum_array([-3, -5]), 0)

Test.it("Real Tests")
Test.assert_equals(sum_array([6, 2, 1, 8, 10]), 16)
Test.assert_equals(sum_array([6, 0, 1, 10, 10]), 17)
Test.assert_equals(sum_array([-6, -20, -1, -10, -12]), -28)