def letter(str): result = [] words = [x for x in str.lower().strip().split() if x] mx = len(max(words, key=len)) if words else 0 starts = set(x[:i] for x in words for i in range(1, mx+1)) for s in starts: matching = [word for word in words if word.startswith(s)] if len(matching) == len(s): result += matching return sorted(result)
import re- def letter(str):
words = re.sub(r"[^a-z]", " ", str.lower()).split(" ")lst = []l1 = []l2 = []sol = []for x in words:word = ""for y in x:word += ylst.append(word)for x in sorted(set(lst)):for y in words:if y.startswith(x):l1.append(y)l2.append(list(l1))l1.clear()dic = dict(zip(sorted(set(lst)), l2))for k, v in dic.items():if len(k) == len(v):for x in v:sol.append(x)return sorted(sol)- result = []
- words = [x for x in str.lower().strip().split() if x]
- mx = len(max(words, key=len)) if words else 0
- starts = set(x[:i] for x in words for i in range(1, mx+1))
- for s in starts:
- matching = [word for word in words if word.startswith(s)]
- if len(matching) == len(s):
- result += matching
- return sorted(result)
- Added functionality and unit tests to deduce the days passed in leap and non-leap years.
days = lambda y, m, d: sum(([31, [28, 29][all([not y % 4, (y % 100 or not y % 400)])]] + [31, 30, 31, 30, 31] * 2)[:m - 1]) + d
def days(months, day):month_by_days = [False,0 +day, 31 +day, 59 +day,90 +day, 120 +day, 151 +day,181 +day, 212 +day, 243 +day,273 +day, 304 +day, 334 +day ]return month_by_days[int(months)]- days = lambda y, m, d: sum(([31, [28, 29][all([not y % 4, (y % 100 or not y % 400)])]] + [31, 30, 31, 30, 31] * 2)[:m - 1]) + d
#TODO: Replace examples and use TDD by writing your own tests. The code provided here is just a how-to example. #include <criterion/criterion.h> #replace with the actual method being tested #def days(month, day): import codewars_test as test from solution import days @test.describe("Fixed Tests") def basic_tests(): @test.it('Basic Test Cases') def basic_test_cases(): test.assert_equals(days(2022, 3, 1), 60) test.assert_equals(days(2022, 12, 31), 365) test.assert_equals(days(2022, 1, 1), 1) test.assert_equals(days(2022, 9, 17), 260) test.assert_equals(days(2024, 9, 17), 261) test.assert_equals(days(1600, 3, 1), 61) test.assert_equals(days(1800, 3, 1), 60)
- #TODO: Replace examples and use TDD by writing your own tests. The code provided here is just a how-to example.
- #include <criterion/criterion.h>
- #replace with the actual method being tested
- #def days(month, day):
- import codewars_test as test
- from solution import days
- @test.describe("Fixed Tests")
- def basic_tests():
- @test.it('Basic Test Cases')
- def basic_test_cases():
test.assert_equals(days(3, 1), 60)test.assert_equals(days(12, 31), 365)test.assert_equals(days(1, 1), 1)test.assert_equals(days(9, 17), 260)- test.assert_equals(days(2022, 3, 1), 60)
- test.assert_equals(days(2022, 12, 31), 365)
- test.assert_equals(days(2022, 1, 1), 1)
- test.assert_equals(days(2022, 9, 17), 260)
- test.assert_equals(days(2024, 9, 17), 261)
- test.assert_equals(days(1600, 3, 1), 61)
- test.assert_equals(days(1800, 3, 1), 60)
spawn_to_range = lambda a, v, r: a[:a.index(v)] + [v] * r + a[a.index(v) + 1:] if v in a else []
def spawn_to_range(a, x, n):# return [] if(len(a)==0) else a[0:a.index(x)] + [x]*n + a[a.index(x)+1:]return [*a[0:(i:=a.index(x))],*[x]*n,*(a[j]for j in range(i+1,z))]if(z:=len(a))else[]- spawn_to_range = lambda a, v, r: a[:a.index(v)] + [v] * r + a[a.index(v) + 1:] if v in a else []
foo = lambda a, b : list(set(a) - set(b))
foo = lambda a, b : [i for i in a if i not in b]- foo = lambda a, b : list(set(a) - set(b))
import unittest from solution import foo class TestFoo(unittest.TestCase): def setUp(self) -> None: self.samples = [ ([1, 2, 3, 4, 5], [4, 5, 6, 7, 8], [1, 2, 3]), ([0, -2, 98, 4, '5'], [4, '15', 6, 98, 8], [0, -2, '5']), ([8, 0, 23, 7, 55, 9], [], [8, 0, 23, 7, 55, 9]), ([], ['-2', 4, 91, 11, 64], [])] def test_foo(self): for a, c, e in self.samples: self.assertCountEqual(foo(a, c), e) if __name__ == '__main__': unittest.main()
- import unittest
- from solution import foo
- class TestFoo(unittest.TestCase):
- def setUp(self) -> None:
- self.samples = [
- ([1, 2, 3, 4, 5], [4, 5, 6, 7, 8], [1, 2, 3]),
- ([0, -2, 98, 4, '5'], [4, '15', 6, 98, 8], [0, -2, '5']),
- ([8, 0, 23, 7, 55, 9], [], [8, 0, 23, 7, 55, 9]),
- ([], ['-2', 4, 91, 11, 64], [])]
- def test_foo(self):
- for a, c, e in self.samples:
self.assertEqual(foo(a, c), e)- self.assertCountEqual(foo(a, c), e)
- if __name__ == '__main__':
- unittest.main()
- Introduced function chaining to reuse existing functions.
- Introduced a base kwarg to override self.num as argument for the function for a more dynamic approach/higher reusability of existing functions.
#!/usr/bin/env python3 """ Debugging: FixDatTrash # 2 """ # constant: PI = 3.1415926535897 class Calculator: """A calculator class.""" def __init__(self, num): """Initialize attributes.""" self.num = num def calculate_power(self, exp, base=None): """ Calculates power of self.num. parameter `exp` is the exponent. parameter `base` is an optional argument to override self.num with. """ return (base or self.num) ** exp def calculate_square_root(self): """Calculates square root of self.num or any other real number.""" return self.calculate_power(0.5) def calculate_cube_root(self): """Calculates cube root of self.num or any other real number.""" return self.calculate_power(1 / 3) def calculate_circumference(self, base=None): """ Calculates circumference of circle. self.num is the diameter of the circle. """ return PI * (base or self.num) def calculate_circle_area(self): """ Calculates area of circle. self.num is the radius of the circle. A=πr2 """ radius_squared = self.calculate_power(2) return self.calculate_circumference(radius_squared)
- #!/usr/bin/env python3
- """
- Debugging: FixDatTrash # 2
- """
import mathfrom dataclasses import dataclassPI = math.pi- # constant:
- PI = 3.1415926535897
@dataclass- class Calculator:
- """A calculator class."""
num: intdef calculate_power(self, exp):- def __init__(self, num):
- """Initialize attributes."""
- self.num = num
- def calculate_power(self, exp, base=None):
- """
- Calculates power of self.num.
- parameter `exp` is the exponent.
- parameter `base` is an optional argument to override self.num with.
- """
return self.num ** exp- return (base or self.num) ** exp
- def calculate_square_root(self):
"""Calculates square root of self.num."""return self.num ** 0.5- """Calculates square root of self.num or any other real number."""
- return self.calculate_power(0.5)
- def calculate_cube_root(self):
"""Calculates cube root of self.num."""return self.num ** (1 / 3)- """Calculates cube root of self.num or any other real number."""
- return self.calculate_power(1 / 3)
def calculate_circumference(self):- def calculate_circumference(self, base=None):
- """
- Calculates circumference of circle.
- self.num is the diameter of the circle.
- """
return PI * self.num- return PI * (base or self.num)
- def calculate_circle_area(self):
- """
- Calculates area of circle.
self.num is the radius of the circle- self.num is the radius of the circle.
- A=πr2
- """
return self.num ** 2 * PI- radius_squared = self.calculate_power(2)
- return self.calculate_circumference(radius_squared)
from solution import Calculator, PI import unittest import math class TestCalculator(unittest.TestCase): def test_calculate_power(self): self.assertEqual(Calculator(2).calculate_power(2), 4) self.assertEqual(Calculator(4).calculate_power(4), 256) def test_calculate_square_root(self): self.assertEqual(Calculator(3).calculate_square_root(), 1.7320508075688772) self.assertEqual(Calculator(16).calculate_square_root(), 4) def test_calculate_cube_root(self): self.assertEqual(Calculator(27).calculate_cube_root(), 3) self.assertEqual(Calculator(125).calculate_cube_root(), 4.999999999999999) def test_calculate_circumference(self): self.assertEqual(Calculator(3).calculate_circumference(), 9.424777960769099) self.assertEqual(Calculator(12).calculate_circumference(), 37.699111843076395) def test_calculate_circle_area(self): self.assertEqual(math.floor(Calculator(3).calculate_circle_area()), 28) self.assertEqual(math.floor(Calculator(54).calculate_circle_area()), 9160) if __name__ == '__main__': unittest.main()
- from solution import Calculator, PI
- import unittest
- import math
- class TestCalculator(unittest.TestCase):
- def test_calculate_power(self):
- self.assertEqual(Calculator(2).calculate_power(2), 4)
- self.assertEqual(Calculator(4).calculate_power(4), 256)
- def test_calculate_square_root(self):
- self.assertEqual(Calculator(3).calculate_square_root(), 1.7320508075688772)
- self.assertEqual(Calculator(16).calculate_square_root(), 4)
- def test_calculate_cube_root(self):
- self.assertEqual(Calculator(27).calculate_cube_root(), 3)
- self.assertEqual(Calculator(125).calculate_cube_root(), 4.999999999999999)
- def test_calculate_circumference(self):
self.assertEqual(Calculator(3).calculate_circumference(), 9.42477796076938)self.assertEqual(Calculator(12).calculate_circumference(), 37.69911184307752)- self.assertEqual(Calculator(3).calculate_circumference(), 9.424777960769099)
- self.assertEqual(Calculator(12).calculate_circumference(), 37.699111843076395)
- def test_calculate_circle_area(self):
- self.assertEqual(math.floor(Calculator(3).calculate_circle_area()), 28)
- self.assertEqual(math.floor(Calculator(54).calculate_circle_area()), 9160)
- if __name__ == '__main__':
- unittest.main()
is_armstrong = lambda n: n == sum(d ** len(str(n)) for d in [(n // max(10 ** i, 1)) % 10 for i in range(len(str(n)))])
from math import log10def is_armstrong(n: int) -> bool:temp = ncount = int(log10(n)) + 1while temp:temp, digit = divmod(temp, 10)n -= digit ** countreturn not n- is_armstrong = lambda n: n == sum(d ** len(str(n)) for d in [(n // max(10 ** i, 1)) % 10 for i in range(len(str(n)))])
fruit_colours = { "Red": ("Apple", "Raspberry", "Strawberry"), "Orange": ("Orange",), "Yellow": ("Banana", "Lemon", "Pineapple"), "Green": ("Avocado", "Lime", "Melon", "Pear"), "Blue": ("Blueberry", "Huckleberry"), "Purple": ("Plum", "Grape", "Maquiberry") } colour_of_fruit = lambda fruit: next((colour for colour, fruits in fruit_colours.items() if fruit in fruits), "Not a fruit!")
- fruit_colours = {
- "Red": ("Apple", "Raspberry", "Strawberry"),
- "Orange": ("Orange",),
- "Yellow": ("Banana", "Lemon", "Pineapple"),
- "Green": ("Avocado", "Lime", "Melon", "Pear"),
- "Blue": ("Blueberry", "Huckleberry"),
- "Purple": ("Plum", "Grape", "Maquiberry")
- }
def colour_of_fruit(fruit: str) -> str:"""Returns the color of given fruit."""for color, fruits in fruit_colours.items():if fruit in fruits: return colorreturn "Not a fruit!"- colour_of_fruit = lambda fruit: next((colour for colour, fruits in fruit_colours.items() if fruit in fruits), "Not a fruit!")
Fundamentals
hello_message = lambda this=__import__("this"), s=lambda this: ''.join([this.d[x] if x.isalpha() else x for x in this.s]): ''.join([s(this)[x] for x in [1, 2, 42, 42, 8, 3, 512, 8, 30, 42, 163, 855]]).title()
def hello_message():t = str.maketrans('_mag', ' Wld')return ''.join(hello_message.__name__.capitalize().translate(t)[:-1].replace('ess', 'or')+ '!')- hello_message = lambda this=__import__("this"), s=lambda this: ''.join([this.d[x] if x.isalpha() else x for x in this.s]): ''.join([s(this)[x] for x in [1, 2, 42, 42, 8, 3, 512, 8, 30, 42, 163, 855]]).title()
Fundamentals
Arrays
Strings
FindTRex = lambda lst: type("FindTRex", tuple(), {"lst" : lst, "find_trex" : lambda : "tyrannosaurus" in lst})
class FindTRex:"""Find Trex class."""def __init__(self, lst):"""Initialize attribute"""self.lst = lstdef find_trex(self):"""Returns True if 'tyrannosaurus' is in self.lst, False if not."""return "tyrannosaurus" in self.lst- FindTRex = lambda lst: type("FindTRex", tuple(), {"lst" : lst, "find_trex" : lambda : "tyrannosaurus" in lst})