-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLoopChain.py
More file actions
46 lines (42 loc) · 1.98 KB
/
Copy pathLoopChain.py
File metadata and controls
46 lines (42 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def methodLoop(initial, method, max_iterations=1000000):
"""
Creates a list where each element is the result of calling the given method with the previous element as the argument.
Stops once it either reaches a value that is already in the list, in which case it returns the list after removing
all elements before the first instance of the repeat, or reaches the maximum number of iterations, where it returns
None.
:param initial: Initial value
:param method: Method to use for the loop
:param max_iterations: Iterations to try before returning None; default value is 1000000
:return: List with the loop, or None if the maximum number of iterations was exceeded
"""
current = initial
retList = [current]
for i in range(max_iterations):
current = method(current)
if current in retList:
while retList[0] != current:
del retList[0]
return retList
retList += [current]
return None
def methodLoopLen(initial, method, max_iterations=1000000):
"""
Creates a list where each element is the result of calling the given method with the previous element as the argument.
Stops once it either reaches a value that is already in the list, in which case it returns the length of the list
after removing all elements before the first instance of the repeat, or reaches the maximum number of iterations,
where it returns None.
:param initial: Initial value
:param method: Method to use for the loop
:param max_iterations: Iterations to try before returning None; default value is 1000000
:return: List with the loop, or None if the maximum number of iterations was exceeded
"""
current = initial
retList = [current]
for i in range(max_iterations):
current = method(current)
if current in retList:
while retList[0] != current:
del retList[0]
return len(retList)
retList += [current]
return None