コード例 #1
0
def get_unique_adjacent(string: str) -> Optional[str]:
    length = len(string)
    freq = {}
    if length == 0:
        return string

    for i in range(length):
        if string[i] not in freq:
            freq[string[i]] = 0
        freq[string[i]] += 1

    sorted_freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
    queue = Queue()
    [queue.enqueue(item) for item in sorted_freq]
    result = ""

    if length % 2 == 0 and sorted_freq[0][1] > length // 2:
        return None
    elif length % 2 == 1 and sorted_freq[0][1] > (length // 2) + 1:
        return None

    while not queue.is_empty():
        if len(queue) == 1:
            elem, freq = queue.peek()
            if freq == 2:
                result = elem + result + elem
                break
            elif freq == 1:
                if result[-1] != elem:
                    result += elem
                else:
                    result = elem + result
                break
            return None

        elem1, freq1 = queue.peek()
        elem2, freq2 = None, None
        if len(queue) > 1:
            elem2, freq2 = queue[1]

        result += elem1 + elem2

        queue[0] = elem1, freq1 - 1
        if len(queue) > 1:
            queue[1] = elem2, freq2 - 1
        if len(queue) > 1 and queue[1][1] == 0:
            queue.dequeue()
        if len(queue) > 0 and queue[0][1] == 0:
            queue.dequeue()
    return result
コード例 #2
0
def sorted_merge(A: list, B: list):
    """
    Time: O(A + B) actually O(2A + 2B), copying then reading back, with O(min(A, B)) comparisons in the worst case
    Space: O(n)
    :param A:
    :param B:
    :return:
    """
    p1, p2 = 0, len(A) - len(B)

    stack_A = Queue(iterable=A[:p2])
    stack_B = Queue(iterable=B)

    for i in range(len(A)):
        if stack_A.is_empty():
            A[i] = stack_B.pop()
        elif stack_B.is_empty():
            A[i] = stack_A.pop()
        elif stack_A.peek() <= stack_B.peek():
            A[i] = stack_A.pop()
        else:
            A[i] = stack_B.pop()
    return A
from DataStructures.Queue import Queue

# Setup
q = Queue(1)
q.enqueue(2)
q.enqueue(3)

# Test peek
# Should be 1
print(q.peek())

# Test dequeue
# Should be 1
print(q.dequeue())

# Test enqueue
q.enqueue(4)
# Should be 2
print(q.dequeue())
# Should be 3
print(q.dequeue())
# Should be 4
print(q.dequeue())
q.enqueue(5)
# Should be 5
print(q.peek())
コード例 #4
0
import sys
sys.path.append("../")

from DataStructures.Queue import Queue

try:
    print("\nStart Queue Tests ..")

    # Setup
    q = Queue(1)
    q.enqueue(2)
    q.enqueue(3)

    # Test peek
    # Should be 1
    assert q.peek() == 1

    # Test dequeue
    # Should be 1
    assert q.dequeue() == 1

    # Test enqueue
    q.enqueue(4)
    # Should be 2
    assert q.dequeue() == 2
    # Should be 3
    assert q.dequeue() == 3
    # Should be 4
    assert q.dequeue() == 4
    q.enqueue(5)
    # Should be 5