Home > front end >  Printing final list in variable
Printing final list in variable

Time:11-12

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])

CodePudding user response:

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

  • Related