开发者

creating a reverse method for a python list from scratch

开发者 https://www.devze.com 2023-02-15 16:20 出处:网络
I want to create a reverse method for a list.I know there already is such a method built into python but I want to try it from scratch.Here\'s what I have and it seems to make sense to me but it just

I want to create a reverse method for a list. I know there already is such a method built into python but I want to try it from scratch. Here's what I have and it seems to make sense to me but it just returns the list in the same order. My understanding was that lists are mutable and I could just reassign values in the loop.

def reverse(data_list):
    length = l开发者_JAVA百科en(data_list)
    s = length

    for item in data_list:
        s = s - 1
        data_list[s] = item
    return data_list


def reverse(data_list):
    return data_list[::-1]
>> reverse([1,2,3,4,5])
[5, 4, 3, 2, 1]


By the time you are half-way through the list, you have swapped all the items; as you continue through the second half, you are swapping them all back to their original locations again.

Instead try

def reverse(lst):
    i = 0            # first item
    j = len(lst)-1   # last item
    while i<j:
        lst[i],lst[j] = lst[j],lst[i]
        i += 1
        j -= 1
    return lst

This can be used in two ways:

a = [1,2,3,4,5]
reverse(a)        # in-place
print a           # -> [5,4,3,2,1]

b = reverse(a[:]) # return the result of reversing a copy of a
print a           # -> [5,4,3,2,1]
print b           # -> [1,2,3,4,5]


You are changing the list that you iterate on it (data_list) because of that it's not working , try like this:

def reverse(data_list):
    length = len(data_list)
    s = length

    new_list = [None]*length

    for item in data_list:
        s = s - 1
        new_list[s] = item
    return new_list


an easy way in python (without using the reverse function) is using the [] access operator with negative values such as (print and create a new list in reverse order):

x = [1, 2 ,3, 4, 5]
newx = []
for i in range(1, len(x)+1):
  newx.append(x[-i])
  print x[-i]

the function would be:

def reverse(list):
  newlist = []
  for i in range(1, len(list)+1):
    newlist.append(list[-1])
  return newlist


I do not get the same list when I try to run your code. But I also do not get a reversed list because the list is moving forward through the list state which is changing from end back. I think the way you are looking to do it is:

def reverse(data_set):
  length = len(data_set)

  for i in range(0, length / 2):
    length = length - 1
    hold = data_set[i]
    data_set[i] = data_set[length]
    data_set[length] = hold
  return data_set

here we actually reverse in half the iterations and we memoize the value of the index we are changing so we can set the "reversal" in the same step.


word_reversed = ''

    for i in range(len(word) -1, -1, -1):
        word_reversed += word[i]

That will reverse a string of unknown length called (word) and call it (word_reversed).

I am using it to check to see if a word is a palindrome and I'm not allowed to use .reverse or word[::-1].

# Tyler G
# April 10, 2018
# Palindromes

import re

word = input("Palindromes are words that spell the same thing forwars or backwards, enter a word and see if its one!: ")
word = word.lower()
word = re.sub("[^a-zA-Z]+", "", word)
# count the number of characters in the string
# make a if <string>[0] = <string[counted char -1]
# repeat that over and over
# make a else print("not a ...")
word_reversed = ''

for i in range(len(word) - 1, -1, -1):
    word_reversed += word[i]

itis = 0
if len(word) > 12:
    print("It is not a Palindrome")

else:
    for i in range(0, len(word)):
        if word[i] == word_reversed[i]:
            itis = itis + 1
        else:
            itis = itis - len(word)
    if itis > 0:
        print("It is a palindrome")
    else:
        print("It is NOT a Palindrome")

itis = 0
if len(word) > 12:
    print("It is not a Palindrome")


There are two simple ways to solve the problem : First using a temp variable :

maList = [2,5,67,8,99,34]
halfLen = len(maList) // 2
for index in range(halfLen):
    temp = maList[index]
    maList[index] = maList[len(maList) - 1 - index]
    maList[len(maList) - 1 - index] = temp
print(maList)

Second is using a new list where to store the reversed values :

newList = []
for index,value in enumerate(maList):
    newList.append(maList[len(maList) - 1 - index])
print(newList)


Something like this should work:

mylist = [1,2,3,4,5]
def reverse(orig_list):
    data_list = orig_list[:]
    length = len(data_list)
    for i in xrange(0, length/2):
        tmp = data_list[length-i-1]
        data_list[length-i-1] = data_list[i]
        data_list[i] = tmp
    return data_list

reverse(mylist)
mylist


There are two ways of doing this

Pythonic Swap:

def Reverse_Function(item):
    for i in range(len(item)/2):
        item[i], item[-(i+1)] = item[-(i+1)], item[i]
    return item

or

XOR application:

def Reverse_Function(item):
    for i in range(len(item)/2):
        item[i] = item[i] ^ item[-(i+1)]
        item[-(i+1)] = item[i] ^ item[-(i+1)]
        item[i] = item[i] ^ item[-(i+1)]
    return item


Not looking to create a new list to hold your "temp" data? Its simple if you look at the pattern:

reverse_list([a, b, c, d, e]) => [e, d, c, b, a]

This means that position 0 -> n, 1 -> (n - 1), 2 -> (n - 2). Which means that you can pop the last item and put it in the current index...

def reverse_list(list):
    i = 0
    while i < (len(list) - 1):
        list.insert(i, list.pop())
        i += 1


from array import *

x=array('i',[1,2,3,98,5,6,7,8])

y=array('i',[])

for i in x:

     y.insert(0,i)

print(y)


Normally you can use either reversed() in general, or [::-1] on sequences. Since you are trying to implement a function from scratch, consider using stack, which is a common Abstract Data Type.

Given

import queue


s = "abc"
lst = list(s)
iter_ = iter(s)

Code

The following works on sequences and iterators similar to reversed():

def reversed_iter(iterable):
    """Yield items in reverse with a queue."""
    stack = queue.LifoQueue()                          # 1
    for x in iterable:                                 # 2
        stack.put(x)
    while not stack.empty():                           # 3
        yield stack.get()

Demo

list(reversed_iter(s))
# ['c', 'b', 'a']
list(reversed_iter(lst))
# ['c', 'b', 'a']
list(reversed_iter(iter_))
# ['c', 'b', 'a']

Details

A stack is type of queue where the last element placed in is the first element removed. Imagine placing elements on top of each other in a container.

       ↓   ↑
    |   "c"   |
    |   "b"   |
    |   "a"   |
    -----------

Here the last element placed (enqueued) is the first to remove (dequeue), e.g. "c".

In the code, we:

  1. Initialize a stack (the same as a LifoQueue)
  2. Enqueue items to the stack
  3. Dequeue items from the stack

The result are elements yielded in reversed order.

A queue is not required. Alternatively, we can emulate a stack with a simple list:

def reversed_iter(iterable):
    """Yield items in reverse with a list."""
    stack = []
    for x in iterable:
        stack.append(x)
    while stack:
        yield stack.pop()


list(reversed_iter(s))
# ['c', 'b', 'a']

Emulating the Abstract Data Type is all that is needed in both examples.


list = [23, 3, 33, 44, 55, 16, 27 ];

1.more codes

def conver(list):
    list.sort()

    length = len(list)
    s = length

    new_list = [None]*length
    for item in list:
        s = s - 1
        new_list[s] = item

    print(new_list)


conver(list)

output:

[55, 44, 33, 27, 23, 16, 3]

2.easiest

list.sort()

list.reverse()

print(list)

output:

[55, 44, 33, 27, 23, 16, 3]


The following code demonstrates how to accept input:

a=[]
n=int(input("enter the no.of elements ")
for I in range(0,n):
      a.insert(I,int(input(" enter elements: ")))
def rev_list(a):
      print(a[::-1])
rev_list(a)


def reverseOrder():
    my_list = []
    a = input("What is your word?")
    count = len(a) - 1


    x = ''
    for i in range(0, len(a)):
        my_list.append(a[count])
        count = count - 1
    x = x.join(my_list)
    print(x)

reverseOrder()

This is what I did. First I made an empty list. Then I stored users answer in a variable and subtracted one for indexing purposes. Now start a for loop and you set 'range' from 0 , len(a) then you append into the list backwards since count is = len(a). After that you set the .join function and join the list together. This is why there was variable x before the for loop.

0

精彩评论

暂无评论...
验证码 换一张
取 消