【问题标题】:Python Selectionsort, can't use len()Python 选择排序,不能使用 len()
【发布时间】:2013-10-02 17:24:15
【问题描述】:
def selectionSort(list1):
   for sixNumbers in range(len(list1) - 1, 0, -1):
       maxPos = 0
       for position in range(1, sixNumbers + 1):
           if list1[position] > list1[maxPos]:
               maxPos = position

       value = list1[sixNumbers]
       list1[sixNumbers] = list1[maxPos]
       list1[maxPos] = value

def main():
    list1 = [45, 7, 5, 24, 12, 1]
    selectionSort(list1)
    print(list1)

main()

如何不使用len()?我的导师告诉我不要使用内置的排序功能。有什么建议吗?另外,不要给我代码,给我一些提示,这样我可以尝试重写它。

【问题讨论】:

  • len() 不是内置的sort() 函数。不允许使用任何内置函数吗?
  • sixNumbers 对于单个号码来说是一个非常糟糕的名字。
  • @ErikAllik 我将其重命名为 i
  • @RohitJain 我想我可能听错了。 “你不能使用任何内置的 Python 排序函数。”那么我对 len() 还好吗?
  • 交换值也比在 python 中容易得多。 list1[six_number], list1[maxPos] = list1[maxPos], list1[six_number]

标签: python sorting built-in


【解决方案1】:

不使用 len() 计算元素的一种非常愚蠢的方法是使用 for 循环遍历值。每次通过循环递增以获取计数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-12
    • 2017-04-24
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 2013-01-19
    • 2015-08-13
    • 1970-01-01
    相关资源
    最近更新 更多