Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to merge two deques

Exist a faster way to merge two deques than this?

# a, b are two deques. The maximum length 
# of a is greater than the current length 
# of a plus the current length of b

while len(b):
  a.append(b.popleft())

Note that I'm not interested in preserving input deques, I'm only interested in having the merged one as fast as possible.

like image 613
gvgramazio Avatar asked Mar 05 '23 03:03

gvgramazio


1 Answers

There's no need for elementwise appending, you can just use +=:

from collections import deque

a = deque([1, 2, 3])
b = deque([4, 5, 6])

a += b

print(a)

deque([1, 2, 3, 4, 5, 6])
like image 155
jpp Avatar answered Mar 07 '23 16:03

jpp