【解決方法】並べ替え、テスト、およびファイル クエリ。

プログラミングQA


import numpy as np
import sys
import timeit
import DSAsorts
import random


REPEATS = 3           #No times to run sorts to get mean time
NEARLY_PERCENT = 0.10 #% of items to move in nearly sorted array
RANDOM_TIMES = 100    #No times to randomly swap elements in array

def usage():
    print(" Usage: java TestHarness n xy [xy ...]")
    print("        where")
    print("        n is number of integers to sort")
    print("        x is one of")
    print("           b - bubblesort")
    print("           i - insertion sort")
    print("           s - selection sort")
    print("           q - quicksort")
    print("           m - mergesort")
    print("        y is one of")
    print("           a - 1..n ascending")
    print("           d - 1..n descending")
    print("           r - 1..n in random order")
    print("           n - 1..n nearly sorted (10% moved)")

def doSort(n, sortType, arrayType):
        A = np.arange(1, n+1, 1)   #create array with values from 1 to n
        
        if arrayType == 'a':
            ...
        elif arrayType =='d':  #convert to descending
            for i in range(0, int(n/2)):
                temp = A[i]
                A[i] = A[n-i-1]
                A[n-i-1] = temp
            print("Descending: ", A)
        elif arrayType == 'r':
            for i in range(RANDOM_TIMES*n):
                x = int(random.random()*n)
                y = int(random.random()*n)
                temp = A[x]
                A[x] = A[y]
                A[y] = temp
            print("Random: ", A)
        elif arrayType == 'n':
            for i in range(int(n*NEARLY_PERCENT/2+1)):
                x = int(random.random()*n)
                y = int(random.random()*n)
                temp = A[x]
                A[x] = A[y]
                A[y] = temp
            print("Nearly sorted: ", A)
        else:
            print("Unsupported array type")

        if sortType == "b":
            DSAsorts.bubbleSort(A)
        elif sortType == "s":
            DSAsorts.selectionSort(A)
        elif sortType == "i":
            DSAsorts.insertionSort(A)
        elif sortType == "m":
            DSAsorts.mergeSort(A)
        elif sortType == "q":
            DSAsorts.quickSort(A)
        else:
            print("Unsupported sort algorithm")

        for i in range(n-2):
            if (A[i] > A[i+1]):
                raise ValueError("Array not in order")

#main program

if len(sys.argv) < 3:
    usage()
else:
    for aa in range(2, len(sys.argv)):
        
        n = int(sys.argv[1])
        sortType = sys.argv[aa][0]
        arrayType = sys.argv[aa][1]

        runningTotal = 0

        for repeat in range(REPEATS):
             startTime = timeit.default_timer()
             doSort(n, sortType, arrayType)
             endTime = timeit.default_timer()

             runningTotal += (endTime - startTime)
    
        print(sortType + arrayType + " " + str(n) + " " + str(runningTotal/(REPEATS - 1)))`

これは、テストするコードを保持する 2 番目のファイルをインポートした後に実行する必要があるテスト コードです。S

私が試したこと:

<pre>def bubbleSort(A):
    n = len(A)
    for i in range(n):
        swapped = False
        for j in range(0, n-i-1):
            if A[j] > A[j+1]:
                A[j], A[j+1] = A[j+1], A[j]
                swapped = True
        if not swapped:
            break
    return A

def insertionSort(A):
    for i in range(1, len(A)):
        key = A[i]
        j = i - 1
        while j >= 0 and key < A[j]:
            A[j + 1] = A[j]
            j -= 1
        A[j + 1] = key
    return A

def selectionSort(A):
    for i in range(len(A)):
        min_idx = i
        for j in range(i+1, len(A)):
            if A[min_idx] > A[j]:
                min_idx = j
        A[i], A[min_idx] = A[min_idx], A[i]
        # start the next pass after the first element
        i += 1
    return A
S
def mergeSort(A):
    """ mergeSort - front-end for kick-starting the recursive algorithm
    """
    ...

def mergeSortRecurse(A, leftIdx, rightIdx):
    ...

def merge(A, leftIdx, midIdx, rightIdx):
    ...

def quickSort(A):
    """ quickSort - front-end for kick-starting the recursive algorithm
    """
    ...

def quickSortRecurse(A, leftIdx, rightIdx):
    ...

def doPartitioning(A, leftIdx, rightIdx, pivotIdx):
This is the code for the sorting methods that I have created, not running the test code does work but the output ends up being:[the output](https://i.stack.imgur.com/UoJxH.png)

Problem is I don't think this is the correct output that should be displayed. Does anyone know what changes I should make?

解決策 1

データに何が含まれているか、またはソートから実際にどのような出力が得られるかがわからないため、実際にお手伝いすることはできません.

だから、それはあなた次第になるでしょう。
幸いなことに、何が起こっているのかを調べるのに役立つツール、デバッガーを利用できます。 ここで始める: pdb — Python デバッガ — Python 3.11.1 ドキュメント[^]

関数の最初の行にブレークポイントを置き、デバッガーでコードを実行します。 次に、コードとデータを見て、何が起こるべきかを手動で解決します。 次に、各行を 1 ステップ実行して、予想どおりの動作を確認します。 そうでない場合は、問題が発生したときであり、後戻りして (またはもう一度実行して詳しく調べて) 原因を突き止めることができます。

申し訳ありませんが、私たちはあなたにそれを行うことはできません – 新しい (そして非常に便利な) スキルを学ぶ時が来ました: デバッグ!

解決策 2

引用:

これは表示されるべき正しい出力ではないと思います。

次のコードで示されているように、これはまさに表示されるはずの出力です。

Python
#main program

if len(sys.argv) < 3:
    usage()

しかし、あなたがコードを書いたので、それは明らかです。

コメント

タイトルとURLをコピーしました