Ad
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)
Code
Diff
  • def foo(param='foo'):
        return f"Hello {param.title()}"
    • print("hello world")
    • def foo(param='foo'):
    • return f"Hello {param.title()}"
Fundamentals
Code
Diff
  • import string
    
    VOWELS = 'aeiou'
    CONSONANTS = ''.join([a for a in string.ascii_lowercase if a not in VOWELS])
    
    
    def inspector_yeezy(word):
        """Determine if Y is a vowel, consonant, or None"""
        
        # Return one if the letter y is not in word:
        if 'y' not in word:
            return None
        
        # Check if there are any vowels
        vowel_check = len([a for a in word if a in VOWELS]) > 0
        
        # If word starts with Y, return False (consonant)
        if word[0] == 'y':
            return False
    
        # If there are no vowels except for Y (vowel)
        elif vowel_check and 'y' in word:
            return True
    
        # If Y follows last vowel or consonant in word, return True (vowel)
        elif word[-1] == 'y' and word[-2] in CONSONANTS or VOWELS:
            return True
    
        # Removing the letter y from word, so it does not get eveluated again in next step:    
        word = word.replace('y', '')
        
        # If Y is in the Middle of the syllable, return True (vowel)
        for i in range(1, len(word) - 1):
            # If letter is Y:
            if word[i] == 'y':
                
                # If the letter to the left, or right of y are consonants then return True (vowel):
                if word[i - 1] in CONSONANTS or word[i + 1] in CONSONANTS:              
                    return True
                # else False (consonant)
                else:
                
                    return False
    
    
    
    
    • import string
    • VOWELS = 'aeiou'
    • CONSONANTS = ''.join([a for a in string.ascii_lowercase if a not in VOWELS])
    • def inspector_yeezy(word):
    • """Determine if Y is a vowel, consonant, or None"""
    • pass
    • # Return one if the letter y is not in word:
    • if 'y' not in word:
    • return None
    • # Check if there are any vowels
    • vowel_check = len([a for a in word if a in VOWELS]) > 0
    • # If word starts with Y, return False (consonant)
    • if word[0] == 'y':
    • return False
    • # If there are no vowels except for Y (vowel)
    • elif vowel_check and 'y' in word:
    • return True
    • # If Y follows last vowel or consonant in word, return True (vowel)
    • elif word[-1] == 'y' and word[-2] in CONSONANTS or VOWELS:
    • return True
    • # Removing the letter y from word, so it does not get eveluated again in next step:
    • word = word.replace('y', '')
    • # If Y is in the Middle of the syllable, return True (vowel)
    • for i in range(1, len(word) - 1):
    • # If letter is Y:
    • if word[i] == 'y':
    • # If the letter to the left, or right of y are consonants then return True (vowel):
    • if word[i - 1] in CONSONANTS or word[i + 1] in CONSONANTS:
    • return True
    • # else False (consonant)
    • else:
    • return False
Fundamentals

Descripion:

Y is a Vowel:
  • When there Are No Other Vowels
  • When Y Follows the Last Consonant of a Word
  • When Y Follows the Last Vowel of a Word
  • When Y Is at the End of a Syllable
  • When Y Is in the Middle of a Syllable

Y is a Consonant:
  • When Y Is the First Letter in a Word
  • When Y is the First Letter in a Syllable

Source: yourdictionary.com


Task:

Given an input string word, either return True if the letter y in the word
is a vowel, False if it is a consonat, or None if the word contains
no letter y.

Examples

INPUT: codecrypt
OUTPUT: True

💡 Explanation: Y is a vowel because there are no vowels in word other than y, therefore, return True.

INPUT: yankee
OUTPUT: False

💡 Explanation: Y is a consonant because the word starts with the letter y, therefore, return False

INPUT: codewars
OUTPUT: None

💡 Explanation: There is no letter Y is word, therefore, return None

Constraints:

🚦 Each word that contains a letter y will only have one (1) occurrence
of the letter.

import string

VOWELS = 'aeiou'
CONSONANTS = ''.join([a for a in string.ascii_lowercase if a not in VOWELS])


def inspector_yeezy(word):
    """Determine if Y is a vowel, consonant, or None"""
    pass
Code
Diff
  • def fools_version(text):
        if len(text) == 1:
            return text
        return fools_version(text[1:]) + (text[:1])
    
    • x = lambda a: ''.join(reversed(a))
    • def fools_version(text):
    • if len(text) == 1:
    • return text
    • return fools_version(text[1:]) + (text[:1])
Loading more items...