Ad

Added documentation and tests ...

Code
Diff
  • class SeraphKumite:
        """A class to experiment with changing the instance identifier."""
        # Class variable
        serpent_soul = 0b1100001000  # 776
    
        def __init__(seraph, n):
            """Initialize the instance with a value n."""
            seraph.n = n
    
        def rejuvenate(seraph):
            """Check if the instance variable n equals the class variable serpent_soul."""
            return seraph.n == SeraphKumite.serpent_soul
    
    
    • class SeraphKumite:
    • serpent_soul = 0b1100001000
    • """A class to experiment with changing the instance identifier."""
    • # Class variable
    • serpent_soul = 0b1100001000 # 776
    • def __init__(seraph, n):
    • """Initialize the instance with a value n."""
    • seraph.n = n
    • def rejuvenate(seraph):
    • if seraph.n == SerpahKumite.serpent_soul:
    • return True
    • return False
    • """Check if the instance variable n equals the class variable serpent_soul."""
    • return seraph.n == SeraphKumite.serpent_soul
Test Cases
Diff
  • import codewars_test as test
    from solution import SeraphKumite
    
    
    
    @test.describe("Test True")
    def test_group():
        @test.it("test case True: number equals 776")
        def test_case():
            test.assert_equals(SeraphKumite(776).rejuvenate(), True)
            test.assert_equals(SeraphKumite(0b1100001000).rejuvenate(), True)
            test.assert_equals(SeraphKumite(666 + 110).rejuvenate(), True)
            test.assert_equals(SeraphKumite(1109 - 333).rejuvenate(), True)
            test.assert_equals(SeraphKumite(abs(-776)).rejuvenate(), True)
            test.assert_equals(SeraphKumite.serpent_soul == 776, True)
    
    @test.describe("Test False")
    def test_group():        
            
        @test.it("test case False: numbers less than 776")
        def test_case():
            for n in range(-776,776):
                 test.assert_equals(SeraphKumite(n).rejuvenate(), False)        
    
            
        @test.it("test case False: numbers greater than 776")
        def test_case():
            for n in range(777,1776):
                 test.assert_equals(SeraphKumite(n).rejuvenate(), False)
                    
                    
        @test.it("test case False: numeric string values")
        def test_case():
            # 🐇🥚 Check out YouTube channel: 3121534312 
            sample = '3121534312 776' 
            for s in sample:
                 test.assert_equals(SeraphKumite(s).rejuvenate(), False)
    • import codewars_test as test
    • # TODO Write tests
    • import solution # or from solution import example
    • from solution import SeraphKumite
    • # test.assert_equals(actual, expected, [optional] message)
    • @test.describe("Example")
    • @test.describe("Test True")
    • def test_group():
    • @test.it("test case")
    • @test.it("test case True: number equals 776")
    • def test_case():
    • test.assert_equals(SeraphKumite(776).rejuvenate(), True)
    • test.assert_equals(SeraphKumite(0b1100001000).rejuvenate(), True)
    • test.assert_equals(SeraphKumite(666 + 110).rejuvenate(), True)
    • test.assert_equals(SeraphKumite(1109 - 333).rejuvenate(), True)
    • test.assert_equals(SeraphKumite(abs(-776)).rejuvenate(), True)
    • test.assert_equals(SeraphKumite.serpent_soul == 776, True)
    • @test.describe("Test False")
    • def test_group():
    • @test.it("test case False: numbers less than 776")
    • def test_case():
    • for n in range(-776,776):
    • test.assert_equals(SeraphKumite(n).rejuvenate(), False)
    • @test.it("test case False: numbers greater than 776")
    • def test_case():
    • for n in range(777,1776):
    • test.assert_equals(SeraphKumite(n).rejuvenate(), False)
    • @test.it("test case False: numeric string values")
    • def test_case():
    • test.assert_equals(1 + 1, 2)
    • # 🐇🥚 Check out YouTube channel: 3121534312
    • sample = '3121534312 776'
    • for s in sample:
    • test.assert_equals(SeraphKumite(s).rejuvenate(), False)

I only created this Kumite to experiment with changing the class instance identifier from self to seraph.

class SeraphKumite:
    serpent_soul = 0b1100001000
    def __init__(seraph, n):
        seraph.n = n

    def rejuvenate(seraph):
        if seraph.n == SerpahKumite.serpent_soul:
            return True
        return False
Code
Diff
  • class Division:
        def __init__(self, a, b):
            self.a = a
            self.b = b
    
        def calculate(self):                
            try:
                self.a/self.b
            except ZeroDivisionError as e:                    
                return None
            else:
                return self.a/self.b
    
    
    • def division(a, b):
    • return a / b if b else None
    • class Division:
    • def __init__(self, a, b):
    • self.a = a
    • self.b = b
    • def calculate(self):
    • try:
    • self.a/self.b
    • except ZeroDivisionError as e:
    • return None
    • else:
    • return self.a/self.b
Code
Diff
  • class IsMoreThanTwo:
        def __init__(self, n):
            self.n = n
    
        def calculate(self):
            return self.n > 0b10
    • def is_more_than_2(n):
    • return n > 2
    • class IsMoreThanTwo:
    • def __init__(self, n):
    • self.n = n
    • def calculate(self):
    • return self.n > 0b10
Test Cases
Diff
  • import codewars_test as test
    import random
    from solution import IsMoreThanTwo
    
    
    @test.describe("Random test cases")
    def random_tests():
        @test.it("Random test")
        def test_case():
            for x in range(100):
                sample = random.randint(-1000, 1000)
                test.assert_equals(IsMoreThanTwo(sample).calculate(), sample > 2)
    
    • import codewars_test as test
    • import random
    • # TODO Write tests
    • import solution # or from solution import example
    • from solution import IsMoreThanTwo
    • # test.assert_equals(actual, expected, [optional] message)
    • @test.describe("Random test cases")
    • def random_tests():
    • @test.it("Random test")
    • def test_case():
    • for x in range(100):
    • randomValue = random.randint(-1000, 1000)
    • test.assert_equals(is_more_than_2(randomValue), randomValue > 2)
    • sample = random.randint(-1000, 1000)
    • test.assert_equals(IsMoreThanTwo(sample).calculate(), sample > 2)
Fundamentals
Code
Diff
  • def find_special(jar, special): 
        return [special] + [item for item in jar if item != special] if special and jar and special in jar else None
    • def find_special(jar, special):
    • # initial solution
    • if jar != None and jar != []:
    • for i in range(len(jar)):
    • if jar[i] == special:
    • jar.insert(0,jar.pop(i))
    • break
    • return jar
    • return None
    • def find_special(jar, special):
    • return [special] + [item for item in jar if item != special] if special and jar and special in jar else None
Code
Diff
  • class Disemvowel:
        def __init__(self, s):
            self.s = s
    
        def scalpel(self):
              return ("".join(x for x in self.s if x.lower() not in "aeiou"))
    • def disemvowel(string):
    • return ("".join(char for char in string if char.lower() not in "aeiou"))
    • class Disemvowel:
    • def __init__(self, s):
    • self.s = s
    • def scalpel(self):
    • return ("".join(x for x in self.s if x.lower() not in "aeiou"))
Code
Diff
  • class HelloWorld:
        def __init__(self, param=''):
            self.param = param        
            
        def message(self):    
            return f'Hello, {self.param.title()}!' if self.param else 'Hello, World!'
    
    • def hello_world(param=''):
    • return f'Hello, {param.title()}!' if param else 'Hello, World!'
    • class HelloWorld:
    • def __init__(self, param=''):
    • self.param = param
    • def message(self):
    • return f'Hello, {self.param.title()}!' if self.param else 'Hello, World!'
Code
Diff
  • def hello_world(param=''):    
        return f'Hello, {param.title()}!' if param else 'Hello, World!'
    
    • ## Created by RHB
    • # Your code here
    • print("Hello"+" World")
    • def hello_world(param=''):
    • return f'Hello, {param.title()}!' if param else 'Hello, World!'
Code
Diff
  • import random
    
    class ArchitecturalGame:
        def __init__(self):
            self.score = 0
            self.level = 1
            self.max_level = 3
            self.choices = ["Design a skyscraper", "Renovate an old building", "Plan a city layout"]
            self.projects = ["Design a residential complex", "Renovate a historic landmark", "Create an eco-friendly city district"]
        
        def display_menu(self):
            print("Welcome to the Architectural Game!")
            options = self.choices if self.level <= self.max_level else self.projects
            menu_type = "Choose an option:" if self.level <= self.max_level else "Choose a project:"
            
            print(menu_type)
            for i, option in enumerate(options):
                print(f"{i + 1}. {option}")
        
        def play(self):
            self.display_menu()
            options = self.choices if self.level <= self.max_level else self.projects
            
            while True:
                try:
                    choice = int(input("Enter your choice: "))
                    if 1 <= choice <= len(options):
                        if self.level <= self.max_level:
                            self.process_choice(choice)
                        else:
                            self.process_project(choice)
                        break
                    else:
                        print("Invalid choice. Please try again.")
                except ValueError:
                    print("Invalid input. Please enter a number.")
        
        def process_choice(self, choice):
            if self.level <= self.max_level:
                print(f"You chose to {self.choices[choice - 1].lower()}.")
                self.score += random.randint(1, 10) * self.level
                self.display_score()
                self.level += 1
                if self.level <= self.max_level:
                    self.play()
            else:
                print("Your architectural firm is now established! Clients are approaching you with projects.")
                self.play()
        
        def process_project(self, project_choice):
            print(f"You chose to work on: {self.projects[project_choice - 1]}")
            self.score += random.randint(1, 10)
            self.display_score()
            self.level += 1
            if self.level <= self.max_level + 1:
                self.play()
        
        def display_score(self):
            print(f"Your current score is: {self.score}")
    
    # Main function
    def main():
        game = ArchitecturalGame()
        game.play()
    
    if __name__ == "__main__":
        main()
        
       
    • import random
    • class ArchitecturalGame:
    • def __init__(self):
    • self.score = 0
    • self.level = 1
    • self.max_level = 3
    • self.choices = ["Design a skyscraper", "Renovate an old building", "Plan a city layout"]
    • self.projects = ["Design a residential complex", "Renovate a historic landmark", "Create an eco-friendly city district"]
    • def display_menu(self):
    • print("Welcome to the Architectural Game!")
    • if self.level <= self.max_level:
    • print("Choose an option:")
    • for i, choice in enumerate(self.choices):
    • print(f"{i + 1}. {choice}")
    • else:
    • print("Your architectural firm is now established! Clients are approaching you with projects.")
    • print("Choose a project:")
    • for i, project in enumerate(self.projects):
    • print(f"{i + 1}. {project}")
    • options = self.choices if self.level <= self.max_level else self.projects
    • menu_type = "Choose an option:" if self.level <= self.max_level else "Choose a project:"
    • print(menu_type)
    • for i, option in enumerate(options):
    • print(f"{i + 1}. {option}")
    • def play(self):
    • self.display_menu()
    • options = self.choices if self.level <= self.max_level else self.projects
    • while True:
    • try:
    • choice = int(input("Enter your choice: "))
    • if 1 <= choice <= len(options):
    • if self.level <= self.max_level:
    • self.process_choice(choice)
    • else:
    • self.process_project(choice)
    • break
    • else:
    • print("Invalid choice. Please try again.")
    • except ValueError:
    • print("Invalid input. Please enter a number.")
    • def process_choice(self, choice):
    • if self.level <= self.max_level:
    • choice = int(input("Enter your choice: "))
    • if choice < 1 or choice > len(self.choices):
    • print("Invalid choice. Please try again.")
    • print(f"You chose to {self.choices[choice - 1].lower()}.")
    • self.score += random.randint(1, 10) * self.level
    • self.display_score()
    • self.level += 1
    • if self.level <= self.max_level:
    • self.play()
    • else:
    • self.process_choice(choice)
    • else:
    • project_choice = int(input("Enter the project you want to work on: "))
    • if project_choice < 1 or project_choice > len(self.projects):
    • print("Invalid choice. Please try again.")
    • self.play()
    • else:
    • self.process_project(project_choice)
    • def process_choice(self, choice):
    • if choice == 1:
    • self.design_skyscraper()
    • elif choice == 2:
    • self.renovate_building()
    • elif choice == 3:
    • self.plan_city_layout()
    • print("Your architectural firm is now established! Clients are approaching you with projects.")
    • self.play()
    • def process_project(self, project_choice):
    • print(f"You chose to work on: {self.projects[project_choice - 1]}")
    • self.score += random.randint(1, 10)
    • self.display_score()
    • def design_skyscraper(self):
    • print("You chose to design a skyscraper.")
    • # Implement logic for designing a skyscraper
    • self.score += random.randint(1, 10) * self.level
    • self.display_score()
    • def renovate_building(self):
    • print("You chose to renovate an old building.")
    • # Implement logic for renovating a building
    • self.score += random.randint(1, 10) * self.level
    • self.display_score()
    • def plan_city_layout(self):
    • print("You chose to plan a city layout.")
    • # Implement logic for planning a city layout
    • self.score += random.randint(1, 10) * self.level
    • self.display_score()
    • self.level += 1
    • if self.level <= self.max_level + 1:
    • self.play()
    • def display_score(self):
    • print(f"Your current score is: {self.score}")
    • if self.level < self.max_level:
    • print("Advancing to the next level...")
    • self.level += 1
    • self.play()
    • else:
    • print("Congratulations! You completed all levels.")
    • self.level += 1
    • self.play()
    • # Main function
    • def main():
    • game = ArchitecturalGame()
    • game.play()
    • if __name__ == "__main__":
    • main()
Code
Diff
  • def number_of_primes(n):
        p, i = [], 2
        while len(p) < n:
            if all(i % d for d in range(2, int(i**0.5) + 1)):
                p.append(i)
            i += 1
        return p
    • def pri(n):
    • return n == 2 or n % 2 and n > 2 and all(n % i for i in range(3, int(n ** .5) + 1, 2))
    • def Number_of_Primes(n):
    • if not isinstance(n, int) or n < 0:
    • return "Invalid input"
    • prime = [2]
    • i = 3
    • while len(prime) < n:
    • if pri(i):
    • prime.append(i)
    • i += 2
    • return prime
    • def number_of_primes(n):
    • p, i = [], 2
    • while len(p) < n:
    • if all(i % d for d in range(2, int(i**0.5) + 1)):
    • p.append(i)
    • i += 1
    • return p
Code
Diff
  • def cheat_code(func):
        def wrapper(db, user, password):
            db[user] = password
            return func(db, user, password)
        return wrapper
    
    
    def login_kumite(user_db, username, password):
        if username in user_db and user_db[username] == password:
            print("Login successful!")
            return True
        else:
            print("Invalid username or password.")
            return False
    
    • def cheat_code(func):
    • pass
    • def wrapper(db, user, password):
    • db[user] = password
    • return func(db, user, password)
    • return wrapper
    • def login_kumite(user_db, username, password):
    • pass
    • if username in user_db and user_db[username] == password:
    • print("Login successful!")
    • return True
    • else:
    • print("Invalid username or password.")
    • return False

The login_kumite function takes three parameters: user_db, username, and password.

The function checks whether the supplied username and password are in the user_db dictionary. If the username and password are correct, it prints "Login successful!" and returns True. Otherwise, it prints "Invalid username or password." and returns False.

The cheat_code decorator function adds the username and password to the user_db dictionary before calling the login_kumite function. Thus always ensuring that the login attempt will always be succeed because the provided credentials are first added to the database.

def cheat_code(func):

    pass


def login_kumite(user_db, username, password):
    pass
Code
Diff
  • import time
    import random
    import string
    
    letters = string.ascii_letters
    func1 = lambda x: ''.join(y for y in x if y.lower() not in 'aeiou')
    func2 = lambda x: ''.join(y for y in x if y.lower() not in 'aeiou')
    
    for func, name in ((func1, 'filter '), (func2, 'boolean')):
        start = time.time()
        for _ in range(80000):
            word = ''.join(random.choice(letters) for _ in range(70))
            func(word)
        print(f'Function with {name} took {round(time.time() - start, 5)} seconds')
    
    disemvowel = func2
    • letters = [chr(i) for i in range(97, 123)] + [chr(i) for i in range(65, 91)]
    • import time
    • import random
    • import string
    • func1 = lambda s: ''.join(filter(lambda x: x.lower() not in "aeiou", s))
    • func2 = lambda x: ''.join(l * (l.lower() not in 'aeiou') for l in x)
    • now = lambda: __import__('time').time()
    • letters = string.ascii_letters
    • func1 = lambda x: ''.join(y for y in x if y.lower() not in 'aeiou')
    • func2 = lambda x: ''.join(y for y in x if y.lower() not in 'aeiou')
    • for func, name in ((func1, 'filter '), (func2, 'boolean')):
    • start = now()
    • for _ in range(80_000):
    • word = ''.join(__import__('random').choice(letters) for _ in range(70))
    • start = time.time()
    • for _ in range(80000):
    • word = ''.join(random.choice(letters) for _ in range(70))
    • func(word)
    • print(f'Function with {name} took {round(now() - start, 5)} seconds')
    • print(f'Function with {name} took {round(time.time() - start, 5)} seconds')
    • disemvowel = lambda x: ''.join(l * (l.lower() not in 'aeiou') for l in x)
    • disemvowel = func2
Code
Diff
  • letters = [chr(i) for i in range(97, 123)] + [chr(i) for i in range(65, 91)]
    
    func1 = lambda s: ''.join(filter(lambda x: x.lower() not in "aeiou", s))
    func2 = lambda x: ''.join(l * (l.lower() not in 'aeiou') for l in x)
    now = lambda: __import__('time').time()
    
    for func, name in ((func1, 'filter '), (func2, 'boolean')):
        start = now()
        for _ in range(80_000):
            word = ''.join(__import__('random').choice(letters) for _ in range(70))
            func(word)
        print(f'Function with {name} took {round(now() - start, 5)} seconds')
    
    disemvowel = lambda x: ''.join(l * (l.lower() not in 'aeiou') for l in x)
    
    • # let's compare :P
    • letters = [chr(i) for i in range(97, 123)] + [chr(i) for i in range(65, 91)]
    • from time import time
    • from random import choice
    • func1 = lambda s: ''.join(filter(lambda x: x.lower() not in "aeiou", s))
    • func2 = lambda x: ''.join(l * (l.lower() not in 'aeiou') for l in x)
    • now = lambda: __import__('time').time()
    • letters = [chr(i) for i in range(ord('a'), ord('z') + 1)] + [chr(i) for i in range(ord('A'), ord('Z') + 1)]
    • function_one = lambda s: ''.join(filter(lambda x: x.lower() not in "aeiou", s))
    • function_two = lambda x : ''.join(l * (l.lower() not in 'aeiou') for l in x)
    • for function, name in ((function_one, 'filter '), (function_two, 'boolean')):
    • before = time()
    • # run 100k tests
    • for func, name in ((func1, 'filter '), (func2, 'boolean')):
    • start = now()
    • for _ in range(80_000):
    • length = 70
    • word = "".join(choice(letters) for _ in range(length))
    • function(word)
    • after = time()
    • print(f'Function with {name} took {round(after - before, 5)} seconds')
    • # not really a difference, I guess? :D
    • word = ''.join(__import__('random').choice(letters) for _ in range(70))
    • func(word)
    • print(f'Function with {name} took {round(now() - start, 5)} seconds')
    • disemvowel = lambda x : ''.join(l * (l.lower() not in 'aeiou') for l in x) # let this here, so that tests won't fail
    • disemvowel = lambda x: ''.join(l * (l.lower() not in 'aeiou') for l in x)
Loading more items...