Function Use: To print all the directories in a folder/sub-folder or directory import os def get_list_or_dir(local_dir): for dir_or_file in os.listdir(local_dir): if os.path.isdir(dir_or_file): path = os.path.join(local_dir, dir_or_file) print(dir_or_file, 'This is a directory') get_list_or_dir(path) else: print(dir_or_file) Path = os.getcwd() or define the path from where you need a file Function Call: get_list_or_dir(path)
The Problem:
The following iterative sequence is defined for the set of positive integers:
Using the rule above and starting with 13, we generate the following sequence:
It can be seen that this sequence (starting at 13 and finishing at 1)
contains 10 terms. Although it has not been proved yet (Collatz
Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
a = [] # will hold the sequence
a.append(n)
while n < n + 1: # will run until the condition is true
if n == 1: # The loop will run till the value of n becomes 1 and if it becomes 1 the loop will break.
return a[0], len(a)
break
elif n % 2 == 0: # For even number
n = n/2
a.append(n)
else: # For odd number
n = 3*n + 1
#count = count + 1
a.append(n)
num = chain(i)
b.append(num)
Third will be sort the values.
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
n → 3n + 1 (n is odd)
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
The Solution:
We can divide the solution in 3 task.
To form the chain of sequence.
To feed the data to the first function.
Third will be sort the values.
To form the chain of sequence:
def chain(n):
a = [] # will hold the sequence
a.append(n)
while n < n + 1: # will run until the condition is true
if n == 1: # The loop will run till the value of n becomes 1 and if it becomes 1 the loop will break.
return a[0], len(a)
break
elif n % 2 == 0: # For even number
n = n/2
a.append(n)
else: # For odd number
n = 3*n + 1
#count = count + 1
a.append(n)
To feed the data to the first function
b = [] # This list will hold the value of each number in (13, 10) fashion
for i in range(1, 1000000):
num = chain(i)
b.append(num)
Third will be sort the values.
Now, we have the list containing the sequence of every number till one million. We just to sort it. Simple sort won't work because we have sequence number as the second element.
def takesec(elem): # This function will return the second element.
return elem[1]
b.sort(key=takesec)
b[len(b) - 1] # this will give you the solution of this question.
(837799, 525) The answer of this ask is 837799 as it can form the highest number of sequence 525.
Comments
Post a Comment