简体   繁体   中英

Best way to run a function in main function when one of the parameters is not in the scope

Basically my brain is not working right now can't figure out the best way to resolve this error. builtins.NameError: name 'numIters' is not defined I know this problem is that numIters is not defined in its scope but don't know the best solution to fix that.

Here is the bulk of my code

import random
alg = int(input("Select the sorting algorithm \n 1 - linear search \n 2 - binary search \nEnter Choice: "))
n = int(input("Choose the size of the list: ")) 
def main():
    createList(n,alg)
    print(runTest(values,n,alg))
    printResults(alg,n,numIters)
    #print(linearSearch(values,2))
    #print(binarySearch(values, 2))


def createList(n,alg):
    global values
    values = []
    random.seed(1456)
    for j in range(n):
        values.append(random.randint(0, 2*n))

    while len(values) == n:
        if alg == 2:
            values.sort()
            print(values)
            return values
        elif alg == 1:
            print(values)
            return values

def linearSearch(values, target):
    numIters = 0
    for i in range(len(values)):
        numIters = numIters + 1
        if values[i] == target:
            return numIters
    return -1
def binarySearch(values, target):
    numIters = 0
    start = 0
    high = len(values) - 1
    while start <= high:

        middle = (start + high)//2

        if values[middle] == target:

            numIters = numIters + 1
            return numIters
        elif values[middle] > target:
            numIters = numIters + 1
            high = middle - 1
        else:
            numIters = numIters + 1
            start = middle + 1

    return -1
def runTest(values,n,alg):
    if alg == 2:
        count = 0
        for j in range(n * 2):
            count = count + 1
            tgt = random.randint(0, 2*n)
            binarySearch(values, tgt)
        return count
    elif alg == 1:
        count = 0
        for j in range(n * 2):
            count = count + 1
            tgt = random.randint(0, 2*n)
            linearSearch(values, tgt)
        return count

def printResults(alg, n, numIters):
    avgIter = n / numIters
    if alg == 2:
        algType = Binary
    if alg == 1:
        algType = Linear
    print("Results \n n = %d \n %s = %f.2 " % (n,algtype,avgIter))

main()

Thank you in advance for any help given as I am still trying to learn and understand how python works as a whole.

You need to return numIters so that you can pass it to the next function. It looks like it currently gets returned from binarySearch and linearSearch to runTest , but it gets discarded there; just bubble it up like this (I'm going to add type annotations and comments to help me keep track of what's going on):

from typing import List, Tuple

def runTest(values: List[int], n: int, alg: int) -> Tuple[int, int]:
    """Returns count, numIters"""
    numIters = 0  # default value in case n is so small we don't iterate
    if alg == 2:
        count = 0
        for j in range(n * 2):
            count = count + 1
            tgt = random.randint(0, 2*n)
            numIters = binarySearch(values, tgt)
        return count, numIters
    elif alg == 1:
        count = 0
        for j in range(n * 2):
            count = count + 1
            tgt = random.randint(0, 2*n)
            numIters = linearSearch(values, tgt)
        return count, numIters
    raise ValueError("alg needs to be 1 or 2!")

Now in your main() you can do:

def main():
    createList(n, alg)
    count, numIters = runTest(values, n, alg)
    print(count)
    printResults(alg, n, numIters)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM