Python – Consecutive Division in List
Given a List, perform consecutive division from each quotient obtained in the intermediate step and treating consecutive elements as divisors.
Input : test_list = [1000, 50, 5, 10, 2]
Output : 0.2
Explanation : 1000 / 50 = 20 / 5 = 4 / 10 = 0.4 / 2 = 0.2. Hence solution.
Input : test_list = [100, 50]
Output : 2
Explanation : 100 / 50 = 2. Hence solution.
Approach: Using loop + “/” operator
In this, we iterate for each element and store the quotient obtained to process as a dividend for the next operation while in the loop. The end result is the final quotient of list.
Python3
def conc_div(test_list):
res = test_list[ 0 ]
for idx in range ( 1 , len (test_list)):
res / = test_list[idx]
return res
test_list = [ 1000 , 50 , 5 , 10 , 2 ]
print ( "The original list is : " + str (test_list))
res = conc_div(test_list)
print ( "The Consecutive Division quotient : " + str (res))
|
Output
The original list is : [1000, 50, 5, 10, 2]
The Consecutive Division quotient : 0.2
Time Complexity: O(n), where n is the length of the input list. This is because we’re iterating which has a time complexity of O(n) in the worst case.
Auxiliary Space: O(1), we’re not using any additional space other than the input list itself.
Approach : Using list(),map(),join() and eval() methods
Python3
test_list = [ 1000 , 50 , 5 , 10 , 2 ]
print ( "The original list is : " + str (test_list))
x = list ( map ( str ,test_list))
x = "/" .join(x)
res = eval (x)
print ( "The Consecutive Division quotient : " + str (res))
|
Output
The original list is : [1000, 50, 5, 10, 2]
The Consecutive Division quotient : 0.2
Time Complexity: O(n)
Auxiliary Space: O(1)
Last Updated :
08 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...