Python sublist by index Full

image 1 1066

Kinh Nghiệm Hướng dẫn Python sublist by index Chi Tiết

Bạn đang tìm kiếm từ khóa Python sublist by index được Cập Nhật vào lúc : 2022-02-03 13:06:18 . Với phương châm chia sẻ Kinh Nghiệm Hướng dẫn trong nội dung bài viết một cách Chi Tiết 2022. Nếu sau khi đọc nội dung bài viết vẫn ko hiểu thì hoàn toàn có thể lại phản hồi ở cuối bài để Ad lý giải và hướng dẫn lại nha.

I’ve been working on implementing common sorting algorithms into Python, and whilst working on selection sort I ran into a problem finding the minimum value of a sublist and swapping it with the first value of the sublist, which from my testing appears to be due to a problem with how I am using min() in my program.

Here is my code:

def selection_sort(li):
for i in range(0, len(li)):
a, b = i, li.index(min(li[i:]))
li[a], li[b] = li[b], li[a]

This works fine for lists that have zero duplicate elements within them:

>>> selection_sort([9,8,7,6,5,4,3,2,1])
[1, 2, 3, 4, 5, 6, 7, 8, 9]

However, it completely fails when there are duplicate elements within the list.

>>> selection_sort([9,8,8,7,6,6,5,5,5,4,2,1,1])
[8, 8, 7, 6, 6, 5, 5, 5, 4, 2, 9, 1, 1]

I tried to solve this problem by examining what min() is doing on line 3 of my code, and found that min() returns the index value of the smallest element inside the sublist as intended, but the index is of the element within the larger list rather than of the sublist, which I hope this experimentation helps to illustrate more clearly:

>>> a = [1,2,1,1,2]
>>> min(a)
1 # expected
>>> a.index(min(a))
0 # also expected
>>> a.index(min(a[1:]))
0 # should be 1?

I’m not sure what is causing this behaviour; it could be possible to copy li[i:] into a temporary variable b and then do b.index(min(b)), but copying li[i:] into b for each loop might require a lot of memory, and selection sort is an in-place algorithm so I am uncertain as to whether this approach is ideal.

question from:://stackoverflow/questions/65643799/find-index-of-minimum-value-in-a-python-sublist-min-returns-index-of-minimum

Reply
8
0
Chia sẻ

Video Python sublist by index ?

Bạn vừa tìm hiểu thêm Post Với Một số hướng dẫn một cách rõ ràng hơn về Review Python sublist by index tiên tiến và phát triển nhất

Chia Sẻ Link Down Python sublist by index miễn phí

You đang tìm một số trong những Chia SẻLink Tải Python sublist by index Free.

Hỏi đáp vướng mắc về Python sublist by index

Nếu Bạn sau khi đọc nội dung bài viết Python sublist by index , bạn vẫn chưa hiểu thì hoàn toàn có thể lại phản hồi ở cuối bài để Ad lý giải và hướng dẫn lại nha
#Python #sublist #index

Exit mobile version