def foo(param='foo'): return f"Hello {param.title()}"
print("hello world")- def foo(param='foo'):
- return f"Hello {param.title()}"
import codewars_test as test from solution import foo # test.assert_equals(actual, expected, [optional] message) @test.describe("Example") def test_group(): @test.it("test case") def test_case(): test.assert_equals(foo('seraph'), 'Hello Seraph') test.assert_equals(foo(), 'Hello Foo')
- import codewars_test as test
# TODO Write testsimport solution # or from solution import example- from solution import foo
- # test.assert_equals(actual, expected, [optional] message)
- @test.describe("Example")
- def test_group():
- @test.it("test case")
- def test_case():
test.assert_equals(1 + 1, 2)- test.assert_equals(foo('seraph'), 'Hello Seraph')
- test.assert_equals(foo(), 'Hello Foo')
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
import codewars_test as test from solution import inspector_yeezy # test.assert_equals(actual, expected, [optional] message) @test.describe("Example") def test_group(): @test.it("test case 1: 'Test words that have no vowels except for Y'") def test_case(): t1 = ('by', 'lynch', 'spy', 'sync', 'myth', 'fly', 'dry', 'crypt', 'nymph', 'psych', 'why', 'tryst') for s in t1: test.assert_equals(inspector_yeezy(s), True ) @test.it("test case 2: 'Test words where Y follows last consonant") def test_case(): t2 = ('agony', 'beauty', 'army', 'easy', 'bury', 'party', 'ugly', 'foxy', 'pony', 'totally', 'pretty', 'sunny') for s in t2: test.assert_equals(inspector_yeezy(s), True ) @test.it("test case 3: 'Test words where Y follows last vowel") def test_case(): t3 = ('alley', 'annoy', 'kidney', 'key', 'survey', 'essay', 'money', 'grey', 'anyway', 'honey', 'decay', 'gooey') for s in t3: test.assert_equals(inspector_yeezy(s), True ) @test.it("test case 4: 'Test words where Y is at the end of a syllable") def test_case(): t4 = ('bicycle', 'oxygen', 'python', 'tyrant', 'royal', 'prayer', 'psychology', 'hyphen', 'typhoon', 'hygiene', 'Egypt', 'prayer') for s in t4: test.assert_equals(inspector_yeezy(s), True ) @test.it("test case 5: 'Test words where Y is in the middle of a syllable") def test_case(): t4 = ('abyss', 'goodbye', 'hype', 'typical', 'symphony', 'paralyze', 'system', 'mastery', 'eye', 'lye', 'crystal', 'anonymous') for s in t4: test.assert_equals(inspector_yeezy(s), True ) @test.it("test case 6: 'Test words that do not contain the letter Y") def test_case(): t5 = ('I', 'am', 'seraph', 'the', 'feathered', 'serpent', 'son', 'of', 'the', 'fabled', 'fallen', 'dragon', 'Abaddon') for s in t5: test.assert_equals(inspector_yeezy(s), None )
- import codewars_test as test
- from solution import inspector_yeezy
- # test.assert_equals(actual, expected, [optional] message)
- @test.describe("Example")
- def test_group():
- @test.it("test case 1: 'Test words that have no vowels except for Y'")
- def test_case():
- t1 = ('by', 'lynch', 'spy', 'sync', 'myth', 'fly', 'dry', 'crypt', 'nymph', 'psych', 'why', 'tryst')
- for s in t1:
- test.assert_equals(inspector_yeezy(s), True )
- @test.it("test case 2: 'Test words where Y follows last consonant")
- def test_case():
- t2 = ('agony', 'beauty', 'army', 'easy', 'bury', 'party', 'ugly', 'foxy', 'pony', 'totally', 'pretty', 'sunny')
- for s in t2:
- test.assert_equals(inspector_yeezy(s), True )
- @test.it("test case 3: 'Test words where Y follows last vowel")
- def test_case():
- t3 = ('alley', 'annoy', 'kidney', 'key', 'survey', 'essay', 'money', 'grey', 'anyway', 'honey', 'decay', 'gooey')
- for s in t3:
- test.assert_equals(inspector_yeezy(s), True )
- @test.it("test case 4: 'Test words where Y is at the end of a syllable")
- def test_case():
- t4 = ('bicycle', 'oxygen', 'python', 'tyrant', 'royal', 'prayer', 'psychology', 'hyphen', 'typhoon', 'hygiene', 'Egypt', 'prayer')
- for s in t4:
- test.assert_equals(inspector_yeezy(s), True )
- @test.it("test case 5: 'Test words where Y is in the middle of a syllable")
- def test_case():
- t4 = ('abyss', 'goodbye', 'hype', 'typical', 'symphony', 'paralyze', 'system', 'mastery', 'eye', 'lye', 'crystal', 'anonymous')
- for s in t4:
- test.assert_equals(inspector_yeezy(s), True )
- @test.it("test case 6: 'Test words that do not contain the letter Y")
- def test_case():
t5 = ('I', 'am', 'seraph', 'the', 'feathered', 'serpent', 'son', 'of', 'the', 'fabled', 'fallen', 'dragon')- t5 = ('I', 'am', 'seraph', 'the', 'feathered', 'serpent', 'son', 'of', 'the', 'fabled', 'fallen', 'dragon', 'Abaddon')
- for s in t5:
- test.assert_equals(inspector_yeezy(s), None )
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
import codewars_test as test
from solution import inspector_yeezy
# test.assert_equals(actual, expected, [optional] message)
@test.describe("Example")
def test_group():
@test.it("test case 1: 'Test words that have no vowels except for Y'")
def test_case():
t1 = ('by', 'lynch', 'spy', 'sync', 'myth', 'fly', 'dry', 'crypt', 'nymph', 'psych', 'why', 'tryst')
for s in t1:
test.assert_equals(inspector_yeezy(s), True )
@test.it("test case 2: 'Test words where Y follows last consonant")
def test_case():
t2 = ('agony', 'beauty', 'army', 'easy', 'bury', 'party', 'ugly', 'foxy', 'pony', 'totally', 'pretty', 'sunny')
for s in t2:
test.assert_equals(inspector_yeezy(s), True )
@test.it("test case 3: 'Test words where Y follows last vowel")
def test_case():
t3 = ('alley', 'annoy', 'kidney', 'key', 'survey', 'essay', 'money', 'grey', 'anyway', 'honey', 'decay', 'gooey')
for s in t3:
test.assert_equals(inspector_yeezy(s), True )
@test.it("test case 4: 'Test words where Y is at the end of a syllable")
def test_case():
t4 = ('bicycle', 'oxygen', 'python', 'tyrant', 'royal', 'prayer', 'psychology', 'hyphen', 'typhoon', 'hygiene', 'Egypt', 'prayer')
for s in t4:
test.assert_equals(inspector_yeezy(s), True )
@test.it("test case 5: 'Test words where Y is in the middle of a syllable")
def test_case():
t4 = ('abyss', 'goodbye', 'hype', 'typical', 'symphony', 'paralyze', 'system', 'mastery', 'eye', 'lye', 'crystal', 'anonymous')
for s in t4:
test.assert_equals(inspector_yeezy(s), True )
@test.it("test case 6: 'Test words that do not contain the letter Y")
def test_case():
t5 = ('I', 'am', 'seraph', 'the', 'feathered', 'serpent', 'son', 'of', 'the', 'fabled', 'fallen', 'dragon')
for s in t5:
test.assert_equals(inspector_yeezy(s), None )
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])
import codewars_test as test from solution import fools_version # test.assert_equals(actual, expected, [optional] message) @test.describe("Main") def test_group(): @test.it("test case") def test_case(): test.assert_equals(fools_version('olleh'), 'hello') test.assert_equals(fools_version('ih'), 'hi') test.assert_equals(fools_version('ecnaidar'), 'radiance')
- import codewars_test as test
from solution import x- from solution import fools_version
- # test.assert_equals(actual, expected, [optional] message)
- @test.describe("Main")
- def test_group():
- @test.it("test case")
- def test_case():
test.assert_equals(x('olleh'), 'hello')test.assert_equals(x('ih'), 'hi')test.assert_equals(x('ecnaidar'), 'radiance')- test.assert_equals(fools_version('olleh'), 'hello')
- test.assert_equals(fools_version('ih'), 'hi')
- test.assert_equals(fools_version('ecnaidar'), 'radiance')
Return None
if the given input array is not missing a natural sequence.
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 = 1for i, el in enumerate(self.arr):if self.arr[i] != 0:xor ^= self.arr[i]xor ^= len(self.arr) + 1return xor- for x, y in zip(self.arr, self.temp):
- if x != y:
- return y
- return None
import codewars_test as test from solution import MissingInteger @test.describe("Example") def test_group(): @test.it("test case") def test_case(): test.assert_equals(MissingInteger([1, 2, 3, 4, 5, 7, 8, 9]).solution(), 6) test.assert_equals(MissingInteger([1, 2, 4, 5, 6, 7, 8, 9]).solution(), 3) test.assert_equals(MissingInteger([-2, 0, 1, 2, 3, 4, 5, 6]).solution(), -1) test.assert_equals(MissingInteger([1, 2, 3, 4, 5, 6, 7, 8, 9]).solution(), None)
- import codewars_test as test
- from solution import MissingInteger
- @test.describe("Example")
- def test_group():
- @test.it("test case")
- def test_case():
- test.assert_equals(MissingInteger([1, 2, 3, 4, 5, 7, 8, 9]).solution(), 6)
- test.assert_equals(MissingInteger([1, 2, 4, 5, 6, 7, 8, 9]).solution(), 3)
test.assert_equals(MissingInteger([1, 2, 3, 4, 5, 6, 7, 8, 9]).solution(), 10)- test.assert_equals(MissingInteger([-2, 0, 1, 2, 3, 4, 5, 6]).solution(), -1)
- test.assert_equals(MissingInteger([1, 2, 3, 4, 5, 6, 7, 8, 9]).solution(), None)
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 hereint 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
import codewars_test as test from solution import MissingInteger @test.describe("Example") def test_group(): @test.it("test case") def test_case(): test.assert_equals(MissingInteger([1, 2, 3, 4, 5, 7, 8, 9]).solution(), 6) test.assert_equals(MissingInteger([1, 2, 4, 5, 6, 7, 8, 9]).solution(), 3) test.assert_equals(MissingInteger([1, 2, 3, 4, 5, 6, 7, 8, 9]).solution(), 10)
import org.junit.jupiter.api.Test;import static org.junit.jupiter.api.Assertions.assertEquals;- import codewars_test as test
- from solution import MissingInteger
// TODO: Replace examples and use TDD by writing your own testsclass SolutionTest {@Testvoid testSomething() {int[] array1 = {1,2,3,4,5,7,8,9};int expected = 6;int actual = MissingInt.findMissingElement(array1);assertEquals(expected, actual);}@Testvoid test2() {int[] array1 = {1,2,4,5,6,7,8,9};int expected = 3;int actual = MissingInt.findMissingElement(array1);assertEquals(expected, actual);}}- @test.describe("Example")
- def test_group():
- @test.it("test case")
- def test_case():
- test.assert_equals(MissingInteger([1, 2, 3, 4, 5, 7, 8, 9]).solution(), 6)
- test.assert_equals(MissingInteger([1, 2, 4, 5, 6, 7, 8, 9]).solution(), 3)
- test.assert_equals(MissingInteger([1, 2, 3, 4, 5, 6, 7, 8, 9]).solution(), 10)
import codewars_test as test from solution import OrdinalNumbers @test.describe("Example") def test_group(): @test.it("test case 1: (1-10)") def test_case(): samples = [n for n in range(1, 11)] expected = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th'] for s, e in zip(samples, expected): test.assert_equals(OrdinalNumbers(s).solution(), e) @test.it("test case 2: (11-30)") def test_case(): samples = [n for n in range(11, 31)] expected = ['11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd', '24th', '25th', '26th', '27th', '28th', '29th', '30th'] for s, e in zip(samples, expected): test.assert_equals(OrdinalNumbers(s).solution(), e) @test.it("test case 3: Random") def test_case(): samples = [776, 411, 1001100, 99999999, 567090803542432, 33197390315682527] expected = ['776th', '411th', '1001100th', '99999999th', '567090803542432nd', '33197390315682527th'] for s, e in zip(samples, expected): test.assert_equals(OrdinalNumbers(s).solution(), e)
- import codewars_test as test
- from solution import OrdinalNumbers
- @test.describe("Example")
- def test_group():
- @test.it("test case 1: (1-10)")
- def test_case():
- samples = [n for n in range(1, 11)]
- expected = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th']
- for s, e in zip(samples, expected):
- test.assert_equals(OrdinalNumbers(s).solution(), e)
- @test.it("test case 2: (11-30)")
- def test_case():
- samples = [n for n in range(11, 31)]
- expected = ['11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd', '24th', '25th', '26th', '27th', '28th', '29th', '30th']
- for s, e in zip(samples, expected):
- test.assert_equals(OrdinalNumbers(s).solution(), e)
- @test.it("test case 3: Random")
- def test_case():
- samples = [776, 411, 1001100, 99999999, 567090803542432, 33197390315682527]
expected = ['776th', '411st', '1001100th', '99999999th', '567090803542432nd', '33197390315682527th']- expected = ['776th', '411th', '1001100th', '99999999th', '567090803542432nd', '33197390315682527th']
- for s, e in zip(samples, expected):
- test.assert_equals(OrdinalNumbers(s).solution(), e)
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}'
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
import codewars_test as test
from solution import OrdinalNumbers
@test.describe("Example")
def test_group():
@test.it("test case 1: (1-10)")
def test_case():
samples = [n for n in range(1, 11)]
expected = ['1st', '2nd', '3rd', '4th', '5th', '6th', '7th', '8th', '9th', '10th']
for s, e in zip(samples, expected):
test.assert_equals(OrdinalNumbers(s).solution(), e)
@test.it("test case 2: (11-30)")
def test_case():
samples = [n for n in range(11, 31)]
expected = ['11th', '12th', '13th', '14th', '15th', '16th', '17th', '18th', '19th', '20th', '21st', '22nd', '23rd', '24th', '25th', '26th', '27th', '28th', '29th', '30th']
for s, e in zip(samples, expected):
test.assert_equals(OrdinalNumbers(s).solution(), e)
@test.it("test case 3: Random")
def test_case():
samples = [776, 411, 1001100, 99999999, 567090803542432, 33197390315682527]
expected = ['776th', '411st', '1001100th', '99999999th', '567090803542432nd', '33197390315682527th']
for s, e in zip(samples, expected):
test.assert_equals(OrdinalNumbers(s).solution(), e)
Test cases added.
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]
import codewars_test as test from solution import is_palindrome @test.describe("Example") def test_group(): @test.it("Simple test case: True") def test_case(): test.assert_equals(is_palindrome('level'), True) test.assert_equals(is_palindrome('Racecar'), True) test.assert_equals(is_palindrome('tenet'), True) test.assert_equals(is_palindrome('taTtarRaTTaT'), True) @test.it("Simple test case: False") def test_case(): test.assert_equals(is_palindrome('codewarz'), False) test.assert_equals(is_palindrome('python'), False) test.assert_equals(is_palindrome('foobar'), False) @test.it("Punctuation and spaces test case: True") def test_case(): test.assert_equals(is_palindrome(' A man, a plan, a canal: Panama'), True) test.assert_equals(is_palindrome('No lemon, no melon'), True) test.assert_equals(is_palindrome('Won\'t lovers revolt now?'), True) test.assert_equals(is_palindrome('Ah. Satan sees Natasha.'), True) @test.it("Tougher punctuation and spaces test cases: True") def test_case(): test.assert_equals(is_palindrome('Name no side in Eden, I\'m mad! A maid I am, Adam mine denied is one man.'), True) test.assert_equals(is_palindrome('Gert, I saw Ron avoid a radio-van, or was it Reg? '), True) test.assert_equals(is_palindrome('On a clover, if alive, erupts a vast pure evil; a fire volcano.'), True) test.assert_equals(is_palindrome('Naomi, Gianna, Ed, Nall, Robert, Allen, Red, Hon, Evan, Eden, Mel, Lola, Alol, Lemned, Enave, Noh, Der, Nella, Trebor, Llan, De, Anna, Ig & I moan. '), True)
- import codewars_test as test
# TODO Write testsimport solution # or from solution import example- from solution import is_palindrome
# test.assert_equals(actual, expected, [optional] message)- @test.describe("Example")
- def test_group():
@test.it("test case")- @test.it("Simple test case: True")
- def test_case():
test.assert_equals(1 + 1, 2)- test.assert_equals(is_palindrome('level'), True)
- test.assert_equals(is_palindrome('Racecar'), True)
- test.assert_equals(is_palindrome('tenet'), True)
- test.assert_equals(is_palindrome('taTtarRaTTaT'), True)
- @test.it("Simple test case: False")
- def test_case():
- test.assert_equals(is_palindrome('codewarz'), False)
- test.assert_equals(is_palindrome('python'), False)
- test.assert_equals(is_palindrome('foobar'), False)
- @test.it("Punctuation and spaces test case: True")
- def test_case():
- test.assert_equals(is_palindrome(' A man, a plan, a canal: Panama'), True)
- test.assert_equals(is_palindrome('No lemon, no melon'), True)
- test.assert_equals(is_palindrome('Won\'t lovers revolt now?'), True)
- test.assert_equals(is_palindrome('Ah. Satan sees Natasha.'), True)
- @test.it("Tougher punctuation and spaces test cases: True")
- def test_case():
- test.assert_equals(is_palindrome('Name no side in Eden, I\'m mad! A maid I am, Adam mine denied is one man.'), True)
- test.assert_equals(is_palindrome('Gert, I saw Ron avoid a radio-van, or was it Reg? '), True)
- test.assert_equals(is_palindrome('On a clover, if alive, erupts a vast pure evil; a fire volcano.'), True)
- test.assert_equals(is_palindrome('Naomi, Gianna, Ed, Nall, Robert, Allen, Red, Hon, Evan, Eden, Mel, Lola, Alol, Lemned, Enave, Noh, Der, Nella, Trebor, Llan, De, Anna, Ig & I moan. '), True)
# 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 Crosseswin_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=Trueturn=1board=["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-1play_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=Falsemake_board()turn=2while 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()
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))
import codewars_test as test from solution import flat_the_list @test.describe("flat_list") def test_group(): @test.it("basic test case") def basic_test_case(): test.assert_equals(flat_the_list([[1,2,3], [4,5,6], [7,8,9]]), [1,2,3,4,5,6,7,8,9]) test.assert_equals(flat_the_list([[0], [1,2,3], [4,5,6,7], [8,9]]), [0,1,2,3,4,5,6,7,8,9]) test.assert_equals(flat_the_list([[], [], []]), []) test.assert_equals(flat_the_list(['eat', (0, ([1, 2, [3, [['sleep', [[4]]]]], (((6,),),), 'code', 7, [[[8]]], 9]),), 'repeat']),['eat', 0, 1, 2, 3, 'sleep', 4, 6, 'code', 7, 8, 9, 'repeat'])
- import codewars_test as test
- from solution import flat_the_list
- @test.describe("flat_list")
- def test_group():
- @test.it("basic test case")
- def basic_test_case():
- test.assert_equals(flat_the_list([[1,2,3], [4,5,6], [7,8,9]]), [1,2,3,4,5,6,7,8,9])
- test.assert_equals(flat_the_list([[0], [1,2,3], [4,5,6,7], [8,9]]), [0,1,2,3,4,5,6,7,8,9])
test.assert_equals(flat_the_list([[], [], []]), [])- test.assert_equals(flat_the_list([[], [], []]), [])
- test.assert_equals(flat_the_list(['eat', (0, ([1, 2, [3, [['sleep', [[4]]]]], (((6,),),), 'code', 7, [[[8]]], 9]),), 'repeat']),['eat', 0, 1, 2, 3, 'sleep', 4, 6, 'code', 7, 8, 9, 'repeat'])
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 | Nonehobbies: 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'
import codewars_test as test from solution import UserInfo @test.describe("Example") def test_group(): @test.it("test case") def test_case(): sample_user = UserInfo('agent', 'smith', 101, 'an Agent of the system', ['capture/kill neo', 'destroy zion','escape the matrix' ] ) test.assert_equals(sample_user.first_name, 'agent') test.assert_equals(sample_user.last_name, 'smith') test.assert_equals(sample_user.full_name, 'agent smith') test.assert_equals(sample_user.job, 'an Agent of the system') test.assert_equals(sample_user.hobbies, ['capture/kill neo', 'destroy zion','escape the matrix' ]) test.assert_equals(sample_user.email, 'asmith@matrix.com')
- import codewars_test as test
- from solution import UserInfo
- @test.describe("Example")
- def test_group():
- @test.it("test case")
- def test_case():
sample_user = UserInfo('agent', 'smith', 101, 'an Agent of the system', ['capture/kill neo', 'detroy zion','escape the matrix' ] )- sample_user = UserInfo('agent', 'smith', 101, 'an Agent of the system', ['capture/kill neo', 'destroy zion','escape the matrix' ] )
- test.assert_equals(sample_user.first_name, 'agent')
- test.assert_equals(sample_user.last_name, 'smith')
- test.assert_equals(sample_user.full_name, 'agent smith')
- test.assert_equals(sample_user.job, 'an Agent of the system')
test.assert_equals(sample_user.hobbies, ['capture/kill neo', 'detroy zion','escape the matrix' ])- test.assert_equals(sample_user.hobbies, ['capture/kill neo', 'destroy zion','escape the matrix' ])
- test.assert_equals(sample_user.email, 'asmith@matrix.com')