Python程式檢查樞紐左側和右側元素是否分別小於或大於
通常,樞紐表是透過聚合一個或多個離散類別中各個元素形成的已分組值的表格。
在Python中,“樞紐”一詞通常與排序演算法或涉及根據特定值或條件重新排列元素的操作相關聯。樞紐可以是資料結構中的任何元素或位置,其目的是將資料分成兩部分:小於樞紐的元素和大於樞紐的元素。
有多種方法可以檢查樞紐左側和右側的元素是否分別小於或大於。
使用迴圈
迴圈用於根據使用者需求迭代元素。在本文中,for迴圈用於迭代給定陣列的元素,並檢查樞紐的較小或較大元素。
示例
在此示例中,我們建立for迴圈以迭代陣列的元素,並建立條件以檢查樞紐左側和右側的較小或較大元素。
def check_pivot(arr, pivot_index): pivot = arr[pivot_index] for i in range(pivot_index): if arr[i] >= pivot: return False for i in range(pivot_index + 1, len(arr)): if arr[i] <= pivot: return False return True my_list = [1, 2, 3, 4, 5] pivot_index = 2 if check_pivot(my_list, pivot_index): print("Elements to the left are smaller and to the right are greater.") else: print("Elements to the left are not smaller and to the right are not greater.")
輸出
Elements to the left are smaller and to the right are greater.
使用列表切片
列表切片是一種將列表分成不同部分的技術。在本文中,我們將把給定的陣列分成不同的部分,並檢查元素是否大於或小於樞紐。
示例
在此示例中,我們將給定的輸入陣列切分成不同的部分,並檢查樞紐右側或左側的元素是否大於或小於。
def check_pivot(arr, pivot_index): left = arr[:pivot_index] right = arr[pivot_index + 1:] return all(x < arr[pivot_index] for x in left) and all(x > arr[pivot_index] for x in right) my_list = [1, 3, 3, 4, 5] pivot_index = 2 if check_pivot(my_list, pivot_index): print("Elements to the left are smaller and to the right are greater.") else: print("Elements to the left are not smaller and to the right are not greater.")
輸出
Elements to the left are not smaller and to the right are not greater.
廣告