-
-
Notifications
You must be signed in to change notification settings - Fork 46.9k
Update 3n+1.py #996
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Update 3n+1.py #996
Changes from 3 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,32 @@ | ||
def main(): | ||
def n31(a):# a = initial number | ||
c = 0 | ||
l = [a] | ||
while a != 1: | ||
if a % 2 == 0:#if even divide it by 2 | ||
a = a // 2 | ||
elif a % 2 == 1:#if odd 3n+1 | ||
a = 3*a +1 | ||
c += 1#counter | ||
l += [a] | ||
from typing import Tuple, List | ||
|
||
def n31(a: int) -> Tuple[List[int], int]: | ||
""" | ||
Returns Collatz sequence of a number | ||
>>> n31(4) | ||
([4, 2, 1], 3) | ||
""" | ||
|
||
if not isinstance(a, int): | ||
raise TypeError('Must be int, not {0}'.format(type(a).__name__)) | ||
if a < 1: | ||
raise ValueError('Given integer must be greater than 1, not {0}'.format(a)) | ||
|
||
return l , c | ||
print(n31(43)) | ||
print(n31(98)[0][-1])# = a | ||
print("It took {0} steps.".format(n31(13)[1]))#optional finish | ||
counter = 0 | ||
path = [a] | ||
while a != 1: | ||
if a % 2 == 0: | ||
a = a // 2 | ||
else: | ||
a = 3*a +1 | ||
counter += 1 | ||
path += [a] | ||
return path, counter + 1 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Would it also work to return path, len(path) ? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes, that is more elegant, thanks! |
||
|
||
def main(): | ||
num = 4 | ||
path , length = n31(num) | ||
print("The Collatz sequence of {0} took {1} steps. \nPath: {2}".format(num,length, path)) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. You can drop the 0, 1, and 2 here and drop the 0 in the raise statements above. |
||
|
||
if __name__ == '__main__': | ||
main() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This comment says that we are only returning the sequence but we are returning the sequence and its length.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
updated docstring