Skip to content

Commit 729aaf6

Browse files
Improve Project Euler problem 014 solution 2 (TheAlgorithms#5744)
* Improve solution * Uncomment code that has been commented due to slow execution affecting Travis * Fix * scikit-fuzzy is causing broken builds * fuzz = None * Update fuzzy_operations.py Co-authored-by: Christian Clauss <[email protected]>
1 parent 7a60576 commit 729aaf6

File tree

3 files changed

+20
-13
lines changed

3 files changed

+20
-13
lines changed

fuzzy_logic/fuzzy_operations.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
"""README, Author - Jigyasa Gandhi(mailto:[email protected])
1+
"""
2+
README, Author - Jigyasa Gandhi(mailto:[email protected])
23
Requirements:
34
- scikit-fuzzy
45
- numpy
@@ -7,7 +8,11 @@
78
- 3.5
89
"""
910
import numpy as np
10-
import skfuzzy as fuzz
11+
12+
try:
13+
import skfuzzy as fuzz
14+
except ImportError:
15+
fuzz = None
1116

1217
if __name__ == "__main__":
1318
# Create universe of discourse in Python using linspace ()

project_euler/problem_014/sol2.py

+12-10
Original file line numberDiff line numberDiff line change
@@ -27,25 +27,27 @@
2727
"""
2828
from __future__ import annotations
2929

30+
COLLATZ_SEQUENCE_LENGTHS = {1: 1}
31+
3032

3133
def collatz_sequence_length(n: int) -> int:
3234
"""Returns the Collatz sequence length for n."""
33-
sequence_length = 1
34-
while n != 1:
35-
if n % 2 == 0:
36-
n //= 2
37-
else:
38-
n = 3 * n + 1
39-
sequence_length += 1
35+
if n in COLLATZ_SEQUENCE_LENGTHS:
36+
return COLLATZ_SEQUENCE_LENGTHS[n]
37+
if n % 2 == 0:
38+
next_n = n // 2
39+
else:
40+
next_n = 3 * n + 1
41+
sequence_length = collatz_sequence_length(next_n) + 1
42+
COLLATZ_SEQUENCE_LENGTHS[n] = sequence_length
4043
return sequence_length
4144

4245

4346
def solution(n: int = 1000000) -> int:
4447
"""Returns the number under n that generates the longest Collatz sequence.
4548
46-
# The code below has been commented due to slow execution affecting Travis.
47-
# >>> solution(1000000)
48-
# 837799
49+
>>> solution(1000000)
50+
837799
4951
>>> solution(200)
5052
171
5153
>>> solution(5000)

requirements.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ pandas
99
pillow
1010
qiskit
1111
requests
12-
scikit-fuzzy
12+
# scikit-fuzzy # Causing broken builds
1313
sklearn
1414
statsmodels
1515
sympy

0 commit comments

Comments
 (0)