Created
June 25, 2015 14:31
-
-
Save rg3915/ca3a73caaf324294741a to your computer and use it in GitHub Desktop.
Happy numbers make with Henrique Bastos Coding Dojo Tutorial
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
| ''' https://www.youtube.com/watch?v=9gokU36gZTY ''' | |
| def happy(number): | |
| # recursivo | |
| next_ = sum(int(char) ** 2 for char in str(number)) | |
| return number in (1, 7) if number < 10 else happy(next_) | |
| ''' | |
| V1 | |
| digits = [] | |
| for char in string: | |
| digits.append(int(char)) | |
| total = 0 | |
| for digit in digits: | |
| total += digit | |
| if number in (1, 10, 100): | |
| string = str(number) | |
| digits = [int(char) for char in string] | |
| total = sum(digits) | |
| if number == 97: | |
| n = number | |
| n = sum_of_squares(n) | |
| n = sum_of_squares(n) | |
| n = sum_of_squares(n) | |
| return n == 1 | |
| if number in (1, 10, 100): | |
| total = sum_of_squares(number) | |
| ''' | |
| ''' | |
| Da erro | |
| if number in (1, 10, 100, 97, 130): | |
| n = number | |
| while n != 1: | |
| n = sum_of_squares(n) | |
| return n == 1 | |
| ''' | |
| ''' | |
| V final sem recursao | |
| def sum_of_squares(number): | |
| string = str(number) | |
| digits = [int(char) ** 2 for char in string] | |
| return sum(digits) | |
| def happy(number): | |
| box = [] | |
| n = number | |
| while n != 1 and n not in box: | |
| box.append(n) | |
| n = sum_of_squares(n) | |
| return n == 1 | |
| ''' | |
| ''' | |
| Recusao V 1 | |
| def sum_of_squares(number): | |
| return sum(int(char) ** 2 for char in str(number)) | |
| def happy(number): | |
| # recursivo | |
| if number < 10: | |
| return number in (1, 7) | |
| return happy(sum_of_squares(number)) | |
| ''' | |
| # print(sum_of_squares(130)) | |
| # assert sum_of_squares(130) == 10 | |
| # assert all([happy(n) for n in (1, 10, 100, 130, 97)]) | |
| # generator expression | |
| assert all(happy(n) for n in (1, 10, 100, 130, 97)) | |
| assert not all(happy(n) for n in (2, 3, 4, 5, 6, 8, 9)) | |
| ''' | |
| assert happy(1) | |
| assert happy(10) | |
| assert happy(100) | |
| assert happy(130) | |
| assert happy(97) | |
| ''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment