Esempio n. 1
0
def example_003():
    print("""
	             1
	          3     5
	       7     9    11
	   13    15    17    19
	21    23    25    27    29		

	Calculate the row sums of this triangle from the row index (starting at index 1) e.g.:

	row_sum_odd_numbers(1); # 1
	row_sum_odd_numbers(2); # 3 + 5 = 8	

	""")

    def row_sum_odd_numbers(n):
        if n == 0:
            return 0
        # odd always start from 1 and increment steps equal "2"
        # row 1 : 1 - 1
        # row 2 : 1 , 3 , 5 - 3
        # row 3:  1, 3, 5, 7, 9, 11 - 6
        # row 4:  1, 3, 5, 7, 9, 11, 13, 15, 17, 19 - 10 = 4 * 5/2
        if n == 1:
            return 1
        sum = 0
        max_number = n * (n + 1) - 1
        print(n, max_number)

        while (n > 0):
            sum += max_number
            max_number -= 2
            n -= 1
        return sum

    test.assert_equals(row_sum_odd_numbers(1), 1)
    test.assert_equals(row_sum_odd_numbers(2), 8)
    test.assert_equals(row_sum_odd_numbers(13), 2197)
    test.assert_equals(row_sum_odd_numbers(19), 6859)
    test.assert_equals(row_sum_odd_numbers(41), 68921)
Esempio n. 2
0
def example_002():
    print('''
		Counting sheep
	''')
    sheeps = [
        True, True, True, False, True, True, True, True, True, False, True,
        False, True, False, False, True, True, True, True, True, False, False,
        True, True
    ]

    def count_sheeps(sheeps):
        # 1st-simple way: use count method of list
        # return sheeps.count(True)
        # 2nd: filter and check length
        # sheeps_filter = filter(lambda x: x == True,sheeps)
        # for k in sheeps_filter:
        # 	print(k)
        # return len(list(sheeps_filter))
        # 3rd: python comprehension
        return len([x for x in sheeps if x])

    test.assert_equals(
        count_sheeps(sheeps), 17,
        "There are 17 sheeps in total, not %s" % count_sheeps(sheeps))
Esempio n. 3
0
import test

OPEN = "([{"
OPP = {"}": "{", ")": "(", "]": "["}


def group_check(s):
    openers = []
    for c in s:
        if c in OPEN:
            openers.append(c)
        else:
            opp = OPP[c]
            if len(openers) and openers[-1] == opp:
                openers.pop()
            else:
                return False
    return len(openers) == 0


test.assert_equals(group_check("()"), True)
test.assert_equals(group_check("({"), False)
test.assert_equals(group_check("[[]"), False)
test.assert_equals(group_check("[]"), True)
test.assert_equals(group_check("{[][]}"), True)
test.assert_equals(group_check("{{{{"), False)
test.assert_equals(group_check("[][]((([])))"), True)
Esempio n. 4
0
File: 14.py Progetto: hbdhj/python
    if len(part2)==0:
        if s==part1:
            return True
        else:
            return False

    if len(part2)+len(part1)!=len(s):
        return False
    ret = []
    for i in range(len(part1)):
        row =  []
        for j in range(len(part2)):
            if s[i+j]==part1[i] or s[i+j]==part2[j]:
                row.append(0)
            else:
                row.append(1)
        print(row)
        ret.append(row)
    print(ret)
    if 0 in ret[-1]:
        return True
    else:
        return False

import test

test.assert_equals(is_merge('codewars', 'code', 'wars'), True)
test.assert_equals(is_merge('codewars', 'cdw', 'oears'),True)
test.assert_equals(is_merge('codewars', 'cod', 'wars'), False)
test.assert_equals(is_merge('Bananas from Bahamas', 'Bahas', 'Bananas from am'), True)
test.assert_equals(is_merge('Can we merge it? Yes, we can!', 'Can mer it?Y cn', 'wege es, wea!'), True)
Esempio n. 5
0
File: 73.py Progetto: hbdhj/python
import test

scores = {"teamA":3,"teamB":3,"teamC":3,"teamD":3}

def league_calculate(team1, team2, result):
    if result=="draw":
        scores[team1]+=1
        scores[team2]+=1
    elif result=="win":
        scores[team1]+=3
    result={}
    for team,score in scores.items():
        if score in result.keys():
            result[score].append(team)
        else:
            result[score]=[team]
    return [[team,score] for score in sorted(result.keys(), reverse=True) for team in sorted(result[score])]



test.describe("Basic tests")
test.assert_equals(league_calculate("teamA","teamB","draw"), [["teamA",4],["teamB",4],["teamC",3],["teamD",3]])
test.assert_equals(league_calculate("teamC","teamD","win"), [["teamC",6],["teamA",4],["teamB",4],["teamD",3]])
test.assert_equals(league_calculate("teamA","teamC","draw"), [["teamC",7],["teamA",5],["teamB",4],["teamD",3]])
test.assert_equals(league_calculate("teamB","teamD","win"), [["teamB",7],["teamC",7],["teamA",5],["teamD",3]])
test.assert_equals(league_calculate("teamA","teamB","win"), [["teamA",8],["teamB",7],["teamC",7],["teamD",3]])
test.assert_equals(league_calculate("teamC","teamD","draw"), [["teamA",8],["teamC",8],["teamB",7],["teamD",4]])
test.assert_equals(league_calculate("teamD","teamA","draw"), [["teamA",9],["teamC",8],["teamB",7],["teamD",5]])
test.assert_equals(league_calculate("teamC","teamB","win"), [["teamC",11],["teamA",9],["teamB",7],["teamD",5]])
test.assert_equals(league_calculate("teamB","teamD","win"), [["teamC",11],["teamB",10],["teamA",9],["teamD",5]])
test.assert_equals(league_calculate("teamA","teamB","draw"), [["teamB",11],["teamC",11],["teamA",10],["teamD",5]])
Esempio n. 6
0
File: 90.py Progetto: hbdhj/python
        return "NaR"
    r = ""
    roman = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
    romanN = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
    frac = ["", ".", ":", ":.", "::", ":.:", "S", "S.", "S:", "S:.", "S::", "S:.:"]
    if number == 0:
        if fraction == 0:
            return "N"
        return frac[fraction]
    while number > 0:
        for i in range(13):
            if romanN[i] <= number:
                r += roman[i]
                number -= romanN[i]
                break
    return r+frac[fraction]

import test

test.describe("Examples")
test.assert_equals(roman_fractions(-12), "NaR")
test.assert_equals(roman_fractions(0, -1), "NaR")
test.assert_equals(roman_fractions(0, 12), "NaR")
test.assert_equals(roman_fractions(0), "N")
test.assert_equals(roman_fractions(1), "I")
test.assert_equals(roman_fractions(1, 5), "I:.:")
test.assert_equals(roman_fractions(1, 9), "IS:.")
test.assert_equals(roman_fractions(1632, 2), "MDCXXXII:")
test.assert_equals(roman_fractions(5000), "MMMMM")
test.assert_equals(roman_fractions(5001), "NaR")
Esempio n. 7
0
  [2,3, 1,4]
])

# Invalid Sudoku
badSudoku1 = Sudoku([
  [0,2,3, 4,5,6, 7,8,9],
  [1,2,3, 4,5,6, 7,8,9],
  [1,2,3, 4,5,6, 7,8,9],
  
  [1,2,3, 4,5,6, 7,8,9],
  [1,2,3, 4,5,6, 7,8,9],
  [1,2,3, 4,5,6, 7,8,9],
  
  [1,2,3, 4,5,6, 7,8,9],
  [1,2,3, 4,5,6, 7,8,9],
  [1,2,3, 4,5,6, 7,8,9]
])

badSudoku2 = Sudoku([
  [1,2,3,4,5],
  [1,2,3,4],
  [1,2,3,4],  
  [1]
])

test.assert_equals(goodSudoku1.is_valid(), True, 'testing valid 9x9')
test.assert_equals(goodSudoku2.is_valid(), True, 'testing valid 4x4')

test.assert_equals(badSudoku1.is_valid(), False, 'Values in wrong order')
test.assert_equals(badSudoku2.is_valid(), False, '4x5 (invalid dimension)')
Esempio n. 8
0
File: 68.py Progetto: hbdhj/python
# Permutation Average

import test

import math

def permutation_average(n):
    n1 = n
    l = len(str(n))
    sum_d=0
    while n>0:
        sum_d+=n%10
        n=int(n/10)
    sum_t=sum_d
    while n1>10:
        sum_t+=sum_d*10
        n1=int(n1/10)
        sum_d*=10
    return math.ceil(sum_t/l)

test.assert_equals(permutation_average(2), 2)
test.assert_equals(permutation_average(25), 39)
test.assert_equals(permutation_average(20), 11)
test.assert_equals(permutation_average(737), 629)
test.assert_equals(permutation_average(107), 296)
Esempio n. 9
0
import test

def remove_comments(line, comments):
  for c in comments:
    pos = line.find(c)
    if pos != -1:
      line = line[: pos]
  return line.rstrip()

def solution(string, markers):
  lines = string.split('\n')
  lines_nc = map(lambda s: remove_comments(s, markers), lines)
  ret = '\n'.join(lines_nc)
  return ret


test.assert_equals(solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"]), "apples, pears\ngrapes\nbananas")
test.assert_equals(solution("a #b\nc\nd $e f g", ["#", "$"]), "a\nc\nd")
Esempio n. 10
0
File: 67.py Progetto: hbdhj/python
        for value in values:
            if check(value, criteria):
                sum+=value
    return sum

def average_if(values,criteria):
    sum = sum_if(values,criteria)
    count = count_if(values,criteria)
    if sum%count==0:
        return sum/count
    else:
        float(sum)/count

test.describe('count_if tests')
test.it('Criteria is exact match')
test.assert_equals(count_if([1,3,5,3],3),2)
test.assert_equals(count_if(['John','Steve','Rachel','Rebecca','John','John'],'John'),3)

test.it('Criteria is ">="')
test.assert_equals(count_if([1,3,5,3],'>=3'),3)

test.it('Criteria is "<="')
test.assert_equals(count_if([1.5,3,5,3,0,-1,-5],'<=1.5'),4)

test.it('Criteria is ">"')
test.assert_equals(count_if([1,3,5,3.5],'>3'),2)

test.it('Criteria is "<"')
test.assert_equals(count_if([1,3,5,3,0,-1,-5],'<1'),3)

test.it('Criteria is "<>"')
Esempio n. 11
0
File: 86.py Progetto: hbdhj/python
# Multirange iterator


def multiiter(*params):
    print(params)
    if 0 in params:
        for i in range(0):
            yield (i, )
    elif len(params) == 1:
        for i in range(params[0]):
            yield (i, )
    else:
        for i in range(params[0]):
            for j in multiiter(*params[1:]):
                yield (i, *j)

import test

test.describe("One parameter tests")


test.assert_equals(list(multiiter(0)), [])
test.assert_equals(list(multiiter(2)), [(0,), (1,)])

test.describe("Two parameter tests")
test.assert_equals(list(multiiter(2, 3)), [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)])
test.assert_equals(list(multiiter(3, 2)), [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)])
Esempio n. 12
0
    for num_digits in range(len(x) + 1, len(y)):
        count += 4 * 5 ** (num_digits // 2 - 1) * (3 if num_digits % 2 == 1 else 1)
    return count


def upsidedown_brutally(x, y):
    count = 1 if is_upsidedown(x) else 0
    while True:
        x = int(x) + 1
        if int(x) > int(y):
            break
        if is_upsidedown(x):
            count += 1
    return count


if __name__ == '__main__':
    import sys
    sys.path.insert(0, './codewars')
    import test

    test.assert_equals(upsidedown('0','10'),3)
    test.assert_equals(upsidedown('6','25'),2)
    test.assert_equals(upsidedown('10','100'),4)
    test.assert_equals(upsidedown('100','1000'),12)
    test.assert_equals(upsidedown('100000','12345678900000000'),718650)
    test.assert_equals(upsidedown('10000000000','10000000000000000000000'),78120000)
    test.assert_equals(upsidedown('861813545615','9813815838784151548487'),74745418)
    test.assert_equals(upsidedown('5748392065435706','643572652056324089572278742'),2978125000)
    test.assert_equals(upsidedown('9090908074312','617239057843276275839275848'),2919867187)
Esempio n. 13
0
File: 75.py Progetto: hbdhj/python
test.describe("Basic tests")

lst1 = [(2, 'tofu'),
       (2, 'potato'),
       (2, 'cucumber'),
       (2, 'cabbage'),
       (1, 'turnip'),
       (1, 'pepper'),
       (1, 'onion'),
       (1, 'mushroom'),
       (1, 'celery'),
       (1, 'carrot')]

s1 = 'potato tofu cucumber cabbage turnip pepper onion carrot celery mushroom potato tofu cucumber cabbage'

test.assert_equals(count_vegetables(s1), (lst1))

lst2 = [(15, 'turnip'),
        (15, 'mushroom'),
        (13, 'cabbage'),
        (10, 'carrot'),
        (9, 'potato'),
        (7, 'onion'),
        (6, 'tofu'),
        (6, 'pepper'),
        (5, 'cucumber'),
        (4, 'celery')]


s2 = '''mushroom chopsticks chopsticks turnip mushroom carrot mushroom cabbage mushroom carrot tofu pepper cabbage potato cucumber
 mushroom mushroom mushroom potato turnip chopsticks cabbage celery celery turnip pepper chopsticks potato potato onion cabbage cucumber
Esempio n. 14
0
 def testThis(config, n=1, val=0):
     for msg, expected, inp in config:
         msg, expected, inp = (s.format(val) for s in (msg, expected, inp))
         for _ in range(n - 1):
             inp = diff(inp)
         test.assert_equals(diff(inp), expected, msg)
Esempio n. 15
0
File: 81.py Progetto: hbdhj/python
                in_word=True
                start = i
        else:
            if in_word==True:
                in_word=False
                word = s[start:i]
                if word.lower() not in word_lst:
                    word_num+=1
                #print(word, word_num)
    if in_word==True:
        word = s[start:]
        #print(word)
        if word not in word_lst:
            word_num+=1
    return word_num

import test
'''
test.assert_equals(word_count("hello there."), 2)
test.assert_equals(word_count("hello there and a hi"), 4)
test.assert_equals(word_count("I'd like to say goodbye"), 6)
test.assert_equals(word_count("Slow-moving user6463 has been here"), 6)
test.assert_equals(word_count("%^&abc!@# wer45tre"), 3)
test.assert_equals(word_count("abc123abc123abc"), 3)
test.assert_equals(word_count("Really2374239847 long ^&#$&(*@# sequence"), 3)
'''
long_text = """
I’d been using my sphere as a stool. I traced counterclockwise circles on it with my fingertips and it shrank until I could palm it. My bolt had shifted while I’d been sitting. I pulled it up and yanked the pleats straight as I careered around tables, chairs, globes, and slow-moving fraas. I passed under a stone arch into the Scriptorium. The place smelled richly of ink. Maybe it was because an ancient fraa and his two fids were copying out books there. But I wondered how long it would take to stop smelling that way if no one ever used it at all; a lot of ink had been spent there, and the wet smell of it must be deep into everything.
"""

test.assert_equals(word_count(long_text), 112)
Esempio n. 16
0
File: 69.py Progetto: hbdhj/python
            sec_list = lst.remove(ch)

            sec_part = get_words_from_list(lst.remove(ch))
            print(ch, sec_part)
    elif len(lst)==2:
        return [[lst[0],lst[1]], [lst[1],lst[0]]]
    elif len(lst)==1:
        return [[lst[0]]]

def get_words(hash_of_letters):
    total_list = []
    for key, list in hash_of_letters.items():
        print(key, list)
        while key>0:
            total_list+=list
            key-=1
    #print(total_list)
    ret_list = get_words_from_list(total_list)
    #print(ret_list)
    ret = []
    for lst in ret_list:
        #print(lst)
        str=""
        for ch in lst:
            str=str+ch
        ret.append(str)
    return ret

#test.assert_equals(get_words({1:["a", "b"]}),  ["ab", "ba"])
test.assert_equals(get_words({1:["a", "b", "c"]}),  ["abc", "acb", "bac", "bca", "cab", "cba"])
#test.assert_equals(get_words({2:["a"], 1:["b", "c"]}), ["aabc", "aacb", "abac", "abca", "acab", "acba", "baac", "baca", "bcaa", "caab", "caba", "cbaa"])
Esempio n. 17
0
File: 42.py Progetto: hbdhj/python
# Which are in?
import test
def in_array(array1, array2):
    # your code
    ret = [item1 for item1 in array1 for item2 in array2 if item2.find(item1)>=0 ]
    return sorted(list(set(ret)))

a1 = ["live", "arp", "strong"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
r = ['arp', 'live', 'strong']
test.assert_equals(in_array(a1, a2), r)
Esempio n. 18
0
import test

def is_isogram(string):
  return len(set(string.lower())) == len(string)

test.assert_equals(is_isogram("Dermatoglyphics"), True )
test.assert_equals(is_isogram("isogram"), True )
test.assert_equals(is_isogram("aba"), False, "same chars may not be adjacent" )
test.assert_equals(is_isogram("moOse"), False, "same chars may not be same case" )
test.assert_equals(is_isogram("isIsogram"), False )
test.assert_equals(is_isogram(""), True, "an empty string is a valid isogram" )
Esempio n. 19
0
        pos += 1
    raise IndexError("No ']'")


def decomp(s):
    s_decomped = ''
    while s:
        m = re.match(r'\d+\[', s)
        if m:
            s = s[m.end():]
            n = int(m.group()[:-1])
            s_decomped += decomp(s) * n
            end = index_of_close_paren(s)
            s = s[end + 1:]
        else:
            if s[0] == ']':
                break
            s_decomped += s[0]
            s = s[1:]
    return s_decomped


if __name__ == '__main__':
    import sys
    sys.path.insert(0, './codewars')
    import test

    test.assert_equals(decomp("10[a]"), "aaaaaaaaaa")
    test.assert_equals(decomp("3[abc]4[ab]c"), "abcabcabcababababc")
    test.assert_equals(decomp("2[3[a]b]c"), "aaabaaabc")
Esempio n. 20
0
import test

def example_sort(arr, example):
  key_to_priority = dict(zip(example, range(len(example))))
  arr.sort(key=lambda val: key_to_priority[val])
  return arr


test.assert_equals(example_sort([1,2,3,4,5],[2,3,4,1,5]),[2,3,4,1,5])

test.assert_equals(example_sort([1,2,3,3,3,4,5],[2,3,4,1,5]),[2,3,3,3,4,1,5])

test.assert_equals(example_sort([1,2,3,3,3,5],[2,3,4,1,5]),[2,3,3,3,1,5])

test.assert_equals(example_sort([1,2,3,3,3,5],
[3,4,5,6,9,11,12,13,1,7,8,2,10]),[3,3,3,5,1,2])

test.assert_equals(example_sort(["a","a","b","f","d","a"],
["c","a","d","b","e","f"]),["a","a","a","d","b","f"])

test.assert_equals(example_sort(["Alice","Bryan","Chad","Darrell",
  "Ellie","Fiona"],["Alice","Bryan","Chad","Darrell","Ellie","Fiona"])
  ,["Alice","Bryan","Chad","Darrell","Ellie","Fiona"])
Esempio n. 21
0
File: 94.py Progetto: hbdhj/python
# My Very Own Python's Split Function

import test


def my_very_own_split(string, delimeter=None):
    pos = string.find(delimeter)
    if pos >= 0:
        ret = string[:pos]
        string = string[pos+1:]
        print(string)
        yield ret
    else:
        yield string


s, d = 'abc,def,ghi', ','
test.assert_equals(list(my_very_own_split(s, d)), s.split(d))

s, d = 'This is test', ','
test.assert_equals(list(my_very_own_split(s, d)), s.split(d))

s, d = 'This is test', ' '
test.assert_equals(list(my_very_own_split(s, d)), s.split(d))
Esempio n. 22
0
File: 92.py Progetto: hbdhj/python
# Triple Trouble


def triple_trouble(one, two, three):
    l = min(len(one), len(two), len(three))
    ret = ""
    for i in range(l):
        ret += one[i]
        ret += two[i]
        ret += three[i]
    return ret

import test

test.describe("Basic tests")
test.assert_equals(triple_trouble("aaa", "bbb", "ccc"), "abcabcabc")
test.assert_equals(triple_trouble("aaaaaa", "bbbbbb", "cccccc"), "abcabcabcabcabcabc")
test.assert_equals(triple_trouble("burn", "reds", "rolls"), "brrueordlnsl")
test.assert_equals(triple_trouble("Bm", "aa", "tn"), "Batman")
test.assert_equals(triple_trouble("LLh", "euo", "xtr"), "LexLuthor")
Esempio n. 23
0
# Python 3.4
# Check DESCRIPTION.md for the problem's full description.

import test


def interweave(s1, s2):

    if len(s1 + s2) % 2 != 0: s2 += " "
    message = ""
    for first, second in zip(s1, s2):
        message += (first if not first.isdigit() else
                    "") + (second if not second.isdigit() else "")

    return message.strip(" ")


# Tests

test.describe("Tests")

msg1 = "hello"
msg2 = "hello world"

test.assert_equals(interweave("hlo", "el"), msg1,
                   "['hlo', 'el'] should equal 'hello': ")
test.assert_equals(interweave("hlowrd", "el ol"), msg2,
                   "['hlowrd', 'el ol'] should equal 'hello world': ")
Esempio n. 24
0
File: 20.py Progetto: hbdhj/python
    #known_list = [0, 1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42, 56, 77, 101, 135, 176, 231, 297, 385, 490, 627, 792, 1002, 1255, 1575, 1958, 2436, 3010, 3718, 4565, 5604, 6842, 8349, 10143, 12310, 14883, 17977, 21637, 26015, 31185, 37338, 44583, 53174, 63261, 75175, 89134, 105558, 124754, 147273, 173525]
    known_list = [1, 1, 2, 3, 5, 7, 11, 15, 22, 30, 42]
    if n<0:
        return 0
    else:
        ret_list=list(1, n+1)
        if n>1:
            step = 2
            print(n+1, len(ret_list), range(step, n+1, step))
            for i in range(step, n+1, step):
                print(i)
                ret_list[i]+=1
            step+=1
        print(ret_list)
        return ret_list[n]

import test

test.assert_equals(exp_sum(-1), 0)
test.assert_equals(exp_sum(0), 1)
test.assert_equals(exp_sum(1), 1)
test.assert_equals(exp_sum(2), 2)
test.assert_equals("==============")
test.assert_equals(exp_sum(3), 3)
test.assert_equals("==============")
test.assert_equals(exp_sum(4), 5)
test.assert_equals(exp_sum(5), 7)
test.assert_equals(exp_sum(10), 42)
test.assert_equals(exp_sum(11), 56)
test.assert_equals(exp_sum(12), 77)
test.assert_equals(exp_sum(13), 101)
Esempio n. 25
0
 def sample_tests():
     test.assert_equals(is_palindrome('a'), True)
     test.assert_equals(is_palindrome('aba'), True)
     test.assert_equals(is_palindrome('Abba'), True)
     test.assert_equals(is_palindrome('malam'), True)
     test.assert_equals(is_palindrome('walter'), False)
     test.assert_equals(is_palindrome('kodok'), True)
     test.assert_equals(is_palindrome('Kasue'), False)
Esempio n. 26
0
            third_band = "violet"
            second_band = color_list[tens]
            first_band = color_list[hundreds]

    fourth_band = "gold"

    out_string = first_band + " " + second_band + " " + third_band + " " + fourth_band

    return out_string


# TESTS

test.describe("Basic tests")
test.it("Some common resistor values")
test.assert_equals(encode_resistor_colors("10 ohms"), "brown black black gold")
test.assert_equals(encode_resistor_colors("47 ohms"),
                   "yellow violet black gold")
test.assert_equals(encode_resistor_colors("100 ohms"),
                   "brown black brown gold")
test.assert_equals(encode_resistor_colors("220 ohms"), "red red brown gold")
test.assert_equals(encode_resistor_colors("330 ohms"),
                   "orange orange brown gold")
test.assert_equals(encode_resistor_colors("470 ohms"),
                   "yellow violet brown gold")
test.assert_equals(encode_resistor_colors("680 ohms"), "blue gray brown gold")
test.assert_equals(encode_resistor_colors("1k ohms"), "brown black red gold")
test.assert_equals(encode_resistor_colors("4.7k ohms"),
                   "yellow violet red gold")
test.assert_equals(encode_resistor_colors("10k ohms"),
                   "brown black orange gold")
Esempio n. 27
0
File: 79.py Progetto: hbdhj/python
# Sum the Repeats

def repeat_sum(l):
    n_dict = {}
    for lst in l:
        this_lst = []
        for n in lst:
            if n not in this_lst:
                this_lst.append(n)
                if n in n_dict.keys():
                    n_dict[n]+=1
                else:
                    n_dict[n]=1
    #print(n_dict)
    ret = 0
    for n, f in n_dict.items():
        if f > 1:
            ret+=n
    return ret

import test

test.assert_equals(repeat_sum([[1, 2, 3],[2, 8, 9],[7, 123, 8]]), 10)
test.assert_equals(repeat_sum([[1], [2], [3, 4, 4, 4], [123456789]]), 0)
test.assert_equals(repeat_sum([[1, 8, 8], [8, 8, 8], [8, 8, 8, 1]]), 9)
test.assert_equals(repeat_sum([[1]]), 0)
Esempio n. 28
0
    if ci != -1:
      if ci % 2 == 0:
        if caps[ci + 1] == caps[ci]:
          # Same character, greedily close.
          if len(openers):
            if openers[-1] == c:
              openers.pop()
            else:
              openers.append(c)
          else:
            openers.append(c)
        else:
          openers.append(c)
      else:
        opp = caps[ci - 1]
        if len(openers) and openers[-1] == opp:
          openers.pop()
        else:
          return False

  return len(openers) == 0


test.assert_equals(is_balanced("Sensei says -yes-!", "--"), True)
test.assert_equals(is_balanced("(Sensei says yes!)", "()"), True)
test.assert_equals(is_balanced("(Sensei says no!", "()"), False)
test.assert_equals(is_balanced("(Sensei [says] yes!)", "()[]"), True)
test.assert_equals(is_balanced("(Sensei [says) no!]", "()[]"), False)
test.assert_equals(is_balanced("Sensei -says no!", "--"), False)

Esempio n. 29
0
File: mix.py Progetto: pminkov/wip
      c[x] += 1
  return c

def mix(s1, s2):
  c1 = count(s1)
  c2 = count(s2)
  letters = set(c1.keys() + c2.keys())
  answer = []
  for let in letters:
    k1 = c1[let]
    k2 = c2[let]
    if k1 > 1 or k2 > 1:
      if k1 > k2:
        answer.append('1:%s' % (let * k1))
      elif k1 < k2:
        answer.append('2:%s' % (let * k2))
      else:
        answer.append('=:%s' % (let * k1))

  answer = sorted(answer, key=lambda x: (-len(x), x))
  return '/'.join(answer)
  
      

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")
Esempio n. 30
0
                        if value in possibles:
                            possibles.remove(value)
                        if len(possibles) == 1:
                            problem[i_r][i_c] = possibles.pop()

    return problem


def print_matrix(mat):
    for row in mat:
        print(row)


if __name__ == '__main__':
    import sys
    sys.path.insert(0, './codewars')
    import test

    puzzle = [[5, 3, 0, 0, 7, 0, 0, 0, 0], [6, 0, 0, 1, 9, 5, 0, 0, 0],
              [0, 9, 8, 0, 0, 0, 0, 6, 0], [8, 0, 0, 0, 6, 0, 0, 0, 3],
              [4, 0, 0, 8, 0, 3, 0, 0, 1], [7, 0, 0, 0, 2, 0, 0, 0, 6],
              [0, 6, 0, 0, 0, 0, 2, 8, 0], [0, 0, 0, 4, 1, 9, 0, 0, 5],
              [0, 0, 0, 0, 8, 0, 0, 7, 9]]

    expected = [[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]]
    test.assert_equals(sudoku(puzzle), expected)
Esempio n. 31
0
File: 93.py Progetto: hbdhj/python
                if count_a > high_a:
                    high_a = count_a
                    ret_a = lst_a
                if count_b > high_b:
                    high_b = count_b
                    ret_b = lst_b
    # print(high_a, high_b, ret_a, ret_b)
    if high_a == high_b:
        return "AB"
    elif high_a > high_b:
        return "A"
    elif high_a < high_b:
        return "B"

# A has Four of a Kind
test.assert_equals(texasHoldem(['6', '3', '3', '5', '2'],
                               ['3', '3'], ['4', '7']), "A")

# B has Pair
test.assert_equals(texasHoldem(['4', '3', '2', '5', 'Q'],
                               ['7', '8'], ['5', '7']), "B")

# Even
test.assert_equals(texasHoldem(['4', '3', '2', '5', '9'],
                               ['Q', 'A'], ['A', 'Q']), "AB")

test.assert_equals(texasHoldem(['2', '3', '7', '8', 'Q'],
                               ['3', '3'], ['7', '7']), "B")

test.assert_equals(texasHoldem(['2', '7', '3', '3', 'Q'],
                               ['3', '7'], ['Q', '3']), "B")
Esempio n. 32
0
File: 85.py Progetto: hbdhj/python
def calc_pol(pol_str, x = None):
    # your code here
    if x is None:
        return "There is no value for x"
    else:
        node = ast.parse(pol_str, mode='eval')
        code_object = compile(node, filename='<string>', mode='eval')
        result = eval(code_object)
    if result == 0:
        return "Result = 0, so "+str(x)+" is a root of "+pol_str
    else:
        return "Result = "+str(result)

import test

test.describe("Example Tests")

pol_str = "2*x**2 + 3*x"
x = 4
test.assert_equals(calc_pol(pol_str, x), "Result = 44")

pol_str = "2*x**2 + 3*x - 44"
x = 4
test.assert_equals(calc_pol(pol_str, x), "Result = 0, so 4 is a root of 2*x**2 + 3*x - 44")

pol_str = "2*x**2 + 3*x"
x = 0
test.assert_equals(calc_pol(pol_str, x), "Result = 0, so 0 is a root of 2*x**2 + 3*x")

pol_str = "2*x**2 + 3*x"
test.assert_equals(calc_pol(pol_str), "There is no value for x")
Esempio n. 33
0
    x = x[0]
    y = y[0]
    if len(x) == len(y):
      if x == y: return 0
      elif x > y: return 1
      elif x < y: return -1
    else:
      return len(x) - len(y)

  def term(x):
    if x[1] == 1: coef = '+'
    elif x[1] == -1: coef = '-'
    elif x[1] > 1: coef = '+' + str(x[1])
    else: coef = str(x[1])
    return coef + x[0]

  clean = filter(lambda x: x[1] != 0, sorted(sums.items(), cmp=compare))
  ret = ''.join(map(term, clean))
  if ret.startswith('+'): ret = ret[1:]
  return ret

test.assert_equals(simplify("dc+dcba"), "cd+abcd")
test.assert_equals(simplify("2xy-yx"),"xy")
test.assert_equals(simplify("-a+5ab+3a-c-2a"),"-c+5ab")
test.assert_equals(simplify("-abc+3a+2ac"),"3a+2ac-abc")
test.assert_equals(simplify("xyz-xz"),"-xz+xyz")
test.assert_equals(simplify("a+ca-ab"),"a-ab+ac")
test.assert_equals(simplify("xzy+zby"),"byz+xyz")
test.assert_equals(simplify("-y+x"),"x-y")
test.assert_equals(simplify("y-x"),"-x+y")
Esempio n. 34
0
    for _ in range(generations):
        add_dead_boundaries_to(cells)
        cells = next_gen(cells)
    remove_dead_boundaries_from(cells)
    return cells


if __name__ == '__main__':
    import sys
    sys.path.insert(0, './codewars')
    import test

    def print_cells(cells):
        for row in cells:
            print(' '.join(map(str, row)))

    start = [[1, 0, 0], [0, 1, 1], [1, 1, 0]]
    end = [[0, 1, 0], [0, 0, 1], [1, 1, 1]]
    orig_start = [row[:] for row in start]
    actual = get_generation(start, 1)
    test.assert_equals(actual, end)
    test.assert_equals(start, orig_start)

    quit()

    cells = start
    for _ in range(10):
        cells = get_generation(cells, 1)
        print_cells(cells)
        print()
Esempio n. 35
0
  for x in lst:
    sx = x

    if x < 0: x = -x

    while True:
      div_found = False

      i = 2 
      while i * i <= x:
        if x % i == 0:
          div_found = True
          psum[i] += sx
          while x % i == 0:
            x = x / i
          break
        i += 1

      if not div_found:
        if x != 1:
          psum[x] += sx
        break

  return [list(x) for x in sorted(psum.items())]

          

 
a = [12, 15]
test.assert_equals(sum_for_list(a), [[2, 12], [3, 27], [5, 15]])
Esempio n. 36
0
def test_sum():
    test.assert_equals(sum(1, 2, 3), 6)
    test.assert_equals(sum(1, 2, 3, 4, 5, 6), 21)
Esempio n. 37
0
import test
# https://www.codewars.com/kata/find-the-odd-int/train/python
# 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.


def find_it(seq):
    occurences = {}
    for i in seq:
        if i in occurences:
            occurences[i] += 1
        else:
            occurences[i] = 1

    for number, occurs in occurences.items():
        if occurs % 2 == 1:
            return number

    return None


if __name__ == '__main__':
    print('tohle se stane když to spustíš')
    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)
    print(find_it([20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5]))
Esempio n. 38
0
def example_001():
    print('''
	Example 001:
	Given an array of integers, find the one that appears an odd number of times.
	There will always be only one integer that appears an odd number of times.
	// Dich
	Cho 1 day so nguyen, tim so tu nhien co so lan xuat hien la 1 so le.
	Biet rang chi co duy nhat 1 so co so lan xuat hien la 1 so le
	''')
    test.assert_equals(
        find_it([20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5]), 5)
    test.assert_equals(find_it([1, 1, 2, -2, 5, 2, 4, 4, -1, -2, 5]), -1)
    test.assert_equals(find_it([20, 1, 1, 2, 2, 3, 3, 5, 5, 4, 20, 4, 5]), 5)
    test.assert_equals(find_it([10]), 10)
    test.assert_equals(find_it([1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1]), 10)
    test.assert_equals(find_it([5, 4, 3, 2, 1, 5, 4, 3, 2, 10, 10]), 1)
Esempio n. 39
0
File: 70.py Progetto: hbdhj/python
                lst.append(int(n))
            else:
                err_lst.append(n)
        elif n==None:
            pass
        else:
            err_lst.append(n)
    if len(err_lst)>1:
        return "There are "+str(len(err_lst))+" invalid entries: "+str(err_lst)
    elif len(err_lst)==1:
        return "There is 1 invalid entry: "+str(err_lst[0])
    else:
        return min_mult(lst)

arr = [18, 22, 4, 3, 21, 6, 3]
test.assert_equals(min_special_mult(arr), 2772)

arr = [16, 15, 23, 'a', '&', '12']
test.assert_equals(min_special_mult(arr), "There are 2 invalid entries: ['a', '&']")

arr = [16, 15, 23, 'a', '&', '12', 'a']
test.assert_equals(min_special_mult(arr), "There are 3 invalid entries: ['a', '&', 'a']")

arr = [16, 15, 23, 'a', '12']
test.assert_equals(min_special_mult(arr), "There is 1 invalid entry: a")

arr = [16, 15, 23, '12']
test.assert_equals(min_special_mult(arr), 5520)

arr = [16, 15, 23, '012']
test.assert_equals(min_special_mult(arr), 5520)
Esempio n. 40
0
def testing(actual, expected):
        test.assert_equals(actual, expected)
Esempio n. 41
0
File: 77.py Progetto: hbdhj/python
            cnt_dict[n]+=1
        else:
            cnt_dict[n]=1
    #print(cnt_dict)
    rvt_dict = {}
    for n, f in cnt_dict.items():
        if f in rvt_dict:
            rvt_dict[f].append(n)
        else:
            rvt_dict[f]=[n]
    #print(rvt_dict)
    ret.append(len(cnt_dict))
    if 1 in rvt_dict.keys():
        ret.append(len(rvt_dict[1]))
    else:
        ret.append(0)
    most_f = sorted(rvt_dict.keys(), reverse=True)[0]
    num_lst = rvt_dict[most_f]
    item_four=[sorted(num_lst)]
    item_four.append(most_f)
    ret.append(item_four)
    return ret

import test

test.describe("Example Tests")
test.assert_equals(count_sel([-3, -2, -1, 3, 4, -5, -5, 5, -1, -5]), [10, 7, 5, [[-5], 3]])
test.assert_equals(count_sel([5, -1, 1, -1, -2, 5, 0, -2, -5, 3]), [10, 7, 4, [[-2, -1, 5], 2]])
test.assert_equals(count_sel([-2, 4, 4, -2, -2, -1, 3, 5, -5, 5]), [10, 6, 3, [[-2], 3]])
test.assert_equals(count_sel([4, -5, 1, -5, 2, 4, -1, 4, -1, 1]), [10, 5, 1, [[4], 3]])
test.assert_equals(count_sel([4, 4, 2, -3, 1, 4, 3, 2, 0, -5, 2, -2, -2, -5]), [14, 8, 4, [[2, 4], 3]])
Esempio n. 42
0
import test
import dig_pow

test.assert_equals(dig_pow(89, 1), 1)
test.assert_equals(dig_pow(92, 1), -1)
test.assert_equals(dig_pow(46288, 3), 51)
Esempio n. 43
0
File: 88.py Progetto: hbdhj/python
# Loose Change (Part 2)


def loose_change(coins_list, amount_of_change):
    if len(coins_list) > 1:
        sorted_lst = sorted(coins_list, reverse=True)
        large_amount = sorted_lst[0]
        # print(sorted_lst, large_amount)
        amount = []
        for n in range(0, amount_of_change + 1, large_amount):
            amount.append(n // large_amount+loose_change(sorted_lst[1:], amount_of_change-n))
        return min(amount)
    elif len(coins_list) == 1:
        return amount_of_change // coins_list[0]

import test

test.assert_equals(loose_change([1, 5, 10, 25], 37), 4)
test.assert_equals(loose_change([1, 3, 4], 6), 2)
test.assert_equals(loose_change([1, 4, 5, 10], 8), 2)
test.assert_equals(loose_change([1, 2, 5, 10, 20, 50, 100, 200], 93), 5)
Esempio n. 44
0
File: 87.py Progetto: hbdhj/python
# Coding 3min: Father and Son

# import string


def sc(s):
    ret = []
    for c in s:
        if c.isupper():
            if chr(ord(c)+32) in s:
                ret.append(c)
        elif c.islower():
            if chr(ord(c)-32) in s:
                ret.append(c)
    return ''.join(ret)

import test

test.assert_equals(sc("Aab"), "Aa", "good luck!")
test.assert_equals(sc("AabBc"), "AabB", "good luck!")
test.assert_equals(sc("SONson"), "SONson", "good luck!")
test.assert_equals(sc("FfAaTtHhEeRr"), "FfAaTtHhEeRr", "good luck!")
test.assert_equals(sc("SONsonfather"), "SONson", "good luck!")
test.assert_equals(sc("sonfather"), "", "good luck!")
test.assert_equals(sc("DONKEYmonkey"), "ONKEYonkey", "good luck!")
test.assert_equals(sc("monkeyDONKEY"), "onkeyONKEY", "good luck!")
test.assert_equals(sc("BANAna"), "ANAna", "good luck!")
Esempio n. 45
0
        if len(color) == 7:
            return "6-digit"
        elif len(color) == 4:
            return "3-digit"
    else:
        if color.lower() in PRESET_COLORS:
            return "preset"
    return "ERROR"


def convert6digitHex(color):
    r = int(color[1], 16) * 16 + int(color[2], 16)
    g = int(color[3], 16) * 16 + int(color[4], 16)
    b = int(color[5], 16) * 16 + int(color[6], 16)
    return (r, g, b)


def convert3digitHex(color):
    r = int(color[1], 16) * 16 + int(color[1], 16)
    g = int(color[2], 16) * 16 + int(color[2], 16)
    b = int(color[3], 16) * 16 + int(color[3], 16)
    return (r, g, b)


# TESTS

test.describe('Example tests')
test.assert_equals(parse_html_color('#80FFA0'), {'r': 128, 'g': 255, 'b': 160})
test.assert_equals(parse_html_color('#3B7'), {'r': 51, 'g': 187, 'b': 119})
test.assert_equals(parse_html_color('LimeGreen'), {'r': 50, 'g': 205, 'b': 50})
Esempio n. 46
0
# Python 3.4
# Check DESCRIPTION.md for the problem's full description.

import test

def filter_lucky(lst):
    return [lucky_number for lucky_number in lst if "7" in str(lucky_number)]

test.describe("Correct tests")

test.it("First test")
l = [1, 2, 4, 6, 7, 12, 30, 50, 60, 65, 70, 68, 69, 77, 80]
test.assert_equals([7, 70, 77], filter_lucky(l))

test.it("Second test")
l = [1, 2, 3, 4, 5, 6, 7, 17, 27, 50]
test.assert_equals([7, 17, 27], filter_lucky(l))