Goal
Write a function that takes an array, and an integer as arguments. Your function should return a sub-array of the given array sorted by longest word -> shortest word. The returned array should be the first n elements where n is the given integer.
You should consider only letters for your sorting. Any other unicode character should be removed before comparison. If there are any empty strings because of this, remove them from the final list. If there are multiple words of the same length, maintain order of appearance. If you encounter a case where the number is longer than the array, or if the array is completely full of invalid words, return a string with the message: 'Invalid Parameters.'
Assume that each element of the array is a string that should be counted as one word.
Examples
INPUT: (["Hello", "world", "Coding", "is", "fun!"], 1)
OUTPUT: ['Coding']
INPUT: (["Python", "Java", "C++", "JavaScript"], 4)
OUTPUT: ['JavaScript', 'Python', 'Java', 'C']
INPUT: (["Hello", "world", "Coding", "is", "fun!"], 6)
OUTPUT: 'Invalid Parameters'
def longest_words(array, num): new = [k for k in sorted([''.join([i for i in j if 97 <= ord(i) <= 122 or 65 <= ord(i) <= 90]) for j in array], key=lambda x: len(x), reverse=True) if k != ''] return new[:num] if num <= len(new) else 'Invalid Parameters'
longest_words(["Hello", "world", "Coding", "is", "fun!"])# Output: ["Hello", "world", "Coding"]longest_words(["Python", "Java", "C++", "JavaScript"])# Output: ["Python", "JavaScript"]- def longest_words(array, num):
- new = [k for k in sorted([''.join([i for i in j if 97 <= ord(i) <= 122 or 65 <= ord(i) <= 90]) for j in array], key=lambda x: len(x), reverse=True) if k != '']
- return new[:num] if num <= len(new) else 'Invalid Parameters'
import codewars_test as test from solution import longest_words import random # Working solution def _solve(array, num): new = [k for k in sorted([''.join([i for i in j if 97 <= ord(i) <= 122 or 65 <= ord(i) <= 90]) for j in array], key=lambda x: len(x), reverse=True) if k != ''] print(new[:num] if num <= len(new) else 'Invalid Parameters') return new[:num] if num <= len(new) else 'Invalid Parameters' # Random word list generator def gen_random(length): word_list = [('Programming', 'ƤŖø¶Ŗ@µµƗƕ¶', 'Prø¶r@mming'), ('is', 'Ɨ$', 'is'), ('often', 'øƒƮƩƕ', 'often'), ('compared', '¢øµƤ@ŖƩƊ', 'comƤ@Ŗed'), ('to', 'Ʈø', 'to'), ('solving', '$øȴƔƗƕ¶', '$olvƗn¶'), ('intricate', 'ƗƕƮŖƗ¢@ƮƩ', 'intri¢aƮe'), ('puzzles,', 'Ƥû§§ȴƩ$,', 'pu§§le$,'), ('', '', '',), ('requiring', 'ŖƩǭûƗŖƗƕ¶', 'ŖeqûƗŖing'), ('a', '@', 'a'), ('sharp', '$ɧ@ŖƤ', 'sharp'), ('analytical', '@ƕ@ȴ¥ƮƗ¢@ȴ', '@nal¥Ʈical'), ('mind', 'µƗƕƊ', 'mind'), ('to', 'Ʈø', 'tø'), ('piece', 'ƤƗƩ¢Ʃ', 'piecƩ'), ('together', 'Ʈø¶ƩƮɧƩŖ', 'togetɧeŖ'), ('the', 'ƮɧƩ', 'the'), ('correct', '¢øŖŖƩ¢Ʈ', 'correct'), ('code.', '¢øƊƩ.', 'code.'), ('One', 'øƕƩ', 'Oƕe'), ('of', 'øƒ', 'oƒ'), ('the', 'ƮɧƩ', 'tɧe'), ('complexities', '¢øµƤȴƩ×ƗƮƗƩ$', 'cøµplexƗƮie$'), ('of', 'øƒ', 'of'), ('programming', 'ƤŖø¶Ŗ@µµƗƕ¶', 'ƤrogrammƗng'), ('lies', 'ȴƗƩ$', 'liƩs'), ('in', 'Ɨƕ', 'in'), ('managing', 'µ@ƕ@¶Ɨƕ¶', 'µaƕagƗn¶'), ('an', '@ƕ', '@n'), ('ever-growing', 'ƩƔƩŖ-¶ŖøƜƗƕ¶', 'eƔƩr-¶røƜing'), ('body', 'ßøƊ¥', 'body'), ('of', 'øƒ', 'oƒ'), ('knowledge', 'ƙƕøƜȴƩƊ¶Ʃ', 'kƕoƜledge'), ('as', '@$', 'as'), ('new', 'ƕƩƜ', 'nƩw'), ('languages', 'ȴ@ƕ¶û@¶Ʃ$', 'laƕgû@ges'), ('and', '@ƕƊ', '@nd'), ('technologies', 'ƮƩ¢ɧƕøȴø¶ƗƩ$', 'technoløgies'), ('emerge.', 'ƩµƩŖ¶Ʃ.', 'emergƩ.'), ('', '', '',), ('Debugging', 'ƊƩßû¶¶Ɨƕ¶', 'Ɗeßûg¶ing'), ('code', '¢øƊƩ', 'cøde'), ('can', '¢@ƕ', 'can'), ('be', 'ßƩ', 'be'), ('like', 'ȴƗƙƩ', 'ȴikƩ'), ('searching', '$Ʃ@Ŗ¢ɧƗƕ¶', 'se@rcɧƗn¶'), ('for', 'ƒøŖ', 'for'), ('a', '@', 'a'), ('needle', 'ƕƩƩƊȴƩ', 'ƕeƩdle'), ('in', 'Ɨƕ', 'Ɨn'), ('a', '@', 'a'), ('haystack,', 'ɧ@¥$Ʈ@¢ƙ,', 'haystacƙ,'), ('as', '@$', '@s'), ('a', '@', 'a'), ('single', '$Ɨƕ¶ȴƩ', 'siƕgle'), ('character', '¢ɧ@Ŗ@¢ƮƩŖ', 'cɧaŖ@cteŖ'), ('error', 'ƩŖŖøŖ', 'errør'), ('can', '¢@ƕ', 'caƕ'), ('lead', 'ȴƩ@Ɗ', 'lƩ@Ɗ'), ('to', 'Ʈø', 'tø'), ('hours', 'ɧøûŖ$', 'hoûŖ$'), ('of', 'øƒ', 'oƒ'), ('troubleshooting.', 'ƮŖøûßȴƩ$ɧøøƮƗƕ¶.', 'trøußlesɧooƮin¶.'), ('The', 'ƮɧƩ', 'Ʈhe'), ('', '', '',), ('', '', '',), ('meticulous', 'µƩƮƗ¢ûȴøû$', 'metƗ¢uȴous'), ('attention', '@ƮƮƩƕƮƗøƕ', 'aƮtention'), ('to', 'Ʈø', 'to'), ('detail', 'ƊƩƮ@Ɨȴ', 'detail'), ('needed', 'ƕƩƩƊƩƊ', 'nƩedƩd'), ('in', 'Ɨƕ', 'in'), ('', '', '',), ('programming', 'ƤŖø¶Ŗ@µµƗƕ¶', 'Ƥro¶rammƗng'), ('can', '¢@ƕ', '¢an'), ('be', 'ßƩ', 'be'), ('', '', '',), ('mentally', 'µƩƕƮ@ȴȴ¥', 'mƩnƮ@ȴȴy'), ('taxing,', 'Ʈ@×Ɨƕ¶,', 'Ʈ@xƗng,'), ('leading', 'ȴƩ@ƊƗƕ¶', 'ȴe@dƗng'), ('to', 'Ʈø', 'to'), ('fatigue', 'ƒ@ƮƗ¶ûƩ', 'fatiguƩ'), ('and', '@ƕƊ', 'aƕd'), ('burnout.', 'ßûŖƕøûƮ.', 'ßuŖnoût.'), ('Staying', '$Ʈ@¥Ɨƕ¶', '$taying'), ('updated', 'ûƤƊ@ƮƩƊ', 'upd@teƊ'), ('in', 'Ɨƕ', 'iƕ'), ('the', 'ƮɧƩ', 'tɧe'), ('fast-paced', 'ƒ@$Ʈ-Ƥ@¢ƩƊ', 'fa$t-ƤacƩƊ'), ('tech', 'ƮƩ¢ɧ', 'tech'), ('world', 'ƜøŖȴƊ', 'wørȴƊ'), ('is', 'Ɨ$', 'is'), ('a', '@', 'a'), ('constant', '¢øƕ$Ʈ@ƕƮ', 'con$Ʈaƕt'), ('challenge,', '¢ɧ@ȴȴƩƕ¶Ʃ,', 'ch@lleƕge,'), ('', '', '',), ('with', 'ƜƗƮɧ', 'ƜiƮh'), ('new', 'ƕƩƜ', 'new'), ('frameworks', 'ƒŖ@µƩƜøŖƙ$', 'ƒŖ@meƜoŖks'), ('and', '@ƕƊ', '@nd'), ('libraries', 'ȴƗßŖ@ŖƗƩ$', 'ȴƗbŖ@rƗes'), ('being', 'ßƩƗƕ¶', 'bƩƗƕ¶'), ('released', 'ŖƩȴƩ@$ƩƊ', 'rƩle@sƩƊ'), ('regularly.', 'ŖƩ¶ûȴ@Ŗȴ¥.', 'ŖƩguȴarly.'), ('The', 'ƮɧƩ', 'ƮhƩ'), ('precise', 'ƤŖƩ¢Ɨ$Ʃ', 'precise'), ('syntax', '$¥ƕƮ@×', 's¥nƮax'), ('and', '@ƕƊ', 'anƊ'), ('semantics', '$Ʃµ@ƕƮƗ¢$', 'seµaƕƮƗc$'), ('of', 'øƒ', 'of'), ('each', 'Ʃ@¢ɧ', 'e@cɧ'), ('programming', 'ƤŖø¶Ŗ@µµƗƕ¶', 'pŖogŖamµing'), ('language', 'ȴ@ƕ¶û@¶Ʃ', 'ȴ@ngua¶e'), ('add', '@ƊƊ', '@dd'), ('layers', 'ȴ@¥ƩŖ$', 'layƩr$'), ('of', 'øƒ', 'of'), ('difficulty,', 'ƊƗƒƒƗ¢ûȴƮ¥,', 'diƒfƗcûlty,'), ('as', '@$', 'as'), ('small', '$µ@ȴȴ', 'smaȴȴ'), ('mistakes', 'µƗ$Ʈ@ƙƩ$', 'mƗstaƙe$'), ('can', '¢@ƕ', 'can'), ('cause', '¢@û$Ʃ', 'caûsƩ'), ('major', 'µ@ǰøŖ', 'µ@ǰøŖ'), ('issues.', 'Ɨ$$ûƩ$.', 'Ɨ$sûes.'), ('', '', '',)] return [random.choice(word_list)[random.randint(0, 2)] for _ in range(length)] # Start of testing @test.describe("Example Tests") def test_group(): @test.it("Testing...") def test_case(): test.assert_equals(longest_words(["Hello", "world", "Coding", "is", "fun!"], 1), ['Coding']) test.assert_equals(longest_words(["Python", "Java", "C++", "JavaScript"], 4), ['JavaScript', 'Python', 'Java', 'C']) test.assert_equals(longest_words(["Hello", "world", "Coding", "is", "fun!"], 6), 'Invalid Parameters') @test.describe("Edge Cases") def test_group2(): @test.it("Testing...") def test_edges(): test.assert_equals(longest_words(["H3ll0", "w0rld", "C0d1ng", "1s", "fun!"], 4), ['wrld', 'Cdng', 'Hll', 'fun']) test.assert_equals(longest_words(["HELLO", '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], 1), ['HELLO']) test.assert_equals(longest_words(["HELLO", 'B123I123G123W123O123R123D', '1', '2', '3', '4', '5', '6', '7', '8', '9'], 2), ['BIGWORD', 'HELLO']) test.assert_equals(longest_words(["HELLO", '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], 2), 'Invalid Parameters') test.assert_equals(longest_words(['k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'], 5), ['k', 'j', 'i', 'h', 'g']) @test.describe('Random Tests') def test_random(): @test.it('Small Tests') def small_rand(): for _ in range(10): for i in range(5, 10): rand_words = gen_random(i) rand_num = random.randint(0, i + 1) test.assert_equals(longest_words(rand_words[:], rand_num), _solve(rand_words[:], rand_num)) @test.it('Medium Tests') def med_rand(): for _ in range(10): for i in range(15, 20): rand_words = gen_random(i) rand_num = random.randint(0, i + 1) test.assert_equals(longest_words(rand_words[:], rand_num), _solve(rand_words[:], rand_num)) @test.it('Large Tests') def med_rand(): for i in range(25, 125): rand_words = gen_random(i) rand_num = random.randint(0, i + 1) test.assert_equals(longest_words(rand_words[:], rand_num), _solve(rand_words[:], rand_num))
- import codewars_test as test
# TODO Write testsimport solution # or from solution import example- from solution import longest_words
- import random
# test.assert_equals(actual, expected, [optional] message)@test.describe("Example")- # Working solution
- def _solve(array, num):
- new = [k for k in sorted([''.join([i for i in j if 97 <= ord(i) <= 122 or 65 <= ord(i) <= 90]) for j in array], key=lambda x: len(x), reverse=True) if k != '']
- print(new[:num] if num <= len(new) else 'Invalid Parameters')
- return new[:num] if num <= len(new) else 'Invalid Parameters'
- # Random word list generator
- def gen_random(length):
- word_list = [('Programming', 'ƤŖø¶Ŗ@µµƗƕ¶', 'Prø¶r@mming'), ('is', 'Ɨ$', 'is'), ('often', 'øƒƮƩƕ', 'often'),
- ('compared', '¢øµƤ@ŖƩƊ', 'comƤ@Ŗed'), ('to', 'Ʈø', 'to'), ('solving', '$øȴƔƗƕ¶', '$olvƗn¶'),
- ('intricate', 'ƗƕƮŖƗ¢@ƮƩ', 'intri¢aƮe'), ('puzzles,', 'Ƥû§§ȴƩ$,', 'pu§§le$,'), ('', '', '',),
- ('requiring', 'ŖƩǭûƗŖƗƕ¶', 'ŖeqûƗŖing'), ('a', '@', 'a'), ('sharp', '$ɧ@ŖƤ', 'sharp'),
- ('analytical', '@ƕ@ȴ¥ƮƗ¢@ȴ', '@nal¥Ʈical'), ('mind', 'µƗƕƊ', 'mind'), ('to', 'Ʈø', 'tø'),
- ('piece', 'ƤƗƩ¢Ʃ', 'piecƩ'), ('together', 'Ʈø¶ƩƮɧƩŖ', 'togetɧeŖ'), ('the', 'ƮɧƩ', 'the'),
- ('correct', '¢øŖŖƩ¢Ʈ', 'correct'), ('code.', '¢øƊƩ.', 'code.'), ('One', 'øƕƩ', 'Oƕe'), ('of', 'øƒ', 'oƒ'),
- ('the', 'ƮɧƩ', 'tɧe'), ('complexities', '¢øµƤȴƩ×ƗƮƗƩ$', 'cøµplexƗƮie$'), ('of', 'øƒ', 'of'),
- ('programming', 'ƤŖø¶Ŗ@µµƗƕ¶', 'ƤrogrammƗng'), ('lies', 'ȴƗƩ$', 'liƩs'), ('in', 'Ɨƕ', 'in'),
- ('managing', 'µ@ƕ@¶Ɨƕ¶', 'µaƕagƗn¶'), ('an', '@ƕ', '@n'), ('ever-growing', 'ƩƔƩŖ-¶ŖøƜƗƕ¶', 'eƔƩr-¶røƜing'),
- ('body', 'ßøƊ¥', 'body'), ('of', 'øƒ', 'oƒ'), ('knowledge', 'ƙƕøƜȴƩƊ¶Ʃ', 'kƕoƜledge'), ('as', '@$', 'as'),
- ('new', 'ƕƩƜ', 'nƩw'), ('languages', 'ȴ@ƕ¶û@¶Ʃ$', 'laƕgû@ges'), ('and', '@ƕƊ', '@nd'),
- ('technologies', 'ƮƩ¢ɧƕøȴø¶ƗƩ$', 'technoløgies'), ('emerge.', 'ƩµƩŖ¶Ʃ.', 'emergƩ.'), ('', '', '',),
- ('Debugging', 'ƊƩßû¶¶Ɨƕ¶', 'Ɗeßûg¶ing'), ('code', '¢øƊƩ', 'cøde'), ('can', '¢@ƕ', 'can'),
- ('be', 'ßƩ', 'be'), ('like', 'ȴƗƙƩ', 'ȴikƩ'), ('searching', '$Ʃ@Ŗ¢ɧƗƕ¶', 'se@rcɧƗn¶'), ('for', 'ƒøŖ', 'for'),
- ('a', '@', 'a'), ('needle', 'ƕƩƩƊȴƩ', 'ƕeƩdle'), ('in', 'Ɨƕ', 'Ɨn'), ('a', '@', 'a'),
- ('haystack,', 'ɧ@¥$Ʈ@¢ƙ,', 'haystacƙ,'), ('as', '@$', '@s'), ('a', '@', 'a'), ('single', '$Ɨƕ¶ȴƩ', 'siƕgle'),
- ('character', '¢ɧ@Ŗ@¢ƮƩŖ', 'cɧaŖ@cteŖ'), ('error', 'ƩŖŖøŖ', 'errør'), ('can', '¢@ƕ', 'caƕ'),
- ('lead', 'ȴƩ@Ɗ', 'lƩ@Ɗ'), ('to', 'Ʈø', 'tø'), ('hours', 'ɧøûŖ$', 'hoûŖ$'), ('of', 'øƒ', 'oƒ'),
- ('troubleshooting.', 'ƮŖøûßȴƩ$ɧøøƮƗƕ¶.', 'trøußlesɧooƮin¶.'), ('The', 'ƮɧƩ', 'Ʈhe'), ('', '', '',), ('', '', '',),
- ('meticulous', 'µƩƮƗ¢ûȴøû$', 'metƗ¢uȴous'), ('attention', '@ƮƮƩƕƮƗøƕ', 'aƮtention'), ('to', 'Ʈø', 'to'),
- ('detail', 'ƊƩƮ@Ɨȴ', 'detail'), ('needed', 'ƕƩƩƊƩƊ', 'nƩedƩd'), ('in', 'Ɨƕ', 'in'), ('', '', '',),
- ('programming', 'ƤŖø¶Ŗ@µµƗƕ¶', 'Ƥro¶rammƗng'), ('can', '¢@ƕ', '¢an'), ('be', 'ßƩ', 'be'), ('', '', '',),
- ('mentally', 'µƩƕƮ@ȴȴ¥', 'mƩnƮ@ȴȴy'), ('taxing,', 'Ʈ@×Ɨƕ¶,', 'Ʈ@xƗng,'), ('leading', 'ȴƩ@ƊƗƕ¶', 'ȴe@dƗng'),
- ('to', 'Ʈø', 'to'), ('fatigue', 'ƒ@ƮƗ¶ûƩ', 'fatiguƩ'), ('and', '@ƕƊ', 'aƕd'), ('burnout.', 'ßûŖƕøûƮ.', 'ßuŖnoût.'),
- ('Staying', '$Ʈ@¥Ɨƕ¶', '$taying'), ('updated', 'ûƤƊ@ƮƩƊ', 'upd@teƊ'), ('in', 'Ɨƕ', 'iƕ'), ('the', 'ƮɧƩ', 'tɧe'),
- ('fast-paced', 'ƒ@$Ʈ-Ƥ@¢ƩƊ', 'fa$t-ƤacƩƊ'), ('tech', 'ƮƩ¢ɧ', 'tech'), ('world', 'ƜøŖȴƊ', 'wørȴƊ'), ('is', 'Ɨ$', 'is'),
- ('a', '@', 'a'), ('constant', '¢øƕ$Ʈ@ƕƮ', 'con$Ʈaƕt'), ('challenge,', '¢ɧ@ȴȴƩƕ¶Ʃ,', 'ch@lleƕge,'), ('', '', '',),
- ('with', 'ƜƗƮɧ', 'ƜiƮh'), ('new', 'ƕƩƜ', 'new'), ('frameworks', 'ƒŖ@µƩƜøŖƙ$', 'ƒŖ@meƜoŖks'), ('and', '@ƕƊ', '@nd'),
- ('libraries', 'ȴƗßŖ@ŖƗƩ$', 'ȴƗbŖ@rƗes'), ('being', 'ßƩƗƕ¶', 'bƩƗƕ¶'), ('released', 'ŖƩȴƩ@$ƩƊ', 'rƩle@sƩƊ'),
- ('regularly.', 'ŖƩ¶ûȴ@Ŗȴ¥.', 'ŖƩguȴarly.'), ('The', 'ƮɧƩ', 'ƮhƩ'), ('precise', 'ƤŖƩ¢Ɨ$Ʃ', 'precise'),
- ('syntax', '$¥ƕƮ@×', 's¥nƮax'), ('and', '@ƕƊ', 'anƊ'), ('semantics', '$Ʃµ@ƕƮƗ¢$', 'seµaƕƮƗc$'), ('of', 'øƒ', 'of'),
- ('each', 'Ʃ@¢ɧ', 'e@cɧ'), ('programming', 'ƤŖø¶Ŗ@µµƗƕ¶', 'pŖogŖamµing'), ('language', 'ȴ@ƕ¶û@¶Ʃ', 'ȴ@ngua¶e'),
- ('add', '@ƊƊ', '@dd'), ('layers', 'ȴ@¥ƩŖ$', 'layƩr$'), ('of', 'øƒ', 'of'), ('difficulty,', 'ƊƗƒƒƗ¢ûȴƮ¥,', 'diƒfƗcûlty,'),
- ('as', '@$', 'as'), ('small', '$µ@ȴȴ', 'smaȴȴ'), ('mistakes', 'µƗ$Ʈ@ƙƩ$', 'mƗstaƙe$'), ('can', '¢@ƕ', 'can'),
- ('cause', '¢@û$Ʃ', 'caûsƩ'), ('major', 'µ@ǰøŖ', 'µ@ǰøŖ'), ('issues.', 'Ɨ$$ûƩ$.', 'Ɨ$sûes.'), ('', '', '',)]
- return [random.choice(word_list)[random.randint(0, 2)] for _ in range(length)]
- # Start of testing
- @test.describe("Example Tests")
- def test_group():
@test.it("test case")- @test.it("Testing...")
- def test_case():
test.assert_equals(1 + 1, 2)- test.assert_equals(longest_words(["Hello", "world", "Coding", "is", "fun!"], 1), ['Coding'])
- test.assert_equals(longest_words(["Python", "Java", "C++", "JavaScript"], 4), ['JavaScript', 'Python', 'Java', 'C'])
- test.assert_equals(longest_words(["Hello", "world", "Coding", "is", "fun!"], 6), 'Invalid Parameters')
- @test.describe("Edge Cases")
- def test_group2():
- @test.it("Testing...")
- def test_edges():
- test.assert_equals(longest_words(["H3ll0", "w0rld", "C0d1ng", "1s", "fun!"], 4), ['wrld', 'Cdng', 'Hll', 'fun'])
- test.assert_equals(longest_words(["HELLO", '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], 1), ['HELLO'])
- test.assert_equals(longest_words(["HELLO", 'B123I123G123W123O123R123D', '1', '2', '3', '4', '5', '6', '7', '8', '9'], 2), ['BIGWORD', 'HELLO'])
- test.assert_equals(longest_words(["HELLO", '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], 2), 'Invalid Parameters')
- test.assert_equals(longest_words(['k', 'j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'], 5), ['k', 'j', 'i', 'h', 'g'])
- @test.describe('Random Tests')
- def test_random():
- @test.it('Small Tests')
- def small_rand():
- for _ in range(10):
- for i in range(5, 10):
- rand_words = gen_random(i)
- rand_num = random.randint(0, i + 1)
- test.assert_equals(longest_words(rand_words[:], rand_num), _solve(rand_words[:], rand_num))
- @test.it('Medium Tests')
- def med_rand():
- for _ in range(10):
- for i in range(15, 20):
- rand_words = gen_random(i)
- rand_num = random.randint(0, i + 1)
- test.assert_equals(longest_words(rand_words[:], rand_num), _solve(rand_words[:], rand_num))
- @test.it('Large Tests')
- def med_rand():
- for i in range(25, 125):
- rand_words = gen_random(i)
- rand_num = random.randint(0, i + 1)
- test.assert_equals(longest_words(rand_words[:], rand_num), _solve(rand_words[:], rand_num))
Goal
Code a function, ceasar
that takes two arguments: string and position.
Your task is to shift all letters by pos. pos will always be an integer such that:
-25 >= pos <= 25
Examples
def ceasar('Az 2', 1): will output -> 'Ba 2'
def ceasar('Az 2', -1): will output -> 'Zy 2'
As shown above, if a character is not a letter, you should keep it as it is.
Fork 1
I improved your initial solution by using indexing instead of unicode math. You did make me think that there would be an interesting application to make a ceaser cypher that shifts characters by their unicode representation and not just their order in the alphabet.
I also added random testing that ended up being way overkill. In case you're curious how it works, I had ChatGPT write me 5 different sentences about programming, and then took each sentence.split() and created 3 lists. list one is the regular word with no substitutions, list two is the word with all substitutions, and list 3 is the word with some, but not all substitutions. The final list is just those three lists zipped together.
def ceasar(string, pos): bet = 'abcdefghijklmnopqrstuvwxyz' new = bet[pos:] + bet[:pos] word = '' for char in string: if char.lower() in bet: word += new[bet.index(char.lower())].upper() if char.isupper() else new[bet.index(char)] else: word += char return word
def ceasar(string,pos):ans = ""if pos<0:pos=26+pos%26for ch in string:if ch.isupper():ans += chr((ord(ch) + pos-65) % 26 + 65)elif ch.islower():ans += chr((ord(ch) + pos-97) % 26 + 97)else: ans+=chreturn ans- def ceasar(string, pos):
- bet = 'abcdefghijklmnopqrstuvwxyz'
- new = bet[pos:] + bet[:pos]
- word = ''
- for char in string:
- if char.lower() in bet: word += new[bet.index(char.lower())].upper() if char.isupper() else new[bet.index(char)]
- else: word += char
- return word
import codewars_test as test from solution import ceasar import random def solve_ceasar(string, pos): bet = 'abcdefghijklmnopqrstuvwxyz' new = bet[pos:] + bet[:pos] word = '' for char in string: if char.lower() in bet: word += new[bet.index(char.lower())].upper() if char.isupper() else new[bet.index(char)] else: word += char return word word_list = [ ('Programming', 'ƤŖø¶Ŗ@µµƗƕ¶', 'Prø¶r@mming'), ('is', 'Ɨ$', 'is'), ('often', 'øƒƮƩƕ', 'often'), ('compared', '¢øµƤ@ŖƩƊ', 'comƤ@Ŗed'), ('to', 'Ʈø', 'to'), ('solving', '$øȴƔƗƕ¶', '$olvƗn¶'), ('intricate', 'ƗƕƮŖƗ¢@ƮƩ', 'intri¢aƮe'), ('puzzles,', 'Ƥû§§ȴƩ$,', 'pu§§le$,'), ('requiring', 'ŖƩǭûƗŖƗƕ¶', 'ŖeqûƗŖing'), ('a', '@', 'a'), ('sharp', '$ɧ@ŖƤ', 'sharp'), ('analytical', '@ƕ@ȴ¥ƮƗ¢@ȴ', '@nal¥Ʈical'), ('mind', 'µƗƕƊ', 'mind'), ('to', 'Ʈø', 'tø'), ('piece', 'ƤƗƩ¢Ʃ', 'piecƩ'), ('together', 'Ʈø¶ƩƮɧƩŖ', 'togetɧeŖ'), ('the', 'ƮɧƩ', 'the'), ('correct', '¢øŖŖƩ¢Ʈ', 'correct'), ('code.', '¢øƊƩ.', 'code.'), ('One', 'øƕƩ', 'Oƕe'), ('of', 'øƒ', 'oƒ'), ('the', 'ƮɧƩ', 'tɧe'), ('complexities', '¢øµƤȴƩ×ƗƮƗƩ$', 'cøµplexƗƮie$'), ('of', 'øƒ', 'of'), ('programming', 'ƤŖø¶Ŗ@µµƗƕ¶', 'ƤrogrammƗng'), ('lies', 'ȴƗƩ$', 'liƩs'), ('in', 'Ɨƕ', 'in'), ('managing', 'µ@ƕ@¶Ɨƕ¶', 'µaƕagƗn¶'), ('an', '@ƕ', '@n'), ('ever-growing', 'ƩƔƩŖ-¶ŖøƜƗƕ¶', 'eƔƩr-¶røƜing'), ('body', 'ßøƊ¥', 'body'), ('of', 'øƒ', 'oƒ'), ('knowledge', 'ƙƕøƜȴƩƊ¶Ʃ', 'kƕoƜledge'), ('as', '@$', 'as'), ('new', 'ƕƩƜ', 'nƩw'), ('languages', 'ȴ@ƕ¶û@¶Ʃ$', 'laƕgû@ges'), ('and', '@ƕƊ', '@nd'), ('technologies', 'ƮƩ¢ɧƕøȴø¶ƗƩ$', 'technoløgies'), ('emerge.', 'ƩµƩŖ¶Ʃ.', 'emergƩ.'), ('Debugging', 'ƊƩßû¶¶Ɨƕ¶', 'Ɗeßûg¶ing'), ('code', '¢øƊƩ', 'cøde'), ('can', '¢@ƕ', 'can'), ('be', 'ßƩ', 'be'), ('like', 'ȴƗƙƩ', 'ȴikƩ'), ('searching', '$Ʃ@Ŗ¢ɧƗƕ¶', 'se@rcɧƗn¶'), ('for', 'ƒøŖ', 'for'), ('a', '@', 'a'), ('needle', 'ƕƩƩƊȴƩ', 'ƕeƩdle'), ('in', 'Ɨƕ', 'Ɨn'), ('a', '@', 'a'), ('haystack,', 'ɧ@¥$Ʈ@¢ƙ,', 'haystacƙ,'), ('as', '@$', '@s'), ('a', '@', 'a'), ('single', '$Ɨƕ¶ȴƩ', 'siƕgle'), ('character', '¢ɧ@Ŗ@¢ƮƩŖ', 'cɧaŖ@cteŖ'), ('error', 'ƩŖŖøŖ', 'errør'), ('can', '¢@ƕ', 'caƕ'), ('lead', 'ȴƩ@Ɗ', 'lƩ@Ɗ'), ('to', 'Ʈø', 'tø'), ('hours', 'ɧøûŖ$', 'hoûŖ$'), ('of', 'øƒ', 'oƒ'), ('troubleshooting.', 'ƮŖøûßȴƩ$ɧøøƮƗƕ¶.', 'trøußlesɧooƮin¶.'), ('The', 'ƮɧƩ', 'Ʈhe'), ('meticulous', 'µƩƮƗ¢ûȴøû$', 'metƗ¢uȴous'), ('attention', '@ƮƮƩƕƮƗøƕ', 'aƮtention'), ('to', 'Ʈø', 'to'), ('detail', 'ƊƩƮ@Ɨȴ', 'detail'), ('needed', 'ƕƩƩƊƩƊ', 'nƩedƩd'), ('in', 'Ɨƕ', 'in'), ('programming', 'ƤŖø¶Ŗ@µµƗƕ¶', 'Ƥro¶rammƗng'), ('can', '¢@ƕ', '¢an'), ('be', 'ßƩ', 'be'), ('mentally', 'µƩƕƮ@ȴȴ¥', 'mƩnƮ@ȴȴy'), ('taxing,', 'Ʈ@×Ɨƕ¶,', 'Ʈ@xƗng,'), ('leading', 'ȴƩ@ƊƗƕ¶', 'ȴe@dƗng'), ('to', 'Ʈø', 'to'), ('fatigue', 'ƒ@ƮƗ¶ûƩ', 'fatiguƩ'), ('and', '@ƕƊ', 'aƕd'), ('burnout.', 'ßûŖƕøûƮ.', 'ßuŖnoût.'), ('Staying', '$Ʈ@¥Ɨƕ¶', '$taying'), ('updated', 'ûƤƊ@ƮƩƊ', 'upd@teƊ'), ('in', 'Ɨƕ', 'iƕ'), ('the', 'ƮɧƩ', 'tɧe'), ('fast-paced', 'ƒ@$Ʈ-Ƥ@¢ƩƊ', 'fa$t-ƤacƩƊ'), ('tech', 'ƮƩ¢ɧ', 'tech'), ('world', 'ƜøŖȴƊ', 'wørȴƊ'), ('is', 'Ɨ$', 'is'), ('a', '@', 'a'), ('constant', '¢øƕ$Ʈ@ƕƮ', 'con$Ʈaƕt'), ('challenge,', '¢ɧ@ȴȴƩƕ¶Ʃ,', 'ch@lleƕge,'), ('with', 'ƜƗƮɧ', 'ƜiƮh'), ('new', 'ƕƩƜ', 'new'), ('frameworks', 'ƒŖ@µƩƜøŖƙ$', 'ƒŖ@meƜoŖks'), ('and', '@ƕƊ', '@nd'), ('libraries', 'ȴƗßŖ@ŖƗƩ$', 'ȴƗbŖ@rƗes'), ('being', 'ßƩƗƕ¶', 'bƩƗƕ¶'), ('released', 'ŖƩȴƩ@$ƩƊ', 'rƩle@sƩƊ'), ('regularly.', 'ŖƩ¶ûȴ@Ŗȴ¥.', 'ŖƩguȴarly.'), ('The', 'ƮɧƩ', 'ƮhƩ'), ('precise', 'ƤŖƩ¢Ɨ$Ʃ', 'precise'), ('syntax', '$¥ƕƮ@×', 's¥nƮax'), ('and', '@ƕƊ', 'anƊ'), ('semantics', '$Ʃµ@ƕƮƗ¢$', 'seµaƕƮƗc$'), ('of', 'øƒ', 'of'), ('each', 'Ʃ@¢ɧ', 'e@cɧ'), ('programming', 'ƤŖø¶Ŗ@µµƗƕ¶', 'pŖogŖamµing'), ('language', 'ȴ@ƕ¶û@¶Ʃ', 'ȴ@ngua¶e'), ('add', '@ƊƊ', '@dd'), ('layers', 'ȴ@¥ƩŖ$', 'layƩr$'), ('of', 'øƒ', 'of'), ('difficulty,', 'ƊƗƒƒƗ¢ûȴƮ¥,', 'diƒfƗcûlty,'), ('as', '@$', 'as'), ('small', '$µ@ȴȴ', 'smaȴȴ'), ('mistakes', 'µƗ$Ʈ@ƙƩ$', 'mƗstaƙe$'), ('can', '¢@ƕ', 'can'), ('cause', '¢@û$Ʃ', 'caûsƩ'), ('major', 'µ@ǰøŖ', 'µ@ǰøŖ'), ('issues.', 'Ɨ$$ûƩ$.', 'Ɨ$sûes.'), ('Complex', '¢øµƤȴƩ×', 'CømƤȴex'), ('algorithms', '@ȴ¶øŖƗƮɧµ$', '@ȴgøŖiƮhms'), ('and', '@ƕƊ', '@ƕd'), ('data', 'Ɗ@Ʈ@', 'dat@'), ('structures', '$ƮŖû¢ƮûŖƩ$', '$trûcturƩs'), ('are', '@ŖƩ', 'are'), ('essential', 'Ʃ$$ƩƕƮƗ@ȴ', 'Ʃs$Ʃƕtiaȴ'), ('in', 'Ɨƕ', 'in'), ('many', 'µ@ƕ¥', 'm@n¥'), ('programs,', 'ƤŖø¶Ŗ@µ$,', 'progŖam$,'), ('but', 'ßûƮ', 'ßût'), ('mastering', 'µ@$ƮƩŖƗƕ¶', 'm@sterƗng'), ('them', 'ƮɧƩµ', 'ƮɧƩm'), ('can', '¢@ƕ', 'caƕ'), ('be', 'ßƩ', 'ßƩ'), ('a', '@', 'a'), ('formidable', 'ƒøŖµƗƊ@ßȴƩ', 'foŖmidabȴe'), ('task.', 'Ʈ@$ƙ.', 't@$ƙ.'), ('Working', 'ƜøŖƙƗƕ¶', 'WøŖkƗƕ¶'), ('with', 'ƜƗƮɧ', 'wƗƮɧ'), ('multiple', 'µûȴƮƗƤȴƩ', 'µulƮƗple'), ('team', 'ƮƩ@µ', 'te@m'), ('members', 'µƩµßƩŖ$', 'membeŖs'), ('on', 'øƕ', 'on'), ('a', '@', 'a'), ('project', 'ƤŖøǰƩ¢Ʈ', 'pŖojecƮ'), ('can', '¢@ƕ', 'can'), ('lead', 'ȴƩ@Ɗ', 'lead'), ('to', 'Ʈø', 'tø'), ('version', 'ƔƩŖ$Ɨøƕ', 'vƩrsiøƕ'), ('conflicts', '¢øƕƒȴƗ¢Ʈ$', '¢onƒlicƮ$'), ('and', '@ƕƊ', '@nd'), ('integration', 'ƗƕƮƩ¶Ŗ@ƮƗøƕ', 'ƗntƩ¶r@tƗon'), ('challenges,', '¢ɧ@ȴȴƩƕ¶Ʃ$,', 'chaȴlenges,'), ('making', 'µ@ƙƗƕ¶', 'm@ƙing'), ('collaboration', '¢øȴȴ@ßøŖ@ƮƗøƕ', 'colȴabor@Ʈiøƕ'), ('challenging.', '¢ɧ@ȴȴƩƕ¶Ɨƕ¶.', '¢haȴleƕging.'), ('Programming', 'ƤŖø¶Ŗ@µµƗƕ¶', 'Ƥrø¶ŖammƗƕg'), ('often', 'øƒƮƩƕ', 'øƒten'), ('involves', 'ƗƕƔøȴƔƩ$', 'ƗƕƔølƔe$'), ('dealing', 'ƊƩ@ȴƗƕ¶', 'de@ȴƗng'), ('with', 'ƜƗƮɧ', 'wiƮh'), ('ambiguous', '@µßƗ¶ûøû$', '@µßi¶ûoûs'), ('problem', 'ƤŖøßȴƩµ', 'pŖobȴem'), ('statements,', '$Ʈ@ƮƩµƩƕƮ$,', 'sƮaƮƩmeƕƮs,'), ('requiring', 'ŖƩǭûƗŖƗƕ¶', 'requirin¶'), ('developers', 'ƊƩƔƩȴøƤƩŖ$', 'developers'), ('to', 'Ʈø', 'to'), ('clarify', '¢ȴ@ŖƗƒ¥', 'claŖƗƒy'), ('requirements', 'ŖƩǭûƗŖƩµƩƕƮ$', 'reǭuƗŖeµƩnts'), ('and', '@ƕƊ', 'and'), ('make', 'µ@ƙƩ', 'make'), ('decisions.', 'ƊƩ¢Ɨ$Ɨøƕ$.', 'ƊecƗsƗon$.'), ('Keeping', 'ƙƩƩƤƗƕ¶', 'ƙeepiƕg'), ('software', '$øƒƮƜ@ŖƩ', '$oftƜare'), ('secure', '$Ʃ¢ûŖƩ', 'sƩcuŖe'), ('is', 'Ɨ$', 'i$'), ('an', '@ƕ', 'an'), ('ongoing', 'øƕ¶øƗƕ¶', 'øƕgoiƕg'), ('battle,', 'ß@ƮƮȴƩ,', 'b@ƮƮle,'), ('with', 'ƜƗƮɧ', 'with'), ('vulnerabilities', 'ƔûȴƕƩŖ@ßƗȴƗƮƗƩ$', 'vulneŖ@biȴƗties'), ('and', '@ƕƊ', 'aƕd'), ('threats', 'ƮɧŖƩ@Ʈ$', 'tɧŖeat$'), ('evolving', 'ƩƔøȴƔƗƕ¶', 'evoȴƔin¶'), ('over', 'øƔƩŖ', 'øvƩŖ'), ('time,', 'ƮƗµƩ,', 'Ʈiµe,'), ('making', 'µ@ƙƗƕ¶', 'm@ƙiƕg'), ('cybersecurity', '¢¥ßƩŖ$Ʃ¢ûŖƗƮ¥', 'c¥bƩrsecurit¥'), ('a', '@', 'a'), ('significant', '$Ɨ¶ƕƗƒƗ¢@ƕƮ', '$ƗgƕƗƒic@nt'), ('challenge.', '¢ɧ@ȴȴƩƕ¶Ʃ.', '¢ɧalleƕ¶e.') ] @test.describe("Example") def test_group(): @test.it("Example Tests") def test_case(): test.assert_equals(ceasar("Az 2", 1),"Ba 2") test.assert_equals(ceasar("Az 2", -1), 'Zy 2') @test.it("Positive pos") def test_case(): test.assert_equals(ceasar("Something",1),"Tpnfuijoh") test.assert_equals(ceasar("iTs G0nn4 b3 l1ke th4t huh?",4),"mXw K0rr4 f3 p1oi xl4x lyl?") @test.it("Negative pos") def test_case(): test.assert_equals(ceasar("Batteries?",-2), "Zyrrcpgcq?") @test.describe("Overkill Random Tests") def pos_shift(): for _ in range(5): shift = random.randint(0, 25) @test.it(f"Testing with shift {shift}") def test_random_pos(): for word in word_list: w = word[random.randint(0, 2)] solved = solve_ceasar(w, shift) test.assert_equals(ceasar(w, shift), solved) for _ in range(5): shift = random.randint(-25, -1) @test.it(f"Testing with shift {shift}") def test_random_neg(): for word in word_list: w = word[random.randint(0, 2)] solved = solve_ceasar(w, shift) test.assert_equals(ceasar(w, shift), solved)
- import codewars_test as test
# TODO Write testsimport solution # or from solution import example- from solution import ceasar
- import random
- def solve_ceasar(string, pos):
- bet = 'abcdefghijklmnopqrstuvwxyz'
- new = bet[pos:] + bet[:pos]
- word = ''
- for char in string:
- if char.lower() in bet: word += new[bet.index(char.lower())].upper() if char.isupper() else new[bet.index(char)]
- else: word += char
- return word
- word_list = [
- ('Programming', 'ƤŖø¶Ŗ@µµƗƕ¶', 'Prø¶r@mming'), ('is', 'Ɨ$', 'is'), ('often', 'øƒƮƩƕ', 'often'),
- ('compared', '¢øµƤ@ŖƩƊ', 'comƤ@Ŗed'), ('to', 'Ʈø', 'to'), ('solving', '$øȴƔƗƕ¶', '$olvƗn¶'),
- ('intricate', 'ƗƕƮŖƗ¢@ƮƩ', 'intri¢aƮe'), ('puzzles,', 'Ƥû§§ȴƩ$,', 'pu§§le$,'),
- ('requiring', 'ŖƩǭûƗŖƗƕ¶', 'ŖeqûƗŖing'), ('a', '@', 'a'), ('sharp', '$ɧ@ŖƤ', 'sharp'),
- ('analytical', '@ƕ@ȴ¥ƮƗ¢@ȴ', '@nal¥Ʈical'), ('mind', 'µƗƕƊ', 'mind'), ('to', 'Ʈø', 'tø'),
- ('piece', 'ƤƗƩ¢Ʃ', 'piecƩ'), ('together', 'Ʈø¶ƩƮɧƩŖ', 'togetɧeŖ'), ('the', 'ƮɧƩ', 'the'),
- ('correct', '¢øŖŖƩ¢Ʈ', 'correct'), ('code.', '¢øƊƩ.', 'code.'), ('One', 'øƕƩ', 'Oƕe'), ('of', 'øƒ', 'oƒ'),
- ('the', 'ƮɧƩ', 'tɧe'), ('complexities', '¢øµƤȴƩ×ƗƮƗƩ$', 'cøµplexƗƮie$'), ('of', 'øƒ', 'of'),
- ('programming', 'ƤŖø¶Ŗ@µµƗƕ¶', 'ƤrogrammƗng'), ('lies', 'ȴƗƩ$', 'liƩs'), ('in', 'Ɨƕ', 'in'),
- ('managing', 'µ@ƕ@¶Ɨƕ¶', 'µaƕagƗn¶'), ('an', '@ƕ', '@n'), ('ever-growing', 'ƩƔƩŖ-¶ŖøƜƗƕ¶', 'eƔƩr-¶røƜing'),
- ('body', 'ßøƊ¥', 'body'), ('of', 'øƒ', 'oƒ'), ('knowledge', 'ƙƕøƜȴƩƊ¶Ʃ', 'kƕoƜledge'), ('as', '@$', 'as'),
- ('new', 'ƕƩƜ', 'nƩw'), ('languages', 'ȴ@ƕ¶û@¶Ʃ$', 'laƕgû@ges'), ('and', '@ƕƊ', '@nd'),
- ('technologies', 'ƮƩ¢ɧƕøȴø¶ƗƩ$', 'technoløgies'), ('emerge.', 'ƩµƩŖ¶Ʃ.', 'emergƩ.'),
- ('Debugging', 'ƊƩßû¶¶Ɨƕ¶', 'Ɗeßûg¶ing'), ('code', '¢øƊƩ', 'cøde'), ('can', '¢@ƕ', 'can'),
- ('be', 'ßƩ', 'be'), ('like', 'ȴƗƙƩ', 'ȴikƩ'), ('searching', '$Ʃ@Ŗ¢ɧƗƕ¶', 'se@rcɧƗn¶'), ('for', 'ƒøŖ', 'for'),
- ('a', '@', 'a'), ('needle', 'ƕƩƩƊȴƩ', 'ƕeƩdle'), ('in', 'Ɨƕ', 'Ɨn'), ('a', '@', 'a'),
- ('haystack,', 'ɧ@¥$Ʈ@¢ƙ,', 'haystacƙ,'), ('as', '@$', '@s'), ('a', '@', 'a'), ('single', '$Ɨƕ¶ȴƩ', 'siƕgle'),
- ('character', '¢ɧ@Ŗ@¢ƮƩŖ', 'cɧaŖ@cteŖ'), ('error', 'ƩŖŖøŖ', 'errør'), ('can', '¢@ƕ', 'caƕ'),
- ('lead', 'ȴƩ@Ɗ', 'lƩ@Ɗ'), ('to', 'Ʈø', 'tø'), ('hours', 'ɧøûŖ$', 'hoûŖ$'), ('of', 'øƒ', 'oƒ'),
- ('troubleshooting.', 'ƮŖøûßȴƩ$ɧøøƮƗƕ¶.', 'trøußlesɧooƮin¶.'), ('The', 'ƮɧƩ', 'Ʈhe'),
- ('meticulous', 'µƩƮƗ¢ûȴøû$', 'metƗ¢uȴous'), ('attention', '@ƮƮƩƕƮƗøƕ', 'aƮtention'), ('to', 'Ʈø', 'to'),
- ('detail', 'ƊƩƮ@Ɨȴ', 'detail'), ('needed', 'ƕƩƩƊƩƊ', 'nƩedƩd'), ('in', 'Ɨƕ', 'in'),
- ('programming', 'ƤŖø¶Ŗ@µµƗƕ¶', 'Ƥro¶rammƗng'), ('can', '¢@ƕ', '¢an'), ('be', 'ßƩ', 'be'),
- ('mentally', 'µƩƕƮ@ȴȴ¥', 'mƩnƮ@ȴȴy'), ('taxing,', 'Ʈ@×Ɨƕ¶,', 'Ʈ@xƗng,'), ('leading', 'ȴƩ@ƊƗƕ¶', 'ȴe@dƗng'),
- ('to', 'Ʈø', 'to'), ('fatigue', 'ƒ@ƮƗ¶ûƩ', 'fatiguƩ'), ('and', '@ƕƊ', 'aƕd'), ('burnout.', 'ßûŖƕøûƮ.', 'ßuŖnoût.'),
- ('Staying', '$Ʈ@¥Ɨƕ¶', '$taying'), ('updated', 'ûƤƊ@ƮƩƊ', 'upd@teƊ'), ('in', 'Ɨƕ', 'iƕ'), ('the', 'ƮɧƩ', 'tɧe'),
- ('fast-paced', 'ƒ@$Ʈ-Ƥ@¢ƩƊ', 'fa$t-ƤacƩƊ'), ('tech', 'ƮƩ¢ɧ', 'tech'), ('world', 'ƜøŖȴƊ', 'wørȴƊ'), ('is', 'Ɨ$', 'is'),
- ('a', '@', 'a'), ('constant', '¢øƕ$Ʈ@ƕƮ', 'con$Ʈaƕt'), ('challenge,', '¢ɧ@ȴȴƩƕ¶Ʃ,', 'ch@lleƕge,'),
- ('with', 'ƜƗƮɧ', 'ƜiƮh'), ('new', 'ƕƩƜ', 'new'), ('frameworks', 'ƒŖ@µƩƜøŖƙ$', 'ƒŖ@meƜoŖks'), ('and', '@ƕƊ', '@nd'),
- ('libraries', 'ȴƗßŖ@ŖƗƩ$', 'ȴƗbŖ@rƗes'), ('being', 'ßƩƗƕ¶', 'bƩƗƕ¶'), ('released', 'ŖƩȴƩ@$ƩƊ', 'rƩle@sƩƊ'),
- ('regularly.', 'ŖƩ¶ûȴ@Ŗȴ¥.', 'ŖƩguȴarly.'), ('The', 'ƮɧƩ', 'ƮhƩ'), ('precise', 'ƤŖƩ¢Ɨ$Ʃ', 'precise'),
- ('syntax', '$¥ƕƮ@×', 's¥nƮax'), ('and', '@ƕƊ', 'anƊ'), ('semantics', '$Ʃµ@ƕƮƗ¢$', 'seµaƕƮƗc$'), ('of', 'øƒ', 'of'),
- ('each', 'Ʃ@¢ɧ', 'e@cɧ'), ('programming', 'ƤŖø¶Ŗ@µµƗƕ¶', 'pŖogŖamµing'), ('language', 'ȴ@ƕ¶û@¶Ʃ', 'ȴ@ngua¶e'),
- ('add', '@ƊƊ', '@dd'), ('layers', 'ȴ@¥ƩŖ$', 'layƩr$'), ('of', 'øƒ', 'of'), ('difficulty,', 'ƊƗƒƒƗ¢ûȴƮ¥,', 'diƒfƗcûlty,'),
- ('as', '@$', 'as'), ('small', '$µ@ȴȴ', 'smaȴȴ'), ('mistakes', 'µƗ$Ʈ@ƙƩ$', 'mƗstaƙe$'), ('can', '¢@ƕ', 'can'),
- ('cause', '¢@û$Ʃ', 'caûsƩ'), ('major', 'µ@ǰøŖ', 'µ@ǰøŖ'), ('issues.', 'Ɨ$$ûƩ$.', 'Ɨ$sûes.'),
- ('Complex', '¢øµƤȴƩ×', 'CømƤȴex'), ('algorithms', '@ȴ¶øŖƗƮɧµ$', '@ȴgøŖiƮhms'), ('and', '@ƕƊ', '@ƕd'),
- ('data', 'Ɗ@Ʈ@', 'dat@'), ('structures', '$ƮŖû¢ƮûŖƩ$', '$trûcturƩs'), ('are', '@ŖƩ', 'are'),
- ('essential', 'Ʃ$$ƩƕƮƗ@ȴ', 'Ʃs$Ʃƕtiaȴ'), ('in', 'Ɨƕ', 'in'), ('many', 'µ@ƕ¥', 'm@n¥'),
- ('programs,', 'ƤŖø¶Ŗ@µ$,', 'progŖam$,'), ('but', 'ßûƮ', 'ßût'), ('mastering', 'µ@$ƮƩŖƗƕ¶', 'm@sterƗng'),
- ('them', 'ƮɧƩµ', 'ƮɧƩm'), ('can', '¢@ƕ', 'caƕ'), ('be', 'ßƩ', 'ßƩ'), ('a', '@', 'a'),
- ('formidable', 'ƒøŖµƗƊ@ßȴƩ', 'foŖmidabȴe'), ('task.', 'Ʈ@$ƙ.', 't@$ƙ.'), ('Working', 'ƜøŖƙƗƕ¶', 'WøŖkƗƕ¶'),
- ('with', 'ƜƗƮɧ', 'wƗƮɧ'), ('multiple', 'µûȴƮƗƤȴƩ', 'µulƮƗple'), ('team', 'ƮƩ@µ', 'te@m'),
- ('members', 'µƩµßƩŖ$', 'membeŖs'), ('on', 'øƕ', 'on'), ('a', '@', 'a'), ('project', 'ƤŖøǰƩ¢Ʈ', 'pŖojecƮ'),
- ('can', '¢@ƕ', 'can'), ('lead', 'ȴƩ@Ɗ', 'lead'), ('to', 'Ʈø', 'tø'), ('version', 'ƔƩŖ$Ɨøƕ', 'vƩrsiøƕ'),
- ('conflicts', '¢øƕƒȴƗ¢Ʈ$', '¢onƒlicƮ$'), ('and', '@ƕƊ', '@nd'), ('integration', 'ƗƕƮƩ¶Ŗ@ƮƗøƕ', 'ƗntƩ¶r@tƗon'),
- ('challenges,', '¢ɧ@ȴȴƩƕ¶Ʃ$,', 'chaȴlenges,'), ('making', 'µ@ƙƗƕ¶', 'm@ƙing'),
- ('collaboration', '¢øȴȴ@ßøŖ@ƮƗøƕ', 'colȴabor@Ʈiøƕ'), ('challenging.', '¢ɧ@ȴȴƩƕ¶Ɨƕ¶.', '¢haȴleƕging.'),
- ('Programming', 'ƤŖø¶Ŗ@µµƗƕ¶', 'Ƥrø¶ŖammƗƕg'), ('often', 'øƒƮƩƕ', 'øƒten'), ('involves', 'ƗƕƔøȴƔƩ$', 'ƗƕƔølƔe$'),
- ('dealing', 'ƊƩ@ȴƗƕ¶', 'de@ȴƗng'), ('with', 'ƜƗƮɧ', 'wiƮh'), ('ambiguous', '@µßƗ¶ûøû$', '@µßi¶ûoûs'),
- ('problem', 'ƤŖøßȴƩµ', 'pŖobȴem'), ('statements,', '$Ʈ@ƮƩµƩƕƮ$,', 'sƮaƮƩmeƕƮs,'), ('requiring', 'ŖƩǭûƗŖƗƕ¶', 'requirin¶'),
- ('developers', 'ƊƩƔƩȴøƤƩŖ$', 'developers'), ('to', 'Ʈø', 'to'), ('clarify', '¢ȴ@ŖƗƒ¥', 'claŖƗƒy'),
- ('requirements', 'ŖƩǭûƗŖƩµƩƕƮ$', 'reǭuƗŖeµƩnts'), ('and', '@ƕƊ', 'and'), ('make', 'µ@ƙƩ', 'make'),
- ('decisions.', 'ƊƩ¢Ɨ$Ɨøƕ$.', 'ƊecƗsƗon$.'), ('Keeping', 'ƙƩƩƤƗƕ¶', 'ƙeepiƕg'), ('software', '$øƒƮƜ@ŖƩ', '$oftƜare'),
- ('secure', '$Ʃ¢ûŖƩ', 'sƩcuŖe'), ('is', 'Ɨ$', 'i$'), ('an', '@ƕ', 'an'), ('ongoing', 'øƕ¶øƗƕ¶', 'øƕgoiƕg'),
- ('battle,', 'ß@ƮƮȴƩ,', 'b@ƮƮle,'), ('with', 'ƜƗƮɧ', 'with'), ('vulnerabilities', 'ƔûȴƕƩŖ@ßƗȴƗƮƗƩ$', 'vulneŖ@biȴƗties'),
- ('and', '@ƕƊ', 'aƕd'), ('threats', 'ƮɧŖƩ@Ʈ$', 'tɧŖeat$'), ('evolving', 'ƩƔøȴƔƗƕ¶', 'evoȴƔin¶'), ('over', 'øƔƩŖ', 'øvƩŖ'),
- ('time,', 'ƮƗµƩ,', 'Ʈiµe,'), ('making', 'µ@ƙƗƕ¶', 'm@ƙiƕg'), ('cybersecurity', '¢¥ßƩŖ$Ʃ¢ûŖƗƮ¥', 'c¥bƩrsecurit¥'), ('a', '@', 'a'),
- ('significant', '$Ɨ¶ƕƗƒƗ¢@ƕƮ', '$ƗgƕƗƒic@nt'), ('challenge.', '¢ɧ@ȴȴƩƕ¶Ʃ.', '¢ɧalleƕ¶e.')
- ]
# test.assert_equals(actual, expected, [optional] message)- @test.describe("Example")
- def test_group():
- @test.it("Example Tests")
- def test_case():
- test.assert_equals(ceasar("Az 2", 1),"Ba 2")
- test.assert_equals(ceasar("Az 2", -1), 'Zy 2')
- @test.it("Positive pos")
- def test_case():
- test.assert_equals(ceasar("Something",1),"Tpnfuijoh")
- test.assert_equals(ceasar("iTs G0nn4 b3 l1ke th4t huh?",4),"mXw K0rr4 f3 p1oi xl4x lyl?")
- @test.it("Negative pos")
- def test_case():
- test.assert_equals(ceasar("Batteries?",-2), "Zyrrcpgcq?")
- @test.describe("Overkill Random Tests")
- def pos_shift():
- for _ in range(5):
- shift = random.randint(0, 25)
- @test.it(f"Testing with shift {shift}")
- def test_random_pos():
- for word in word_list:
- w = word[random.randint(0, 2)]
- solved = solve_ceasar(w, shift)
- test.assert_equals(ceasar(w, shift), solved)
- for _ in range(5):
- shift = random.randint(-25, -1)
- @test.it(f"Testing with shift {shift}")
- def test_random_neg():
- for word in word_list:
- w = word[random.randint(0, 2)]
- solved = solve_ceasar(w, shift)
- test.assert_equals(ceasar(w, shift), solved)
Goal
Get dice roll results from multiple dice of the same type.
Dice notation
Dice are entered as strings such as "2d6" where the first number indicates the quantity of dice thrown and the last number indicates the number of sides on the dice. Assume input is "XdN"
where 1 <= X <= 250
and <= N <= 5000
e.g. "2d6" means 2 dice are thrown. Each dice is a 6 sided dice with values 1-6.
2d6 should have results such as [2,5] or [1,6] or [3,3]
e.g. 3d500 (after setting random.seed(444) should result in [159,148,7]
Fork 1
Solved the problem, and added random testing. Currently the random tests will use any dice noted here and then each multiple of 50 above that.Calculating which number
import random def roll_dice(dice): return [random.randint(1, int(dice[dice.index('d') + 1:])) for _ in range(int(dice[:dice.index('d')]))]
- import random
def roll_dice(dice_text:str):#this returns the correct value for roll_dice("2d1000")return [random.randint(1,1000), random.randint(1,1000)]- def roll_dice(dice):
- return [random.randint(1, int(dice[dice.index('d') + 1:])) for _ in range(int(dice[:dice.index('d')]))]
import codewars_test as test from solution import roll_dice import random def get_dice(dice): return [random.randint(1, int(dice[dice.index('d') + 1:])) for _ in range(int(dice[:dice.index('d')]))] def gen_dice(num1, num2): random.seed() sizes = [1, 2, 3, 4, 5, 6, 7, 12, 14, 16, 18, 20, 24, 30, 34, 48, 50, 60, 100, 120] + [i for i in range(150, 5001, 50)] r_seed = random.randint(0, 1000) return (r_seed, f'{random.randint(num1, num2)}d{random.choice(sizes)}') @test.describe("Example Test Cases") def test_group(): @test.it("Known Seeded Random Values") def test_case(): random.seed(444) test.assert_equals(roll_dice("2d1000"), [317, 295]) random.seed(444) test.assert_equals(roll_dice("3d500"), [159, 148, 7]) @test.describe("Small Random Test Cases") def test_group(): for _ in range(25): dice = gen_dice(1, 10) random.seed(dice[0]) sol = get_dice(dice[1]) @test.it(f"Seed: {dice[0]} Dice: {dice[1]}") def test_case(): random.seed(dice[0]) test.assert_equals(roll_dice(dice[:][1]), sol) @test.describe("Medium Random Test Cases") def test_group(): for _ in range(25): dice = gen_dice(10, 25) random.seed(dice[0]) sol = get_dice(dice[1]) @test.it(f"Seed: {dice[0]} Dice: {dice[1]}") def test_case(): random.seed(dice[0]) test.assert_equals(roll_dice(dice[:][1]), sol) @test.describe("Large Random Test Cases") def test_group(): for _ in range(25): dice = gen_dice(25, 100) random.seed(dice[0]) sol = get_dice(dice[1]) @test.it(f"Seed: {dice[0]} Dice: {dice[1]}") def test_case(): random.seed(dice[0]) test.assert_equals(roll_dice(dice[:][1]), sol) @test.describe("Largest Random Test Cases") def test_group(): for _ in range(25): dice = gen_dice(100, 250) random.seed(dice[0]) sol = get_dice(dice[1]) @test.it(f"Seed: {dice[0]} Dice: {dice[1]}") def test_case(): random.seed(dice[0]) test.assert_equals(roll_dice(dice[:][1]), sol)
- import codewars_test as test
import random- from solution import roll_dice
- import random
- def get_dice(dice):
- return [random.randint(1, int(dice[dice.index('d') + 1:])) for _ in range(int(dice[:dice.index('d')]))]
- def gen_dice(num1, num2):
- random.seed()
- sizes = [1, 2, 3, 4, 5, 6, 7, 12, 14, 16, 18, 20,
- 24, 30, 34, 48, 50, 60, 100, 120] + [i for i in range(150, 5001, 50)]
- r_seed = random.randint(0, 1000)
- return (r_seed, f'{random.randint(num1, num2)}d{random.choice(sizes)}')
# test.assert_equals(actual, expected, [optional] message)- @test.describe("Example Test Cases")
- def test_group():
@test.it("Seeded random values (return correct values for known seeded 'random' results)")- @test.it("Known Seeded Random Values")
- def test_case():
- random.seed(444)
- test.assert_equals(roll_dice("2d1000"), [317, 295])
- random.seed(444)
- test.assert_equals(roll_dice("3d500"), [159, 148, 7])
@test.it("Quantity of dice in list")def test_case():random.seed(444)test.assert_equals(len(roll_dice("2d1000")), 2)random.seed(444)test.assert_equals(len(roll_dice("3d500")), 3)- @test.describe("Small Random Test Cases")
- def test_group():
- for _ in range(25):
- dice = gen_dice(1, 10)
- random.seed(dice[0])
- sol = get_dice(dice[1])
- @test.it(f"Seed: {dice[0]} Dice: {dice[1]}")
- def test_case():
- random.seed(dice[0])
- test.assert_equals(roll_dice(dice[:][1]), sol)
- @test.describe("Medium Random Test Cases")
- def test_group():
- for _ in range(25):
- dice = gen_dice(10, 25)
- random.seed(dice[0])
- sol = get_dice(dice[1])
- @test.it(f"Seed: {dice[0]} Dice: {dice[1]}")
- def test_case():
- random.seed(dice[0])
- test.assert_equals(roll_dice(dice[:][1]), sol)
- @test.describe("Large Random Test Cases")
- def test_group():
- for _ in range(25):
- dice = gen_dice(25, 100)
- random.seed(dice[0])
- sol = get_dice(dice[1])
- @test.it(f"Seed: {dice[0]} Dice: {dice[1]}")
- def test_case():
- random.seed(dice[0])
- test.assert_equals(roll_dice(dice[:][1]), sol)
- @test.describe("Largest Random Test Cases")
- def test_group():
- for _ in range(25):
- dice = gen_dice(100, 250)
- random.seed(dice[0])
- sol = get_dice(dice[1])
- @test.it(f"Seed: {dice[0]} Dice: {dice[1]}")
- def test_case():
- random.seed(dice[0])
- test.assert_equals(roll_dice(dice[:][1]), sol)
Goal
write a function that will return the integer of a string evaluation. Your function should catch any errors related to this process. If it does catch and error, it should return a string: "Invalid Input"
Fork 1
Added testing, and error checking. I think random tests should cover all realistic inputs that don't try to intentionally break the function. For example, KeyError would be pretty easy to create here, but why would you put something as complicated as a dictionary into this function without already knowing the keys?
def calc(string): try: return int(eval(string)) except (NameError, SyntaxError, TypeError, ValueError, ZeroDivisionError) as e: print(e) return 'Invalid Input'
- def calc(string):
return int(eval(string))- try: return int(eval(string))
- except (NameError, SyntaxError, TypeError, ValueError, ZeroDivisionError) as e:
- print(e)
- return 'Invalid Input'
import codewars_test as test from solution import calc import random # Working Solution def calc_expression(string): try: return int(eval(string)) except (NameError, SyntaxError, TypeError, ValueError, ZeroDivisionError) as e: print('Error Recieved: ', type(e), e) return 'Invalid Input' # Random Generator def get_rand_expression(): math_dict = {"a" : "+", "s" : "-", "m" : "*", "d" : "/", "mod" : "%", "p" : "**",} expressions = ["a", "s", "m", "d", "mod", "p", "4 ^ 2", "2 << 3", "8 >> 2", "9 | 5", "7 & 3", "-5", "+5", "1 / 0", "1 / 1", "1 // 0", "1 % 0", "1.5 + 2.5", "3.0 / 1.5", 'one + one', 'variable', 'True', "4.2 * 5.5", "-1.2", "+0.0", "-0.0", "0.1 + 0.2", "1 / 3", "0.1 + 0.1 + 0.1", "0b1101 + 0b1011", "0o755 - 0o644", "0x1A * 0x2F", "0b1010 / 0o12", "0x1A >> 2", "0b101 & 0o74", "-0b1101", 'False', "+0o777", "-0xABC", "1 / '0'", "2 + '2'", "'1' + '2'", "'Hello' * 3", "'Python'[1]", 'None', "'543 + 210'.replace('+', '*')", '3 + 4j', '1 - 2j', 'None', '1.2e10^8', '7 + 3 * 2', f'pow({random.randint(1, 100)}, {random.randint(1, 100)})', 'abs(-7.5)', '7 * (3 + 2)', f'min([i for i in range({random.randint(0, 1000)}, {random.randint(0, 1000)})])', f'round({random.randint(1, 100)} + {random.random()})', f'len([i for i in range({random.randint(0, 1000)})])', f'sum([i for i in range({random.randint(0, 1000)})])', f'sum([i + i // 10 for i in range({random.randint(0, 1000)})])'] rand = random.choice(expressions) if rand in math_dict: if rand != 'p': return f'{random.randint(-10000, 10000)} {math_dict[rand]} {random.randint(-10000, 10000)}' return f'{random.randint(-100, 100)} {math_dict[rand]} {random.randint(-100, 100)}' return rand # Start of Testing @test.describe("Standard Operations") def test_group(): @test.it("Addition") def test_add(): test.assert_equals(calc('1 + 1'), 2) @test.it("Subtraction") def test_sub(): test.assert_equals(calc('1 - 1'), 0) @test.it("Multiplication") def test_mult(): test.assert_equals(calc('2 * 3'), 6) @test.it("Division") def test_div(): test.assert_equals(calc('6 // 2'), 3) @test.it("Modulous") def test_mod(): test.assert_equals(calc('6 % 2'), 0) @test.describe("Edge Case Expressions") def test_edge_group(): @test.it("") def test_edge(): test.assert_equals(calc('7 / 2'), 3) test.assert_equals(calc('7*7+7-7*7/7'), 49) test.assert_equals(calc('5.1234 + 1.1234'), 6) test.assert_equals(calc('one plus one'), 'Invalid Input', 'Your function did not catch the error correctly') test.assert_equals(calc('one + one'), 'Invalid Input', 'Your function did not catch the error correctly') test.assert_equals(calc('5 if 1 == 1 else 0'), 5) test.assert_equals(calc('"Uh-Oh" if True else 0'), 'Invalid Input', 'Your function did not catch the error correctly') test.assert_equals(calc('"Uh-Oh" + 5'), 'Invalid Input', 'Your function did not catch the error correctly') @test.describe("Simple Random Tests") def test_random(): for _ in range(100): random_exp = get_rand_expression() @test.it(f"{random_exp}") def test_random_edition(): test.assert_equals(calc(random_exp), calc_expression(random_exp)) @test.describe("Complex Random Tests") def test_random(): for _ in range(100): rand_exp = get_rand_expression() + random.choice([' + ', ' - ', ' * ', ' / ', ' % ']) + get_rand_expression() @test.it(f"{rand_exp}") def test_random_edition(): test.assert_equals(calc(rand_exp), calc_expression(rand_exp))
- import codewars_test as test
# TODO Write testsimport solution # or from solution import example- from solution import calc
- import random
# test.assert_equals(actual, expected, [optional] message)@test.describe("Easy")- # Working Solution
- def calc_expression(string):
- try: return int(eval(string))
- except (NameError, SyntaxError, TypeError, ValueError, ZeroDivisionError) as e:
- print('Error Recieved: ', type(e), e)
- return 'Invalid Input'
- # Random Generator
- def get_rand_expression():
- math_dict = {"a" : "+", "s" : "-", "m" : "*", "d" : "/", "mod" : "%", "p" : "**",}
- expressions = ["a", "s", "m", "d", "mod", "p", "4 ^ 2", "2 << 3", "8 >> 2", "9 | 5", "7 & 3", "-5", "+5",
- "1 / 0", "1 / 1", "1 // 0", "1 % 0", "1.5 + 2.5", "3.0 / 1.5", 'one + one', 'variable', 'True',
- "4.2 * 5.5", "-1.2", "+0.0", "-0.0", "0.1 + 0.2", "1 / 3", "0.1 + 0.1 + 0.1", "0b1101 + 0b1011",
- "0o755 - 0o644", "0x1A * 0x2F", "0b1010 / 0o12", "0x1A >> 2", "0b101 & 0o74", "-0b1101", 'False',
- "+0o777", "-0xABC", "1 / '0'", "2 + '2'", "'1' + '2'", "'Hello' * 3", "'Python'[1]", 'None',
- "'543 + 210'.replace('+', '*')", '3 + 4j', '1 - 2j', 'None', '1.2e10^8', '7 + 3 * 2',
- f'pow({random.randint(1, 100)}, {random.randint(1, 100)})', 'abs(-7.5)', '7 * (3 + 2)',
- f'min([i for i in range({random.randint(0, 1000)}, {random.randint(0, 1000)})])',
- f'round({random.randint(1, 100)} + {random.random()})',
- f'len([i for i in range({random.randint(0, 1000)})])',
- f'sum([i for i in range({random.randint(0, 1000)})])',
- f'sum([i + i // 10 for i in range({random.randint(0, 1000)})])']
- rand = random.choice(expressions)
- if rand in math_dict:
- if rand != 'p':
- return f'{random.randint(-10000, 10000)} {math_dict[rand]} {random.randint(-10000, 10000)}'
- return f'{random.randint(-100, 100)} {math_dict[rand]} {random.randint(-100, 100)}'
- return rand
- # Start of Testing
- @test.describe("Standard Operations")
- def test_group():
@test.it("test case")def test_case():test.assert_equals(solution.calc('1 + 1'), 2)- @test.it("Addition")
- def test_add():
- test.assert_equals(calc('1 + 1'), 2)
- @test.it("Subtraction")
- def test_sub():
- test.assert_equals(calc('1 - 1'), 0)
- @test.it("Multiplication")
- def test_mult():
- test.assert_equals(calc('2 * 3'), 6)
- @test.it("Division")
- def test_div():
- test.assert_equals(calc('6 // 2'), 3)
- @test.it("Modulous")
- def test_mod():
- test.assert_equals(calc('6 % 2'), 0)
- @test.describe("Edge Case Expressions")
- def test_edge_group():
- @test.it("")
- def test_edge():
- test.assert_equals(calc('7 / 2'), 3)
- test.assert_equals(calc('7*7+7-7*7/7'), 49)
- test.assert_equals(calc('5.1234 + 1.1234'), 6)
- test.assert_equals(calc('one plus one'), 'Invalid Input', 'Your function did not catch the error correctly')
- test.assert_equals(calc('one + one'), 'Invalid Input', 'Your function did not catch the error correctly')
- test.assert_equals(calc('5 if 1 == 1 else 0'), 5)
- test.assert_equals(calc('"Uh-Oh" if True else 0'), 'Invalid Input', 'Your function did not catch the error correctly')
- test.assert_equals(calc('"Uh-Oh" + 5'), 'Invalid Input', 'Your function did not catch the error correctly')
- @test.describe("Simple Random Tests")
- def test_random():
- for _ in range(100):
- random_exp = get_rand_expression()
- @test.it(f"{random_exp}")
- def test_random_edition():
- test.assert_equals(calc(random_exp), calc_expression(random_exp))
- @test.describe("Complex Random Tests")
- def test_random():
- for _ in range(100):
- rand_exp = get_rand_expression() + random.choice([' + ', ' - ', ' * ', ' / ', ' % ']) + get_rand_expression()
- @test.it(f"{rand_exp}")
- def test_random_edition():
- test.assert_equals(calc(rand_exp), calc_expression(rand_exp))
Story
The pandemic has spread to all countries of the world, and Berland is no exception. Even at the All-Berland Olympiad in Computer Science, antiviral measures were introduced. In total, n
people participate in the Olympiad, and in order to comply with all the instructions of the management, the Olympiad jury decided to invite participants to the tour one at a time with an interval of x
minutes. Thus, the first participant will start the tour at time 0, the second participant will start the tour at time x
, the third — at time 2x
and so on.
Despite the different start times, the duration of the tour for each participant is exactly t
minutes. Because of this, some participants finish writing the tour before the rest. When a participant finishes writing a tour, the amount of dissatisfaction with the organization of the Olympiad for this participant is equal to the number of other participants who are currently still writing or just starting to write a tour, but have not finished it yet.
Goal
Help the organizers of the Olympiad to find out what the total dissatisfaction of all participants of the Olympiad is equal to.
Input:
A single integer n is entered in the first line 1<=n<=2 * 10^9 — the number of participants of the Olympiad.
A single integer x is entered in the second line 1<=x<=2 * 10^9 — the interval in minutes between the start times of the tour for participants.
In the third line, a single integer t is entered 1<=t<=2 * 10^9 — duration of the tour.
Output:
In a single line, return one number — the total dissatisfaction of all participants of the Olympiad.
Examples
def satisfaction(4, 2, 5) --> 5
def satisfaction(3, 1, 2) --> 3
def satisfaction(3, 3, 10) --> 3
-
In the first example , the first participant will start writing the tour at time 0 and finish at time 5. By this time, the second and third participants will already start writing the tour, so the dissatisfaction of the first participant will be equal to 2. The second participant will start writing at time 2 and finish at time 7. By this point, the third and fourth participants will already start writing the tour, so the dissatisfaction of the second will be equal to 2. The third participant will start writing the tour at time 4 and finish at time 9. By this time, the fourth participant will already start writing the tour, so the dissatisfaction of the third will be equal to 1. The fourth participant will start writing the tour at time 6 and finish at time 11. At time 9 no one will write a tour anymore, so the dissatisfaction of the fourth will be equal to 0. Thus, the total dissatisfaction of all participants will be equal to 2+2+1+0=5.
-
In the second example , the first participant will start writing the tour at time 0 and finish at time 2. By this point, the second participant will already be writing the tour, and the third participant will just start at time 2. Therefore , the dissatisfaction of the first participant will be equal to 2. The second participant will start at time 1and finish at time 3. By this point, only the third participant will still be writing the tour. Thus, the total dissatisfaction of all participants will be equal to 2+1=3.
Fork 1
I think I met the bid here. I wrote some edge cases that you should check to make sure that they follow the rules as well, but I've been treating all comparisons as <= since you said:
currently still writing or just starting to write a tour, but have not finished it yet.
Either way, really fun challenge! If this is looking good for you, just add some random tests and this will be ready for a kata IMO. This was a really fun puzzle to figure out because it's not just math that helps you get to the right solution, but clever coding logic as well. This would be a really fun kata when you're satisfied... get it?
def satisfaction(n, x, t): start_times = [i * x for i in range(n)] finish_times = [(i * x) + t for i in range(n)] upset_factor = 0 for i, writer in enumerate(finish_times): for j, others in enumerate(start_times): if others <= writer and i < j: upset_factor += 1 print(start_times, finish_times) return upset_factor
def qwerty(n, x, t):time_finish_before_start = t + x * (n - 1)time_start_before_finish = t + x * (n - 2)dissatisfaction_finish_before_start = min(n - 1, time_finish_before_start // x)dissatisfaction_start_before_finish = max(0, n - 2 - dissatisfaction_finish_before_start)total_dissatisfaction = dissatisfaction_finish_before_start * dissatisfaction_start_before_finishreturn total_dissatisfaction- def satisfaction(n, x, t):
- start_times = [i * x for i in range(n)]
- finish_times = [(i * x) + t for i in range(n)]
- upset_factor = 0
- for i, writer in enumerate(finish_times):
- for j, others in enumerate(start_times):
- if others <= writer and i < j:
- upset_factor += 1
- print(start_times, finish_times)
- return upset_factor
import codewars_test as test from solution import satisfaction @test.describe("Example Tests") def test_group(): @test.it("Example One") def example_one(): test.assert_equals(satisfaction(4, 2, 5), 5) @test.it("Example Two") def example_two(): test.assert_equals(satisfaction(3, 1, 2), 3) @test.it("Example Three") def example_three(): test.assert_equals(satisfaction(3, 3, 10), 3) @test.describe("Fixed Tests") def test_group(): @test.it("Fixed Tests") def test_fixed_edition(): test.assert_equals(satisfaction(1, 1, 1), 0) test.assert_equals(satisfaction(1, 10, 10), 0) test.assert_equals(satisfaction(10, 1, 10), 45) test.assert_equals(satisfaction(1, 10, 10), 0)
- import codewars_test as test
# TODO Write testsimport solution # or from solution import example- from solution import satisfaction
# test.assert_equals(actual, expected, [optional] message)@test.describe("Example")- @test.describe("Example Tests")
- def test_group():
@test.it("test case")def test_case():test.assert_equals(1 + 1, 2)- @test.it("Example One")
- def example_one():
- test.assert_equals(satisfaction(4, 2, 5), 5)
- @test.it("Example Two")
- def example_two():
- test.assert_equals(satisfaction(3, 1, 2), 3)
- @test.it("Example Three")
- def example_three():
- test.assert_equals(satisfaction(3, 3, 10), 3)
- @test.describe("Fixed Tests")
- def test_group():
- @test.it("Fixed Tests")
- def test_fixed_edition():
- test.assert_equals(satisfaction(1, 1, 1), 0)
- test.assert_equals(satisfaction(1, 10, 10), 0)
- test.assert_equals(satisfaction(10, 1, 10), 45)
- test.assert_equals(satisfaction(1, 10, 10), 0)
Goal
Not really sure. But it looks like we're calculating the actual probability of a ruleset and comparing it to the calculated probability.
Fork 1
I changed the testing to use assert_approx_equals
instead of assert_equals
since the implementation was the same, and it makes testing more consistent. Added a zero to the range we're using to increase the odds we will match expected probability, and made a minor optimization to use a comprehension since we're iterating 100,000 times.
I also refactored the funtion to take our alternate ruleset, and run those rules if true. Can't get it to pass the tests though. It's something though.
from random import randint playing_board = [0] * 100 # board is 100 positions long position = 0 # player starts at position 0 on the board while position < 100: # end when position moves off board playing_board[position] = 1 # player was here position += randint(1, 6) # throw a die and move # what's the probability that playing_board[n] == 1? # there is a prize if you land on position n # but a cost for playing the game # let's run N times def probability(other_rule=False): successes = [0] * 100 if not other_rule: for n in range(100000): # maybe this isn't big enough # maybe it is now? playing_board = [0] * 100 position = 0 while position < 100: successes[position] += 1 position += randint(1, 6) return [s / n for s in successes] # what if we add a rule # if the player lands on square 99, they teleport back to 0 for n in range(100000): playing_board = [0] * 100 # board is 100 positions long position = 0 # player starts at position 0 on the board while position < 100: # end when position moves off board successes[position] += 1 # player was here position += randint(1, 6) # throw a die and move if position == 99: position = 0 # snakey snake return [s / n for s in successes] # can you calculate the probability of the prize now?
- from random import randint
- playing_board = [0] * 100 # board is 100 positions long
- position = 0 # player starts at position 0 on the board
- while position < 100: # end when position moves off board
- playing_board[position] = 1 # player was here
- position += randint(1, 6) # throw a die and move
- # what's the probability that playing_board[n] == 1?
- # there is a prize if you land on position n
- # but a cost for playing the game
- # let's run N times
def probability():N = 10000 # maybe this isn't big enough- def probability(other_rule=False):
- successes = [0] * 100
for _ in range(N):playing_board = [0] * 100position = 0while position < 100:successes[position] += 1position += randint(1, 6)ret = []for s in successes:ret.append(s / N)return ret- if not other_rule:
- for n in range(100000): # maybe this isn't big enough # maybe it is now?
- playing_board = [0] * 100
- position = 0
- while position < 100:
- successes[position] += 1
- position += randint(1, 6)
- return [s / n for s in successes]
- # what if we add a rule
- # if the player lands on square 99, they teleport back to 0
- for n in range(100000):
- playing_board = [0] * 100 # board is 100 positions long
- position = 0 # player starts at position 0 on the board
- while position < 100: # end when position moves off board
- successes[position] += 1 # player was here
- position += randint(1, 6) # throw a die and move
- if position == 99: position = 0 # snakey snake
- return [s / n for s in successes]
# what if we add a rule# if the player lands on square 99, they teleport back to 0playing_board = [0] * 100 # board is 100 positions longposition = 0 # player starts at position 0 on the boardwhile position < 100: # end when position moves off boardplaying_board[position] = 1 # player was hereposition += randint(1, 6) # throw a die and moveif position == 99: position = 0 # snakey snake- # can you calculate the probability of the prize now?
import codewars_test as test from solution import probability default = [1] for _ in range(99): default.append(sum(default[-6:]) / 6) other = [1.28571428571428753] for _ in range(99): other.append(sum(other[-6:]) / 6) # test.assert_equals(actual, expected, [optional] message) # this should be used for strict equals # test.assert_approx_equals(actual, expected, margin=1e-9, message=None, allow_raise=False) # we use this instead @test.describe("Get close enough") def test_group(): @test.it("Stay within 1 d.p. of accuracy, default rule") def test_case(): user_probs = probability() for n in range(100): test.assert_approx_equals(user_probs[n], default[n], margin=0.1) @test.it("Stay within 2 d.p. of accuracy, default rule") def test_case(): user_probs = probability() for n in range(100): test.assert_approx_equals(user_probs[n], default[n], margin=0.01) @test.it("Stay within 1 d.p. of accuracy, other rule") def test_case(): user_probs = probability(True) for n in range(100): test.assert_approx_equals(user_probs[n], other[n], margin=0.1) @test.it("Stay within 2 d.p. of accuracy, other rule") def test_case(): user_probs = probability(True) for n in range(100): test.assert_approx_equals(user_probs[n], other[n], margin=0.01)
- import codewars_test as test
- from solution import probability
probabilities = [1]- default = [1]
- for _ in range(99):
probabilities.append(sum(probabilities[-6:]) / 6)- default.append(sum(default[-6:]) / 6)
- other = [1.28571428571428753]
- for _ in range(99):
- other.append(sum(other[-6:]) / 6)
# test.assert_equals(actual, expected, [optional] message)- # test.assert_equals(actual, expected, [optional] message) # this should be used for strict equals
- # test.assert_approx_equals(actual, expected, margin=1e-9, message=None, allow_raise=False) # we use this instead
- @test.describe("Get close enough")
- def test_group():
@test.it("Say within 1 d.p. of accuracy")- @test.it("Stay within 1 d.p. of accuracy, default rule")
- def test_case():
- user_probs = probability()
- for n in range(100):
test.assert_equals(abs(user_probs[n] - probabilities[n]) < 0.1, True, "The error was " + str(abs(user_probs[n] - probabilities[n])))@test.it("Say within 2 d.p. of accuracy")- test.assert_approx_equals(user_probs[n], default[n], margin=0.1)
- @test.it("Stay within 2 d.p. of accuracy, default rule")
- def test_case():
- user_probs = probability()
- for n in range(100):
test.assert_equals(abs(user_probs[n] - probabilities[n]) < 0.01, True, "The error was " + str(abs(user_probs[n] - probabilities[n])))- test.assert_approx_equals(user_probs[n], default[n], margin=0.01)
- @test.it("Stay within 1 d.p. of accuracy, other rule")
- def test_case():
- user_probs = probability(True)
- for n in range(100):
- test.assert_approx_equals(user_probs[n], other[n], margin=0.1)
- @test.it("Stay within 2 d.p. of accuracy, other rule")
- def test_case():
- user_probs = probability(True)
- for n in range(100):
- test.assert_approx_equals(user_probs[n], other[n], margin=0.01)
Goal
Write a function matrix()
that takes a 2D array, an operation, a target location, and an optional write_data as an input.
def matrix(matrice=[[1,2,3],
[4,5,6],
[7,8,9]], operation="write", location=(0, 1), write_data=7)
Your function should catch any IndexError that occers. Return values should be:
- if write: The new matrix, after adding write_data in the location given.
- if read: The existing data at the requested location.
- if neither: raise an AttributeError with any message.
Fork 1
Cleaned up some of the error checking to use best practices. Added testing for the error checking. Added random testing with basic matricies from numpy.
The random tests are honestly scuffed beyond belief. I've never worked with numpy before, and this is probably a bad first experience. I would love to see someone fix the mess that I've made lol... sorry in advance. I decided to cap the size of random tests at 100 since this isn't really meant to be a preformance type kumite. Ran a couple times and seems like a good upper limit imo.
def matrix(matrice=list, operation=str, location=tuple, write_data=None): if operation == "read": try: return matrice[location[0]][location[1]] except IndexError as e: print(e) return 0 elif operation == "write": try: matrice[location[0]][location[1]] = write_data return matrice except IndexError as e: print(e) return 0 else: raise AttributeError("That is not a valid operation for this system.")
def matrix(matrice=list, operation=str, location=tuple, writedata=None):- def matrix(matrice=list, operation=str, location=tuple, write_data=None):
- if operation == "read":
try:- try:
- return matrice[location[0]][location[1]]
except Exception as e:- except IndexError as e:
- print(e)
- return 0
- elif operation == "write":
- try:
matrice[location[0]][location[1]] = writedata- matrice[location[0]][location[1]] = write_data
- return matrice
except Exception as e:- except IndexError as e:
- print(e)
- return 0
- else:
raise OperationError("That is not a valid operation for this system.")- raise AttributeError("That is not a valid operation for this system.")
import codewars_test as test from solution import matrix import numpy import random # Working solution def working_matrix(mx, op, loc, wd=None): if op == "read": try: return mx[loc[0]][loc[1]] except IndexError as e: return 0 elif op == "write": try: mx[loc[0]][loc[1]] = wd return mx except IndexError as e: return 0 else: raise AttributeError("That is not a valid operation for this system.") def get_rand_matrix(size): return [i for i in numpy.random.randint(0, 100, (size, size))] # Start of testing @test.describe("Example") def test_group(): @test.it("Fixed Tests") def test_case(): test.assert_equals(matrix([[1,2,3], [4,5,6], [7,8,9]], "read", (0,1)), 2) test.assert_equals(matrix([[1,2,3], [4,5,6], [7,8,9]], "write", (0,1), 7), [[1,7,3], [4,5,6], [7,8,9]]) test.assert_equals(matrix([[1,2,3], [4,5,6], [7,8,9]], "read", (1,2)), 6) test.assert_equals(matrix([[1,2,3], [4,5,6], [7,8,9]], "write", (1,2), 7), [[1,2,3], [4,5,7], [7,8,9]]) @test.it("Test Error Catching") def test_case(): try: matrix([[1,2,3],[1,2,3]], 'copy', (0,1)) test.fail('Your function did not raise the correct error.') except AttributeError as e: test.pass_() try: test.assert_equals(matrix([[1,2,3],[1,2,3]], 'read', (2,4)), 0) except IndexError as e: test.fail('Your function allowed for an IndexError. Expected 0') try: test.assert_equals(matrix([[1,2,3],[1,2,3]], 'write', (2,4)), 0) except IndexError as e: test.fail('Your function allowed for an IndexError. Expected 0') test.assert_equals(matrix([[1,2,3],[1,2,3]], 'write', (1, 1)), [[1, 2, 3], [1, None, 3]]) @test.describe('Random Tests') def random_time(): @test.it('Small Tests') def small_rand(): for i in range(25): length = random.randrange(3, 10) test_matrix = get_rand_matrix(length) user_test = test_matrix.copy() rand_index = (random.randrange(-length, length + 2), random.randrange(-length, length + 2)) if i % 2: data = random.randrange(0, 100) sol = working_matrix(test_matrix, 'write', rand_index, data) test.assert_equals(matrix(user_test, 'write', rand_index, data), sol) else: sol = working_matrix(test_matrix, 'read', rand_index) test.assert_equals(matrix(user_test, 'read', rand_index), sol) @test.it('Medium Tests') def medium_rand(): for i in range(25): length = random.randrange(10, 50) test_matrix = get_rand_matrix(length) user_test = test_matrix.copy() rand_index = (random.randrange(-length, length + 2), random.randrange(-length, length + 2)) if i % 2: data = random.randrange(0, 100) sol = working_matrix(test_matrix, 'write', rand_index, data) test.assert_equals(matrix(user_test, 'write', rand_index, data), sol) else: sol = working_matrix(test_matrix, 'read', rand_index) test.assert_equals(matrix(user_test, 'read', rand_index), sol) @test.it('Large Tests') def large_rand(): for i in range(25): length = random.randrange(50, 100) test_matrix = get_rand_matrix(length) user_test = test_matrix.copy() rand_index = (random.randrange(-length, length + 2), random.randrange(-length, length + 2)) if i % 2: data = random.randrange(0, 100) sol = working_matrix(test_matrix, 'write', rand_index, data) test.assert_equals(matrix(user_test, 'write', rand_index, data), sol) else: sol = working_matrix(test_matrix, 'read', rand_index) test.assert_equals(matrix(user_test, 'read', rand_index), sol)
- import codewars_test as test
# TODO Write testsfrom solution import matrix # or from solution import example- from solution import matrix
# test.assert_equals(actual, expected, [optional] message)- import numpy
- import random
- # Working solution
- def working_matrix(mx, op, loc, wd=None):
- if op == "read":
- try: return mx[loc[0]][loc[1]]
- except IndexError as e:
- return 0
- elif op == "write":
- try:
- mx[loc[0]][loc[1]] = wd
- return mx
- except IndexError as e:
- return 0
- else:
- raise AttributeError("That is not a valid operation for this system.")
- def get_rand_matrix(size):
- return [i for i in numpy.random.randint(0, 100, (size, size))]
- # Start of testing
- @test.describe("Example")
- def test_group():
@test.it("test case")- @test.it("Fixed Tests")
- def test_case():
- test.assert_equals(matrix([[1,2,3],
- [4,5,6],
- [7,8,9]], "read", (0,1)), 2)
- test.assert_equals(matrix([[1,2,3],
- [4,5,6],
- [7,8,9]], "write", (0,1), 7), [[1,7,3],
- [4,5,6],
- [7,8,9]])
- test.assert_equals(matrix([[1,2,3],
- [4,5,6],
- [7,8,9]], "read", (1,2)), 6)
- test.assert_equals(matrix([[1,2,3],
- [4,5,6],
- [7,8,9]], "write", (1,2), 7), [[1,2,3],
- [4,5,7],
- [7,8,9]])
- @test.it("Test Error Catching")
- def test_case():
- try:
- matrix([[1,2,3],[1,2,3]], 'copy', (0,1))
- test.fail('Your function did not raise the correct error.')
- except AttributeError as e:
- test.pass_()
- try:
- test.assert_equals(matrix([[1,2,3],[1,2,3]], 'read', (2,4)), 0)
- except IndexError as e:
- test.fail('Your function allowed for an IndexError. Expected 0')
- try:
- test.assert_equals(matrix([[1,2,3],[1,2,3]], 'write', (2,4)), 0)
- except IndexError as e:
- test.fail('Your function allowed for an IndexError. Expected 0')
- test.assert_equals(matrix([[1,2,3],[1,2,3]], 'write', (1, 1)), [[1, 2, 3], [1, None, 3]])
- @test.describe('Random Tests')
- def random_time():
- @test.it('Small Tests')
- def small_rand():
- for i in range(25):
- length = random.randrange(3, 10)
- test_matrix = get_rand_matrix(length)
- user_test = test_matrix.copy()
- rand_index = (random.randrange(-length, length + 2), random.randrange(-length, length + 2))
- if i % 2:
- data = random.randrange(0, 100)
- sol = working_matrix(test_matrix, 'write', rand_index, data)
- test.assert_equals(matrix(user_test, 'write', rand_index, data), sol)
- else:
- sol = working_matrix(test_matrix, 'read', rand_index)
- test.assert_equals(matrix(user_test, 'read', rand_index), sol)
- @test.it('Medium Tests')
- def medium_rand():
- for i in range(25):
- length = random.randrange(10, 50)
- test_matrix = get_rand_matrix(length)
- user_test = test_matrix.copy()
- rand_index = (random.randrange(-length, length + 2), random.randrange(-length, length + 2))
- if i % 2:
- data = random.randrange(0, 100)
- sol = working_matrix(test_matrix, 'write', rand_index, data)
- test.assert_equals(matrix(user_test, 'write', rand_index, data), sol)
- else:
- sol = working_matrix(test_matrix, 'read', rand_index)
- test.assert_equals(matrix(user_test, 'read', rand_index), sol)
- @test.it('Large Tests')
- def large_rand():
- for i in range(25):
- length = random.randrange(50, 100)
- test_matrix = get_rand_matrix(length)
- user_test = test_matrix.copy()
- rand_index = (random.randrange(-length, length + 2), random.randrange(-length, length + 2))
- if i % 2:
- data = random.randrange(0, 100)
- sol = working_matrix(test_matrix, 'write', rand_index, data)
- test.assert_equals(matrix(user_test, 'write', rand_index, data), sol)
- else:
- sol = working_matrix(test_matrix, 'read', rand_index)
- test.assert_equals(matrix(user_test, 'read', rand_index), sol)
Goal
You are collecting data that fits a wave signal. Your must determine witch mathematical expression fits the signal. You will receive an array of numbers into your function called find_signal()
All numbers in the array will obey one of these expressions:
y = sin x,
y = cos x,
y = sin x + cos x
The given y values will always correspond to x input values of 0, 1, 2, ... n where n is the length of the array - 1. Your function will identify which signal is coming in and return string: 'sin x', 'cos x' or 'sin x + cos x'. Otherwise, None
All inputs will have at least 2 numbers to indicate a clear answer.
Fork 1
Removed duplicate tests. Added more precise floating point values instead of rounded numbers. (I think its best practice to avoid rounding where it is not absolutely necessary? Either way, it makes the random tests easier to build, and the actual code more accurate). Added random tests
In addition to what's above, I refactored pretty much the whole code to accept more than just 4 numbers. The random tests will give an array of size 2 <= n <= 1000
. We start at 2 to avoid edge cases between cos, and sin + cos. I'm sure someone smarter than I could find a way to include those as well, but I think this is good enough for a pretty simple problem like this.
import math as m def find_signal(wave): sinx = ('sin x', [i for i in range(len(wave)) if wave[i] == m.sin(i)]) cosx = ('cos x', [i for i in range(len(wave)) if wave[i] == m.cos(i)]) cossin = ('sin x + cos x', [i for i in range(len(wave)) if wave[i] == m.cos(i) + m.sin(i)]) final = max([sinx, cosx, cossin], key=lambda x : sum(x[1])) return final[0] if sum(final[1]) == sum([i for i in range(len(wave))]) else None
- import math as m
def find_signal(s):k=0; k1=0; k2=0for i in range(4):if s[i]==round(m.sin(i),2):k=k+1if k==4:return('sin x')if s[i]==round(m.cos(i),2):k1=k1+1if k1==4:return('cos x')if s[i]==round(m.cos(i)+m.sin(i),2):k2=k2+1if k2==4:return('sin x + cos x')- def find_signal(wave):
- sinx = ('sin x', [i for i in range(len(wave)) if wave[i] == m.sin(i)])
- cosx = ('cos x', [i for i in range(len(wave)) if wave[i] == m.cos(i)])
- cossin = ('sin x + cos x', [i for i in range(len(wave)) if wave[i] == m.cos(i) + m.sin(i)])
- final = max([sinx, cosx, cossin], key=lambda x : sum(x[1]))
- return final[0] if sum(final[1]) == sum([i for i in range(len(wave))]) else None
import codewars_test as test from solution import find_signal import math import random # Working solution def found_signal(wave): sinx = ('sin x', [i for i in range(len(wave)) if wave[i] == math.sin(i)]) cosx = ('cos x', [i for i in range(len(wave)) if wave[i] == math.cos(i)]) cossin = ('sin x + cos x', [i for i in range(len(wave)) if wave[i] == math.cos(i) + math.sin(i)]) final = max([sinx, cosx, cossin], key=lambda x : sum(x[1])) return final[0] if sum(final[1]) == sum([i for i in range(len(wave))]) else None # Generate random tests def get_random(): waves = ['math.sin(i)', 'math.cos(i)', '(math.sin(i) + math.cos(i))', '(math.tan(i))'] expression = random.choice(waves) array = eval(f'[{expression} for i in range(random.randrange(2, 1000))]') return array # Start of testing @test.describe("Fixed Tests") def test_group(): @test.it("Standard Tests") def test_case(): test.assert_equals(find_signal([0.0, 0.8414709848078965, 0.9092974268256817, 0.1411200080598672]), 'sin x') test.assert_equals(find_signal([1.0, 0.5403023058681398, -0.4161468365471424, -0.9899924966004454]), 'cos x') test.assert_equals(find_signal([1.0, 1.3817732906760363, 0.4931505902785393, -0.8488724885405782]), 'sin x + cos x') test.assert_equals(find_signal([0, 0, 0, 0.14]), None) @test.describe('Random Tests') def rand_tests(): for _ in range(100): seed = get_random() exp = found_signal(seed) @test.it(f'Expression: {exp} \nLength of array: {len(seed)}') def test_random_edition(): test.assert_equals(find_signal(seed), exp)
- import codewars_test as test
# TODO Write testsfrom solution import find_signal # or from solution import example- from solution import find_signal
# test.assert_equals(actual, expected, [optional] message)@test.describe("Example")- import math
- import random
- # Working solution
- def found_signal(wave):
- sinx = ('sin x', [i for i in range(len(wave)) if wave[i] == math.sin(i)])
- cosx = ('cos x', [i for i in range(len(wave)) if wave[i] == math.cos(i)])
- cossin = ('sin x + cos x', [i for i in range(len(wave)) if wave[i] == math.cos(i) + math.sin(i)])
- final = max([sinx, cosx, cossin], key=lambda x : sum(x[1]))
- return final[0] if sum(final[1]) == sum([i for i in range(len(wave))]) else None
- # Generate random tests
- def get_random():
- waves = ['math.sin(i)', 'math.cos(i)', '(math.sin(i) + math.cos(i))', '(math.tan(i))']
- expression = random.choice(waves)
- array = eval(f'[{expression} for i in range(random.randrange(2, 1000))]')
- return array
- # Start of testing
- @test.describe("Fixed Tests")
- def test_group():
@test.it("test case")- @test.it("Standard Tests")
- def test_case():
test.assert_equals(find_signal([0,.84,.91,.14]),'sin x')test.assert_equals(find_signal([1,.54,-.42,-.99]),'cos x')test.assert_equals(find_signal([1,1.38,.49,-.85]),'sin x + cos x')test.assert_equals(find_signal([0,.84,.91,.14]),'sin x')test.assert_equals(find_signal([0,.84,.91,.14]),'sin x')test.assert_equals(find_signal([1,.54,-.42,-.99]),'cos x')test.assert_equals(find_signal([1,1.38,.49,-.85]),'sin x + cos x')test.assert_equals(find_signal([0,0,0,.14]),None)- test.assert_equals(find_signal([0.0, 0.8414709848078965, 0.9092974268256817, 0.1411200080598672]), 'sin x')
- test.assert_equals(find_signal([1.0, 0.5403023058681398, -0.4161468365471424, -0.9899924966004454]), 'cos x')
- test.assert_equals(find_signal([1.0, 1.3817732906760363, 0.4931505902785393, -0.8488724885405782]), 'sin x + cos x')
- test.assert_equals(find_signal([0, 0, 0, 0.14]), None)
- @test.describe('Random Tests')
- def rand_tests():
- for _ in range(100):
- seed = get_random()
- exp = found_signal(seed)
- @test.it(f'Expression: {exp} \nLength of array: {len(seed)}')
- def test_random_edition():
- test.assert_equals(find_signal(seed), exp)
GOAL:
write a class that will greet a person when called.
class Greeting: def __init__(self, name, rank=None, formal=False): self.name = name self.rank = rank self.formal = formal def __call__(self): if self.formal: return f'Hello,{" " + self.rank if self.rank is not None else ""} {self.name}.' else: return f'Hey, {self.name}!'
class greeting:def __init__(self, name: str, formal: bool = False):- class Greeting:
- def __init__(self, name, rank=None, formal=False):
- self.name = name
- self.rank = rank
- self.formal = formal
def __call__(self) -> str:if self.formal: return f'Hello, Sir {self.name}.'else: return f'Hello, {self.name}!'g1 = greeting('John')g2 = greeting('Churchill', True)print(g1()) # 'Hello, John!'print(g2()) # 'Hello, Sir Churchill.'- def __call__(self):
- if self.formal: return f'Hello,{" " + self.rank if self.rank is not None else ""} {self.name}.'
- else: return f'Hey, {self.name}!'
import codewars_test as test from solution import Greeting import random # Working solution / random generator def get_greeting(name, rank=None, formal=False): print(f'Hello,{" " + rank if rank is not None else ""} {name}.' if formal else f'Hey, {name}!') return f'Hello,{" " + rank if rank is not None else ""} {name}.' if formal else f'Hey, {name}!' def get_person(): names = [ 'Lisa', 'Skylar', 'Dylan', 'Harper', 'Susan', 'Kenneth', 'Quinn', 'Kevin', 'Morgan', 'Jordan', 'Finley', 'Karen', 'Michael', 'Emerson', 'Daniel', 'Avery', 'William', 'Michelle', 'Justice', 'David', 'Donald', 'Richard', 'Jennifer', 'Robert', 'Payton', 'John', 'James', 'Ariel', 'Skyler', 'Dorothy', 'Charles', 'Paul', 'Drew', 'Rory', 'Steven', 'Riley', 'Reese', 'Robin', 'Cameron', 'Mark', 'Jamie', 'Sarah', 'Jessica', 'Nancy', 'Anthony', 'Brian', 'Sandra', 'George', 'Helen', 'Melissa', 'Dakota', 'Mary', 'Alexis', 'Peyton', 'Alex', 'Charlie', 'Matthew', 'Patricia', 'Christopher', 'Edward', 'Elizabeth', 'Amanda', 'Sawyer', 'Margaret', 'Donna', 'Emily', 'Thomas', 'Bailey', 'Hayden', 'Rowan', 'Harley', 'Kai', 'Carol', 'Laura', 'Linda', 'Casey', 'Parker', 'Andrew', 'Joseph', 'Reagan', 'Emery', 'Phoenix', 'Taylor', 'Betty' ] titles = [ 'Duchess', 'Ambassador', 'Mistress', 'Executive', 'Sultan', 'Pharaoh', 'Baron', 'Mayor', 'Magistrate', 'Sergeant', 'Doctor', 'Sir', 'Lord', 'Vice President', 'Baroness', 'Cardinal', 'Officer', 'Archbishop', 'Duke', 'Agent', 'Madam', 'Queen', 'Minister', 'King', 'Captain', 'Pope', 'Master', 'Admiral', 'Princess', 'Lieutenant', 'Director', 'President', 'Governor', 'Commander', 'Prince', 'Detective', 'Professor', 'Sheikh', 'Bishop', 'Chancellor', 'Countess', 'Empress', 'Chief', 'Senator', 'Counselor', 'Emperor', 'Judge', 'General', 'Count' ] rand_num = random.randrange(1, 4) if rand_num == 1: return random.choice(names) if rand_num == 2: rand_name = random.choice(names) title_or_formal = random.choice([(random.choice(titles)), (random.randrange(1, 10) % 2 == 0)]) return rand_name, title_or_formal rand_name = random.choice(names) rand_title = random.choice(titles) form = random.randrange(1, 10) % 2 == 0 return rand_name, rand_title, form # START OF TESTING @test.describe("Example") def test_group(): @test.it("Test case") def test_case(): test.assert_equals(Greeting('John')(), 'Hey, John!') test.assert_equals(Greeting('Churchill','Sir', True)(), 'Hello, Sir Churchill.') test.assert_equals(Greeting('Einstein', 'Proffessor', False)(), 'Hey, Einstein!') test.assert_equals(Greeting('Jane', formal=True)(), 'Hello, Jane.') @test.describe("Random Tests") def random_stuff(): for _ in range(100): person = get_person() @test.it(f"Testing: {person}") def test_random(): if isinstance(person, tuple): if len(person) == 2: if isinstance(person[1], str): test.assert_equals(Greeting(person[0], rank=person[1])(), get_greeting(person[0], rank=person[1])) else: test.assert_equals(Greeting(person[0], formal=person[1])(), get_greeting(person[0], formal=person[1])) else: test.assert_equals(Greeting(*person)(), get_greeting(*person)) else: test.assert_equals(Greeting(person)(), f'Hey, {person}!')
- import codewars_test as test
# TODO Write testsimport solution # or from solution import example- from solution import Greeting
- import random
- # Working solution / random generator
- def get_greeting(name, rank=None, formal=False):
- print(f'Hello,{" " + rank if rank is not None else ""} {name}.' if formal else f'Hey, {name}!')
- return f'Hello,{" " + rank if rank is not None else ""} {name}.' if formal else f'Hey, {name}!'
- def get_person():
- names = [
- 'Lisa', 'Skylar', 'Dylan', 'Harper', 'Susan', 'Kenneth', 'Quinn', 'Kevin', 'Morgan', 'Jordan', 'Finley',
- 'Karen', 'Michael', 'Emerson', 'Daniel', 'Avery', 'William', 'Michelle', 'Justice', 'David', 'Donald',
- 'Richard', 'Jennifer', 'Robert', 'Payton', 'John', 'James', 'Ariel', 'Skyler', 'Dorothy', 'Charles', 'Paul',
- 'Drew', 'Rory', 'Steven', 'Riley', 'Reese', 'Robin', 'Cameron', 'Mark', 'Jamie', 'Sarah', 'Jessica', 'Nancy',
- 'Anthony', 'Brian', 'Sandra', 'George', 'Helen', 'Melissa', 'Dakota', 'Mary', 'Alexis', 'Peyton', 'Alex',
- 'Charlie', 'Matthew', 'Patricia', 'Christopher', 'Edward', 'Elizabeth', 'Amanda', 'Sawyer', 'Margaret',
- 'Donna', 'Emily', 'Thomas', 'Bailey', 'Hayden', 'Rowan', 'Harley', 'Kai', 'Carol', 'Laura', 'Linda', 'Casey',
- 'Parker', 'Andrew', 'Joseph', 'Reagan', 'Emery', 'Phoenix', 'Taylor', 'Betty'
- ]
- titles = [
- 'Duchess', 'Ambassador', 'Mistress', 'Executive', 'Sultan', 'Pharaoh', 'Baron', 'Mayor', 'Magistrate',
- 'Sergeant', 'Doctor', 'Sir', 'Lord', 'Vice President', 'Baroness', 'Cardinal', 'Officer', 'Archbishop',
- 'Duke', 'Agent', 'Madam', 'Queen', 'Minister', 'King', 'Captain', 'Pope', 'Master', 'Admiral', 'Princess',
- 'Lieutenant', 'Director', 'President', 'Governor', 'Commander', 'Prince', 'Detective', 'Professor',
- 'Sheikh', 'Bishop', 'Chancellor', 'Countess', 'Empress', 'Chief', 'Senator', 'Counselor', 'Emperor', 'Judge',
- 'General', 'Count'
- ]
- rand_num = random.randrange(1, 4)
- if rand_num == 1:
- return random.choice(names)
- if rand_num == 2:
- rand_name = random.choice(names)
- title_or_formal = random.choice([(random.choice(titles)), (random.randrange(1, 10) % 2 == 0)])
- return rand_name, title_or_formal
- rand_name = random.choice(names)
- rand_title = random.choice(titles)
- form = random.randrange(1, 10) % 2 == 0
- return rand_name, rand_title, form
- # START OF TESTING
# test.assert_equals(actual, expected, [optional] message)- @test.describe("Example")
- def test_group():
@test.it("test case")- @test.it("Test case")
- def test_case():
test.assert_equals(greeting('John')(), 'Hello, John!')test.assert_equals(greeting('Churchill', True)(), 'Hello, Sir Churchill.')- test.assert_equals(Greeting('John')(), 'Hey, John!')
- test.assert_equals(Greeting('Churchill','Sir', True)(), 'Hello, Sir Churchill.')
- test.assert_equals(Greeting('Einstein', 'Proffessor', False)(), 'Hey, Einstein!')
- test.assert_equals(Greeting('Jane', formal=True)(), 'Hello, Jane.')
- @test.describe("Random Tests")
- def random_stuff():
- for _ in range(100):
- person = get_person()
- @test.it(f"Testing: {person}")
- def test_random():
- if isinstance(person, tuple):
- if len(person) == 2:
- if isinstance(person[1], str):
- test.assert_equals(Greeting(person[0], rank=person[1])(), get_greeting(person[0], rank=person[1]))
- else:
- test.assert_equals(Greeting(person[0], formal=person[1])(), get_greeting(person[0], formal=person[1]))
- else:
- test.assert_equals(Greeting(*person)(), get_greeting(*person))
- else:
- test.assert_equals(Greeting(person)(), f'Hey, {person}!')
Description:
The grid is a rectangular matrix consisting of non-negative integers representing the cost of moving to a specific cell. Each cell in the grid corresponds to a position in the path, and the value of the cell represents the cost associated with taking a step to that position.
Goal:
Move from position grid[0][0]
to position grid[-1][-1]
with as little cost as possible.
Allowed Moves:
You can only move horizontally (left or right) or vertically (up or down) to adjacent cells. Diagonal moves are not allowed
Additional Logic:
If there is uncertainty for which direction to go, AKA a tie, prioritize moving right. If you cannot move right, move down.
Examples:
Input:
[[0, 5, 4, 3],
[1, 0, 0, 0],
[2, 6, 7, 0]]
Logic:
(0,0) -> (1,0) -> (1,1) -> (1,2) -> (1,3) -> (2,3)
Output:
(0 + 1 + 0 + 0 + 0 + 0) = 1
Input (Edge case):
[[0, 9, 0, 0, 0],
[0, 9, 0, 9, 0],
[0, 0, 0, 9, 0]]
Logic:
(0,0) -> (1,0) -> (2,0) -> (2,1) -> (2,2) -> (1,2) -> (0,2) -> (0,3) ...
... -> (0,4) -> (1,4) -> (2,4)
Output:
0 (no values higher than zero collected on this path)
Fork #1:
Based off of the description you made, you left a couple of edge cases. Mainly that you never clarified that up or left are invalid. It could be assumed by the way your code ran, but it wasn't clear. I covered three of those edge cases here, but I left edge case 4 as a failed test just because my brain already hurts too much to add depth to the algorithm. Either way, this was a fun challenge! If no one makes improvements on this in a few days, I'll refactor again and write random tests for this.
def kimite(grid): rows, cols = len(grid), len(grid[0]) position = (0, 0) seen = set() total_cost = 0 # Helper function to find the min cost based on current coordinates def get_step_cost(*directions, ): compare = sorted([i for i in directions if i != None], key=lambda x: x[0]) multiple = [x for x in [i for i in directions if i != None] if x[0] == compare[0][0]] if len(multiple) > 1: for i in multiple: if i[1] == 'right': return i for i in multiple: if i[1] == 'down': return i else: return compare[0] # Helper function to find polar directions def get_direction(): up, down, left, right = None, None, None, None # Check Y if position[0] > 0 and (position[0] - 1, position[1]) not in seen: up = (grid[position[0] - 1][position[1]], 'up') if position[0] + 1 < rows and (position[0] + 1, position[1]) not in seen: down = (grid[position[0] + 1][position[1]], 'down') # Check X if position[1] > 0 and (position[0], position[1] - 1) not in seen: left = (grid[position[0]][position[1] - 1], 'left') if position[1] + 1 < cols and (position[0], position[1] + 1) not in seen: right = (grid[position[0]][position[1] + 1], 'right') return (up, down, left, right) # Traverse the grid to find the minimum cost path while position != (rows - 1, cols - 1): direction = get_direction() cost, move = get_step_cost(*direction) if move == 'up': position = (position[0] - 1, position[1]) total_cost += cost seen.add(position) continue if move == 'down': position = (position[0] + 1, position[1]) total_cost += cost seen.add(position) continue if move == 'left': position = (position[0], position[1] - 1) total_cost += cost seen.add(position) continue if move == 'right': position = (position[0], position[1] + 1) total_cost += cost seen.add(position) return total_cost
- def kimite(grid):
rows = len(grid)cols = len(grid[0])# Helper function to calculate the cost of a step based on current coordinates and directiondef get_step_cost(x, y, direction):if direction == "right" and x + 1 < cols:return grid[y][x + 1]elif direction == "down" and y + 1 < rows:return grid[y + 1][x]- rows, cols = len(grid), len(grid[0])
- position = (0, 0)
- seen = set()
- total_cost = 0
- # Helper function to find the min cost based on current coordinates
- def get_step_cost(*directions, ):
- compare = sorted([i for i in directions if i != None], key=lambda x: x[0])
- multiple = [x for x in [i for i in directions if i != None] if x[0] == compare[0][0]]
- if len(multiple) > 1:
- for i in multiple:
- if i[1] == 'right':
- return i
- for i in multiple:
- if i[1] == 'down':
- return i
- else:
return float('inf') # Return a very high cost if the step is not allowed- return compare[0]
# Initialize a 2D list to keep track of the minimum cost to reach each cellmin_costs = [[float('inf')] * cols for _ in range(rows)]min_costs[0][0] = grid[0][0]- # Helper function to find polar directions
- def get_direction():
- up, down, left, right = None, None, None, None
- # Check Y
- if position[0] > 0 and (position[0] - 1, position[1]) not in seen:
- up = (grid[position[0] - 1][position[1]], 'up')
- if position[0] + 1 < rows and (position[0] + 1, position[1]) not in seen:
- down = (grid[position[0] + 1][position[1]], 'down')
- # Check X
- if position[1] > 0 and (position[0], position[1] - 1) not in seen:
- left = (grid[position[0]][position[1] - 1], 'left')
- if position[1] + 1 < cols and (position[0], position[1] + 1) not in seen:
- right = (grid[position[0]][position[1] + 1], 'right')
- return (up, down, left, right)
- # Traverse the grid to find the minimum cost path
for y in range(rows):for x in range(cols):# Check rightward moveright_cost = min_costs[y][x] + get_step_cost(x, y, "right")if x + 1 < cols and right_cost < min_costs[y][x + 1]:min_costs[y][x + 1] = right_cost# Check downward movedown_cost = min_costs[y][x] + get_step_cost(x, y, "down")if y + 1 < rows and down_cost < min_costs[y + 1][x]:min_costs[y + 1][x] = down_cost# The minimum cost to reach the destination is stored at the bottom-right celldestination_cost = min_costs[rows - 1][cols - 1]return destination_cost if destination_cost != float('inf') else -1# Test casesgrid1 = [[0, 5, 4, 3],[1, 0, 0, 0],[2, 6, 7, 0]]print(kimite(grid1)) # Output: 12grid2 = [[0, 2, 3, 4],[5, 0, 0, 0],[6, 7, 8, 0]]print(kimite(grid2)) # Output: 9grid3 = [[0, 1, 2, 3],[6, 0, 4, 0],[5, 9, 8, 0]]print(kimite(grid3)) # Output: 6- while position != (rows - 1, cols - 1):
- direction = get_direction()
- cost, move = get_step_cost(*direction)
- if move == 'up':
- position = (position[0] - 1, position[1])
- total_cost += cost
- seen.add(position)
- continue
- if move == 'down':
- position = (position[0] + 1, position[1])
- total_cost += cost
- seen.add(position)
- continue
- if move == 'left':
- position = (position[0], position[1] - 1)
- total_cost += cost
- seen.add(position)
- continue
- if move == 'right':
- position = (position[0], position[1] + 1)
- total_cost += cost
- seen.add(position)
- return total_cost
import codewars_test as test # TODO Write tests import solution # Replace 'solution' with the actual name of your Python file # test.assert_equals(actual, expected, [optional] message) @test.describe("The Perplexing Path Puzzle") def test_group(): @test.it("Test Case 1") def test_case1(): grid = [[0, 5, 4, 3], [1, 0, 0, 0], [2, 6, 7, 0]] test.assert_equals(solution.kimite(grid), 1, "Failed Test Case 1") @test.it("Test Case 2") def test_case2(): grid = [[0, 2, 3, 4], [5, 0, 0, 0], [6, 7, 8, 0]] test.assert_equals(solution.kimite(grid), 2, "Failed Test Case 2") @test.it("Test Case 3") def test_case3(): grid = [[0, 1, 2, 3], [6, 0, 4, 0], [5, 9, 8, 0]] test.assert_equals(solution.kimite(grid), 5, "Failed Test Case 3") @test.it("Edge Case") def test_edge1(): grid = [ [0, 9, 0, 0, 0, 9, 0, 0, 0, 9], [0, 9, 0, 9, 0, 9, 0, 9, 0, 9], [0, 9, 0, 9, 0, 9, 0, 9, 0, 9], [0, 9, 0, 9, 0, 9, 0, 9, 0, 9], [0, 9, 0, 9, 0, 9, 0, 9, 0, 9], [0, 0, 0, 9, 0, 0, 0, 9, 0, 0], ] test.assert_equals(solution.kimite(grid), 0, "Failed Edge Case 1") @test.it('Edge Case 2') def test_edge2(): grid = [ [0, 9, 0, 0, 0, 9, 0, 0, 0, 9], [9, 9, 0, 9, 0, 9, 0, 9, 0, 9], [0, 9, 0, 9, 0, 9, 0, 9, 0, 9], [0, 9, 0, 9, 0, 9, 0, 9, 0, 9], [0, 9, 0, 9, 0, 9, 0, 9, 0, 9], [0, 0, 0, 9, 0, 0, 0, 9, 9, 0], ] test.assert_equals(solution.kimite(grid), 18, "Failed Edge Case 2") @test.it('Edge Case 3') def test_edge2(): grid = [ [0, 9, 0, 0, 0, 0, 0, 0, 0, 0], [0, 9, 0, 9, 0, 0, 9, 9, 9, 0], [0, 9, 0, 9, 9, 9, 9, 9, 0, 0], [0, 9, 0, 0, 0, 0, 0, 0, 9, 0], [0, 9, 9, 9, 9, 9, 9, 0, 9, 0], [0, 0, 0, 0, 0, 0, 0, 0, 9, 0], ] test.assert_equals(solution.kimite(grid), 0, "Failed Edge Case 3") @test.it('Edge Case 4') def test_edge2(): grid = [ [9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [0, 0, 0, 0, 0, 0, 0, 0, 9, 9], [0, 0, 0, 0, 0, 0, 0, 0, 9, 9], [0, 0, 0, 0, 0, 0, 0, 0, 9, 9], [0, 0, 0, 0, 0, 0, 0, 0, 9, 9], ] test.assert_equals(solution.kimite(grid), 36, "Failed Edge Case 4")
- import codewars_test as test
- # TODO Write tests
- import solution # Replace 'solution' with the actual name of your Python file
- # test.assert_equals(actual, expected, [optional] message)
- @test.describe("The Perplexing Path Puzzle")
- def test_group():
- @test.it("Test Case 1")
- def test_case1():
- grid = [[0, 5, 4, 3],
- [1, 0, 0, 0],
- [2, 6, 7, 0]]
- test.assert_equals(solution.kimite(grid), 1, "Failed Test Case 1")
- @test.it("Test Case 2")
- def test_case2():
- grid = [[0, 2, 3, 4],
- [5, 0, 0, 0],
- [6, 7, 8, 0]]
- test.assert_equals(solution.kimite(grid), 2, "Failed Test Case 2")
- @test.it("Test Case 3")
- def test_case3():
- grid = [[0, 1, 2, 3],
- [6, 0, 4, 0],
- [5, 9, 8, 0]]
- test.assert_equals(solution.kimite(grid), 5, "Failed Test Case 3")
- @test.it("Edge Case")
- def test_edge1():
- grid = [
- [0, 9, 0, 0, 0, 9, 0, 0, 0, 9],
- [0, 9, 0, 9, 0, 9, 0, 9, 0, 9],
- [0, 9, 0, 9, 0, 9, 0, 9, 0, 9],
- [0, 9, 0, 9, 0, 9, 0, 9, 0, 9],
- [0, 9, 0, 9, 0, 9, 0, 9, 0, 9],
- [0, 0, 0, 9, 0, 0, 0, 9, 0, 0],
- ]
- test.assert_equals(solution.kimite(grid), 0, "Failed Edge Case 1")
- @test.it('Edge Case 2')
- def test_edge2():
- grid = [
- [0, 9, 0, 0, 0, 9, 0, 0, 0, 9],
- [9, 9, 0, 9, 0, 9, 0, 9, 0, 9],
- [0, 9, 0, 9, 0, 9, 0, 9, 0, 9],
- [0, 9, 0, 9, 0, 9, 0, 9, 0, 9],
- [0, 9, 0, 9, 0, 9, 0, 9, 0, 9],
- [0, 0, 0, 9, 0, 0, 0, 9, 9, 0],
- ]
- test.assert_equals(solution.kimite(grid), 18, "Failed Edge Case 2")
- @test.it('Edge Case 3')
- def test_edge2():
- grid = [
- [0, 9, 0, 0, 0, 0, 0, 0, 0, 0],
- [0, 9, 0, 9, 0, 0, 9, 9, 9, 0],
- [0, 9, 0, 9, 9, 9, 9, 9, 0, 0],
- [0, 9, 0, 0, 0, 0, 0, 0, 9, 0],
- [0, 9, 9, 9, 9, 9, 9, 0, 9, 0],
- [0, 0, 0, 0, 0, 0, 0, 0, 9, 0],
- ]
- test.assert_equals(solution.kimite(grid), 0, "Failed Edge Case 3")
- @test.it('Edge Case 4')
- def test_edge2():
- grid = [
- [9, 9, 9, 9, 9, 9, 9, 9, 9, 9],
- [9, 9, 9, 9, 9, 9, 9, 9, 9, 9],
- [0, 0, 0, 0, 0, 0, 0, 0, 9, 9],
- [0, 0, 0, 0, 0, 0, 0, 0, 9, 9],
- [0, 0, 0, 0, 0, 0, 0, 0, 9, 9],
- [0, 0, 0, 0, 0, 0, 0, 0, 9, 9],
- ]
- test.assert_equals(solution.kimite(grid), 36, "Failed Edge Case 4")
Task:
You are given two words, begin_word
and end_word
, and an array of words, word_list
. Your task is to find the shortest transformation sequence from begin_word
to end_word
, such that:
- Only one letter can be changed at a time.
- Each transformed word must exist in the given wordList.
Return the length of the shortest transformation sequence. If there is no such transformation sequence, return None.
Example:
Input:
begin_word = "hit"
end_word = "cog"
word_list = ["hot","dot","dog","lot","log","cog"]
Output: 5
Explanation:
One shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog"
returning its length gives us 5.
Input Parameters:
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word_list.
You may assume begin_word and end_word are non-empty and are not the same.
Fork #1:
I re-wrote the variable names to use python naming conventions. Also added some random tests of various sizes, as well as clarifying some of the test names to be more detailed. (e.g. Test Case #1
-> Valid: hit -> cog
). This will be helpful for debugging when made into a kata (which it looks pretty much ready for imo). I also just used a function instead of a class. Not sure why you would assign a class that only has one method, and doesn't need to keep track of instances, but like I said, it looks like you're used to different conventions where this is typical, or even the only way to use functions.
Have you also written this in a c-type language? That looks like the convention that you were using.
def ladder_length(begin_word, end_word, word_list): if end_word not in word_list: return 0 word_set = set(word_list) queue = {(begin_word, 1)} visited = set() while queue: word, level = queue.pop() if word == end_word: return level for i in range(len(word)): for char in 'abcdefghijklmnopqrstuvwxyz': new_word = word[:i] + char + word[i+1:] if new_word in word_set and new_word not in visited: queue.add((new_word, level + 1)) visited.add(new_word) return 0
from collections import deque- def ladder_length(begin_word, end_word, word_list):
- if end_word not in word_list: return 0
class Solution:@staticmethoddef ladderLength(beginWord, endWord, wordList):if endWord not in wordList:return 0wordSet = set(wordList)queue = deque([(beginWord, 1)])visited = set()while queue:word, level = queue.popleft()if word == endWord:return levelfor i in range(len(word)):for char in 'abcdefghijklmnopqrstuvwxyz':newWord = word[:i] + char + word[i+1:]if newWord in wordSet and newWord not in visited:queue.append((newWord, level + 1))visited.add(newWord)return 0- word_set = set(word_list)
- queue = {(begin_word, 1)}
- visited = set()
- while queue:
- word, level = queue.pop()
- if word == end_word: return level
- for i in range(len(word)):
- for char in 'abcdefghijklmnopqrstuvwxyz':
- new_word = word[:i] + char + word[i+1:]
- if new_word in word_set and new_word not in visited:
- queue.add((new_word, level + 1))
- visited.add(new_word)
- return 0
import random import codewars_test as test from solution import ladder_length # working solution for tests def my_ladder(begin_word, end_word, word_list): if end_word not in word_list: return 0 word_set = set(word_list) queue = {(begin_word, 1)} visited = set() while queue: word, level = queue.pop() if word == end_word: return level for i in range(len(word)): for char in 'abcdefghijklmnopqrstuvwxyz': new_word = word[:i] + char + word[i+1:] if new_word in word_set and new_word not in visited: queue.add((new_word, level + 1)) visited.add(new_word) return 0 # random word list generator def random_words(): words = ['and', 'fix', 'own', 'are', 'fly', 'odd', 'ape', 'fry', 'our', 'ace', 'for', 'pet', 'act', 'got', 'pat', 'ask', 'get', 'peg', 'arm', 'god', 'paw', 'age', 'gel', 'pup', 'ago', 'gas', 'pit', 'air', 'hat', 'put', 'ate', 'hit', 'pot', 'all', 'has', 'pop', 'but', 'had', 'pin', 'bye', 'how', 'rat', 'bad', 'her', 'rag', 'big', 'his', 'rub', 'bed', 'hen', 'row', 'bat', 'ink', 'rug', 'boy', 'ice', 'run', 'bus', 'ill', 'rap', 'bag', 'jab', 'ram', 'box', 'jug', 'sow', 'bit', 'jet', 'see', 'bee', 'jam', 'saw', 'buy', 'jar', 'set', 'bun', 'job', 'sit', 'cub', 'jog', 'sir', 'cat', 'kit', 'sat', 'car', 'key', 'sob', 'cut', 'lot', 'tap', 'cow', 'lit', 'tip', 'cry', 'let', 'top', 'cab', 'lay', 'tug', 'can', 'mat', 'tow', 'dad', 'man', 'toe', 'dab', 'mad', 'tan', 'dam', 'mug', 'ten', 'did', 'mix', 'two', 'dug', 'map', 'use', 'den', 'mum', 'van', 'dot', 'mud', 'vet', 'dip', 'mom', 'was', 'day', 'may', 'wet', 'ear', 'met', 'win', 'eye', 'net', 'won', 'eat', 'new', 'wig', 'end', 'nap', 'war', 'elf', 'now', 'why', 'egg', 'nod', 'who', 'far', 'net', 'way', 'fat', 'not', 'wow', 'few', 'nut', 'you', 'fan', 'oar', 'yes', 'fun', 'one', 'yak', 'fit', 'out', 'yet', 'fin', 'owl', 'zip', 'fox', 'old', 'zap'] start = random.choice(words) words.remove(start) end = random.choice(words) return start, end, words # Start of testing @test.describe("Example Tests") def test_group(): @test.it("Valid: hit --> cog") def test_case_1(): begin_word = "hit" end_word = "cog" word_list = ["hot", "dot", "dog", "lot", "log", "cog"] test.assert_equals(ladder_length(begin_word, end_word, word_list), 5) @test.it("Valid: a --> c") def test_case_2(): begin_word = "a" end_word = "c" word_list = ["a", "b", "c"] test.assert_equals(ladder_length(begin_word, end_word, word_list), 2) @test.it("Valid: red --> tax") def test_case_3(): begin_word = "red" end_word = "tax" word_list = ["ted", "tex", "red", "tax", "tad", "den", "rex", "pee"] test.assert_equals(ladder_length(begin_word, end_word, word_list), 4) @test.it("Invalid: hot --> dog") def test_case_4(): begin_word = "hot" end_word = "dog" word_list = ["hot", "dog"] test.assert_equals(ladder_length(begin_word, end_word, word_list), 0) @test.it("Invalid: a --> z") def test_case_5(): begin_word = "a" end_word = "z" word_list = ["b"] test.assert_equals(ladder_length(begin_word, end_word, word_list), 0) @test.describe('Random Tests') def run_random(): for _ in range(100): rand = random_words() @test.it(f'Testing {rand[0]} --> {rand[1]}') def test_random(): test.assert_equals(ladder_length(*rand), my_ladder(*rand))
- import random
- import codewars_test as test
# TODO Write testsimport solution # or from solution import example- from solution import ladder_length
# test.assert_equals(actual, expected, [optional] message)@test.describe("Example")- # working solution for tests
- def my_ladder(begin_word, end_word, word_list):
- if end_word not in word_list: return 0
- word_set = set(word_list)
- queue = {(begin_word, 1)}
- visited = set()
- while queue:
- word, level = queue.pop()
- if word == end_word:
- return level
- for i in range(len(word)):
- for char in 'abcdefghijklmnopqrstuvwxyz':
- new_word = word[:i] + char + word[i+1:]
- if new_word in word_set and new_word not in visited:
- queue.add((new_word, level + 1))
- visited.add(new_word)
- return 0
- # random word list generator
- def random_words():
- words = ['and', 'fix', 'own', 'are', 'fly', 'odd', 'ape', 'fry', 'our', 'ace', 'for', 'pet', 'act', 'got', 'pat', 'ask',
- 'get', 'peg', 'arm', 'god', 'paw', 'age', 'gel', 'pup', 'ago', 'gas', 'pit', 'air', 'hat', 'put', 'ate', 'hit', 'pot',
- 'all', 'has', 'pop', 'but', 'had', 'pin', 'bye', 'how', 'rat', 'bad', 'her', 'rag', 'big', 'his', 'rub', 'bed', 'hen',
- 'row', 'bat', 'ink', 'rug', 'boy', 'ice', 'run', 'bus', 'ill', 'rap', 'bag', 'jab', 'ram', 'box', 'jug', 'sow', 'bit',
- 'jet', 'see', 'bee', 'jam', 'saw', 'buy', 'jar', 'set', 'bun', 'job', 'sit', 'cub', 'jog', 'sir', 'cat', 'kit', 'sat',
- 'car', 'key', 'sob', 'cut', 'lot', 'tap', 'cow', 'lit', 'tip', 'cry', 'let', 'top', 'cab', 'lay', 'tug', 'can', 'mat',
- 'tow', 'dad', 'man', 'toe', 'dab', 'mad', 'tan', 'dam', 'mug', 'ten', 'did', 'mix', 'two', 'dug', 'map', 'use', 'den',
- 'mum', 'van', 'dot', 'mud', 'vet', 'dip', 'mom', 'was', 'day', 'may', 'wet', 'ear', 'met', 'win', 'eye', 'net', 'won',
- 'eat', 'new', 'wig', 'end', 'nap', 'war', 'elf', 'now', 'why', 'egg', 'nod', 'who', 'far', 'net', 'way', 'fat', 'not',
- 'wow', 'few', 'nut', 'you', 'fan', 'oar', 'yes', 'fun', 'one', 'yak', 'fit', 'out', 'yet', 'fin', 'owl', 'zip', 'fox',
- 'old', 'zap']
- start = random.choice(words)
- words.remove(start)
- end = random.choice(words)
- return start, end, words
- # Start of testing
- @test.describe("Example Tests")
- def test_group():
@test.it("Test Case 1")- @test.it("Valid: hit --> cog")
- def test_case_1():
beginWord = "hit"endWord = "cog"wordList = ["hot", "dot", "dog", "lot", "log", "cog"]test.assert_equals(Solution.ladderLength(beginWord, endWord, wordList), 5)- begin_word = "hit"
- end_word = "cog"
- word_list = ["hot", "dot", "dog", "lot", "log", "cog"]
- test.assert_equals(ladder_length(begin_word, end_word, word_list), 5)
@test.it("Test Case 2")- @test.it("Valid: a --> c")
- def test_case_2():
beginWord = "a"endWord = "c"wordList = ["a", "b", "c"]test.assert_equals(Solution.ladderLength(beginWord, endWord, wordList), 2)- begin_word = "a"
- end_word = "c"
- word_list = ["a", "b", "c"]
- test.assert_equals(ladder_length(begin_word, end_word, word_list), 2)
@test.it("Test Case 3")- @test.it("Valid: red --> tax")
- def test_case_3():
beginWord = "red"endWord = "tax"wordList = ["ted", "tex", "red", "tax", "tad", "den", "rex", "pee"]test.assert_equals(Solution.ladderLength(beginWord, endWord, wordList), 4)- begin_word = "red"
- end_word = "tax"
- word_list = ["ted", "tex", "red", "tax", "tad", "den", "rex", "pee"]
- test.assert_equals(ladder_length(begin_word, end_word, word_list), 4)
@test.it("Test Case 4")- @test.it("Invalid: hot --> dog")
- def test_case_4():
beginWord = "hot"endWord = "dog"wordList = ["hot", "dog"]test.assert_equals(Solution.ladderLength(beginWord, endWord, wordList), 0)- begin_word = "hot"
- end_word = "dog"
- word_list = ["hot", "dog"]
- test.assert_equals(ladder_length(begin_word, end_word, word_list), 0)
@test.it("Test Case 5")- @test.it("Invalid: a --> z")
- def test_case_5():
beginWord = "a"endWord = "z"wordList = ["b"]test.assert_equals(Solution.ladderLength(beginWord, endWord, wordList), 0)- begin_word = "a"
- end_word = "z"
- word_list = ["b"]
- test.assert_equals(ladder_length(begin_word, end_word, word_list), 0)
- @test.describe('Random Tests')
- def run_random():
- for _ in range(100):
- rand = random_words()
- @test.it(f'Testing {rand[0]} --> {rand[1]}')
- def test_random():
- test.assert_equals(ladder_length(*rand), my_ladder(*rand))
Hungarian notation is a variable naming convention that describes the type of variable within the first letter of the variable name. For more info click here. For example, if you have a variable equal to None, hungarian case would be to name this nVariable.
Write a function that will convert our variable names to use this convention. Assume that variable names are one word strings, and the value that the variable is holding is an actual value. Return a string that fits the format for the examples below:
Input: ('variable', None) -> 'nVariable'
Input: ('sTRING', ''), -> 'sString'
Input: ('Decimal', 1.0) -> 'fDecimal'
Note to others:
Not sure how much value this would have as a kata, but I think there's some potential here. I think its just not quite interesting enough. Let me know if there's some way to re-factor the challenge in a fun way!
FORK 1:
Figured out a more clever one-liner that doesn't import re.
Goal: Re-write this function as a lambda function:
def summ(*args):
numbers = 0
for x in args:
numbers += x
return numbers
Wrote tests that are assuming the input is a sequence of numbers.
summ = lambda *x : sum([i for i in x])
def summ(*args):numbers = 0for x in args:numbers += xreturn numbers- summ = lambda *x : sum([i for i in x])
import codewars_test as test from solution import summ import random mysum = lambda *x : sum([i for i in x]) @test.describe("Example Test") def test_group(): @test.it("Positive") def test_case(): test.assert_equals(summ(1, 2, 3, 4, 5), 15) test.assert_equals(summ(1.0, 2.0, 3.0, 4.0, 5.0), 15) @test.it('Negative') def test_negative(): test.assert_equals(summ(-1, -2, -3, -4, -5), -15) test.assert_equals(summ(-1.0, -2.0, -3.0, -4.0, -5.0), -15) @test.it('Mixed') def test_mixed(): test.assert_equals(summ(1, 2, -3, -4, 5), 1) test.assert_equals(summ(1.2, 2.2, -3.3, 4.0, -5), -0.8999999999999995) @test.describe('Random Integers') def test_random_int(): for _ in range(50): start = random.randrange(0, 100) * random.choice([1, -1]) end = random.randrange(start, 10000) * random.choice([1, -1]) gen = tuple(i for i in range(start, end)) @test.it(f'Testing range({start}, {end})') def test_int(): test.assert_equals(summ(*gen), mysum(*gen)) @test.describe('Random Floats') def test_random_float(): for _ in range(50): start = random.randrange(0, 100) * random.choice([1, -1]) end = random.randrange(start, 10000) * random.choice([1, -1]) gen = tuple(i + random.random() for i in range(start, end)) @test.it(f'Testing range({start}, {end})') def test_int(): test.assert_equals(summ(*gen), mysum(*gen))
- import codewars_test as test
# TODO Write testsimport solution # or from solution import example- from solution import summ
- import random
# test.assert_equals(actual, expected, [optional] message)@test.describe("Example")- mysum = lambda *x : sum([i for i in x])
- @test.describe("Example Test")
- def test_group():
@test.it("test case")- @test.it("Positive")
- def test_case():
test.assert_equals(1 + 1, 2)- test.assert_equals(summ(1, 2, 3, 4, 5), 15)
- test.assert_equals(summ(1.0, 2.0, 3.0, 4.0, 5.0), 15)
- @test.it('Negative')
- def test_negative():
- test.assert_equals(summ(-1, -2, -3, -4, -5), -15)
- test.assert_equals(summ(-1.0, -2.0, -3.0, -4.0, -5.0), -15)
- @test.it('Mixed')
- def test_mixed():
- test.assert_equals(summ(1, 2, -3, -4, 5), 1)
- test.assert_equals(summ(1.2, 2.2, -3.3, 4.0, -5), -0.8999999999999995)
- @test.describe('Random Integers')
- def test_random_int():
- for _ in range(50):
- start = random.randrange(0, 100) * random.choice([1, -1])
- end = random.randrange(start, 10000) * random.choice([1, -1])
- gen = tuple(i for i in range(start, end))
- @test.it(f'Testing range({start}, {end})')
- def test_int():
- test.assert_equals(summ(*gen), mysum(*gen))
- @test.describe('Random Floats')
- def test_random_float():
- for _ in range(50):
- start = random.randrange(0, 100) * random.choice([1, -1])
- end = random.randrange(start, 10000) * random.choice([1, -1])
- gen = tuple(i + random.random() for i in range(start, end))
- @test.it(f'Testing range({start}, {end})')
- def test_int():
- test.assert_equals(summ(*gen), mysum(*gen))
Write a function that returns the fibonacci sequence starting at 1, and ending at the first number greater than n inclusive, with the sum of the sequence as a tuple. Assume all inputs are positive integers.
def fibthing(make=int): fibseq = [] while max(fibseq, default=0) < make: if len(fibseq) > 1: fibseq.append(fibseq[-1] + fibseq[-2]) else: fibseq.append(1) return fibseq, sum(fibseq)
- def fibthing(make=int):
- fibseq = []
n1 = 0n2 = 1cur = 0sum = 0while cur < make:fibseq.append(n2)cur = n2n2 = n1 + curn1 = curfor i in fibseq:sum += ireturn fibseq, sum- while max(fibseq, default=0) < make:
- if len(fibseq) > 1:
- fibseq.append(fibseq[-1] + fibseq[-2])
- else:
- fibseq.append(1)
- return fibseq, sum(fibseq)
import codewars_test as test from solution import fibthing import random def myfib(n): seq = [] while max(seq, default=0) < n: if len(seq) > 1: seq.append(seq[-1] + seq[-2]) else: seq.append(1) return seq, sum(seq) @test.describe("Base") def test_group(): @test.it("Base Cases") def test_case(): test.assert_equals(fibthing(199218), ([1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811], 832039)) test.assert_equals(fibthing(199), ([1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233], 609)) test.assert_equals(fibthing(55), ([1, 1, 2, 3, 5, 8, 13, 21, 34, 55], 143)) @test.it("Edge Cases") def edge_case(): test.assert_equals(fibthing(1), ([1], 1)) test.assert_equals(fibthing(2), ([1, 1, 2], 4)) @test.describe("Random") def random_group(): for _ in range(100): num = random.randrange(0, 1000000) @test.it(str(num)) def test_random(): test.assert_equals(fibthing(num), myfib(num))
- import codewars_test as test
# TODO Write testsfrom solution import fibthing# or from solution import example- from solution import fibthing
- import random
- def myfib(n):
- seq = []
- while max(seq, default=0) < n:
- if len(seq) > 1: seq.append(seq[-1] + seq[-2])
- else: seq.append(1)
- return seq, sum(seq)
# test.assert_equals(actual, expected, [optional] message)- @test.describe("Base")
- def test_group():
- @test.it("Base Cases")
- def test_case():
- test.assert_equals(fibthing(199218), ([1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811], 832039))
- test.assert_equals(fibthing(199), ([1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233], 609))
test.assert_equals(fibthing(55), ([1, 1, 2, 3, 5, 8, 13, 21, 34, 55], 143))- test.assert_equals(fibthing(55), ([1, 1, 2, 3, 5, 8, 13, 21, 34, 55], 143))
- @test.it("Edge Cases")
- def edge_case():
- test.assert_equals(fibthing(1), ([1], 1))
- test.assert_equals(fibthing(2), ([1, 1, 2], 4))
- @test.describe("Random")
- def random_group():
- for _ in range(100):
- num = random.randrange(0, 1000000)
- @test.it(str(num))
- def test_random():
- test.assert_equals(fibthing(num), myfib(num))
Goal: You have to print the string n times if a is True.
(added some tests, and a working function for the previous task you described. Not exactly sure what the goal is, so I just had it return the string + newline for n lines.)
def print_n(string, n, a): if isinstance(a, bool) and a is True: for _ in range(n): print(string) return '\n'.join([string for _ in range(n)]) return None
a = Trueif a == True:print("hi")- def print_n(string, n, a):
- if isinstance(a, bool) and a is True:
- for _ in range(n): print(string)
- return '\n'.join([string for _ in range(n)])
- return None
import codewars_test as test from solution import print_n import random # Working solution def my_print(string, n, a): if isinstance(a, bool) and a is True: return '\n'.join([string for _ in range(n)]) return None # Random greetings + random number + random true or false def get_random(): words = [ 'Hello', 'Hi', 'Hey', 'Greetings', 'Salutations', 'Howdy', 'Aloha', 'Hola', 'Bonjour', 'Ciao', 'Namaste', 'Salaam', 'Shalom', 'Konnichiwa', 'Ahoy', 'Sup', 'Yo', 'Good morning', 'Good afternoon', 'Good evening', 'Welcome', "How's it going?", "What's up?", 'How are you?', 'Nice to meet you', 'Pleasure to meet you', "How's everything?", 'Long time no see', 'Hey there, stranger', "What's the good word?", 'How have you been?', "How's your day?", 'Top of the morning to you', "How's life treating you?", "How's your day going?", "What's new?", "How's your week been?", "How's your family?", "It's been a while", 'Hey, buddy', "How's the weather?", "How's your health?", "How's your job?", "How's your weekend?", "How's your vacation?", "How's your trip?", "How's your project?", "How's your study?", "How's your hobby?", "How's your game?" ] selection = random.choice(words) num = random.randrange(0, 50) truth = random.randrange(10000, 100000) % 2 == 0 return (selection, num, truth) @test.describe("Example Tests") def test_group(): @test.it("Test with A = True") def test_true(): test.assert_equals(print_n('Hello', 1, True), 'Hello') test.assert_equals(print_n('.', 3, True), '.\n.\n.') test.assert_equals(print_n('hi', 9, True), 'hi\nhi\nhi\nhi\nhi\nhi\nhi\nhi\nhi') test.assert_equals(print_n('Nothing', 0, True), '') @test.it("Test with A = False") def test_false(): test.assert_equals(print_n('Hello', 1, False), None) test.assert_equals(print_n('.', 3, 0), None) test.assert_equals(print_n('hi', 9, 'True'), None) @test.describe('Random Tests') def test_random(): for _ in range(50): s, n, a = get_random() @test.it(f'String: {s} | Num: {n} | A: {a}') def test_rand(): test.assert_equals(print_n(s,n,a), my_print(s,n,a))
- import codewars_test as test
# TODO Write testsimport solution # or from solution import example- from solution import print_n
- import random
# test.assert_equals(actual, expected, [optional] message)@test.describe("Example")- # Working solution
- def my_print(string, n, a):
- if isinstance(a, bool) and a is True:
- return '\n'.join([string for _ in range(n)])
- return None
- # Random greetings + random number + random true or false
- def get_random():
- words = [
- 'Hello', 'Hi', 'Hey', 'Greetings', 'Salutations', 'Howdy', 'Aloha', 'Hola', 'Bonjour',
- 'Ciao', 'Namaste', 'Salaam', 'Shalom', 'Konnichiwa', 'Ahoy', 'Sup', 'Yo', 'Good morning',
- 'Good afternoon', 'Good evening', 'Welcome', "How's it going?", "What's up?", 'How are you?',
- 'Nice to meet you', 'Pleasure to meet you', "How's everything?", 'Long time no see',
- 'Hey there, stranger', "What's the good word?", 'How have you been?', "How's your day?",
- 'Top of the morning to you', "How's life treating you?", "How's your day going?", "What's new?",
- "How's your week been?", "How's your family?", "It's been a while", 'Hey, buddy', "How's the weather?",
- "How's your health?", "How's your job?", "How's your weekend?", "How's your vacation?", "How's your trip?",
- "How's your project?", "How's your study?", "How's your hobby?", "How's your game?"
- ]
- selection = random.choice(words)
- num = random.randrange(0, 50)
- truth = random.randrange(10000, 100000) % 2 == 0
- return (selection, num, truth)
- @test.describe("Example Tests")
- def test_group():
@test.it("test case")def test_case():test.assert_equals(1 + 1, 2)- @test.it("Test with A = True")
- def test_true():
- test.assert_equals(print_n('Hello', 1, True), 'Hello')
- test.assert_equals(print_n('.', 3, True), '.\n.\n.')
- test.assert_equals(print_n('hi', 9, True), 'hi\nhi\nhi\nhi\nhi\nhi\nhi\nhi\nhi')
- test.assert_equals(print_n('Nothing', 0, True), '')
- @test.it("Test with A = False")
- def test_false():
- test.assert_equals(print_n('Hello', 1, False), None)
- test.assert_equals(print_n('.', 3, 0), None)
- test.assert_equals(print_n('hi', 9, 'True'), None)
- @test.describe('Random Tests')
- def test_random():
- for _ in range(50):
- s, n, a = get_random()
- @test.it(f'String: {s} | Num: {n} | A: {a}')
- def test_rand():
- test.assert_equals(print_n(s,n,a), my_print(s,n,a))