-1

how can i do queue?

mylist = [1, 2, 3]

i want to enter mylist in this function and i want get new list like this: [4, 2, 3] further [5, 4, 3] further [6, 5, 4] etc

def testfunc(mylist):
    return mylist

Thanks in advance.

RAINGM
  • 133
  • 7

3 Answers3

2

It looks like there might be two interpretations to your question (from the comments).

  1. enqueuing a provided item to the front of the list and removing an item at the end
  2. putting an item in and popping off the smallest item

There are other data structures that may be better suited to what you're ultimately looking to do. I'll give two examples of alternatives. I'm not sure if either of these alone give you exactly what you want, but I think they're steps towards it.

Using deque

One comment seems to mention being able to pass the value. That would work well with a deque:

from collections import deque

q = deque([1, 2, 3], maxlen=3)
print(q)  # [1, 2, 3]
q.appendleft(4)
print(q)  # [4, 1, 2]
q.appendleft(5)
print(q)  # [5, 4, 1]

You can then use q.popleft to get the "first" item.

Using heapq

Another comment seems to be about keeping just the max value, which would work well to treat your list as a "priority queue":

import heapq

q = [1, 2, 3]
heapq.heapify(q)
print(q)  # [1, 2, 3]

# push item on the heap, and pop the smallest item
heapq.heappushpop(q, 4)
print(q)  # [2, 4, 3]
heapq.heappushpop(q, 5)
print(q)  # [3, 4, 5]

heapq.heappop(q) from this heap will yield the smallest item. You should use the heapq functions to interact with items on this list. You'll notice the order (visually) might not be what you expect, but that's what the heapq functions take care of.

If, instead, you want a max-heap, another post has tons of opinions on that.

NikT
  • 1,590
  • 2
  • 16
  • 29
1

i guess this would work for what it seems you want

def testfunc(mylist):
    mylist=[mylist[0]+1]+mylist
    mylist.pop(-1)
    return mylist

or if you want to always remove the smallest element from the list, change mylist.pop(-1) to mylist.remove(min(mylist))

edit to pass new element

def testfunc(mylist,newitem):
         mylist=[newitem]+mylist
         mylist.remove(min(mylist))
         return mylist
SuperStew
  • 2,857
  • 2
  • 15
  • 27
0

This function will insert the given element at the front of the list, then slice to exclude the last item:

def enqueue(l, item):
    l.insert(0, item)
    l.pop()

If you always want to enqueue the maximum element +1:

def enqueue(l):
    l.insert(0, max(l) + 1)
    l.pop()

Usage:

mylist = [1, 2, 3]
enqueue(mylist)
print(mylist)
enqueue(mylist)
print(mylist)
enqueue(mylist)
print(mylist)

Output:

[4, 1, 2]
[5, 4, 1]
[6, 5, 4]
zr0gravity7
  • 2,917
  • 1
  • 12
  • 33