Last active
August 30, 2018 16:31
-
-
Save Dimanaux/c0613483b1856d4c7d878a82d45bec77 to your computer and use it in GitHub Desktop.
Write a function that takes a text and returns amount of words in the text. Write it in two styles: imperative and declarative
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # encoding: utf-8 | |
| # посчитать количество слов в предложении | |
| # входные данные: str | |
| # выходные данные: int | |
| SPECIAL_CHARS = ['-'] | |
| def is_alphabetic(char: str) -> bool: | |
| return char.isalpha() or char in SPECIAL_CHARS | |
| def word_count_loop(sentence: str) -> int: | |
| word_count = 0 | |
| in_word = False | |
| for char in sentence: | |
| if not in_word and is_alphabetic(char): | |
| word_count += 1 | |
| in_word = True | |
| elif in_word and not is_alphabetic(char): | |
| in_word = False | |
| return word_count | |
| def word_count(sentence: str) -> int: | |
| return len(sentence.split(' ')) | |
| def test(func, tests): | |
| for params, expectation in tests.items(): | |
| actual = func(params) | |
| assert actual == expectation, \ | |
| "{}({}) expected to be {}, instead got {}" \ | |
| .format(func, params, expectation, actual) | |
| return True | |
| # common cases | |
| tests = { | |
| 'I love you': 3, | |
| 'I love you!': 3, | |
| 'Я тебя люблю': 3, | |
| 'я тебя люблю, родная': 4, | |
| 'Привет, желтый шарик.': 3, | |
| 'Приветик': 1, | |
| 'Hello, world!': 2, | |
| 'чёрно-красный': 1, | |
| 'чёрно-красное дерево': 2, | |
| } | |
| test(word_count, tests) | |
| test(word_count_loop, tests) | |
| print('SUCCESS!') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
oh finally it works!!!