On Mon, May 7, 2018 at 12:26 AM, boB Stepp <robertvst...@gmail.com> wrote:
> def get_collatz_number(integer): > """Returns the Collatz sequence number corresponding to integer. integer > must be > 0, or the sequence will not converge to 1.""" > > if integer % 2 == 0: > return integer // 2 > else: > return 3 * integer + 1 > > def generate_collatz_sequence(seed): > """Creates a generator, which will yield a Collatz sequence starting from > seed. seed must be a positive integer, or the sequence will not converge > to > 1.""" > > collatz_number = seed > while True: > collatz_number = get_collatz_number(collatz_number) > yield collatz_number > if collatz_number == 1: > return > Questions and comments: After taking a break from this and coming at this afresh, I immediately saw an answer to this question: > 2) I spent a lot of effort trying to come up with a way to combine > the two functions, get_collatz_number() and > generate_collatz_sequence(), into something both more compact and more > readable, but I was unsuccessful. I suspect there is a better way. > Is there? And how would I do it? def generate_collatz_sequence(seed): """Creates a generator, which will yield a Collatz sequence starting from seed. seed must be a positive integer, or the sequence will not converge to 1.""" collatz_number = seed while True: if collatz_number % 2 == 0: collatz_number //= 2 else: collatz_number = 3 * collatz_number + 1 yield collatz_number if collatz_number == 1: return Judging from the lack of responses, I guess I must have been on track on the other questions. -- boB _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor