Datenstrukturen – Stack in Python
Eine Einführung in die Stack-Datenstruktur in Python – mit sequenzieller und verlinkter Implementierung, einem Geschwindigkeitsvergleich von push/pop und zwei Anwendungen: ein Infix-zu-Postfix-Konverter und ein Labyrinth-Löser.

from random import randint
import sys
import numpy as np
import time
import pandas as pd
Definition
Ein Stack ist eine lineare Datenstruktur, gekennzeichnet durch ihr LIFO-Prinzip (Last In, First Out). Es ist eine geordnete Sammlung von Elementen, bei der das Hinzufügen und Entfernen nur an einem Ende stattfindet, dem sogenannten Top of the Stack. Der Stack folgt einer strikten Regel des Einfügens und Entfernens über sein oberes Ende – das zuletzt hinzugefügte Element wird als Erstes entfernt. Diese Struktur kann als abstrakter Datentyp implementiert werden, der Operationen zur Manipulation seines Inhalts bereitstellt.
Verwendung
Stacks finden wegen ihrer Effizienz und Einfachheit breite Anwendung in verschiedensten Bereichen. Sie werden häufig zur Lösung von Problemen genutzt, die Umkehren oder Rückgängigmachen von Operationen betreffen. Die Stack-Datenstruktur ist zentral beim Parsen von Ausdrücken, der Implementierung rekursiver Algorithmen, der Auswertung von Postfix-Ausdrücken und beim Backtracking in rekursiven Tiefensuchen. Außerdem sind Stacks grundlegend für die Implementierung von Laufzeit-Call-Stacks in Programmiersprachen und ermöglichen, Funktionsaufrufe und ihre Rücksprungadressen effizient zu speichern und zu verwalten. Die Vielseitigkeit und Nützlichkeit der Stack-Datenstruktur machen sie zu einer grundlegenden Komponente des Algorithmen-Designs und der Analyse.
Sequenzieller Stack
Definition
Ein sequenzieller Stack, auch array-basierter Stack genannt, ist eine Stack-Implementierung, die ein zugrunde liegendes Array zum Speichern ihrer Elemente nutzt. Er verwaltet ein Array fester Größe, in das Elemente an einem Ende – typischerweise dem oberen – hinzugefügt und daraus entfernt werden. Sequenzielle Stacks bieten effizienten wahlfreien Zugriff und Insert-/Delete-Operationen in konstanter Zeit. Allerdings ist die Größe eines sequenziellen Stacks fest und kann nicht dynamisch angepasst werden, um unterschiedliche Elementzahlen aufzunehmen.
Vorteile sequenzieller Stacks
- Effizienter wahlfreier Zugriff: Durch die Array-Repräsentation bieten sequenzielle Stacks effizienten wahlfreien Zugriff auf Elemente.
- Operationen in konstanter Zeit: Einfügen und Löschen haben konstante Zeitkomplexität.
- Speichereffizienz: Sequenzielle Stacks nutzen Speicher effizient – nur die Elemente selbst und das Array fester Größe brauchen Speicherplatz.
Nachteile sequenzieller Stacks
- Feste Größe: Die Größe wird bei der Initialisierung festgelegt; eine dynamische Anpassung an unterschiedliche Elementzahlen ist nicht möglich. Das kann zu Stack-Overflow oder -Underflow führen, wenn die Elementzahl die Kapazität überschreitet oder der Stack leer wird.
- Ineffizientes Vergrößern: Das Vergrößern erfordert ein neues, größeres Array und das Kopieren aller Elemente – mit zusätzlicher Zeitkomplexität und potenziellen Speicherallokationsproblemen.
- Verschwendeter Speicher: Wird die Kapazität nicht voll genutzt, ist der Speicher des ungenutzten Array-Teils verschwendet.
- Begrenzte Skalierbarkeit: Wegen der festen Größe eignen sich sequenzielle Stacks weniger für Anwendungen mit unvorhersehbarer oder wechselnder Elementzahl, da die maximale Kapazität vorab festgelegt werden muss.
Vorteile
- Effizienter wahlfreier Zugriff
- Operationen in konstanter Zeit
- Speichereffizienz
Nachteile
- Feste Größe
- Ineffizientes Vergrößern
- Verschwendeter Speicher
- Begrenzte Skalierbarkeit
In Python wachsen und schrumpfen Listen und einige andere Datenstrukturen dynamisch. Streng genommen ist die Implementierung eines sequenziellen Stacks mit einer Liste also nicht erreichbar – hauptsächlich, weil Python immer freien Platz für das nächste Element im Stack bereithält. Um diesen „Makel” zu umgehen, implementieren wir in unserer SequentialStack-Klasse eine eigene Funktion, die uns sagt, wann wir die beim Initialisieren gesetzte theoretische max_size erreicht haben.
Beschreibung der Klasse SequentialStack
Die Klasse SequentialStack implementiert eine Stack-Datenstruktur mit einer Python-Liste und folgenden Funktionalitäten:
Initialisierung
__init__(max_size:int): Initialisiert den Stack mit einer angegebenen Maximalgröße.data: leere Liste zum Speichern der Elemente.max_size: maximale Kapazität des Stacks.top_idx: Index-Zeiger auf das oberste Element (-1 wenn leer).bottom_idx: Index-Zeiger auf das unterste Element (0 wenn leer).
Magic Methods
__len__(): Gibt die aktuelle Länge (Elementanzahl) des Stacks zurück.__str__(): Liefert eine String-Repräsentation des Stacks mit hervorgehobenen obersten und untersten Elementen.
Private Methode
__reached_max_size(): Prüft, ob der Stack seine maximale Kapazität erreicht hat.
Stack-Operationen
push(element): Fügt ein Element oben auf den Stack, sofern die Kapazität reicht.pop(): Entfernt das oberste Element und gibt es zurück.
Beide Operationen behandeln Underflow (Pop auf leerem Stack) bzw. Overflow (Push bei vollem Stack) und werfen entsprechende Exceptions.
Properties
size: Gibt die aktuelle Größe (Elementanzahl) des Stacks zurück.is_empty: Prüft, ob der Stack leer ist.top: Gibt den Index des obersten Elements zurück.bottom: Gibt den Index des untersten Elements zurück.
Dieser Stack folgt dem LIFO-Prinzip (Last In, First Out) und ermöglicht grundlegende Stack-Operationen bei gleichzeitiger Verfolgung von Größe, Leerezustand und Positionen der obersten und untersten Elemente.
class SequentialStack():
def __init__(self, max_size:int):
self.data = ['' for i in range(max_size)]
self.max_size = max_size
self.top_idx = -1
self.bottom_idx = 0
def __len__(self):
return len(self.data)
def __str__(self):
output = list()
if self.top_idx == -1:
return '[]'
for idx, elmt in enumerate(self.data):
if self.top_idx == idx and self.bottom_idx == idx:
output.append( '[' + str(elmt) + ']' + ' <- top/bottom')
continue
elif self.top_idx == idx:
output.append('[' + str(elmt) + ']' + ' <- top')
elif self.bottom_idx == idx:
output.append('[' + str(elmt) + ']' + ' <- bottom')
else:
output.append('[' + str(elmt) + ']')
output = '\n'.join(output[::-1])
return output
def __reached_max_size(self):
''' We implement this function in order to cope with Pythons dynamic variable growth '''
return True if self.top_idx == (self.max_size - 1) else False
def push(self, element):
if not self.__reached_max_size():
# self.data.append(element)
self.data[self.top_idx + 1] = element
self.top_idx += 1
else:
raise Exception('Stack overflow')
def pop(self):
if not self.is_empty:
element = self.data.pop()
self.top_idx -= 1
return element
else:
raise Exception('Stack is empty')
@property
def size(self):
return len(self.data)
@property
def is_empty(self):
# return True if self.size == 0 else False
return True if self.top_idx == -1 else False
@property
def top(self):
return self.top_idx
@property
def bottom(self):
return self.bottom_idx
@property
def top_element(self):
return self.data[self.top_idx] if self.top_idx >= 0 else None
@property
def bottom_element(self):
return self.data[self.bottom_idx]
seq_stack_max_size = 10
seq_stack = SequentialStack(seq_stack_max_size)
pushed_sequence_squential_stack = list()
for i in range(seq_stack_max_size):
tmp_element = randint(10, 100)
seq_stack.push(tmp_element)
pushed_sequence_squential_stack.append(tmp_element)
print('Number of elements pushed: ', len(pushed_sequence_squential_stack))
print('Pushed sequendce => ', pushed_sequence_squential_stack, '\n')
print(seq_stack)
print()
Number of elements pushed: 10
Pushed sequendce => [87, 41, 88, 29, 65, 69, 74, 44, 100, 19]
[19] <- top
[100]
[44]
[74]
[69]
[65]
[29]
[88]
[41]
[87] <- bottom
popped_sequence_sequential_stack = [seq_stack.pop()for i in range(seq_stack_max_size - randint(2, seq_stack_max_size - 2))]
print('Number of elements popped: ', len(popped_sequence_sequential_stack))
print('Popped sequendce => ', popped_sequence_sequential_stack, '\n')
print(seq_stack)
print()
Number of elements popped: 8
Popped sequendce => [19, 100, 44, 74, 69, 65, 29, 88]
[41] <- top
[87] <- bottom
Verlinkter Stack
Definition
Ein verlinkter Stack, auch listenbasierter Stack genannt, ist eine Stack-Implementierung, die eine verkettete Liste zum Speichern ihrer Elemente nutzt. Er besteht aus Knoten, von denen jeder ein Element und eine Referenz auf den nächsten Knoten enthält. Der Top of the Stack wird durch den ersten Knoten der Liste repräsentiert. Verlinkte Stacks sind in der Größe flexibel, da sie dynamisch wachsen oder schrumpfen können. Einfüge- und Löschoperationen sind effizient und erfordern nur die Manipulation der Zeiger der Liste. Verlinkte Stacks erlauben effiziente Speichernutzung, verursachen aber durch die gespeicherten Knotenreferenzen zusätzlichen Overhead.
Vorteile des verlinkten Stacks:
- Dynamische Größe: Elemente lassen sich leicht hinzufügen oder entfernen, ohne Vergrößern oder Verschieben.
- Effiziente Speichernutzung: Es wird nur Speicher für tatsächlich gespeicherte Elemente allokiert – anders als beim array-basierten Stack mit fester Allokation.
- Einfache Implementierung: Die Implementierung ist relativ straightforward, mit minimalem Code und ohne komplexe Vergrößerungsstrategien.
- Flexibilität: Zusätzliche Operationen wie das Kopieren oder Zusammenführen von Stacks lassen sich leicht umsetzen – nützlich in verschiedenen Anwendungen.
Nachteile des verlinkten Stacks:
- Zeiger-Overhead: Jedes Element benötigt zusätzlichen Speicher für Zeiger – mehr Overhead als bei einem array-basierten Stack.
- Langsamere Zugriffszeiten: Der Zugriff auf ein Element erfordert das Durchlaufen der Knoten – langsamer als die direkte Indizierung im Array.
- Extra Speicher-Overhead: Die gespeicherten Zeiger verursachen höheren Speicher-Overhead im Verhältnis zu den eigentlichen Daten.
- Potenzielle Speicherfragmentierung: Werden Elemente häufig hinzugefügt und entfernt, kann sich mit der Zeit Speicherfragmentierung ergeben und die Speichernutzung verschlechtern.
Vorteile
- Dynamische Größe
- Effiziente Speichernutzung
- Einfache Implementierung
- Flexibilität
Nachteile
- Zeiger-Overhead
- Langsamere Zugriffszeiten
- Extra Speicher-Overhead
- Potenzielle Speicherfragmentierung
Beschreibung der Klasse LinkedStack
Die Klasse LinkedStack implementiert eine Stack-Datenstruktur mit einer Python-Liste und folgenden Funktionalitäten:
Initialisierung
__init__(): Initialisiert den Stack.data: leere Liste zum Speichern der Elemente.top_idx: Index-Zeiger auf das oberste Element (-1 wenn leer).bottom_idx: Index-Zeiger auf das unterste Element (0 wenn leer).
Magic Methods
__len__(): Gibt die aktuelle Länge (Elementanzahl) des Stacks zurück.__str__(): Liefert eine String-Repräsentation des Stacks mit hervorgehobenen obersten und untersten Elementen.
Stack-Operationen
push(element): Fügt ein Element oben auf den Stack.pop(): Entfernt das oberste Element und gibt es zurück.
Beide Operationen behandeln Underflow (Pop auf leerem Stack) und aktualisieren den Top-Index entsprechend.
Properties
size: Gibt die aktuelle Größe (Elementanzahl) des Stacks zurück.is_empty: Prüft, ob der Stack leer ist.top: Gibt den Index des obersten Elements zurück.bottom: Gibt den Index des untersten Elements zurück.
Dieser Stack folgt dem LIFO-Prinzip und ermöglicht grundlegende Operationen wie Pushen, Poppen sowie das Verfolgen von Größe und Leerezustand.
class Node():
def __init__(self, data):
self.data = data
self.next_node = None
def __iter__(self):
tmp_node = self
return_iterable = list()
while tmp_node is not None:
return_iterable.append(tmp_node)
tmp_node = tmp_node.next_node
return iter(return_iterable)
def __str__(self):
return str(self.data)
def __len__(self):
counter = 1
tmp_node = self
while tmp_node.next_node is not None:
counter += 1
tmp_node = tmp_node.next_node
return counter
class LinkedNodeStack():
def __init__(self):
self.data = None
self.top_idx = -1
self.bottom_idx = 0
def __len__(self):
return 0 if self.data is None else len(self.data)
def __str__(self):
output = list()
if self.top_idx == -1:
return '[]'
for idx, elmt in enumerate(self.data):
if self.top_idx == idx and self.bottom_idx == idx:
output.append( '[' + str(elmt) + ']' + ' <- top/bottom')
continue
elif self.top_idx == idx:
output.append('[' + str(elmt) + ']' + ' <- top')
elif self.bottom_idx == idx:
output.append('[' + str(elmt) + ']' + ' <- bottom')
else:
output.append('[' + str(elmt) + ']')
output = '\n'.join(output[::-1])
return output
def push(self, element):
if self.data is None:
self.data = Node(element)
self.top_idx += 1
return
tmp_node = Node(element)
last_node = self.data
for i in range(self.top):
last_node = last_node.next_node
last_node.next_node = tmp_node
self.top_idx += 1
def pop(self):
if self.data is not None:
tmp_node = self.data
prev_node = None
while tmp_node.next_node is not None:
prev_node = tmp_node
tmp_node = tmp_node.next_node
if prev_node is not None:
prev_node.next_node = None
self.top_idx -= 1
else:
self.data = None
return tmp_node
else:
raise Exception('Stack is empty')
@property
def size(self):
return self.__len__()
@property
def is_empty(self):
# return True if self.size == 0 else False
return True if self.top_idx == -1 else False
@property
def top(self):
return self.top_idx
@property
def bottom(self):
return self.bottom_idx
@property
def top_element(self):
tmp_node = self.data
while tmp_node.next_node is not None:
tmp_node = tmp_node.next_node
return tmp_node
@property
def bottom_element(self):
return self.data
linked_node_stack = LinkedNodeStack()
linked_node_stack.push(55)
linked_node_stack.push(6)
linked_node_stack.push(7)
linked_node_stack.push(8)
linked_node_stack.push(9)
linked_node_stack.push(10)
linked_node_stack.push(11)
print("The size of the stack is => ", len(linked_node_stack), '\n')
print(linked_node_stack)
The size of the stack is => 7
[11] <- top
[10]
[9]
[8]
[7]
[6]
[55] <- bottom
popped_element = linked_node_stack.pop()
print("The size of the stack is => ", len(linked_node_stack))
print("Popped element => ", popped_element, '\n')
print(linked_node_stack)
The size of the stack is => 6
Popped element => 11
[10] <- top
[9]
[8]
[7]
[6]
[55] <- bottom
class LinkedStack():
def __init__(self):
self.data = list()
self.top_idx = -1
self.bottom_idx = 0
def __len__(self):
return len(self.data)
def __str__(self):
output = list()
if self.top_idx == -1:
return '[]'
for idx, elmt in enumerate(self.data):
if self.top_idx == idx and self.bottom_idx == idx:
output.append( '[' + str(elmt) + ']' + ' <- top/bottom')
continue
elif self.top_idx == idx:
output.append('[' + str(elmt) + ']' + ' <- top')
elif self.bottom_idx == idx:
output.append('[' + str(elmt) + ']' + ' <- bottom')
else:
output.append('[' + str(elmt) + ']')
output = '\n'.join(output[::-1])
return output
def push(self, element):
self.data.append(element)
self.top_idx += 1
def pop(self):
if not self.is_empty:
element = self.data.pop()
self.top_idx -= 1
return element
else:
raise Exception('Stack is empty')
@property
def size(self):
return len(self.data)
@property
def is_empty(self):
# return True if self.size == 0 else False
return True if self.top_idx == -1 else False
@property
def top(self):
return self.top_idx
@property
def bottom(self):
return self.bottom_idx
@property
def top_element(self):
return self.data[-1] if len(self.data) > 0 else None
@property
def bottom_element(self):
return self.data[0] if len(self.data) > 0 else None
linked_stack = LinkedStack()
linked_stack_number_of_elements_to_push = 20
pushed_sequence_linked_stack = list()
for i in range(linked_stack_number_of_elements_to_push):
tmp_element = randint(10, 100)
linked_stack.push(tmp_element)
pushed_sequence_linked_stack.append(tmp_element)
print('Number of elements pushed: ', len(pushed_sequence_linked_stack))
print('Pushed sequendce => ', pushed_sequence_linked_stack, '\n')
print(linked_stack)
print()
Number of elements pushed: 20
Pushed sequendce => [58, 78, 83, 78, 36, 74, 56, 62, 89, 11, 15, 66, 24, 45, 61, 58, 95, 19, 36, 59]
[59] <- top
[36]
[19]
[95]
[58]
[61]
[45]
[24]
[66]
[15]
[11]
[89]
[62]
[56]
[74]
[36]
[78]
[83]
[78]
[58] <- bottom
popped_sequence_linked_stack = [linked_stack.pop()for i in range(linked_stack_number_of_elements_to_push - randint(2, linked_stack_number_of_elements_to_push - 2))]
print('Number of elements popped: ', len(popped_sequence_linked_stack))
print('Popped sequendce => ', popped_sequence_linked_stack, '\n')
print(linked_stack)
print()
Number of elements popped: 5
Popped sequendce => [59, 36, 19, 95, 58]
[61] <- top
[45]
[24]
[66]
[15]
[11]
[89]
[62]
[56]
[74]
[36]
[78]
[83]
[78]
[58] <- bottom
(Test) Geschwindigkeitsvergleich: Push
def time_push(number_of_iterations, stack_obj):
time_all_iterations = None
time_per_operation = []
start_time_all_iterations = time.time()
for i in range(number_of_iterations):
random_number = randint(0,100)
start_time_per_operation = time.time()
stack_obj.push(random_number)
end_time_per_operation = time.time()
delta_t = end_time_per_operation - start_time_per_operation
time_per_operation.append(delta_t)
end_time_all_iterations = time.time()
time_all_iterations = end_time_all_iterations - start_time_all_iterations
avg_time_per_operation = sum(time_per_operation)/len(time_per_operation)
return time_all_iterations, avg_time_per_operation
test_number_of_iteratons = 100_000
print('\nTesting Push operation\n')
test_sequential_stack = SequentialStack(test_push_number_of_iteratons)
test_linked_stack = LinkedStack()
test_linked_node_stack = LinkedNodeStack()
push_sequential_stack_time_for_all_iterations, push_sequential_stack_avg_time_per_operations = time_push(test_number_of_iteratons, test_sequential_stack)
push_linked_stack_time_for_all_iterations, push_linked_stack_avg_time_per_operations = time_push(test_number_of_iteratons, test_linked_stack)
push_linked_node_stack_time_for_all_iterations, push_linked_node_stack_avg_time_per_operations = time_push(test_number_of_iteratons, test_linked_node_stack)
print('\nSequential Stack')
print('Time for all iterations: ', push_sequential_stack_time_for_all_iterations)
print('Avg time per operation: ', push_sequential_stack_avg_time_per_operations)
print('\nLinked Stack')
print("This stack utilizes Python's in-built list() type. Therefore, it will have the best performance in terms of tme.")
print('Time for all iterations: ', push_linked_stack_time_for_all_iterations)
print('Avg time per operation: ', linked_stack_avg_time_per_operations)
print('\nLinked Node Stack')
print('Time for all iterations: ', push_linked_node_stack_time_for_all_iterations)
print('Avg time per operation: ', push_linked_node_stack_avg_time_per_operations)
Testing Push operation
Sequential Stack
Time for all iterations: 0.22549724578857422
Avg time per operation: 7.430005073547363e-07
Linked Stack
This stack utilizes Python's in-built list() type. Therefore, it will have the best performance in terms of tme.
Time for all iterations: 0.1650378704071045
Avg time per operation: 3.8222551345825195e-07
Linked Node Stack
Time for all iterations: 267.0029981136322
Avg time per operation: 0.0026655999803543093
Bei der Analyse der Iterations-Performance zeigt sich: Der verlinkte (Knoten-)Stack schneidet insgesamt am schlechtesten ab. Das liegt vor allem daran, dass jeder Knoten bis zum letzten durchlaufen werden muss, was erheblich Zeit kostet. In puncto Zeitkomplexität ist der sequenzielle Stack dank seiner effizienten Struktur überlegen – allerdings auf Kosten höherer Speichernutzung, da er viel Speicher für die Datenspeicherung benötigt.
Die durchschnittliche Zeit pro Push-Operation unterstreicht die Überlegenheit des sequenziellen Stacks noch weiter: Durch die direkte Indizierung des allokierten Speichers für das Zielobjekt bei jeder Iteration gelingt das Pushen schnell. Der verlinkte (Knoten-)Stack dagegen muss alle Knoten der Liste durchlaufen, um den letzten Knoten zu erreichen und dessen next_node-Zeiger zu setzen – entsprechend langsamer.
(Test) Geschwindigkeitsvergleich: Pop
def time_pop(number_of_iterations, stack_obj):
time_all_iterations = None
time_per_operation = []
start_time_all_iterations = time.time()
for i in range(number_of_iterations):
start_time_per_operation = time.time()
stack_obj.pop()
end_time_per_operation = time.time()
delta_t = end_time_per_operation - start_time_per_operation
time_per_operation.append(delta_t)
end_time_all_iterations = time.time()
time_all_iterations = end_time_all_iterations - start_time_all_iterations
avg_time_per_operation = sum(time_per_operation)/len(time_per_operation)
return time_all_iterations, avg_time_per_operation
print('\nTesting Pop operation\n')
pop_sequential_stack_time_for_all_iterations, pop_sequential_stack_avg_time_per_operations = time_pop(test_number_of_iteratons, test_sequential_stack)
pop_linked_stack_time_for_all_iterations, pop_linked_stack_avg_time_per_operations = time_pop(test_number_of_iteratons, test_linked_stack)
pop_linked_node_stack_time_for_all_iterations, pop_linked_node_stack_avg_time_per_operations = time_pop(test_number_of_iteratons, test_linked_node_stack)
print('\nSequential Stack')
print('Time for all iterations: ', pop_sequential_stack_time_for_all_iterations)
print('Avg time per operation: ', pop_sequential_stack_avg_time_per_operations)
print('\nLinked Stack')
print("This stack utilizes Python's in-built list() type. Therefore, it will have the best performance in terms of tme.")
print('Time for all iterations: ', pop_linked_stack_time_for_all_iterations)
print('Avg time per operation: ', pop_linked_stack_avg_time_per_operations)
print('\nLinked Node Stack')
print('Time for all iterations: ', pop_linked_node_stack_time_for_all_iterations)
print('Avg time per operation: ', pop_linked_node_stack_avg_time_per_operations)
Testing Pop operation
Sequential Stack
Time for all iterations: 0.11483001708984375
Avg time per operation: 8.0641508102417e-07
Linked Stack
This stack utilizes Python's in-built list() type. Therefore, it will have the best performance in terms of tme.
Time for all iterations: 0.07549548149108887
Avg time per operation: 5.283856391906738e-07
Linked Node Stack
Time for all iterations: 348.05520272254944
Avg time per operation: 0.003479842984676361
Bei der Analyse der Iterations-Performance zeigt sich: Der verlinkte (Knoten-)Stack schneidet insgesamt am schlechtesten ab. Das liegt vor allem daran, dass jeder Knoten bis zum letzten durchlaufen werden muss, was erheblich Zeit kostet. In puncto Zeitkomplexität ist der sequenzielle Stack dank seiner effizienten Struktur überlegen – allerdings auf Kosten höherer Speichernutzung, da er viel Speicher für die Datenspeicherung benötigt.
Die durchschnittliche Zeit pro Pop-Operation unterstreicht die Überlegenheit des sequenziellen Stacks noch weiter: Durch die direkte Indizierung des allokierten Speichers für das Zielobjekt bei jeder Iteration gelingt das Entfernen schnell. Der verlinkte (Knoten-)Stack dagegen muss alle Knoten der Liste durchlaufen, um den vorletzten Knoten zu erreichen und dessen next_node-Zeiger zu aktualisieren – entsprechend langsamer.
Anwendungen
Ausdrucksrechner
- Infix: <operand_1> <operation_symbol> <operand_2>
- Präfix: <operation_symbol> <operand_1> <operand_2>
- Postfix: <operand_1> <operand_2> <operation_symbol>
operations_priority = dict()
operations_priority['isp'] = dict()
operations_priority['icp'] = dict()
operations_list = ['(', '*', '/', '%', '+', '-', ')']
# ISP
# In Stack Precedence
operations_priority['isp']['#'] = 0
operations_priority['isp']['('] = 1
operations_priority['isp']['*'] = 5
operations_priority['isp']['/'] = 5
operations_priority['isp']['%'] = 5
operations_priority['isp']['+'] = 3
operations_priority['isp']['-'] = 3
operations_priority['isp'][')'] = 6
# ICP
# Incomming Precedence
operations_priority['icp']['#'] = 0
operations_priority['icp']['('] = 6
operations_priority['icp']['*'] = 4
operations_priority['icp']['/'] = 4
operations_priority['icp']['%'] = 4
operations_priority['icp']['+'] = 2
operations_priority['icp']['-'] = 2
operations_priority['icp'][')'] = 1
def infix_to_postfix(expression:str):
step_count = 0
steps_list = list()
output_str = ''
linked_stack = LinkedStack()
linked_stack.push('#')
for expression_character in expression:
# print('Current Character => ', expression_character)
stack_top = linked_stack.top_element
# print('[Before Logic] Top element => ', stack_top)
if expression_character not in operations_list:
output_str += expression_character
else:
# expression_character is an operation
if operations_priority['icp'][expression_character] > operations_priority['isp'][stack_top]:
# print('[icp] > [isp] [PUSH]')
linked_stack.push(expression_character)
elif operations_priority['icp'][expression_character] < operations_priority['isp'][stack_top]:
# print('[icp] < [isp] [POP]')
popped_element = linked_stack.pop()
stack_top = linked_stack.top_element
output_str += popped_element
while operations_priority['icp'][expression_character] <= operations_priority['isp'][stack_top]:
# print('[icp] < [isp] [POP] until ([icp] > [isp])')
if stack_top == '(':
linked_stack.pop()
break
popped_element = linked_stack.pop()
stack_top = linked_stack.top_element
output_str += popped_element
else:
# print('[icp] == [isp] [POP] until ([icp] > [isp])')
popped_element = linked_stack.pop()
while popped_element != '(':
output_str += popped_element
popped_element = linked_stack.pop()
else:
popped_element = linked_stack.pop()
continue
while linked_stack.top_element != '#':
output_str += linked_stack.pop()
return output_str
infix_expression = 'A+B*(C-D)-E/F'
postfix_expression = infix_to_postfix(infix_expression)
print('Infix Expression: ', infix_expression)
print('Postfix Expression: ', postfix_expression)
ABCD-*+EF/
Labyrinth-Löser
Beschreibung:
Das Problem besteht darin, ein als 2D-Array der Größe MxN dargestelltes Labyrinth zu durchqueren, wobei jedes Element entweder 0 (begehbarer Weg) oder 1 (eine Wand) enthält. Eine Person oder Entität startet an einem festgelegten Eingangspunkt und will den Ausgang erreichen – nur zu benachbarten Elementen in einer der acht Richtungen (N, NE, E, SE, S, SW, W, NW).
Algorithmus:
- Initialisiere einen Stack, der den aktuell erkundeten Pfad speichert.
- Beginne am Eingangspunkt des Labyrinths.
- Lege die Startposition auf den Stack.
- Solange der Stack nicht leer ist:
- Entferne das oberste Element vom Stack.
- Prüfe, ob das entfernte Element der Ausgangspunkt ist.
- Falls ja: Das Labyrinth ist gelöst; Algorithmus beenden.
- Erkunde benachbarte Zellen in alle acht Richtungen.
- Ist eine benachbarte Zelle ein gültiger Zug (keine Wand und innerhalb der Grenzen) und noch nicht besucht:
- Lege diese Zelle auf den Stack.
- Markiere die Zelle als besucht.
- Ist eine benachbarte Zelle ein gültiger Zug (keine Wand und innerhalb der Grenzen) und noch nicht besucht:
Wird der Stack leer, ohne dass der Ausgang gefunden wurde, hat das Labyrinth keine Lösung.
Anmerkungen:
Dieser Ansatz nutzt eine Tiefensuche (DFS): Jeder Pfad wird so weit wie möglich verfolgt, bevor zurückgegangen wird.
Der Stack zeichnet den zurückgelegten Weg auf und erlaubt dem Algorithmus, zurückzugehen, wenn von einer Position aus kein Zug mehr möglich ist.
Implementierungen können je nach Programmiersprache und den konkreten Datenstrukturen für Stack und Labyrinth variieren.
maze_matrix = [
[1 for i in range(0, 17) ],
[0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1 ],
[1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1 ],
[1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1 ],
[1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1 ],
[1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 ],
[1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1 ],
[1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1 ],
[1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 ],
[1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1 ],
[1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1 ],
[1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1 ],
[1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0 ],
[1 for i in range(0, 17) ]
]
move_directions = [
{"direction": "N", "i": -1, "j": 0},
{"direction": "NE", "i": -1, "j": 1},
{"direction": "E", "i": 0, "j": 1},
{"direction": "SE", "i": 1, "j": 1},
{"direction": "S", "i": 1, "j": 0},
{"direction": "SW", "i": 1, "j": -1},
{"direction": "W", "i": 0, "j": -1},
{"direction": "NW", "i": -1, "j": -1},
]
def path_around_wall(maze_matrix, move_directions, maze_width, maze_height, maze_exit_x, maze_exit_y, print_stack=False):
# Inicialization
walked_path_mark = [ [0 for i in range(0, 17) ] for j in range(0, 14) ]
# Preprocessing
walked_path_mark[1][0] = 1
_stack = LinkedStack()
starting_position = {'x':1, 'y':1, 'direction':0}
_stack.push(starting_position)
while not _stack.is_empty:
current_item = _stack.pop()
i = current_item['x']
j = current_item['y']
d = current_item['direction']
while d < 8:
g = i + move_directions[d]['i']
h = j + move_directions[d]['j']
direction_name = move_directions[d]['direction']
is_current_direction_a_wall = True if maze_matrix[g][h] == 1 else False
has_current_direction_been_walked = True if walked_path_mark[g][h] == 1 else False
# print(f'Direction is {direction_name} [{d}] < 8')
# print(f'g: {g} \th: {h}')
# print(f'in the maze_this is [{maze_matrix[g][h]}]')
# print(f'is_wall:{is_current_direction_a_wall}')
# print(f'walked: {has_current_direction_been_walked}')
if ((g == maze_exit_x) and (h == maze_exit_y)):
walked_position = {}
walked_position['x'] = i
walked_position['y'] = j
walked_position['direction'] = d
_stack.push(walked_position)
final_position = {}
final_position['x'] = g
final_position['y'] = h
final_position['direction'] = 2
_stack.push(final_position)
if print_stack:
print('Exiting Maze\n')
print(_stack)
return _stack
if ((g == maze_width) and (h == maze_height)):
if print_stack:
print('Direction Stack\n')
print(_stack)
print(f"m: {maze_width}\tp: {maze_height}")
return _stack
if (not is_current_direction_a_wall) and (not has_current_direction_been_walked):
walked_path_mark[g][h] = 1
# print(f'Walking on [{g}][{h}] \t In the maze it is [{maze_matrix[g][h]}]')
# print(f'Walking on [{g}][{h}]')
walked_position = {}
walked_position['x'] = i
walked_position['y'] = j
walked_position['direction'] = d
_stack.push(walked_position)
i = g
j = h
d = 0
else:
d += 1
print('No path in maze')
print_path = [ ['-' for i in range(0, 17) ] for j in range(0, 14) ]
print_path[1][0] = 'o'
path_stack = path_around_wall(
maze_matrix=maze_matrix,
move_directions=move_directions,
maze_width=14,
maze_height=17,
maze_exit_x=12,
maze_exit_y=16)
while not path_stack.is_empty:
current_position = path_stack.pop()
_x = current_position['x']
_y = current_position['y']
print_path[_x][_y] = 'o'
for l in print_path:
print(l)
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['o', 'o', '-', 'o', 'o', 'o', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', 'o', '-', 'o', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', '-', 'o', 'o', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', 'o', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', '-', 'o', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', 'o', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', 'o', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', 'o', '-', '-', '-', '-', 'o', 'o', '-', '-', '-', '-', '-', '-', '-', '-', '-']
['-', '-', 'o', '-', '-', 'o', '-', '-', 'o', '-', '-', '-', '-', '-', 'o', '-', '-']
['-', '-', '-', 'o', 'o', '-', '-', '-', 'o', '-', '-', 'o', 'o', 'o', '-', 'o', '-']
['-', '-', '-', '-', '-', '-', '-', '-', '-', 'o', 'o', '-', '-', '-', '-', 'o', '-']
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', 'o']
['-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', '-']
