我遇到一个简单的多维数组问题。
Python代码是:
SelectionSort.py
class SelectionSort(object):
@staticmethod
def sort(list):
for i in range(0, len(list)):
min = i;
for j in range (i+1, len(list)):
if j < list[min]:
min = j;
tmp = list[min];
list[min] = list[i];
list[i] = tmp;
return list;
MatriceSelectionSort.py
import sys;
import traceback;
import re;
from SelectionSort import SelectionSort;
class MatriceSelectionSort(object):
def run(self):
if len(sys.argv) < 2:
print("Missing fileName arg! Examplu de rulare: python MatriceSelectionSort C:\\wsmt\\matrice.txt\n");
sys.exit(1);
fileName = sys.argv[1];
try:
matrix = self.readMatrix(fileName);
for row in matrix:
SelectionSort.sort(row);
self.writeResult(fileName, matrix);
except Exception as e:
print("Nu pot citi/parsa fisierul\n");
traceback.print_exc();
def readMatrix(self, fileName):
matrix = [];
with open(fileName, "r") as file:
for line in file:
row = [];
tokens = re.split("\s+", line);
for token in tokens:
if token:
row.append(int(token));
matrix.append(row);
return matrix;
def writeResult(self, fileName, matrix):
with open(fileName, "a") as file:
file.write("\n\n"); # python will translate \n to os.linesep
for row in matrix:
for item in row:
file.write(str(item) + " ");
file.write("\n");
if __name__ == '__main__':
MatriceSelectionSort().run();
Matrice.txt
7 3 1 9 4
2 1 10 4 9
12 4 23
问题是文件的输出是: (排序的矩阵应该在文件的末尾,像这样) 的 Matrice.txt
7 3 1 9 4
2 1 10 4 9
12 4 23
1 4 3 7 9
1 2 4 9 10
23 12 4
所以,它不像世界上最好的那种...... 我认为问题出在SelectionSort.py文件中,我搞砸了“length [i]”和“i”变量。我是初学者,感谢任何帮助! 谢谢!
答案 0 :(得分:0)
<div>$name$: $id$</div>
方法中有一个小错误,它将循环计数器name + "_id"
与最小值进行比较。如果您进行以下更改,则可以解决问题:
name + "_id"