Python - 列表中的连续除法
给定一个List,对中间步骤中得到的每个商进行连续除法,并将连续的元素作为除数处理。
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.
方法:使用循环+“/”运算符
在这种情况下,我们对每个元素进行迭代,并将获得的商存储为循环中下一个操作的被除数。最终结果是列表的最终商。
Python3
# Python3 code to demonstrate working of
# Consecutive Division in List
# Using loop + / operator
# utility fnc.
def conc_div(test_list):
res = test_list[0]
for idx in range(1, len(test_list)):
# Consecutive Division
res /= test_list[idx]
return res
# initializing list
test_list = [1000, 50, 5, 10, 2]
# printing original list
print("The original list is : " + str(test_list))
# getting conc. Division
res = conc_div(test_list)
# printing result
print("The Consecutive Division quotient : " + str(res))
输出
The original list is : [1000, 50, 5, 10, 2]
The Consecutive Division quotient : 0.2