![](/img/trans.png)
[英]how do i remove the Nth element from my list until there's only one element remains and print that remaining element in python
[英]Split a list by certain value until only the first element remains python
我想計算我可以將一組元素除以某個值多少次,直到只剩下一個元素
10 個元素的數組可以除以 3 次,但我的循環只執行一次然后停止。 顯然我錯過了一些東西..
# a function that takes an integer as input
def split_a_list(length):
# create an array of elements where the input to the function determines the length of the array
elements = list(range(1, (length +1)))
begin_index = 0
end_index = len(elements)-1
count = 0
# a value that specifies the size of remaining size of the array
divider = 2
while begin_index < end_index:
# because divider = 2 (as defined above), this divides the array in half
mid_index = math.floor(float((begin_index + end_index)/divider))
# this counts the number of times the array has been divided
count += 1
# the last index of the array is now the mid index of the previous array
end_index = mid_index - 1
# here I would like the function to be called again, but with the integer corresponding to
# the the updated end index which is the mid index of the previous array
return split_a_list(end_index), count
# An array of 10 elements can be divided in half 3 times until 1 element remains
# I would like the function to store the number of times the array can be divided in the variable count
# and return this value as output
length = 10
split_a_list(length)
這返回 ((None, 1), 1) 但我希望它返回 3,因為 10 的數組可以被划分 3 次,直到剩下 1 個元素
提前非常感謝!
如果您只是在尋找 integer,請保持簡單,使用地板除法。
length = len(your_list)
n = 0
while length > 1:
length //= 2
n += 1
//
運算符 ( floor division ) 在這里用於將length
分成 2 個(整體)部分。 然后將地板除法的結果分配回length
並繼續操作,直到length
等於1
。
你可以看到它在這里工作:
>>> length = 10
>>> length //= 2
5
>>> length //= 2
2
>>> length //= 2
1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.