From f93e1618cd177faeffb26fb49a987c8dda7ab578 Mon Sep 17 00:00:00 2001 From: Radoslaw Tomaszeski Date: Wed, 21 Feb 2018 09:31:06 +0100 Subject: [PATCH 1/2] added files --- .gitignore | 197 ++++++++++++++++++ .idea/Checkio.iml | 11 + .../inspectionProfiles/profiles_settings.xml | 7 + .idea/misc.xml | 4 + .idea/modules.xml | 8 + .idea/vcs.xml | 6 + absolute-sorting.py | 17 ++ all-the-same.py | 19 ++ best-stock.py | 25 +++ between-markers.py | 42 ++++ bigger-price.py | 37 ++++ black-holes.py | 21 ++ brackets.py | 34 +++ building-base.py | 37 ++++ cipher-map2.py | 37 ++++ correct-sentence.py | 27 +++ currency-style.py | 35 ++++ days-diff.py | 16 ++ digits-multiplication.py | 16 ++ easy-unpack.py | 12 ++ even-last.py | 13 ++ find-sequence.py | 57 +++++ first-word.py | 24 +++ fizz-buzz.py | 27 +++ hamming-distance2.py | 27 +++ house-password.py | 21 ++ index-power.py | 16 ++ long-repeat.py | 27 +++ median.py | 17 ++ min-max.py | 23 ++ monkey-typing.py | 20 ++ most-numbers.py | 17 ++ most-wanted-letter.py | 43 ++++ non-unique-elements.py | 21 ++ number-factory.py | 32 +++ number-radix.py | 16 ++ pawn-brotherhood.py | 17 ++ popular-words.py | 30 +++ right-to-left.py | 16 ++ roman-numerals.py | 33 +++ say-history.py | 15 ++ second-index.py | 26 +++ secret-message.py | 11 + striped-words.py | 47 +++++ the-longest-palindromic.py | 38 ++++ the-most-frequent.py | 24 +++ three-words.py | 29 +++ x-o-referee.py | 45 ++++ 48 files changed, 1340 insertions(+) create mode 100644 .gitignore create mode 100644 .idea/Checkio.iml create mode 100644 .idea/inspectionProfiles/profiles_settings.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/vcs.xml create mode 100644 absolute-sorting.py create mode 100644 all-the-same.py create mode 100644 best-stock.py create mode 100644 between-markers.py create mode 100644 bigger-price.py create mode 100644 black-holes.py create mode 100644 brackets.py create mode 100644 building-base.py create mode 100644 cipher-map2.py create mode 100644 correct-sentence.py create mode 100644 currency-style.py create mode 100644 days-diff.py create mode 100644 digits-multiplication.py create mode 100644 easy-unpack.py create mode 100644 even-last.py create mode 100644 find-sequence.py create mode 100644 first-word.py create mode 100644 fizz-buzz.py create mode 100644 hamming-distance2.py create mode 100644 house-password.py create mode 100644 index-power.py create mode 100644 long-repeat.py create mode 100644 median.py create mode 100644 min-max.py create mode 100644 monkey-typing.py create mode 100644 most-numbers.py create mode 100644 most-wanted-letter.py create mode 100644 non-unique-elements.py create mode 100644 number-factory.py create mode 100644 number-radix.py create mode 100644 pawn-brotherhood.py create mode 100644 popular-words.py create mode 100644 right-to-left.py create mode 100644 roman-numerals.py create mode 100644 say-history.py create mode 100644 second-index.py create mode 100644 secret-message.py create mode 100644 striped-words.py create mode 100644 the-longest-palindromic.py create mode 100644 the-most-frequent.py create mode 100644 three-words.py create mode 100644 x-o-referee.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..520de46 --- /dev/null +++ b/.gitignore @@ -0,0 +1,197 @@ + +# Created by https://www.gitignore.io/api/osx,pycharm,python + +### OSX ### +*.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### PyCharm ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff: +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/dictionaries + +# Sensitive or high-churn files: +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.xml +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml + +# Gradle: +.idea/**/gradle.xml +.idea/**/libraries + +# CMake +cmake-build-debug/ + +# Mongo Explorer plugin: +.idea/**/mongoSettings.xml + +## File-based project format: +*.iws + +## Plugin-specific files: + +# IntelliJ +/out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Ruby plugin and RubyMine +/.rakeTasks + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +### PyCharm Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +# *.iml +# modules.xml +# .idea/misc.xml +# *.ipr + +# Sonarlint plugin +.idea/sonarlint + +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +.pytest_cache/ +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule.* + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + + +# End of https://www.gitignore.io/api/osx,pycharm,python diff --git a/.idea/Checkio.iml b/.idea/Checkio.iml new file mode 100644 index 0000000..6711606 --- /dev/null +++ b/.idea/Checkio.iml @@ -0,0 +1,11 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000..c23ecac --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,7 @@ + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..517284e --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..f0ad1f7 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/absolute-sorting.py b/absolute-sorting.py new file mode 100644 index 0000000..6e97d20 --- /dev/null +++ b/absolute-sorting.py @@ -0,0 +1,17 @@ +def checkio(numbers_array): + + numbers_array = sorted(numbers_array, key=abs) + + return numbers_array + +#These "asserts" using only for self-checking and not necessary for auto-testing +if __name__ == '__main__': + def check_it(array): + if not isinstance(array, (list, tuple)): + raise TypeError("The result should be a list or tuple.") + return list(array) + + assert check_it(checkio((-20, -5, 10, 15))) == [-5, 10, 15, -20], "Example" # or (-5, 10, 15, -20) + assert check_it(checkio((1, 2, 3, 0))) == [0, 1, 2, 3], "Positive numbers" + assert check_it(checkio((-1, -2, -3, 0))) == [0, -1, -2, -3], "Negative numbers" + print("Coding complete? Click 'Check' to review your tests and earn cool rewards!") diff --git a/all-the-same.py b/all-the-same.py new file mode 100644 index 0000000..66fb391 --- /dev/null +++ b/all-the-same.py @@ -0,0 +1,19 @@ +from typing import List, Any + + +def all_the_same(elements: List[Any]) -> bool: + + return all(elements[i] == elements[i+1] for i in range(len(elements)-1)) + + +if __name__ == '__main__': + print("Example:") + print(all_the_same([1, 1, 1])) + + # These "asserts" are used for self-checking and not for an auto-testing + assert all_the_same([1, 1, 1]) == True + assert all_the_same([1, 2, 1]) == False + assert all_the_same(['a', 'a', 'a']) == True + assert all_the_same([]) == True + assert all_the_same([1]) == True + print("Coding complete? Click 'Check' to earn cool rewards!") diff --git a/best-stock.py b/best-stock.py new file mode 100644 index 0000000..daee931 --- /dev/null +++ b/best-stock.py @@ -0,0 +1,25 @@ +def best_stock(data): + + return max(data, key=data.get) + + +if __name__ == '__main__': + print("Example:") + print(best_stock({ + 'CAC': 10.0, + 'ATX': 390.2, + 'WIG': 1.2 + })) + + # These "asserts" are used for self-checking and not for an auto-testing + assert best_stock({ + 'CAC': 10.0, + 'ATX': 390.2, + 'WIG': 1.2 + }) == 'ATX', "First" + assert best_stock({ + 'CAC': 91.1, + 'ATX': 1.01, + 'TASI': 120.9 + }) == 'TASI', "Second" + print("Coding complete? Click 'Check' to earn cool rewards!") diff --git a/between-markers.py b/between-markers.py new file mode 100644 index 0000000..53fc64c --- /dev/null +++ b/between-markers.py @@ -0,0 +1,42 @@ +def between_markers(text: str, begin: str, end: str) -> str: + """ + returns substring between two given markers + """ + try: + idb = text.index(begin) + len(begin) + except ValueError: + idb = None + try: + ide = text.index(end) + except ValueError: + ide = None + + + if idb is None and ide is None: + return text + + if idb == None and ide: + return text[:ide] + elif ide == None and idb: + return text[idb:] + elif ide > idb: + return text[idb:ide] + else: + return '' + + + + +if __name__ == '__main__': + print('Example:') + print(between_markers('What is >apple<', '>', '<')) + + # These "asserts" are used for self-checking and not for testing + assert between_markers('What is >apple<', '>', '<') == "apple", "One sym" + assert between_markers("My new site", + "", "") == "My new site", "HTML" + assert between_markers('No[/b] hi', '[b]', '[/b]') == 'No', 'No opened' + assert between_markers('No [b]hi', '[b]', '[/b]') == 'hi', 'No close' + assert between_markers('No hi', '[b]', '[/b]') == 'No hi', 'No markers at all' + assert between_markers('No ', '>', '<') == '', 'Wrong direction' + print('Wow, you are doing pretty good. Time to check it!') diff --git a/bigger-price.py b/bigger-price.py new file mode 100644 index 0000000..e416aaf --- /dev/null +++ b/bigger-price.py @@ -0,0 +1,37 @@ +def bigger_price(limit, data): + """ + TOP most expensive goods + """ + l = (sorted(data, key=lambda x: x['price'], reverse=True)) + + return l[:limit] + + + +if __name__ == '__main__': + from pprint import pprint + print('Example:') + pprint(bigger_price(2, [ + {"name": "bread", "price": 100}, + {"name": "wine", "price": 138}, + {"name": "meat", "price": 15}, + {"name": "water", "price": 1} + ])) + + # These "asserts" using for self-checking and not for auto-testing + assert bigger_price(2, [ + {"name": "bread", "price": 100}, + {"name": "wine", "price": 138}, + {"name": "meat", "price": 15}, + {"name": "water", "price": 1} + ]) == [ + {"name": "wine", "price": 138}, + {"name": "bread", "price": 100} + ], "First" + + assert bigger_price(1, [ + {"name": "pen", "price": 5}, + {"name": "whiteboard", "price": 170} + ]) == [{"name": "whiteboard", "price": 170}], "Second" + + print('Done! Looks like it is fine. Go and check it') diff --git a/black-holes.py b/black-holes.py new file mode 100644 index 0000000..772a2ac --- /dev/null +++ b/black-holes.py @@ -0,0 +1,21 @@ +def checkio(data): + + d = data[0][2] - data[1][2] + + print(d) + + if d > data[0][2] + data[1][2]: + return data + elif d < abs(data[0][2] - data[1][2]): + return data + elif + + + + +if __name__ == '__main__': + # These "asserts" using only for self-checking and not necessary for auto-testing + assert checkio([(2, 4, 2), (3, 9, 3)]) == [(2, 4, 2), (3, 9, 3)] + assert checkio([(0, 0, 2), (-1, 0, 2)]) == [(0, 0, 2), (-1, 0, 2)] + assert checkio([(4, 3, 2), (2.5, 3.5, 1.4)]) == [(4, 3, 2.44)] + assert checkio([(3, 3, 3), (2, 2, 1), (3, 5, 1.5)]) == [(3, 3, 3.5)] diff --git a/brackets.py b/brackets.py new file mode 100644 index 0000000..ae28c58 --- /dev/null +++ b/brackets.py @@ -0,0 +1,34 @@ +def checkio(expression): + d = {'(': ')', '{': '}', '[': ']'} + stack = [] + + for i in expression: + if i in "({[": + stack.append(i) + elif i in ")}]": + if len(stack) > 0: + if i != d[stack.pop()]: + return False + else: + return False + if len(stack) > 0: + return False + return True + + + + + + + + +#These "asserts" using only for self-checking and not necessary for auto-testing +if __name__ == '__main__': + assert checkio("(((1+(1+1))))]") == False, 'idk' + assert checkio("((5+3)*2+1)") == True, "Simple" + assert checkio("{[(3+1)+2]+}") == True, "Different types" + assert checkio("(3+{1-1)}") == False, ") is alone inside {}" + assert checkio("[1+1]+(2*2)-{3/3}") == True, "Different operators" + assert checkio("(({[(((1)-2)+3)-3]/3}-3)") == False, "One is redundant" + assert checkio("2+3") == True, "No brackets, no problem" + diff --git a/building-base.py b/building-base.py new file mode 100644 index 0000000..13465b1 --- /dev/null +++ b/building-base.py @@ -0,0 +1,37 @@ +class Building: + def __init__(self, south, west, width_WE, width_NS, height=10): + self.south = south + self.west = west + self.widthWE = width_WE + self.widthNS = width_NS + self.height = height + + def corners(self): + return {'north-west': [self.south + self.widthNS, self.west], + 'north-east': [self.south + self.widthNS, self.west + self.widthWE], + 'south-west': [self.south, self.west], + 'south-east': [self.south, self.west + self.widthWE]} + + def area(self): + return round(self.widthWE*self.widthNS, 2) + + def volume(self): + return round(self.area()*self.height, 2) + + def __repr__(self): + return "Building({}, {}, {}, {}, {})".format(self.south, self.west, self.widthWE, self.widthNS, self.height) + + +if __name__ == '__main__': + #These "asserts" using only for self-checking and not necessary for auto-testing + def json_dict(d): + return dict((k, list(v)) for k, v in d.items()) + + b = Building(1, 2, 2, 3) + b2 = Building(1, 2, 2, 3, 5) + assert json_dict(b.corners()) == {'north-east': [4, 4], 'south-east': [1, 4], + 'south-west': [1, 2], 'north-west': [4, 2]}, "Corners" + assert b.area() == 6, "Area" + assert b.volume() == 60, "Volume" + assert b2.volume() == 30, "Volume2" + assert str(b) == "Building(1, 2, 2, 3, 10)", "String" diff --git a/cipher-map2.py b/cipher-map2.py new file mode 100644 index 0000000..e8c27c1 --- /dev/null +++ b/cipher-map2.py @@ -0,0 +1,37 @@ +def rotate_matrix(matrix): + return list(zip(*matrix[::-1])) + + +def recall_password(cipher_grille, ciphered_password): + result = '' + + for n in range(4): + for i in range(len(ciphered_password)): + for j in range(len(ciphered_password)): + if cipher_grille[i][j] == 'X': + result += ciphered_password[i][j] + cipher_grille = rotate_matrix(cipher_grille) + + return result + +if __name__ == '__main__': + #These "asserts" using only for self-checking and not necessary for auto-testing + assert recall_password( + ('X...', + '..X.', + 'X..X', + '....'), + ('itdf', + 'gdce', + 'aton', + 'qrdi')) == 'icantforgetiddqd', 'First example' + + assert recall_password( + ('....', + 'X..X', + '.X..', + '...X'), + ('xhwc', + 'rsqx', + 'xqzz', + 'fyzr')) == 'rxqrwsfzxqxzhczy', 'Second example' diff --git a/correct-sentence.py b/correct-sentence.py new file mode 100644 index 0000000..dd7c321 --- /dev/null +++ b/correct-sentence.py @@ -0,0 +1,27 @@ +def correct_sentence(text: str) -> str: + """ + returns a corrected sentence which starts with a capital letter + and ends with a dot. + """ + + if text[-1] != '.': + text += '.' + + tempChar = text[0] + + if text[0] != tempChar.upper(): + text = tempChar.upper() + text[1:] + + return text + + +if __name__ == '__main__': + print("Example:") + print(correct_sentence("greetings, friends")) + + # These "asserts" are used for self-checking and not for an auto-testing + assert correct_sentence("greetings, friends") == "Greetings, friends." + assert correct_sentence("Greetings, friends") == "Greetings, friends." + assert correct_sentence("Greetings, friends.") == "Greetings, friends." + assert correct_sentence("hi") == "Hi." + print("Coding complete? Click 'Check' to earn cool rewards!") diff --git a/currency-style.py b/currency-style.py new file mode 100644 index 0000000..58d31ca --- /dev/null +++ b/currency-style.py @@ -0,0 +1,35 @@ +def checkio(text): + + words = text.split(' ') + + result = [] + + for word in words: + if word.startswith('$'): + if word.endswith('.') or word.endswith(','): + front = word[:-4].replace('.', ',') + back = word[-4:-1].replace(',', '.', 1) + rest = word[-1] + new_word = front + back + rest + else: + front = word[:-3].replace('.', ',') + back = word[-3:].replace(',', '.', 1) + new_word = front + back + # print(new_word) + result.append(new_word) + else: + result.append(word) + + return ' '.join(result) + +if __name__ == '__main__': + + #These "asserts" using only for self-checking and not necessary for auto-testing + assert checkio("$1.234.567,89") == "$1,234,567.89", "1st Example" + assert checkio("$0,89") == "$0.89", "2nd Example" + assert checkio("Euro Style = $12.345,67, US Style = $12,345.67") == \ + "Euro Style = $12,345.67, US Style = $12,345.67" , "European and US" + assert checkio("Us Style = $12,345.67, Euro Style = $12.345,67") == \ + "Us Style = $12,345.67, Euro Style = $12,345.67" , "US and European" + assert checkio("$1.234, $5.678 and $9") == \ + "$1,234, $5,678 and $9", "Dollars without cents" diff --git a/days-diff.py b/days-diff.py new file mode 100644 index 0000000..585bdc5 --- /dev/null +++ b/days-diff.py @@ -0,0 +1,16 @@ +from datetime import datetime + +def days_diff(date1, date2): + """ + Find absolute diff in days between dates + """ + d1 = datetime(*date1) + d2 = datetime(*date2) + + return abs((d2-d1).days) + +if __name__ == '__main__': + #These "asserts" using only for self-checking and not necessary for auto-testing + assert days_diff((1982, 4, 19), (1982, 4, 22)) == 3 + assert days_diff((2014, 1, 1), (2014, 8, 27)) == 238 + assert days_diff((2014, 8, 27), (2014, 1, 1)) == 238 diff --git a/digits-multiplication.py b/digits-multiplication.py new file mode 100644 index 0000000..f2a9d7d --- /dev/null +++ b/digits-multiplication.py @@ -0,0 +1,16 @@ +def checkio(number): + result = 1 + + for i in str(number): + if i != '0': + result *= int(i) + + return result + +#These "asserts" using only for self-checking and not necessary for auto-testing +if __name__ == '__main__': + assert checkio(123405) == 120 + assert checkio(999) == 729 + assert checkio(1000) == 1 + assert checkio(1111) == 1 + print("Coding complete? Click 'Check' to review your tests and earn cool rewards!") diff --git a/easy-unpack.py b/easy-unpack.py new file mode 100644 index 0000000..c75cff5 --- /dev/null +++ b/easy-unpack.py @@ -0,0 +1,12 @@ +def easy_unpack(elements): + """ + returns a tuple with 3 elements - first, third and second to the last + """ + return (elements[0], elements[2], elements[-2]) + +if __name__ == '__main__': + #These "asserts" using only for self-checking and not necessary for auto-testing + assert easy_unpack((1, 2, 3, 4, 5, 6, 7, 9)) == (1, 3, 7) + assert easy_unpack((1, 1, 1, 1)) == (1, 1, 1) + assert easy_unpack((6, 3, 7)) == (6, 7, 3) + print('Done! Go Check!') diff --git a/even-last.py b/even-last.py new file mode 100644 index 0000000..0006e0c --- /dev/null +++ b/even-last.py @@ -0,0 +1,13 @@ +def checkio(array): + """ + sums even-indexes elements and multiply at the last + """ + return sum([array[i] for i in range(0, len(array), 2)]) * array[-1] if len(array) > 0 else 0 + +#These "asserts" using only for self-checking and not necessary for auto-testing +if __name__ == '__main__': + assert checkio([0, 1, 2, 3, 4, 5]) == 30, "(0+2+4)*5=30" + assert checkio([1, 3, 5]) == 30, "(1+5)*5=30" + assert checkio([6]) == 36, "(6)*6=36" + assert checkio([]) == 0, "An empty array = 0" + print("Coding complete? Click 'Check' to review your tests and earn cool rewards!") diff --git a/find-sequence.py b/find-sequence.py new file mode 100644 index 0000000..a825052 --- /dev/null +++ b/find-sequence.py @@ -0,0 +1,57 @@ +def iterate_submatrix(matrix): + submat = [row for row in matrix] + for r in submat: + yield tuple(r) + for c in range(0, len(matrix[0])): + yield tuple(r[c] for r in submat) + yield tuple(submat[rc][rc] for rc in range(0, len(matrix[0]))) + yield tuple(submat[rc][len(matrix[0])-1-rc] for rc in range(0, len(matrix[0]))) + for r in range(1, len(matrix)-3): + yield tuple(submat[rc+r][rc] for rc in range(0, len(matrix[0])-r)) + for c in range(1, len(matrix)-3): + yield tuple(submat[rc][rc+c] for rc in range(0, len(matrix[0])-c)) + for r in range(1, len(matrix) - 3): + yield tuple(submat[rc+r][len(matrix[0])-1-rc] for rc in range(0, len(matrix[0])-r)) + for c in range(1, len(matrix) - 3): + yield tuple(submat[rc][len(matrix[0])-1-rc-c] for rc in range(0, len(matrix[0])-c)) + + +def checkio(matrix): + + for item in iterate_submatrix(matrix): + # print(item) + for i in range(len(item)-3): + if item[i] == item[i+1] == item[i+2] == item[i+3]: + return True + return False + + +if __name__ == '__main__': + #These "asserts" using only for self-checking and not necessary for auto-testing + assert checkio([ + [1, 2, 1, 1], + [1, 1, 4, 1], + [1, 3, 1, 6], + [1, 7, 2, 5] + ]) == True, "Vertical" + assert checkio([ + [7, 1, 4, 1], + [1, 2, 5, 2], + [3, 4, 1, 3], + [1, 1, 8, 1] + ]) == False, "Nothing here" + assert checkio([ + [2, 1, 1, 6, 1], + [1, 3, 2, 1, 1], + [4, 1, 1, 3, 1], + [5, 5, 5, 5, 5], + [1, 1, 3, 1, 1] + ]) == True, "Long Horizontal" + assert checkio([ + [7, 1, 1, 8, 1, 1], + [1, 1, 7, 3, 1, 5], + [2, 3, 1, 2, 5, 1], + [1, 1, 1, 5, 1, 4], + [4, 6, 5, 1, 3, 1], + [1, 1, 9, 1, 2, 1] + ]) == True, "Diagonal" diff --git a/first-word.py b/first-word.py new file mode 100644 index 0000000..b4be3c4 --- /dev/null +++ b/first-word.py @@ -0,0 +1,24 @@ +def first_word(text: str) -> str: + """ + returns the first word in a given text. + """ + text = text.replace(',', ' ') + text = text.replace('.', ' ') + + text = text.split() + + return text[0] + + +if __name__ == '__main__': + print("Example:") + print(first_word("Hello world")) + + # These "asserts" are used for self-checking and not for an auto-testing + assert first_word("Hello world") == "Hello" + assert first_word(" a word ") == "a" + assert first_word("don't touch it") == "don't" + assert first_word("greetings, friends") == "greetings" + assert first_word("... and so on ...") == "and" + assert first_word("hi") == "hi" + print("Coding complete? Click 'Check' to earn cool rewards!") diff --git a/fizz-buzz.py b/fizz-buzz.py new file mode 100644 index 0000000..1d8b96f --- /dev/null +++ b/fizz-buzz.py @@ -0,0 +1,27 @@ +#Your optional code here +#You can import some modules or create additional functions + + +def checkio(number): + result = '' + if number%3 == 0and number%5 == 0: + result += 'Fizz Buzz' + elif number%3 == 0: + result += 'Fizz' + elif number%5 == 0: + result += 'Buzz' + else: + result += str(number) + + return result + +#Some hints: +#Convert a number in the string with str(n) + +#These "asserts" using only for self-checking and not necessary for auto-testing +if __name__ == '__main__': + assert checkio(15) == "Fizz Buzz", "15 is divisible by 3 and 5" + assert checkio(6) == "Fizz", "6 is divisible by 3" + assert checkio(5) == "Buzz", "5 is divisible by 5" + assert checkio(7) == "7", "7 is not divisible by 3 or 5" + print("Coding complete? Click 'Check' to review your tests and earn cool rewards!") diff --git a/hamming-distance2.py b/hamming-distance2.py new file mode 100644 index 0000000..ca42cd1 --- /dev/null +++ b/hamming-distance2.py @@ -0,0 +1,27 @@ +def checkio(n, m): + bin1 = '0{0:b}'.format(n) + bin2 = '0{0:b}'.format(m) + + if len(bin1) < len(bin2): + temp = '0' * (len(bin2) - len(bin1)) + + bin1 = temp + bin1 + elif len(bin1) > len(bin2): + temp = '0' * (len(bin1) - len(bin2)) + + bin2 = temp + bin2 + + result = [i != j for i, j in zip(bin1, bin2)] + + + cnt = 0 + for i in result: + if i: + cnt += 1 + return cnt + +if __name__ == '__main__': + #These "asserts" using only for self-checking and not necessary for auto-testing + assert checkio(117, 17) == 3, "First example" + assert checkio(1, 2) == 2, "Second example" + assert checkio(16, 15) == 5, "Third example" diff --git a/house-password.py b/house-password.py new file mode 100644 index 0000000..debdbea --- /dev/null +++ b/house-password.py @@ -0,0 +1,21 @@ +def checkio(data): + if len(data) >= 10: + if any(i.isupper() for i in data) and any(i.islower() for i in data) and any( i.isnumeric() for i in data): + return True + else: + return False + else: + return False +#Some hints +#Just check all conditions + + +if __name__ == '__main__': + #These "asserts" using only for self-checking and not necessary for auto-testing + assert checkio('A1213pokl') == False, "1st example" + assert checkio('bAse730onE4') == True, "2nd example" + assert checkio('asasasasasasasaas') == False, "3rd example" + assert checkio('QWERTYqwerty') == False, "4th example" + assert checkio('123456123456') == False, "5th example" + assert checkio('QwErTy911poqqqq') == True, "6th example" + print("Coding complete? Click 'Check' to review your tests and earn cool rewards!") diff --git a/index-power.py b/index-power.py new file mode 100644 index 0000000..aae6161 --- /dev/null +++ b/index-power.py @@ -0,0 +1,16 @@ +def index_power(array, n): + """ + Find Nth power of the element with index N. + """ + if n < len(array): + return array[n]**n + else: + return -1 + +if __name__ == '__main__': + #These "asserts" using only for self-checking and not necessary for auto-testing + assert index_power([1, 2, 3, 4], 2) == 9, "Square" + assert index_power([1, 3, 10, 100], 3) == 1000000, "Cube" + assert index_power([0, 1], 0) == 1, "Zero power" + assert index_power([1, 2], 3) == -1, "IndexError" + print("Coding complete? Click 'Check' to review your tests and earn cool rewards!") diff --git a/long-repeat.py b/long-repeat.py new file mode 100644 index 0000000..2533f41 --- /dev/null +++ b/long-repeat.py @@ -0,0 +1,27 @@ +def long_repeat(line): + """ + length the longest substring that consists of the same char + """ + + if len(line) == 0: + return 0 + + cnt = 1 + tempCnt = 1 + char = line[0] + for i in range(1, len(line)): + if char == line[i]: + tempCnt += 1 + else: + char = line[i] + tempCnt = 1 + if cnt < tempCnt: + cnt = tempCnt + return cnt + + +if __name__ == '__main__': + #These "asserts" using only for self-checking and not necessary for auto-testing + assert long_repeat('sdsffffse') == 4, "First" + assert long_repeat('ddvvrwwwrggg') == 3, "Second" + print('"Run" is good. How is "Check"?') diff --git a/median.py b/median.py new file mode 100644 index 0000000..4ceb1ec --- /dev/null +++ b/median.py @@ -0,0 +1,17 @@ +def checkio(data): + data = sorted(data) + + if len(data)%2 != 0: + return data[len(data)//2] + else: + return (data[len(data)//2] + data[len(data)//2 - 1])/2 + +#These "asserts" using only for self-checking and not necessary for auto-testing +if __name__ == '__main__': + assert checkio([1, 2, 3, 4, 5]) == 3, "Sorted list" + assert checkio([3, 1, 2, 5, 3]) == 3, "Not sorted list" + assert checkio([1, 300, 2, 200, 1]) == 2, "It's not an average" + assert checkio([3, 6, 20, 99, 10, 15]) == 12.5, "Even length" + print("Start the long test") + assert checkio(list(range(1000000))) == 499999.5, "Long." + print("The local tests are done.") \ No newline at end of file diff --git a/min-max.py b/min-max.py new file mode 100644 index 0000000..1ba3949 --- /dev/null +++ b/min-max.py @@ -0,0 +1,23 @@ +def min(*args, key=None): + if len(args) == 1: + return sorted(iter(args[0]), key=key, reverse=False)[0] + elif len(args) > 1: + return sorted(args, key=key, reverse=False)[0] + +def max(*args, key=None): + if len(args) == 1: + return sorted(iter(args[0]), key=key, reverse=True)[0] + elif len(args) > 1: + return sorted(args, key=key, reverse=True)[0] + + +if __name__ == '__main__': + #These "asserts" using only for self-checking and not necessary for auto-testing + assert min((9,)) == 9, 'idk' + assert max(3, 2) == 3, "Simple case max" + assert min(3, 2) == 2, "Simple case min" + assert max([1, 2, 0, 3, 4]) == 4, "From a list" + assert min("hello") == "e", "From string" + assert max(2.2, 5.6, 5.9, key=int) == 5.6, "Two maximal items" + assert min([[1, 2], [3, 4], [9, 0]], key=lambda x: x[1]) == [9, 0], "lambda key" + print("Coding complete? Click 'Check' to review your tests and earn cool rewards!") diff --git a/monkey-typing.py b/monkey-typing.py new file mode 100644 index 0000000..e967f04 --- /dev/null +++ b/monkey-typing.py @@ -0,0 +1,20 @@ +def count_words(text, words): + text = text.lower() + # text = text.split(' ') + + cnt = 0 + + for i in words: + if i in text: + cnt += 1 + # print(cnt) + return cnt + + +if __name__ == '__main__': + #These "asserts" using only for self-checking and not necessary for auto-testing + assert count_words("How aresjfhdskfhskd you?", {"how", "are", "you", "hello"}) == 3, "Example" + assert count_words("Bananas, give me bananas!!!", {"banana", "bananas"}) == 2, "BANANAS!" + assert count_words("Lorem ipsum dolor sit amet, consectetuer adipiscing elit.", + {"sum", "hamlet", "infinity", "anything"}) == 1, "Weird text" + print("Coding complete? Click 'Check' to review your tests and earn cool rewards!") diff --git a/most-numbers.py b/most-numbers.py new file mode 100644 index 0000000..586ec10 --- /dev/null +++ b/most-numbers.py @@ -0,0 +1,17 @@ +def checkio(*args): + if len(args) == 0: + return 0 + else: + return round(max(args) - min(args), 3) + +#These "asserts" using only for self-checking and not necessary for auto-testing +if __name__ == '__main__': + def almost_equal(checked, correct, significant_digits): + precision = 0.1 ** significant_digits + return correct - precision < checked < correct + precision + + assert almost_equal(checkio(1, 2, 3), 2, 3), "3-1=2" + assert almost_equal(checkio(5, -5), 10, 3), "5-(-5)=10" + assert almost_equal(checkio(10.2, -2.2, 0, 1.1, 0.5), 12.4, 3), "10.2-(-2.2)=12.4" + assert almost_equal(checkio(), 0, 3), "Empty" + print("Coding complete? Click 'Check' to review your tests and earn cool rewards!") diff --git a/most-wanted-letter.py b/most-wanted-letter.py new file mode 100644 index 0000000..9a51ca7 --- /dev/null +++ b/most-wanted-letter.py @@ -0,0 +1,43 @@ + +from string import ascii_lowercase +def checkio(text): + + text = text.lower() + tempText = '' + for i in text: + if i in ascii_lowercase: + tempText += i + + text = tempText + + l = list(map(lambda x: [x, text.count(x)], set(text))) + + temp = [1, 0] + + for i in l: + if temp[1] < i[1]: + temp = i + + tempL = [] + for i in l: + if i[1] == temp[1]: + tempL += [i] + + if len(tempL) == 0: + return temp[0] + else: + temp = sorted(tempL)[0] + return temp[0] + +if __name__ == '__main__': + #These "asserts" using only for self-checking and not necessary for auto-testing + assert checkio("Lorem ipsum dolor sit amet") == "m" + assert checkio("Hello World!") == "l", "Hello test" + assert checkio("How do you do?") == "o", "O is most wanted" + assert checkio("One") == "e", "All letter only once." + assert checkio("Oops!") == "o", "Don't forget about lower case." + assert checkio("AAaooo!!!!") == "a", "Only letters." + assert checkio("abe") == "a", "The First." + print("Start the long test") + assert checkio("a" * 9000 + "b" * 1000) == "a", "Long." + print("The local tests are done.") diff --git a/non-unique-elements.py b/non-unique-elements.py new file mode 100644 index 0000000..15d5899 --- /dev/null +++ b/non-unique-elements.py @@ -0,0 +1,21 @@ +#Your optional code here +#You can import some modules or create additional functions + + +def checkio(data): + l = [i for i in data if data.count(i) > 1] + return l + +#Some hints +#You can use list.count(element) method for counting. +#Create new list with non-unique elements +#Loop over original list + + +if __name__ == "__main__": + #These "asserts" using only for self-checking and not necessary for auto-testing + assert list(checkio([1, 2, 3, 1, 3])) == [1, 3, 1, 3], "1st example" + assert list(checkio([1, 2, 3, 4, 5])) == [], "2nd example" + assert list(checkio([5, 5, 5, 5, 5])) == [5, 5, 5, 5, 5], "3rd example" + assert list(checkio([10, 9, 10, 10, 9, 8])) == [10, 9, 10, 10, 9], "4th example" + print("It is all good. Let's check it now") \ No newline at end of file diff --git a/number-factory.py b/number-factory.py new file mode 100644 index 0000000..0adc9bc --- /dev/null +++ b/number-factory.py @@ -0,0 +1,32 @@ +def checkio(number): + + nums = [] + + while number > 9: + found = False + for i in range(9, 1, -1): + if number % i == 0: + found = True + nums.append(i) + number = number // i + break + + if found is False: + return 0 + + nums.append(number) + + rt = "" + for num in sorted(nums): + rt += str(num) + + return int(rt) + +if __name__ == '__main__': + #These "asserts" using only for self-checking and not necessary for auto-testing + assert checkio(20) == 45, "1st example" + assert checkio(21) == 37, "2nd example" + assert checkio(17) == 0, "3rd example" + assert checkio(33) == 0, "4th example" + assert checkio(3125) == 55555, "5th example" + assert checkio(9973) == 0, "6th example" diff --git a/number-radix.py b/number-radix.py new file mode 100644 index 0000000..23e5539 --- /dev/null +++ b/number-radix.py @@ -0,0 +1,16 @@ +def checkio(str_number, radix): + + try: + return int(str_number, radix) + except ValueError: + return -1 + + +#These "asserts" using only for self-checking and not necessary for auto-testing +if __name__ == '__main__': + assert checkio("AF", 16) == 175, "Hex" + assert checkio("101", 2) == 5, "Bin" + assert checkio("101", 5) == 26, "5 base" + assert checkio("Z", 36) == 35, "Z base" + assert checkio("AB", 10) == -1, "B > A = 10" + print("Coding complete? Click 'Check' to review your tests and earn cool rewards!") diff --git a/pawn-brotherhood.py b/pawn-brotherhood.py new file mode 100644 index 0000000..417b43e --- /dev/null +++ b/pawn-brotherhood.py @@ -0,0 +1,17 @@ +def safe_pawns(pawns): + cnt = 0 + for i in pawns: + left = chr(ord(i[0]) - 1) + str(int(i[1]) - 1) + right = chr(ord(i[0]) + 1) + str(int(i[1]) - 1) + + # print(left, right) + + if left in pawns or right in pawns: + cnt += 1 + return cnt + +if __name__ == '__main__': + #These "asserts" using only for self-checking and not necessary for auto-testing + assert safe_pawns({"b4", "d4", "f4", "c3", "e3", "g5", "d2"}) == 6 + assert safe_pawns({"b4", "c4", "d4", "e4", "f4", "g4", "e5"}) == 1 + print("Coding complete? Click 'Check' to review your tests and earn cool rewards!") diff --git a/popular-words.py b/popular-words.py new file mode 100644 index 0000000..bee939f --- /dev/null +++ b/popular-words.py @@ -0,0 +1,30 @@ +def popular_words(text, words): + + text = text.lower() + + result = dict(map(lambda x: [x, text.count(x)], words)) + + return result + + +if __name__ == '__main__': + print("Example:") + print(popular_words(''' +When I was One, +I had just begun. +When I was Two, +I was nearly new. +''', ['i', 'was', 'three'])) + + # These "asserts" are used for self-checking and not for an auto-testing + assert popular_words(''' +When I was One, +I had just begun. +When I was Two, +I was nearly new. +''', ['i', 'was', 'three']) == { + 'i': 4, + 'was': 3, + 'three': 0 + } + print("Coding complete? Click 'Check' to earn cool rewards!") diff --git a/right-to-left.py b/right-to-left.py new file mode 100644 index 0000000..6acede0 --- /dev/null +++ b/right-to-left.py @@ -0,0 +1,16 @@ +def left_join(phrases): + """ + Join strings and replace "right" to "left" + """ + string = ','.join(phrases) + + string = string.replace('right', 'left') + return string + +if __name__ == '__main__': + #These "asserts" using only for self-checking and not necessary for auto-testing + assert left_join(("left", "right", "left", "stop")) == "left,left,left,stop", "All to left" + assert left_join(("bright aright", "ok")) == "bleft aleft,ok", "Bright Left" + assert left_join(("brightness wright",)) == "bleftness wleft", "One phrase" + assert left_join(("enough", "jokes")) == "enough,jokes", "Nothing to replace" + print("Coding complete? Click 'Check' to review your tests and earn cool rewards!") diff --git a/roman-numerals.py b/roman-numerals.py new file mode 100644 index 0000000..5eb2df1 --- /dev/null +++ b/roman-numerals.py @@ -0,0 +1,33 @@ +def checkio(data): + + romanNumbers = { + 'M': 1000, + 'CM': 900, + 'D': 500, + 'CD': 400, + 'C': 100, + 'XC': 90, + 'L': 50, + 'XL': 40, + 'X': 10, + 'IX': 9, + 'V': 5, + 'IV': 4, + 'I': 1 + } + + result = '' + + for i, j in romanNumbers.items(): + while data >= j: + result += i + data -= j + + return ''.join(result) + +if __name__ == '__main__': + #These "asserts" using only for self-checking and not necessary for auto-testing + assert checkio(6) == 'VI', '6' + assert checkio(76) == 'LXXVI', '76' + assert checkio(499) == 'CDXCIX', '499' + assert checkio(3888) == 'MMMDCCCLXXXVIII', '3888' diff --git a/say-history.py b/say-history.py new file mode 100644 index 0000000..f253115 --- /dev/null +++ b/say-history.py @@ -0,0 +1,15 @@ +# 1. on CheckiO your solution should be a function +# 2. the function should return the right answer, not print it. + +def say_hi(name, age): + """ + Hi! + """ + # your code here + return "Hi. My name is " + str(name) + " and I'm " + str(age) + " years old" + +if __name__ == '__main__': + #These "asserts" using only for self-checking and not necessary for auto-testing + assert say_hi("Alex", 32) == "Hi. My name is Alex and I'm 32 years old", "First" + assert say_hi("Frank", 68) == "Hi. My name is Frank and I'm 68 years old", "Second" + print('Done. Time to Check.') diff --git a/second-index.py b/second-index.py new file mode 100644 index 0000000..c7acd79 --- /dev/null +++ b/second-index.py @@ -0,0 +1,26 @@ +def second_index(text: str, symbol: str): + """ + returns the second index of a symbol in a given text + """ + cnt = 0 + for i in range(len(text)): + if text[i] == symbol: + cnt += 1 + if cnt == 2: + return i + + if cnt == 0: + return None + + +if __name__ == '__main__': + print('Example:') + print(second_index("sims", "s")) + + # These "asserts" are used for self-checking and not for an auto-testing + assert second_index("sims", "s") == 3, "First" + assert second_index("find the river", "e") == 12, "Second" + assert second_index("hi", " ") is None, "Third" + assert second_index("hi mayor", " ") is None, "Fourth" + assert second_index("hi mr Mayor", " ") == 5, "Fifth" + print('You are awesome! All tests are done! Go Check it!') diff --git a/secret-message.py b/secret-message.py new file mode 100644 index 0000000..6170ae6 --- /dev/null +++ b/secret-message.py @@ -0,0 +1,11 @@ +def find_message(text): + """Find a secret message""" + result = ''.join([i for i in text if i.isupper()]) + return result + +if __name__ == '__main__': + #These "asserts" using only for self-checking and not necessary for auto-testing + assert find_message("How are you? Eh, ok. Low or Lower? Ohhh.") == "HELLO", "hello" + assert find_message("hello world!") == "", "Nothing" + assert find_message("HELLO WORLD!!!") == "HELLOWORLD", "Capitals" + print("Coding complete? Click 'Check' to review your tests and earn cool rewards!") diff --git a/striped-words.py b/striped-words.py new file mode 100644 index 0000000..b70d391 --- /dev/null +++ b/striped-words.py @@ -0,0 +1,47 @@ +VOWELS = "AEIOUY" +CONSONANTS = "BCDFGHJKLMNPQRSTVWXZ" + +from re import split + +def checkio(text): + + text = split('[ ,.?!]', text) + text = [i for i in text if len(i) > 1] + + print(text) + + result = 0 + for i in text: + try: + if i[0].upper() in VOWELS: + cnt = 0 + elif i[0].upper() in CONSONANTS: + cnt = 1 + else: + raise ValueError + + for j in i[1:]: + if cnt % 2 == 0: + if j.upper() not in CONSONANTS: + raise ValueError + elif cnt % 2 == 1: + if j.upper() not in VOWELS: + raise ValueError + cnt += 1 + except ValueError: + pass + else: + result += 1 + + # print(result) + return result + + + +#These "asserts" using only for self-checking and not necessary for auto-testing +if __name__ == '__main__': + assert checkio("1st 2a ab3er root rate") == 1, "nalesnik" + assert checkio("My name is ...") == 3, "All words are striped" + assert checkio("Hello world") == 0, "No one" + assert checkio("A quantity of striped words.") == 1, "Only of" + assert checkio("Dog,cat,mouse,bird.Human.") == 3, "Dog, cat and human" diff --git a/the-longest-palindromic.py b/the-longest-palindromic.py new file mode 100644 index 0000000..4a1656c --- /dev/null +++ b/the-longest-palindromic.py @@ -0,0 +1,38 @@ +def longest_palindromic(text): + maxLength = 1 + + begin = 0 + end = len(text) + + low = 0 + high = 0 + + for i in range(1, end): + + low = i-1 + high = i + while low >= 0 and high < end and text[low] == text[high]: + if high - low + 1 > maxLength: + begin = low + maxLength = high - low + 1 + low -= 1 + high += 1 + + low = i - 1 + high = i + 1 + while low >= 0 and high < end and text[low] == text[high]: + if high - low + 1 > maxLength: + begin = low + maxLength = high - low + 1 + low -= 1 + high += 1 + + + return text[begin:begin+maxLength] + + + +if __name__ == '__main__': + assert longest_palindromic("artrartrt") == "rtrartr", "The Longest" + assert longest_palindromic("abacada") == "aba", "The First" + assert longest_palindromic("aaaa") == "aaaa", "The A" diff --git a/the-most-frequent.py b/the-most-frequent.py new file mode 100644 index 0000000..c3705e2 --- /dev/null +++ b/the-most-frequent.py @@ -0,0 +1,24 @@ +def most_frequent(data): + """ + determines the most frequently occurring string in the sequence. + """ + result = [] + + + for i in set(data): + result.append([i, data.count(i)]) + + + + return sorted(result, key=lambda x: x[1], reverse=True)[0][0] + +if __name__ == '__main__': + #These "asserts" using only for self-checking and not necessary for auto-testing + assert most_frequent([ + 'a', 'b', 'c', + 'a', 'b', + 'a' + ]) == 'a' + + assert most_frequent(['a', 'a', 'bi', 'bi', 'bi']) == 'bi' + print('Done') diff --git a/three-words.py b/three-words.py new file mode 100644 index 0000000..5b9808c --- /dev/null +++ b/three-words.py @@ -0,0 +1,29 @@ +def checkio(words): + + words = words.split() + print(words) + + cnt = 0 + tempCnt = 0 + for i in words: + try: + int(i) + tempCnt = 0 + except ValueError: + tempCnt += 1 + + if tempCnt > cnt: + cnt = tempCnt + + return True if cnt > 2 else False + + +#These "asserts" using only for self-checking and not necessary for auto-testing +if __name__ == '__main__': + assert checkio("one two 3 four five six 7 eight 9 ten eleven 12") == True + assert checkio("Hello World hello") == True, "Hello" + assert checkio("He is 123 man") == False, "123 man" + assert checkio("1 2 3 4") == False, "Digits" + assert checkio("bla bla bla bla") == True, "Bla Bla" + assert checkio("Hi") == False, "Hi" + print("Coding complete? Click 'Check' to review your tests and earn cool rewards!") diff --git a/x-o-referee.py b/x-o-referee.py new file mode 100644 index 0000000..9990510 --- /dev/null +++ b/x-o-referee.py @@ -0,0 +1,45 @@ +def checkio(game_result): + if "XXX" in game_result: + return "X" + elif "OOO" in game_result: + return "O" + + for i in range(3): + temp = game_result[0][i] + game_result[1][i] + game_result[2][i] + if temp in "XXX/OOO": + return temp[0] + + temp = game_result[0][0] + game_result[1][1] + game_result[2][2] + if temp in "XXX/OOO": + return temp[0] + + temp = game_result[0][2] + game_result[1][1] + game_result[2][0] + if temp in "XXX/OOO": + return temp[0] + + return "D" + + + + + +if __name__ == '__main__': + #These "asserts" using only for self-checking and not necessary for auto-testing + assert checkio([ + "X.O", + "XX.", + "XOO"]) == "X", "Xs wins" + assert checkio([ + "OO.", + "XOX", + "XOX"]) == "O", "Os wins" + assert checkio([ + "OOX", + "XXO", + "OXX"]) == "D", "Draw" + assert checkio([ + "O.X", + "XX.", + "XOO"]) == "X", "Xs wins again" + print("Coding complete? Click 'Check' to review your tests and earn cool rewards!") + From 9e25b90c763c2b767908c4dc7db79ad297a5c2e4 Mon Sep 17 00:00:00 2001 From: Radoslaw Tomaszeski Date: Wed, 21 Feb 2018 16:34:11 +0100 Subject: [PATCH 2/2] rewrite some solutions --- all-the-same.py | 2 +- black-holes.py | 49 +++++++++++++++++++++++++++++++++------- cipher-map2.py | 9 ++++---- correct-sentence.py | 11 +-------- days-diff.py | 5 +--- determine-the-order.py | 36 +++++++++++++++++++++++++++++ digits-multiplication.py | 10 +++----- easy-unpack.py | 2 +- even-last.py | 2 +- first-word.py | 5 +--- fizz-buzz.py | 13 +++++------ flatten-dict.py | 47 ++++++++++++++++++++++++++++++++++++++ hamming-distance2.py | 21 +---------------- house-password.py | 2 +- index-power.py | 5 +--- loading-cargo.py | 23 +++++++++++++++++++ long-repeat.py | 7 +++--- merge-intervals.py | 29 ++++++++++++++++++++++++ monkey-typing.py | 11 +-------- most-numbers.py | 5 +--- most-wanted-letter.py | 2 +- non-unique-elements.py | 3 +-- popular-words.py | 7 +----- right-to-left.py | 5 +--- say-history.py | 2 +- 25 files changed, 209 insertions(+), 104 deletions(-) create mode 100644 determine-the-order.py create mode 100644 flatten-dict.py create mode 100644 loading-cargo.py create mode 100644 merge-intervals.py diff --git a/all-the-same.py b/all-the-same.py index 66fb391..cc22adc 100644 --- a/all-the-same.py +++ b/all-the-same.py @@ -3,7 +3,7 @@ def all_the_same(elements: List[Any]) -> bool: - return all(elements[i] == elements[i+1] for i in range(len(elements)-1)) + return all(i == elements[0] for i in elements) if __name__ == '__main__': diff --git a/black-holes.py b/black-holes.py index 772a2ac..7892cb9 100644 --- a/black-holes.py +++ b/black-holes.py @@ -1,16 +1,49 @@ -def checkio(data): +from math import acos, pi, hypot +from itertools import combinations + +def distance(a, b): + + x1, y1, _ = a + x2, y2, _ = b + + return hypot(x1 - x2, y1 - y2) + + +def area(r): + return pi*r**2 - d = data[0][2] - data[1][2] - print(d) +def intersection_area(a, b, d): + r1, r2 = a[-1], b[-1] + if r1 + r2 <= d: + return 0 + if r1 > d + r2: + return area(r2) + + s = (2*d*r1)**2 - (d**2 + r1**2 - r2**2)**2 + d1 = (d**2 + r1**2 - r2**2)/(2*d*r1) + d2 = (d**2 + r2**2 - r1**2)/(2*d*r2) + + return r1**2*acos(d1) + r2**2*acos(d2) - 0.5*s**0.5 + + +def checkio(data): - if d > data[0][2] + data[1][2]: - return data - elif d < abs(data[0][2] - data[1][2]): - return data - elif + holes = [list(hole) for hole in data] + while True: + pairs = sorted((distance(a, b), a, b) for a, b in combinations(holes, 2)) + for d, a, b in pairs: + pair = sorted((a, b), key=lambda x: x[-1]) + inter = intersection_area(pair[1], pair[0], distance(*pair)) + if inter >= area(pair[0][-1]) * 0.55 and area(pair[1][-1]) > area(pair[0][-1]) * 1.2: + pair[1][2] = round(((area(pair[1][-1]) + area(pair[0][-1]))/pi)**0.5, 2) + holes.remove(pair[0]) + break + else: + break + return [(x, y, r) for (x, y, r) in holes] if __name__ == '__main__': diff --git a/cipher-map2.py b/cipher-map2.py index e8c27c1..3d06cc4 100644 --- a/cipher-map2.py +++ b/cipher-map2.py @@ -6,10 +6,11 @@ def recall_password(cipher_grille, ciphered_password): result = '' for n in range(4): - for i in range(len(ciphered_password)): - for j in range(len(ciphered_password)): - if cipher_grille[i][j] == 'X': - result += ciphered_password[i][j] + for g, p in zip(cipher_grille, ciphered_password): + for i, j in zip(g, p): + if i =='X': + result += j + cipher_grille = rotate_matrix(cipher_grille) return result diff --git a/correct-sentence.py b/correct-sentence.py index dd7c321..389f607 100644 --- a/correct-sentence.py +++ b/correct-sentence.py @@ -3,16 +3,7 @@ def correct_sentence(text: str) -> str: returns a corrected sentence which starts with a capital letter and ends with a dot. """ - - if text[-1] != '.': - text += '.' - - tempChar = text[0] - - if text[0] != tempChar.upper(): - text = tempChar.upper() + text[1:] - - return text + return f"{text[0].upper()}{text[1:].replace('.', '')}." if __name__ == '__main__': diff --git a/days-diff.py b/days-diff.py index 585bdc5..4e2f0c7 100644 --- a/days-diff.py +++ b/days-diff.py @@ -4,10 +4,7 @@ def days_diff(date1, date2): """ Find absolute diff in days between dates """ - d1 = datetime(*date1) - d2 = datetime(*date2) - - return abs((d2-d1).days) + return abs((datetime(*date1)-datetime(*date2)).days) if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing diff --git a/determine-the-order.py b/determine-the-order.py new file mode 100644 index 0000000..257e77c --- /dev/null +++ b/determine-the-order.py @@ -0,0 +1,36 @@ +from collections import defaultdict + +def checkio(data): + + graphs = defaultdict(set) + elements = set([char for i in data for char in i]) + result = [] + + # make topology + for s in data: + chars = [c for c in s] + for i in range(len(chars)): + [graphs[c].add(chars[i]) for c in s[i+1:] if c != chars[i]] + + while elements: + roots = sorted([c for c in elements if len(graphs[c]) == 0]) + root = roots[0] + + result.extend(root) + elements.difference_update(root) + [graphs[c].discard(root) for c in elements] + + return ''.join(result) + +#These "asserts" using only for self-checking and not necessary for auto-testing +if __name__ == '__main__': + assert checkio(["acb", "bd", "zwa"]) == "zwacbd", \ + "Just concatenate it" + assert checkio(["klm", "kadl", "lsm"]) == "kadlsm", \ + "Paste in" + assert checkio(["a", "b", "c"]) == "abc", \ + "Cant determine the order - use english alphabet" + assert checkio(["aazzss"]) == "azs", \ + "Each symbol only once" + assert checkio(["dfg", "frt", "tyg"]) == "dfrtyg", \ + "Concatenate and paste in" diff --git a/digits-multiplication.py b/digits-multiplication.py index f2a9d7d..9df3114 100644 --- a/digits-multiplication.py +++ b/digits-multiplication.py @@ -1,11 +1,7 @@ -def checkio(number): - result = 1 - - for i in str(number): - if i != '0': - result *= int(i) +from functools import reduce - return result +def checkio(number): + return reduce((lambda prev, curr: prev * curr), [int(num) for num in str(number) if num != '0'], 1) #These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': diff --git a/easy-unpack.py b/easy-unpack.py index c75cff5..5592244 100644 --- a/easy-unpack.py +++ b/easy-unpack.py @@ -2,7 +2,7 @@ def easy_unpack(elements): """ returns a tuple with 3 elements - first, third and second to the last """ - return (elements[0], elements[2], elements[-2]) + return elements[0], elements[2], elements[-2] if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing diff --git a/even-last.py b/even-last.py index 0006e0c..fa2fe9f 100644 --- a/even-last.py +++ b/even-last.py @@ -2,7 +2,7 @@ def checkio(array): """ sums even-indexes elements and multiply at the last """ - return sum([array[i] for i in range(0, len(array), 2)]) * array[-1] if len(array) > 0 else 0 + return sum([item for item in array[::2]]) * array[-1] if len(array) > 0 else 0 #These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': diff --git a/first-word.py b/first-word.py index b4be3c4..ec3b808 100644 --- a/first-word.py +++ b/first-word.py @@ -2,12 +2,9 @@ def first_word(text: str) -> str: """ returns the first word in a given text. """ - text = text.replace(',', ' ') - text = text.replace('.', ' ') - text = text.split() - return text[0] + return text.replace(',', '').replace('.', '').split()[0] if __name__ == '__main__': diff --git a/fizz-buzz.py b/fizz-buzz.py index 1d8b96f..5eb6bd9 100644 --- a/fizz-buzz.py +++ b/fizz-buzz.py @@ -3,15 +3,14 @@ def checkio(number): - result = '' - if number%3 == 0and number%5 == 0: - result += 'Fizz Buzz' - elif number%3 == 0: - result += 'Fizz' + if number%3 == 0: + result = 'Fizz' + if number%5 == 0: + result += ' Buzz' elif number%5 == 0: - result += 'Buzz' + result = 'Buzz' else: - result += str(number) + result = str(number) return result diff --git a/flatten-dict.py b/flatten-dict.py new file mode 100644 index 0000000..108daf8 --- /dev/null +++ b/flatten-dict.py @@ -0,0 +1,47 @@ +def flatten(dictionary): + stack = [((), dictionary)] + + result = {} + + while stack: + path, current = stack.pop() + for k, v in current.items(): + if v == {}: + result["/".join((path + (k,)))] = " " + elif isinstance(v, dict): + stack.append((path + (k,), v)) + else: + result["/".join((path + (k,)))] = v + + print(result) + +if __name__ == '__main__': + test_input = {"key": {"deeper": {"more": {"enough": "value"}}}} + print(' Input: {}'.format(test_input)) + print('Output: {}'.format(flatten(test_input))) + + #These "asserts" using only for self-checking and not necessary for auto-testing + assert flatten({"key": "value"}) == {"key": "value"}, "Simple" + assert flatten( + {"key": { + "deeper": { + "more": { + "enough": "value"}}}} + ) == {"key/deeper/more/enough": "value"}, "Nested" + assert flatten({"empty": {}}) == {"empty": ""}, "Empty value" + assert flatten({"name": { + "first": "One", + "last": "Drone"}, + "job": "scout", + "recent": {}, + "additional": { + "place": { + "zone": "1", + "cell": "2"}}} + ) == {"name/first": "One", + "name/last": "Drone", + "job": "scout", + "recent": "", + "additional/place/zone": "1", + "additional/place/cell": "2"} + print('You all set. Click "Check" now!') diff --git a/hamming-distance2.py b/hamming-distance2.py index ca42cd1..ce374ae 100644 --- a/hamming-distance2.py +++ b/hamming-distance2.py @@ -1,24 +1,5 @@ def checkio(n, m): - bin1 = '0{0:b}'.format(n) - bin2 = '0{0:b}'.format(m) - - if len(bin1) < len(bin2): - temp = '0' * (len(bin2) - len(bin1)) - - bin1 = temp + bin1 - elif len(bin1) > len(bin2): - temp = '0' * (len(bin1) - len(bin2)) - - bin2 = temp + bin2 - - result = [i != j for i, j in zip(bin1, bin2)] - - - cnt = 0 - for i in result: - if i: - cnt += 1 - return cnt + return bin(n ^ m).count('1') if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing diff --git a/house-password.py b/house-password.py index debdbea..064619c 100644 --- a/house-password.py +++ b/house-password.py @@ -1,6 +1,6 @@ def checkio(data): if len(data) >= 10: - if any(i.isupper() for i in data) and any(i.islower() for i in data) and any( i.isnumeric() for i in data): + if any(i.isupper() for i in data) and any(i.islower() for i in data) and any(i.isnumeric() for i in data): return True else: return False diff --git a/index-power.py b/index-power.py index aae6161..20559e1 100644 --- a/index-power.py +++ b/index-power.py @@ -2,10 +2,7 @@ def index_power(array, n): """ Find Nth power of the element with index N. """ - if n < len(array): - return array[n]**n - else: - return -1 + return array[n] ** n if n < len(array) else -1 if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing diff --git a/loading-cargo.py b/loading-cargo.py new file mode 100644 index 0000000..528175f --- /dev/null +++ b/loading-cargo.py @@ -0,0 +1,23 @@ +from itertools import combinations + +def checkio(data): + + if len(data) == 1: + return data[0] + + bal = sum(data)/2 + half_range = range(len(data)//2+1) + sums = [sum(val) for n in half_range for val in combinations(data, n)] + closet = min(sums, key=lambda x: abs(bal - x)) + + return 2 * abs(bal - closet) + + +#These "asserts" using only for self-checking and not necessary for auto-testing +if __name__ == '__main__': + assert checkio([10, 10]) == 0, "1st example" + assert checkio([10]) == 10, "2nd example" + assert checkio([5, 8, 13, 27, 14]) == 3, "3rd example" + assert checkio([5, 5, 6, 5]) == 1, "4th example" + assert checkio([12, 30, 30, 32, 42, 49]) == 9, "5th example" + assert checkio([1, 1, 1, 3]) == 0, "6th example" diff --git a/long-repeat.py b/long-repeat.py index 2533f41..de54023 100644 --- a/long-repeat.py +++ b/long-repeat.py @@ -9,17 +9,16 @@ def long_repeat(line): cnt = 1 tempCnt = 1 char = line[0] - for i in range(1, len(line)): - if char == line[i]: + for item in line[1:]: + if char == item: tempCnt += 1 else: - char = line[i] + char = item tempCnt = 1 if cnt < tempCnt: cnt = tempCnt return cnt - if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert long_repeat('sdsffffse') == 4, "First" diff --git a/merge-intervals.py b/merge-intervals.py new file mode 100644 index 0000000..0effb82 --- /dev/null +++ b/merge-intervals.py @@ -0,0 +1,29 @@ +def merge_intervals(intervals): + """ + Merge overlapped intervals. + """ + result = [] + + for interval in intervals: + if not result: + result.append(interval) + else: + low = result[-1] + if interval[0] <= low[1] + 1: + result[-1] = (low[0], max(low[1], interval[1])) + else: + result.append(interval) + + # print(result) + + return result + + + + +if __name__ == '__main__': + #These "asserts" using only for self-checking and not necessary for auto-testing + assert merge_intervals([(1, 4), (2, 6), (8, 10), (12, 19)]) == [(1, 6), (8, 10), (12, 19)], "First" + assert merge_intervals([(1, 12), (2, 3), (4, 7)]) == [(1, 12)], "Second" + assert merge_intervals([(1, 5), (6, 10), (10, 15), (17, 20)]) == [(1, 15), (17, 20)], "Third" + print('Done! Go ahead and Check IT') diff --git a/monkey-typing.py b/monkey-typing.py index e967f04..88b3cb6 100644 --- a/monkey-typing.py +++ b/monkey-typing.py @@ -1,14 +1,5 @@ def count_words(text, words): - text = text.lower() - # text = text.split(' ') - - cnt = 0 - - for i in words: - if i in text: - cnt += 1 - # print(cnt) - return cnt + return [i in text.lower() for i in words].count(True) if __name__ == '__main__': diff --git a/most-numbers.py b/most-numbers.py index 586ec10..4b3b45a 100644 --- a/most-numbers.py +++ b/most-numbers.py @@ -1,8 +1,5 @@ def checkio(*args): - if len(args) == 0: - return 0 - else: - return round(max(args) - min(args), 3) + return 0 if len(args) == 0 else round(max(args) - min(args), 3) #These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': diff --git a/most-wanted-letter.py b/most-wanted-letter.py index 9a51ca7..4bb3154 100644 --- a/most-wanted-letter.py +++ b/most-wanted-letter.py @@ -1,5 +1,5 @@ - from string import ascii_lowercase + def checkio(text): text = text.lower() diff --git a/non-unique-elements.py b/non-unique-elements.py index 15d5899..af5d6b9 100644 --- a/non-unique-elements.py +++ b/non-unique-elements.py @@ -3,8 +3,7 @@ def checkio(data): - l = [i for i in data if data.count(i) > 1] - return l + return [i for i in data if data.count(i) > 1] #Some hints #You can use list.count(element) method for counting. diff --git a/popular-words.py b/popular-words.py index bee939f..ad53463 100644 --- a/popular-words.py +++ b/popular-words.py @@ -1,10 +1,5 @@ def popular_words(text, words): - - text = text.lower() - - result = dict(map(lambda x: [x, text.count(x)], words)) - - return result + return dict(map(lambda x: [x, text.lower().count(x)], words)) if __name__ == '__main__': diff --git a/right-to-left.py b/right-to-left.py index 6acede0..76d2497 100644 --- a/right-to-left.py +++ b/right-to-left.py @@ -2,10 +2,7 @@ def left_join(phrases): """ Join strings and replace "right" to "left" """ - string = ','.join(phrases) - - string = string.replace('right', 'left') - return string + return ','.join(phrases).replace('right', 'left') if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing diff --git a/say-history.py b/say-history.py index f253115..698fbe5 100644 --- a/say-history.py +++ b/say-history.py @@ -6,7 +6,7 @@ def say_hi(name, age): Hi! """ # your code here - return "Hi. My name is " + str(name) + " and I'm " + str(age) + " years old" + return f"Hi. My name is {str(name)} and I'm {str(age)} years old" if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing