. Advertisement .
..3..
. Advertisement .
..4..
I have the following python code, but I do not know how to find the correct result. Why has this problem occurred, and how can it be solved?
Here is the code that I am running:
import wx
import myLoopGUI
import commands
class MyLoopFrame(myLoopGUI.MyFrame1):
def __init__(self, parent):
myLoopGUI.MyFrame1.__init__(self, parent)
def clkAddData(self,parent):
if len(self.txtAddData.Value) != 0:
try:
myname = str(self.txtAddData.Value)
self.listMyData.Append(str(myname))
except:
wx.MessageBox("This has to be a name!")
else:
wx.MessageBox("This can't be empty")
def clkFindMost(self, parent):
self.listMyData = []
unique_names = set(self.listMyData)
frequencies = {}
for name in unique_names:
if frequencies.get[name]:
frequencies[name] += 1
else:
frequencies[name] = 0
v = list(frequencies.values())
k = list(frequencies.keys())
self.txtResults.Value = k.index(max(v))
def clkFindLeast(self, parent):
unique_names = set(self.listMyData)
frequencies = {}
for name in unique_names:
if frequencies.get(name):
frequencies[name] += 1
else:
frequencies[name] = 0
v = list(frequencies.values())
k = list(frequencies.keys())
self.txtResults.Value = k.index(min(v))
myApp = wx.App(False)
myFrame = MyLoopFrame(None)
myFrame.Show()
myApp.MainLoop()
And this is the error text I receive:
ValueError: max() arg is an empty sequence
The cause: Because in
clkFindMost
, you always setself.listMyData
to an empty list. As bothunique_names
andfrequencies
are empty iterables after that, your code will always result in this error.In addition, you can’t use
[]
withdict.get
because it’s a method, not a list/dictionary:Solution:
To fix “valueerror: max() arg is an empty sequence”, you can follow my methods:
Run the right code using
()
instead of[]
It returns an error, when an empty iterable is supplied to
max()
andmin()
. Before runningmax()
onv
, you can check its length.If it is being used with an iterator, you’ll need to consume it first before executing
max()
on it, while the iterator’s boolean value is alwaysTrue
, so we can’t useif
instantly. Do like the following:If the sequence is empty, pass a
default
value that can be returned tomax
by passing: