Ad
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])

Return None if the given input array is not missing a natural sequence.

Code
Diff
  • class MissingInteger:
        def __init__(self, arr):
            self.arr = arr
            self.temp = [i for i in range(min(self.arr), max(self.arr) + 1)]
    
        def solution(self):
            for x, y in zip(self.arr, self.temp):
                if x != y:
                    return y      
            return None
    
    • class MissingInteger:
    • def __init__(self, arr):
    • self.arr = arr
    • self.temp = [i for i in range(min(self.arr), max(self.arr) + 1)]
    • def solution(self):
    • xor = 1
    • for i, el in enumerate(self.arr):
    • if self.arr[i] != 0:
    • xor ^= self.arr[i]
    • xor ^= len(self.arr) + 1
    • return xor
    • for x, y in zip(self.arr, self.temp):
    • if x != y:
    • return y
    • return None
Code
Diff
  • class MissingInteger:
        def __init__(self, arr):
            self.arr = arr
    
        def solution(self):
            xor = 1
    
            for i, el in enumerate(self.arr):
                if self.arr[i] != 0:
                    xor ^= self.arr[i]
                xor ^= len(self.arr) + 1
    
            return xor
    
    • public class MissingInt {
    • public static int findMissingElement(int[] array) {
    • // write yor code here
    • int XOR = 0;
    • for (int i = 0; i < array.length; i++) {
    • if (array[i] != 0) {
    • XOR ^= array[i];
    • }
    • XOR ^= (i + 1);
    • }
    • XOR ^= array.length + 1;
    • return XOR;
    • }
    • }
    • class MissingInteger:
    • def __init__(self, arr):
    • self.arr = arr
    • def solution(self):
    • xor = 1
    • for i, el in enumerate(self.arr):
    • if self.arr[i] != 0:
    • xor ^= self.arr[i]
    • xor ^= len(self.arr) + 1
    • return xor
Fundamentals
Fundamentals
Code
Diff
  • class OrdinalNumbers:
        def __init__(self, n):
            self.n = n
            
        def solution(self):
            ht = {1: 'st', 2: 'nd', 3: 'rd'}
            if len(str(self.n)) < 2 or self.n in [11, 12, 13]:
                suffix = ht.get(self.n, 'th')
                return f'{self.n}{suffix}'
            else:
                last_digit = self.n % 10
                suffix = ht.get(last_digit, 'th')
                return f'{self.n}{suffix}'
    
    • class OrdinalNumbers:
    • def __init__(self, n):
    • self.n = n
    • def solution(self):
    • pass
    • ht = {1: 'st', 2: 'nd', 3: 'rd'}
    • if len(str(self.n)) < 2 or self.n in [11, 12, 13]:
    • suffix = ht.get(self.n, 'th')
    • return f'{self.n}{suffix}'
    • else:
    • last_digit = self.n % 10
    • suffix = ht.get(last_digit, 'th')
    • return f'{self.n}{suffix}'
Fundamentals
Ordinal numbers are numbers that indicate their position in a series, 
such as "1st," "2nd," or "3rd."

Task

Given an input integer `n`, return its ordinal position.

Example 1

INPUT: 21
OUTPUT: 21st

Example 2

INPUT: 776
OUTPUT: 776th

Example 3

INPUT: 33
OUTPUT: 33rd
class OrdinalNumbers:
    def __init__(self, n):
        self.n = n
        
    def solution(self):
        pass
Code
Diff
  • def is_palindrome(s: str) -> bool:
        return 'All’s Fair in Love and War... :)'
    • def is_palindrome(s: str) -> bool:
    • s = [c for c in s.lower() if c.isalpha()]
    • return s == s[::-1]
    • return 'All’s Fair in Love and War... :)'

Test cases added.

Code
Diff
  • import string
    
    
    def is_palindrome(s: str) -> bool:
        s = s.replace(' ', '').lower().translate(str.maketrans('', '', string.punctuation))
        return s == s[::-1]
    • import string
    • def is_palindrome(s: str) -> bool:
    • return s.lower() == s.lower()[::-1]
    • s = s.replace(' ', '').lower().translate(str.maketrans('', '', string.punctuation))
    • return s == s[::-1]
Code
Diff
  • def solution(param: list) -> bool:
        return len([x for x in param if x is bool('codewarz strikes back!')]) > 1
    • def solution(param: list) -> bool:
    • return len([x for x in param if x is True]) > 1
    • return len([x for x in param if x is bool('codewarz strikes back!')]) > 1
Code
Diff
  • # constants
    WIN_COMBOS = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]
    BOARD = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
    
    
    def make_board():
        """This function creates the board"""
        print("--- Noughts and Crosses ---")
        print(f'{BOARD[0]:<2}: {BOARD[1]:<2}: {BOARD[2]:>1}')
        print("..........")
        print(f'{BOARD[3]:<2}: {BOARD[4]:<2}: {BOARD[5]:>1}')
        print("..........")
        print(f'{BOARD[6]:<2}: {BOARD[7]:<2}: {BOARD[8]:>1}')
    
    
    def main():
        # Main menu
        print("*" * 50)
        print("Welcome to our Noughts and Crosses Game!")
        print("*" * 50)
        play_loc_list1 = []
        play_loc_list2 = []
        # Get player's names
        player_1 = input("Enter the name of the first player:\n> ")
        player_2 = input("Enter the name of the second player:\n> ")
        while True:
            turn = 1
            # Player 1 turn
            while turn == 1:
                print("Hi", player_1)
                while True:
                    make_board()
                    while True:
                        # User input validation loop:
                        loc_x = input("Cross location(choose 1 - 9):\n> ")
                        if not loc_x.isdigit() or int(loc_x) not in range(10):
                            print('>>> Invalid input!')
                            continue
                        else:
                            loc_x = int(loc_x)
                            break  # break User input validation loop:
    
                    # Check if position is empty:
                    if BOARD[loc_x - 1] == 'X' or BOARD[loc_x - 1] == 'O':
                        print('>>> Position taken, try again!')
                        continue
                    else:
                        BOARD[loc_x - 1] = "X"
                        break  # Break player 1 turn:
    
                # Check win combos:
                loc_attempt = loc_x - 1
                play_loc_list1.append(loc_attempt)
                play_loc_list1.sort()
                for i in range(0, len(WIN_COMBOS)):
                    if WIN_COMBOS[i] == play_loc_list1:
                        print("You have won!")
                        break
    
            make_board()
            turn = 2
            # Player 2 turn:
            while turn == 2:
                print("Hi", player_2)
                while True:
                    make_board()
                    while True:
                        # User input validation loop:
                        loc_y = input("Noughts location(choose 1 - 9):\n> ")
                        if not loc_y.isdigit() or int(loc_y) not in range(10):
                            print('>>> Invalid input')
                            continue
                        else:
                            loc_y = int(loc_y)
                            break  # break User input validation loop:
    
                    # Check if position is empty:
                    if BOARD[loc_y - 1] == 'X' or BOARD[loc_y - 1] == 'O':
                        print('>>> Position taken, try again!')
                        continue
                    else:
                        BOARD[loc_y - 1] = "O"
                        break  # Break player 2 turn:
                        
                # Check win combos:
                loc_attempt = loc_y - 1
                play_loc_list2.append(loc_attempt)
                play_loc_list2.sort()
                for i in range(0, len(WIN_COMBOS)):
                    if WIN_COMBOS[i] == play_loc_list2:
                        print("You have won!")
                        break
    
                make_board()
                turn = 1
    
    
    if __name__ == '__main__':
        main()
    
    • #Noughts and Crosses
    • win_combinations=[[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]
    • play_loc_list1=[]
    • play_loc_list2=[]
    • board=["1","2","3","4","5","6","7","8","9"]
    • print("*"*50)
    • print("Welcome to our Noughts and Crosses Game!")
    • print("*"*50)
    • player1=input("Enter the name of the first player: ")
    • player2=input("Enter the name of the second player: ")
    • no_win=True
    • turn=1
    • board=["1","2","3","4","5","6","7","8","9"]
    • # constants
    • WIN_COMBOS = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]
    • BOARD = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
    • def make_board():
    • print("Noughts and Crosses")
    • print(board[0],":",board[1],":",board[2])
    • print(".........")
    • print(board[3],":",board[4],":",board[5])
    • print(".........")
    • print(board[6],":",board[7],":",board[8])
    • make_board()
    • while no_win:
    • while turn==1 and no_win:
    • print("Hi",player1)
    • locx=int(input("Cross location(choose 1 - 9): "))
    • board[locx-1]="X"
    • loc_attempt=locx-1
    • play_loc_list1.append(loc_attempt)
    • play_loc_list1.sort()
    • for i in range (0,len(win_combinations)):
    • if win_combinations[i]==play_loc_list1:
    • print("You have won!")
    • no_win=False
    • make_board()
    • turn=2
    • while turn==2 and no_win:
    • print("Hi",player2)
    • locx=int(input("Noughts location(choose 1 - 9): "))
    • board[locx-1]="O"
    • loc_attempt=locx-1
    • """This function creates the board"""
    • print("--- Noughts and Crosses ---")
    • print(f'{BOARD[0]:<2}: {BOARD[1]:<2}: {BOARD[2]:>1}')
    • print("..........")
    • print(f'{BOARD[3]:<2}: {BOARD[4]:<2}: {BOARD[5]:>1}')
    • print("..........")
    • print(f'{BOARD[6]:<2}: {BOARD[7]:<2}: {BOARD[8]:>1}')
    • def main():
    • # Main menu
    • print("*" * 50)
    • print("Welcome to our Noughts and Crosses Game!")
    • print("*" * 50)
    • play_loc_list1 = []
    • play_loc_list2 = []
    • # Get player's names
    • player_1 = input("Enter the name of the first player:\n> ")
    • player_2 = input("Enter the name of the second player:\n> ")
    • while True:
    • turn = 1
    • # Player 1 turn
    • while turn == 1:
    • print("Hi", player_1)
    • while True:
    • make_board()
    • while True:
    • # User input validation loop:
    • loc_x = input("Cross location(choose 1 - 9):\n> ")
    • if not loc_x.isdigit() or int(loc_x) not in range(10):
    • print('>>> Invalid input!')
    • continue
    • else:
    • loc_x = int(loc_x)
    • break # break User input validation loop:
    • # Check if position is empty:
    • if BOARD[loc_x - 1] == 'X' or BOARD[loc_x - 1] == 'O':
    • print('>>> Position taken, try again!')
    • continue
    • else:
    • BOARD[loc_x - 1] = "X"
    • break # Break player 1 turn:
    • # Check win combos:
    • loc_attempt = loc_x - 1
    • play_loc_list1.append(loc_attempt)
    • play_loc_list1.sort()
    • for i in range(0, len(WIN_COMBOS)):
    • if WIN_COMBOS[i] == play_loc_list1:
    • print("You have won!")
    • break
    • make_board()
    • turn = 2
    • # Player 2 turn:
    • while turn == 2:
    • print("Hi", player_2)
    • while True:
    • make_board()
    • while True:
    • # User input validation loop:
    • loc_y = input("Noughts location(choose 1 - 9):\n> ")
    • if not loc_y.isdigit() or int(loc_y) not in range(10):
    • print('>>> Invalid input')
    • continue
    • else:
    • loc_y = int(loc_y)
    • break # break User input validation loop:
    • # Check if position is empty:
    • if BOARD[loc_y - 1] == 'X' or BOARD[loc_y - 1] == 'O':
    • print('>>> Position taken, try again!')
    • continue
    • else:
    • BOARD[loc_y - 1] = "O"
    • break # Break player 2 turn:
    • # Check win combos:
    • loc_attempt = loc_y - 1
    • play_loc_list2.append(loc_attempt)
    • play_loc_list2.sort()
    • for i in range (0,len(win_combinations)):
    • if win_combinations[i]==play_loc_list2:
    • for i in range(0, len(WIN_COMBOS)):
    • if WIN_COMBOS[i] == play_loc_list2:
    • print("You have won!")
    • no_win=False
    • break
    • make_board()
    • turn=1
    • turn = 1
    • if __name__ == '__main__':
    • main()
Code
Diff
  • def flat_the_list(lst):
        def flatten(l):
            for i in l:
                if isinstance(i, (list, tuple)):
                    for j in flat_the_list(i):
                        yield j
                else:
                    yield i
        return list(flatten(lst))
    • def flat_the_list(item_list):
    • return [subitem for item in item_list for subitem in item]
    • def flat_the_list(lst):
    • def flatten(l):
    • for i in l:
    • if isinstance(i, (list, tuple)):
    • for j in flat_the_list(i):
    • yield j
    • else:
    • yield i
    • return list(flatten(lst))
Code
Diff
  • from dataclasses import dataclass, field
    
    
    @dataclass
    class UserInfo:
        first_name: str
        last_name: str
        age: int
        job: str = field(default=None)
        hobbies: list[str] = field(default=None)
    
        @property
        def full_name(self):
            return f'{self.first_name} {self.last_name}'
    
        @property
        def email(self):
            return f'{self.first_name[0]}{self.last_name}@matrix.com'
    • from dataclasses import dataclass
    • from dataclasses import dataclass, field
    • @dataclass
    • class UserInfo:
    • first_name: str
    • last_name: str
    • age: int
    • job: str | None
    • hobbies: list[str] | None
    • job: str = field(default=None)
    • hobbies: list[str] = field(default=None)
    • @property
    • def full_name(self):
    • return f'{self.first_name} {self.last_name}'
    • @property
    • def email(self):
    • return f'{self.first_name[0]}{self.last_name}@matrix.com'
Loading more items...