Max arg is an empty sequence python ошибка

Given problem:

Given 4 integers, A, B, C, D, they can be arranged as

 A B
 C D

then the table value of this table is (A/C-B/D)
If we rotate 90 degrees clockwise, then we have

 C A
 D B

Then the table value is C/D -A/B

Give 4 integers, implement a function table(A, B, C, D) which returns
the minimum number of clockwise rotations required for the maximum of
the table value.

Implementation

Implement a function table(A, B, C, D),
where A, B, C and D are integers and 0

Sample

table(1, 2 , 3 ,4) = 3

Here is my code

def table(a, b, c, d):

    x = [[a, b, c, d], [c, a, d, b], [d, c, b, a], [b, d, a, c]]
    ans = []

    for count in range(4):
        if (x[count][2] == 0 or x[count][3] == 0) and x[count][0] != 0 and x[count][1] != 0:
            y = -(x[count][0] / x[count][1])
        elif x[count][2] != 0 and x[count][3] != 0 and (x[count][0] == 0 or x[count][1] == 0):
            y = x[count][2] / x[count][3]
        elif x[count][2] == 0 and x[count][3] == 0 and x[count][0] == 0 and x[count][1] == 0:
            y = 0
        else:
            y = x[count][2] / x[count][3] - x[count][0] / x[count][1]

        ans.append(y)
    print(ans)
    temp = ans
    for count in range(4):
        z = temp[0]
        temp.remove(temp[0])
        if z not in temp:
            return ans.index(max(ans)) + 1
    return 0


import time
x = time.time()
print(table(0, 0, 0, 0))
print(time.time() - x)

Upon running, it throws these errors:

Traceback (most recent call last):
[0, 0, 0, 0]
  File "C:/Users/lisha/PycharmProjects/untitled/lab 5 qn 2.py", line 27, in <module>
    print(table(0, 0, 0, 0))
  File "C:/Users/lisha/PycharmProjects/untitled/lab 5 qn 2.py", line 22, in table
    return ans.index(max(ans)) + 1
ValueError: max() arg is an empty sequence

Process finished with exit code 1

Can someone please point the error out?

Since you are always initialising self.listMyData to an empty list in clkFindMost your code will always lead to this error* because after that both unique_names and frequencies are empty iterables, so fix this.

Another thing is that since you’re iterating over a set in that method then calculating frequency makes no sense as set contain only unique items, so frequency of each item is always going to be 1.

Lastly dict.get is a method not a list or dictionary so you can’t use [] with it:

Correct way is:

if frequencies.get(name):

And Pythonic way is:

if name in frequencies:

The Pythonic way to get the frequency of items is to use collections.Counter:

from collections import Counter   #Add this at the top of file.

def clkFindMost(self, parent):

        #self.listMyData = []   
        if self.listMyData:
           frequencies = Counter(self.listMyData)
           self.txtResults.Value = max(frequencies, key=frequencies.get)
        else:
           self.txtResults.Value = '' 

max() and min() throw such error when an empty iterable is passed to them. You can check the length of v before calling max() on it.

>>> lst = []
>>> max(lst)

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    max(lst)
ValueError: max() arg is an empty sequence
>>> if lst:
    mx = max(lst)
else:
    #Handle this here

If you are using it with an iterator then you need to consume the iterator first before calling max() on it because boolean value of iterator is always True, so we can’t use if on them directly:

>>> it = iter([])
>>> bool(it)
True
>>> lst = list(it)
>>> if lst:
       mx = max(lst)
    else:
      #Handle this here   

Good news is starting from Python 3.4 you will be able to specify an optional return value for min() and max() in case of empty iterable.

The max() function is built into Python and returns the item with the highest value in an iterable or the item with the highest value from two or more objects of the same type. When you pass an iterable to the max() function, such as a list, it must have at least one value to work. If you use the max() function on an empty list, you will raise the error “ValueError: max() arg is an empty sequence”.

To solve this error, ensure you only pass iterables to the max() function with at least one value. You can check if an iterable has more than one item by using an if-statement, for example,

if len(iterable) > 0: 
    max_value = max(iterable)

This tutorial will go through the error in detail and how to solve it with a code example.


Table of contents

  • ValueError: max() arg is an empty sequence
    • What is a Value Error in Python?
    • Using max() in Python
  • Example: Returning a Maximum Value from a List using max() in Python
    • Solution
  • Summary

ValueError: max() arg is an empty sequence

What is a Value Error in Python?

In Python, a value is a piece of information stored within a particular object. You will encounter a ValueError in Python when you use a built-in operation or function that receives an argument with the right type but an inappropriate value. Let’s look at an example of a ValueError:

value = 'string'

print(float(value))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
print(float(value))

ValueError: could not convert string to float: 'string'

The above code throws the ValueError because the value ‘string‘ is an inappropriate (non-convertible) string. You can only convert numerical strings using the float() method, for example:

value = '5'
print(float(value))
5.0

The code does not throw an error because the float function can convert a numerical string. The value of 5 is appropriate for the float function.

The error ValueError: max() arg is an empty sequence is a ValueError because while an iterable is a valid type of object to pass to the max() function, the value it contains is not valid.

Using max() in Python

The max() function returns the largest item in an iterable or the largest of two or more arguments. Let’s look at an example of the max() function to find the maximum of three integers:

var_1 = 3
var_2 = 5
var_3 = 2

max_val = max(var_1, var_2, var_2)

print(max_val)

The arguments of the max() function are the three integer variable. Let’s run the code to get the result:

5

Let’s look at an example of passing an iterable to the max() function. In this case, we will use a string. The max() function finds the maximum alphabetical character in a string.

string = "research"

max_val = max(string)

print(max_val)

Let’s run the code to get the result:

s

When you pass an iterable the max() function, it must contain at least one value. The max() function cannot return the largest item if no items are present in the list. The same applies to the min() function, which finds the smallest item in a list.

Example: Returning a Maximum Value from a List using max() in Python

Let’s write a program that finds the maximum number of bottles sold for different drinks across a week. First, we will define a list of drinks:

drinks = [

{"name":"Coca-Cola", "bottles_sold":[10, 4, 20, 50, 29, 100, 70]},

{"name":"Fanta", "bottles_sold":[20, 5, 10, 50, 90, 10, 50]},

{"name":"Sprite", "bottles_sold":[33, 10, 8, 7, 34, 50, 21]},

{"name":"Dr Pepper", "bottles_sold":[]}

]

The list contains four dictionaries. Each dictionary contains the name of a drink and a list of the bottles sold over seven days. The drink Dr Pepper recently arrived, meaning no bottles were sold. Next, we will iterate over the list using a for loop and find the largest amount of bottles sold for each drink over seven days.

for d in drinks:

    most_bottles_sold = max(d["bottles_sold"])

    print("The largest amount of {} bottles sold this week is {}.".format(d["name"], most_bottles_sold))

We use the max() function in the above code to get the largest item in the bottles_sold list. Let’s run the code to get the result:

The largest amount of Coca-Cola bottles sold this week is 100.
The largest amount of Fanta bottles sold this week is 90.
The largest amount of Sprite bottles sold this week is 50.

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
      1 for d in drinks:
      2     most_bottles_sold = max(d["bottles_sold"])
      3     print("The largest amount of {} bottles sold this week is {}.".format(d["name"], most_bottles_sold))
      4 

ValueError: max() arg is an empty sequence

The program raises the ValueError because Dr Pepper has an empty list.

Solution

To solve this error, we can add an if statement to check if any bottles were sold in a week before using the max() function. Let’s look at the revised code:

for d in drinks:

    if len(d["bottles_sold"]) > 0:

        most_bottles_sold = max(d["bottles_sold"])

        print("The largest amount of {} bottles sold this week is {}.".format(d["name"], most_bottles_sold)

    else:

        print("No {} bottles were sold this week.".format(d["name"]))

The program will only calculate the maximum amount of bottles sold for a drink if it was sold for at least one day. Otherwise, the program will inform us that the drink was not sold for that week. Let’s run the code to get the result:

The largest amount of Coca-Cola bottles sold this week is 100.
The largest amount of Fanta bottles sold this week is 90.
The largest amount of Sprite bottles sold this week is 50.
No Dr Pepper bottles were sold this week.

The program successfully prints the maximum amount of bottles sold for Coca-Cola, Fanta, and Sprite. The bottles_sold list for Dr Pepper is empty; therefore, the program informs us that no Dr Pepper bottles were sold this week.

Summary

Congratulations on reading to the end of this tutorial! The error: “ValueError: max() arg is an empty sequence” occurs when you pass an empty list as an argument to the max() function. The max() function cannot find the largest item in an iterable if there are no items. To solve this, ensure your list has items or include an if statement in your program to check if a list is empty before calling the max() function.

For further reading of ValueError, go to the articles:

  • How to Solve Python ValueError: cannot convert float nan to integer
  • How to Solve Python ValueError: if using all scalar values, you must pass an index

For further reading on using the max() function, go to the article:

How to Find the Index of the Max Value in a List in Python

Go to the Python online courses page to learn more about coding in Python for data science and machine learning.

Have fun and happy researching!

The max() method only works if you pass a sequence with at least one value into the method.

If you try to find the largest item in an empty list, you’ll encounter the error “ValueError: max() arg is an empty sequence”.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

In this guide, we talk about what this error means and why you may encounter it. We walk through an example to help you figure out how to resolve this error.

ValueError: max() arg is an empty sequence

The max() method lets you find the largest item in a list. It is similar to the min() method which finds the smallest item in a list.

For this method to work, max() needs a sequence with at least one value. This is because you cannot find the largest item in a list if there are no items. The largest item is non-existent because there are no items to search through.

A variation of the “ValueError: max() arg is an empty sequence” error is found when you try to pass an empty list into the min() method. This error is “ValueError: min() arg is an empty sequence”. This min() error occurs for the same reason: you cannot find the smallest value in a list with no values.

An Example Scenario

We’re going to build a program that finds the highest grade a student has earned in all their chemistry tests. To start, define a list of students:

students = [
	   { "name": "Ron", "grades": [75, 92, 84] },
	   { "name": "Katy", "grades": [92, 86, 81] },
	   { "name": "Rachel", "grades": [64, 72, 72] },
	   { "name": "Miranda", "grades": [] }
]

Our list of students contains four dictionaries. These dictionaries contain the names of each student as well as a list of the grades they have earned. Miranda does not have any grades yet because she has just joined the chemistry class.

Next, use a for loop to go through each student in our list of students and find the highest grade each student has earned and the average grade of each student:

for s in students:
	     highest_grade = max(s["grades"])
	     average_grade = round(sum(s["grades"]) / len(s["grades"]))
	     print("The highest grade {} has earned is {}. Their average grade is {}.".format(s["name"], highest_grade, average_grade))

We use the max() function to find the highest grade a student has earned. To calculate a student’s average grade, we divide the total of all their grades by the number of grades they have received.

We round each student’s average grade to the nearest whole number using the round() method.

Run our code and see what happens:

The highest grade Ron has earned is 92. Their average grade is 84.
The highest grade Katy has earned is 92. Their average grade is 86.
The highest grade Rachel has earned is 72. Their average grade is 69.
Traceback (most recent call last):
  File "main.py", line 10, in <module>
	     highest_grade = max(s["grades"])
ValueError: max() arg is an empty sequence

Our code runs successfully until it reaches the fourth item in our list. We can see Ron, Katy, and Rachel’s highest and average grades. We cannot see any values for Miranda.

The Solution

Our code works on the first three students because each of those students have a list of grades with at least one grade. Miranda does not have any grades yet. 

Because Miranda does not have any grades, the max() function fails to execute. max() cannot find the largest value in an empty list.

To solve this error, see if each list of grades contains any values before we try to calculate the highest grade in a list. If a list contains no values, we should show a different message to the user.

Let’s use an “if” statement to check if a student has any grades before we perform any calculations:

for s in students:
	     if len(s["grades"]) > 0:
	               highest_grade = max(s["grades"])
	               average_grade = round(sum(s["grades"]) / len(s["grades"]))
	               print("The highest grade {} has earned is {}. Their                average grade is {}.".format(s["name"], highest_grade, average_grade))
	     else:
		           print("{} has not earned any grades.".format(s["name"]))

Our code above will only calculate a student’s highest and average grade if they have earned at least one grade. Otherwise, the user will be informed that the student has not earned any grades. Let’s run our code:

The highest grade Ron has earned is 92. Their average grade is 84.
The highest grade Katy has earned is 92. Their average grade is 86.
The highest grade Rachel has earned is 72. Their average grade is 69.
Miranda has not earned any grades.

Our code successfully calculates the highest and average grades for our first three students. When our code reaches Miranda, our code does not calculate her highest and average grades. Instead, our code informs us that Miranda has not earned any grades yet.

Conclusion

The “ValueError: max() arg is an empty sequence” error is raised when you try to find the largest item in an empty list using the max() method.

To solve this error, make sure you only pass lists with at least one value through a max() statement. Now you have the knowledge you need to fix this problem like a professional coder!

In Python, an inbuilt function “max()” is used in a program to find the maximum value of the input sequence. Trying to execute the “max()” function on an empty sequence will throw the “max() arg is an empty sequence” error in Python. To resolve this error, various solutions are provided by Python.

This Python write-up will give you the reason and various solutions for “ValueError: max() arg is an empty sequence”.

  • Reason: Passing Empty Sequence
  • Solution 1: Passing Sequence With Values
  • Solution 2: Using the “default” Parameter
  • Solution 3: Using len() Function
  • Solution 4: Using try-except

Reason: Passing Empty Sequence

One of the prominent reasons which cause this error in Python programs is initializing an empty sequence as an argument to the “max()” function.

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

In this guide, we talk about what this error means and why you may encounter it. We walk through an example to help you figure out how to resolve this error.

ValueError: max() arg is an empty sequence

The max() method lets you find the largest item in a list. It is similar to the min() method which finds the smallest item in a list.

For this method to work, max() needs a sequence with at least one value. This is because you cannot find the largest item in a list if there are no items. The largest item is non-existent because there are no items to search through.

A variation of the “ValueError: max() arg is an empty sequence” error is found when you try to pass an empty list into the min() method. This error is “ValueError: min() arg is an empty sequence”. This min() error occurs for the same reason: you cannot find the smallest value in a list with no values.

An Example Scenario

We’re going to build a program that finds the highest grade a student has earned in all their chemistry tests. To start, define a list of students:

students = [
	   { "name": "Ron", "grades": [75, 92, 84] },
	   { "name": "Katy", "grades": [92, 86, 81] },
	   { "name": "Rachel", "grades": [64, 72, 72] },
	   { "name": "Miranda", "grades": [] }
]

Our list of students contains four dictionaries. These dictionaries contain the names of each student as well as a list of the grades they have earned. Miranda does not have any grades yet because she has just joined the chemistry class.

Next, use a for loop to go through each student in our list of students and find the highest grade each student has earned and the average grade of each student:

for s in students:
	     highest_grade = max(s["grades"])
	     average_grade = round(sum(s["grades"]) / len(s["grades"]))
	     print("The highest grade {} has earned is {}. Their average grade is {}.".format(s["name"], highest_grade, average_grade))

We use the max() function to find the highest grade a student has earned. To calculate a student’s average grade, we divide the total of all their grades by the number of grades they have received.

We round each student’s average grade to the nearest whole number using the round() method.

Run our code and see what happens:

The highest grade Ron has earned is 92. Their average grade is 84.
The highest grade Katy has earned is 92. Their average grade is 86.
The highest grade Rachel has earned is 72. Their average grade is 69.
Traceback (most recent call last):
  File "main.py", line 10, in <module>
	     highest_grade = max(s["grades"])
ValueError: max() arg is an empty sequence

Our code runs successfully until it reaches the fourth item in our list. We can see Ron, Katy, and Rachel’s highest and average grades. We cannot see any values for Miranda.

The Solution

Our code works on the first three students because each of those students have a list of grades with at least one grade. Miranda does not have any grades yet. 

Because Miranda does not have any grades, the max() function fails to execute. max() cannot find the largest value in an empty list.

To solve this error, see if each list of grades contains any values before we try to calculate the highest grade in a list. If a list contains no values, we should show a different message to the user.

Let’s use an “if” statement to check if a student has any grades before we perform any calculations:

for s in students:
	     if len(s["grades"]) > 0:
	               highest_grade = max(s["grades"])
	               average_grade = round(sum(s["grades"]) / len(s["grades"]))
	               print("The highest grade {} has earned is {}. Their                average grade is {}.".format(s["name"], highest_grade, average_grade))
	     else:
		           print("{} has not earned any grades.".format(s["name"]))

Our code above will only calculate a student’s highest and average grade if they have earned at least one grade. Otherwise, the user will be informed that the student has not earned any grades. Let’s run our code:

The highest grade Ron has earned is 92. Their average grade is 84.
The highest grade Katy has earned is 92. Their average grade is 86.
The highest grade Rachel has earned is 72. Their average grade is 69.
Miranda has not earned any grades.

Our code successfully calculates the highest and average grades for our first three students. When our code reaches Miranda, our code does not calculate her highest and average grades. Instead, our code informs us that Miranda has not earned any grades yet.

Conclusion

The “ValueError: max() arg is an empty sequence” error is raised when you try to find the largest item in an empty list using the max() method.

To solve this error, make sure you only pass lists with at least one value through a max() statement. Now you have the knowledge you need to fix this problem like a professional coder!

In Python, an inbuilt function “max()” is used in a program to find the maximum value of the input sequence. Trying to execute the “max()” function on an empty sequence will throw the “max() arg is an empty sequence” error in Python. To resolve this error, various solutions are provided by Python.

This Python write-up will give you the reason and various solutions for “ValueError: max() arg is an empty sequence”.

  • Reason: Passing Empty Sequence
  • Solution 1: Passing Sequence With Values
  • Solution 2: Using the “default” Parameter
  • Solution 3: Using len() Function
  • Solution 4: Using try-except

Reason: Passing Empty Sequence

One of the prominent reasons which cause this error in Python programs is initializing an empty sequence as an argument to the “max()” function.

The above snippet shows “ValueError” because an empty dictionary sequence “dict_value” is passed inside the max() function.

Solution 1: Passing Sequence With Values

To resolve this error, a sequence containing at least one value must be passed to the max() function.

Code:

dict_value = {5:'Lily', 10: 'John'}
Output = max(dict_value)
print(Output)

In the above code, a sequence “dict_value” with multiple elements is initialized in the program. The “max()” function accepts the “dict_value” variable as an argument and returns the dictionary key having the maximum value.

Output:

The above output shows that the max() function retrieves the maximum dictionary key from the input dictionary sequence.

Solution 2: Using the “default” Parameter

This error can also be overcome in Python by assigning the “default” parameter value to “0”.

Code:

dict_value = {}
Output = max(dict_value, default=0)
print(Output)

In the above code, the dictionary variable “dict_value” is initialized with an empty value. The “max()” function accepts two arguments, the input variable “dict_Value” and the default parameter “default=0”. Whenever the input sequence is empty, the “max()” function returns the value “0” by default.

Output:

The above output verified that the input sequence is empty.

Solution 3: Using len() Function

To overcome this error, the “len()” function is also used in Python programs. The “len()” function is used along with the “if-else” statement to get the length and perform the operation on the input sequence based on the specified condition.

Code;

dict_value = {}
if len(dict_value)>0:
    Output = max(dict_value)
    print(Output)
else:
    print('Input Sequence is Empty')

In the above code, the “dict_value” dictionary sequence variable is initialized in the program. The “max()” function will be used on the input sequences if the length of the sequence is greater than “0”; otherwise, the “else” block will execute.

Output:

The above output shows that the input sequence is empty.

Solution 4: Using try-except

The “try-except” is also used to handle the “ValueError: max() arg is an empty sequence” in Python. Let’s see it via the following code:

Code:

dict_value = {}

try: 
    Output = max(dict_value)
    print(Output)
except:
    print('Input Sequence is Empty')

In the above code, the variable “dict_value” is initialized in the program. The “try” block executes its code and finds the maximum value of the input sequence using the “max()” function. But if the error arises, the “except” block will execute its code.

Output:

The above output shows that the “except” block executes its code because the input sequence is empty.

Conclusion

The “ValueError: max() arg is an empty sequence” occurs when a user tries to pass an empty sequence as an argument to the max() function. To resolve this error, various solutions are used in Python, such as passing sequence value, using default parameters, using the len() function, and using the try-except block. The “len()” function can be utilized along with the “if-else” statement to resolve this error. This article delivered multiple solutions for the error “max() arg is an empty sequence” in Python.

Возможно, вам также будет интересно:

  • Mdv коды ошибок наружного блока
  • Mdv mdou 48hn1 l коды ошибок
  • Mdv mdou 36hn1 l ошибки
  • Mdou 60hn1 l mdv коды ошибок
  • Mdou 36hn1 l коды ошибок

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии