Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python – Consecutive Division in List
When it is required to find the consecutive division in a list, a method is defined that iterates over the elements of the list and uses the '/' operator to determine the result. This operation divides the first element by all subsequent elements sequentially.
Below is a demonstration of the same ?
Example
def consec_division(my_list):
my_result = my_list[0]
for idx in range(1, len(my_list)):
my_result /= my_list[idx]
return my_result
my_list = [2200, 500, 100, 50, 20, 5]
print("The list is :")
print(my_list)
my_result = consec_division(my_list)
print("The result is :")
print(my_result)
Output
The list is : [2200, 500, 100, 50, 20, 5] The result is : 8.8e-06
How It Works
The consecutive division operation follows this pattern ?
# For list [2200, 500, 100, 50, 20, 5]
# Step by step calculation:
numbers = [2200, 500, 100, 50, 20, 5]
result = numbers[0] # Start with 2200
print(f"Initial: {result}")
result = result / numbers[1] # 2200 / 500 = 4.4
print(f"After dividing by {numbers[1]}: {result}")
result = result / numbers[2] # 4.4 / 100 = 0.044
print(f"After dividing by {numbers[2]}: {result}")
result = result / numbers[3] # 0.044 / 50 = 0.00088
print(f"After dividing by {numbers[3]}: {result}")
result = result / numbers[4] # 0.00088 / 20 = 0.000044
print(f"After dividing by {numbers[4]}: {result}")
result = result / numbers[5] # 0.000044 / 5 = 0.0000088
print(f"Final result after dividing by {numbers[5]}: {result}")
Initial: 2200 After dividing by 500: 4.4 After dividing by 100: 0.044 After dividing by 50: 0.00088 After dividing by 20: 4.4e-05 Final result after dividing by 5: 8.8e-06
Alternative Implementation
You can also implement consecutive division using Python's reduce() function ?
from functools import reduce
import operator
def consec_division_reduce(numbers):
return reduce(operator.truediv, numbers)
numbers = [2200, 500, 100, 50, 20, 5]
result = consec_division_reduce(numbers)
print("Using reduce():")
print(f"Result: {result}")
Using reduce(): Result: 8.8e-06
Conclusion
Consecutive division takes the first element of a list and divides it by each subsequent element in sequence. The operation can be implemented using a simple loop or functional programming approaches like reduce().
Advertisements
