该程序在n = 3时工作,但在大于3时不工作 [英] The program is working when n=3 but not when is greater than 3

查看:79
本文介绍了该程序在n = 3时工作,但在大于3时不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

程序在列表中输入n个元素

然后随机选择列表中的两个索引并比较它们按递增顺序切换它们

该过程重复直到列表已分类



我的尝试:



The program inputs n numbers of elements in list
then randomly selects two indexes in the list and compares them switches them in increasing order
the process repeats until the list is sorted

What I have tried:

from random import randint
n=input()
n=int(n)
list_1=[]
for i in range (n):
  x=input()
  list_1.append(x)
k=2**n
for i in range (k):
    i=randint(0,n-1)
    j=randint(0,n-1)
    i=int(i)
    j=int(j)
    if(i>j):
        i,j=j,i
    print(list_1)
    print(i)
    print(j)
    if(list_1[i]>list_1[j]):
        list_1[i],list_1[j]=list_1[j],list_1[i]
print(k)

推荐答案

这是因为你的列表包含字符串而不是整数。按字符串顺序排序,19将出现在3等之前
It is because your list contains strings and not integers. Sorting in string order, "19" will come before "3", etc.


Quote:

该程序在n = 3时工作,但在大于3时不工作

The program is working when n=3 but not when is greater than 3



定义不起作用!举个例子。


Define not work! Give example.

引用:

重复该过程直到列表排序

the process repeats until the list is sorted



没有你的代码无法知道列表是否排序。

由于随机选择的位置没有确保你有效地对列表进行排序。

您的代码是不确定的。它不是一种排序列表的方法。



因为randint返回一个整数,你可以简化你的代码:


No your code have no way to know if the list is sorted or not.
Because of the random pick of positions nothing ensure that you effectively sort the list.
Your code is non deterministic. it is not a method to sort a list.

Because randint return an integer, you can simplify your code as:

i=randint(0,n-1)
j=randint(0,n-1)
i=int(i)
j=int(j)

这篇关于该程序在n = 3时工作,但在大于3时不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆