简体   繁体   中英

Reverseing a 1-D array - PYTHON

How can I write a Python function that given an array A of numbers returns an array B that has the elements of A in reverse order? WITHOUT using the reverse function in python, and instead use a for loop?

This is what I have so far and then I call the function main() in the shell and it gives me some errors and one of them is 'B' is not defined.

def ReverseArray(A):
    n = len(A)
    for i in range(0, n-1):
        B[n-i-1] = A[i]
    return (B)

def main():
    A = [13, 21, 15, 38, 49]  # Test case for ReverseArray function
    B = ReverseArray(A)
    print(B)

Where did I go wrong?

Your first problem, as you say, is that you haven't defined B .

The obvious answer is to define B . What's the starting value when you're accumulating a list ? Presumably any empty list , right? So:

def ReverseArray(A):
    B = []
    n = len(A)
    for i in range(0, n-1):
        B[n-i-1] = A[i]
    return (B)

The next problem you'll run into is an IndexError from that B[ni-1] = A[i] . That's because you're trying to modify B 's items in-place, so it has to have n items to start with. In other words, you want something with as many items as A . How about a copy of A ?

B = list(A)

Or, if you understand list comprehensions, this might be better:

B = [None for _ in A]

Finally, your algorithm is not actually correct. For example, given your A , n will be 5 , so range(0, n-1) will be [0, 1, 2, 3] . This means you never set B[0] to anything.

You may not have realized that the Python range function returns a range that excludes the stop parameter. Just range(0, n) (or, more simply, range(n) ) is what you want.

You can iterate over a list backwards like this, then add each element to the list B.

def ReverseArray(A):
    B = list()
    for i in xrange(len(A)-1,-1,-1):
        B.append(A[i])
    return B

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