loading...

leetcode reverse an array

tonetheman profile image Tony Colston ・1 min read

I am always looking to learn something. Sometimes it is re-working problems like I am a complete beginner. Almost like starting over. I have read that called "beginners mind" in some literature.

So today I looked at unopened emails and I had one from Passion of Programming. It was a programming problem of reversing an array.

So I started a Python repl and started figuring out how to reverse an array.

def r(a,start,end):
    print(a,start,end)

    def swapit(pos1,pos2):
        tmp = a[pos1]
        a[pos1] = a[pos2]
        a[pos2] = tmp

    for i in range(int(len(a)/2)):
        swapit(start+i,end-i)
    print(a,start,end)
    return a

I wrote a few test cases and it looked correct.

Is it the best way to do it? Probably not but it is what I came up with fairly quickly and it passed my tests.

One thing that I like about Python is being able to define a function exactly where you need it. The

def swapit(pos1,pos2):

only works in the function r. Another way to say that is that swapit is scoped to only run in the function r.

One other thing I noticed is that it skips the middle element if you have an array that has an odd length.

So there you are. Now the next time I am asked an array for a job interview. BOOM!

Posted on by:

tonetheman profile

Tony Colston

@tonetheman

wanna be gamedev ... all around nerd and dev

Discussion

markdown guide