'Using List comprehensions to solve Collatz conjecture
Is there a way to use list comprehension's to workout Collatz conjecture without using a while statement or another method to append the n value to the ls without adding ls after each statement?
from random import choice
from time import sleep
n = choice([x for x in range(2, 99*99) if all(x%y != 0 for y in range(2, x))])
ls = []
ls.append(n)
while True:
if n % 2 == 0:
n = n // 2
ls.append(n)
elif n % 2 != 0:
n = (3 * n) + 1
ls.append(n)
if n == 1:
break
print(ls)
Solution 1:[1]
Well while is what you use when you don't know yet how many steps it will take and since that is kind of baked into the logic of finding the conjecture for a value there is not really a way around it. I personally think there is nothing bad about using while loops.
You can still make the code a bit more compact and readable while keeping the while loop, e.g. like this:
from random import choice
n = choice([x for x in range(2, 99 * 99) if all(x % y != 0 for y in range(2, x))])
ls = [n]
while n != 1:
n = n // 2 if n % 2 == 0 else (3 * n) + 1
ls.append(n)
print(ls)
Edit:
A slightly modified version of @Kelly Bundys answer does the trick for me to make it even more compact (let's not mention the readability though):
from random import choice
n = choice([x for x in range(2, 99 * 99) if all(x % y != 0 for y in range(2, x))])
ls = [n] + [n := n // 2 if n % 2 == 0 else (3 * n) + 1 for _ in iter(lambda: n, 1)]
print(ls)
Solution 2:[2]
seq = [
*(lambda memo: [n] + [
memo.append(n // 2 if n%2==0 else n*3+1) or memo[-1]
for n in memo
if memo[-1] != 1
])([n])
]
It's not a pure comprehension, but sort of.
The core idea was to introduce a named list, memo, which I can refer to as a variable and push values to
Solution 3:[3]
n=1024
ls=[n]
[ls.append(n//2 if n%2==0 else 3*n+1) for n in ls if n!=1]
print (ls)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | kolypto |
| Solution 3 | Juan Lozano |
