Python :: Aufgabe #82
3 Lösungen
Das Häufigste Element in einem Array
Anfänger - Python
von klhlubek19
- 16.07.2015 um 13:46 Uhr
Schreiben Sie ein Programm, das aus einem Array das häufigste Element findet. Sollte es mehrere gleicher Anzahl finden, so darf irgend ein Element dieser Häufigsten ausgegeben werden.
Lösungen:
Python-Code
liste = [] array = ["gf","fniu","ds","fe","geo","erpo","fe","rf","gr","gf","gf","fea","fes","fe","fe","fe"] for i in range(len(array)): liste.append(array.count(array[i])) maximum = max(liste) for i in range(len(liste)): if array.count(array[i]) == maximum: print("Das haeufigste Element lautet:", array[i]) break
Ich hatte den Ehrgeiz die Aufgabe ohne Verwendung der count() Methode zu lösen. Allerdings ist diese Lösung langsamer als eine Lösung mit count().
Ausgabe:
Python-Code
# -*- coding: utf-8 -*- x = 0 counter = 0 arrElemente = [] arrAnzahl = [] arrInput = "b", 1, "a", 4, "a", "a", 1, "a", 3, 2, "a", "c" while x < len(arrInput): if arrInput[x] not in arrElemente: # Elemente-Array mit neuem Element füllen tmp = arrInput[x] arrElemente.append(tmp) # Vorkommen des Elementes zählen for i in range(x, len(arrInput)): if arrInput[i] == tmp: counter = counter + 1 # Anzahl-Array mit Anzahl des Elementes füllen arrAnzahl.append(counter) counter = 0 x = x + 1 # größten Wert aus Anzahl-Array ermitteln anzahl = max(arrAnzahl) # Index des größten Wertes in Anzahl-Array ermitteln y = arrAnzahl.index(anzahl) # Wert des gleichen Index aus Elemente-Array ermitteln value = str(arrElemente[y]) print "Das häufigste Element ist " + "'" + value + "'" + ". \ Es kommt " + str(anzahl) + " mal vor."
Ausgabe:
Zitat:
Das häufigste Element ist 'a'. Es kommt 5 mal vor.
Python-Code
def find_max_occurs(l): x = {} for i in l : x[i] = x[i] +1 if i in x else 1 x = dict( (v,k) for k,v in x.items()) return x[max(x.keys())]