简体   繁体   中英

Printing final list in variable

I'm working my way through Elements of Programming Interview in Python and I'm trying to find an alternative solution for the first problem in the Arrays chapter. The idea is that you are to write a program that takes an array A and index i into A and rearranges the elements such that all elements less than A[i] appear first, followed by elements equal to the pivot followed by elements greater than the pivot. In the book, they already provided a solution but I'm trying to figure out an alternative one. In a nutshell, I'm creating subarrays for each aspect such as smaller, equal, and larger than A[i]. For right now I'm working on storing the integer values of A that are less than the pivot. I want to iterate over the list of A and store the values of all elements less than the pivot in the smaller (variable). The idea is to eventually return the variable smaller which will contain all values smaller than the pivot. To check my work I used the print function just to check the value of smaller. It stored each iteration smaller than the pivot in that variable. Ideally using this approach I just want to return the final iteration of the smaller variable instead of each iteration. What should be my next steps? Hopefully, that makes sense, I really don't mind elaborating on any part. Thanks in advance.

def properArray(pivot_index, A):
    pivot = A[pivot_index]
    smaller = []
    for i in range(len(A)):
        if A[i] < pivot:
            smaller.append(A[i])
            print (smaller)

resized_array =properArray
resized_array(3, [1,5,6,9,3,4,6])

I guess this is what you are trying to achieve

def properArray(pivot_index, A):
     pivot = A[pivot_index]
     smaller = []
     for i in range(len(A)):
         if A[i] < pivot:
             smaller.append(A[i])
     print (smaller)

resized_array =properArray
resized_array(3, [1,5,6,9,3,4,6])

Instead of printing smaller array on every iteration, you need to print it once, after the for loop is complete

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