Learn Interfaces by Building an Equation Solver - Step 17

Tell us what’s happening:

?You should use a dictionary comprehension to store your coefficients.?
Not sure why it’s failing. creates a dictionary value of {1: 2, 0: 3}.

    self.coefficients =  dict(reversed({i: arg for i, arg in enumerate(reversed(args))}.items())) 
    print(self.coefficients)

{1: 2, 0: 3}

Your code so far

from abc import ABC, abstractmethod

class Equation(ABC):
    degree: int
    
    def __init__(self, *args):
        if (self.degree + 1) != len(args):
            raise TypeError(
                f"'Equation' object takes {self.degree + 1} positional arguments but {len(args)} were given"
            )
        if any(not isinstance(arg, (int, float)) for arg in args):
            raise TypeError("Coefficients must be of type 'int' or 'float'")
        if args[0] == 0:

# User Editable Region

            raise ValueError("Highest degree coefficient must be different from zero") 

        self.coefficients =  dict(reversed({i: arg for i, arg in enumerate(reversed(args))}.items())) 
        print(self.coefficients)

# User Editable Region

    def __init_subclass__(cls):
        if not hasattr(cls, "degree"):
            raise AttributeError(
                f"Cannot create '{cls.__name__}' class: missing required attribute 'degree'"
            )
    
    @abstractmethod
    def solve(self):
        pass
        
    @abstractmethod
    def analyze(self):
        pass
        
class LinearEquation(Equation):
    degree = 1
    
    def solve(self):
        pass
    
    def analyze(self):
        pass

    
lin_eq = LinearEquation(2, 3)

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36

Challenge Information:

Learn Interfaces by Building an Equation Solver - Step 17

Hey, your code seems correct to me. The thing here is that the test is checking that the value assigned to self.contents is a dictionary comprehension. So, since you are passing the comprehension to dict(reversed( )), you are not able to pass.

removed dict() and replaced with
self.coefficients = {x: y for x, y in (reversed({i: arg for i, arg in enumerate(reversed(args))}.items()))}
Not the correct solution.

googled “python dictionary comprehension”
PEP 274 – Dict Comprehensions | peps.python.org,
Python Dictionary Comprehensions (With Examples) • datagy
Python Dictionary Comprehension ( i can keep on going)
stated that the two, dict() is equivalent to {k: v for k,v in } iterable.

“Create the key-value pairs in your new dictionary following the same order as in args .”
“You should use a dictionary comprehension to store your coefficients.” my conclusion is I don’t understand the comment nor the request.

self.coefficients contains the dictionary {1: 2, 0: 3}. The argument order and coefficient order.
This is not the answer. The checking is looking for something else. Can some please provide a hint as to what the something else is? Kind of stuck on this step.

As I have already told you, the test is specifically checking that the value assigned to self.coefficients is a dictionary comprehension.

That means that you’ll be able to pass only if you have:

self.contents = {this is a dictionary comprehension}

If you have

self.contents = function_call({this is a dictionary comprehension})

or anything else, you won’t be able to pass the test.

Excuse me but I’m new to Python. But I’m not understanding your usage of terms nor your comments .
The instruction:
" Create the key-value pairs in your new dictionary following the same order as in args ."
“For example, a LinearEquation object instantiated with 2 and 4 should have the following coefficients attribute: {1: 2, 0: 4} , because 2 corresponds to the first degree of x and 4 corresponds to zero-th degree of x .”

Googled both terms and I found these definitions:

List Comprehension

List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
##Dictionary comprehension
A dictionary comprehension takes the form {key: value for (key, value) in iterable}

lin_eq = LinearEquation(3, 2.5 )
self.coefficients = dictionay compresnsion :{1: 2, 0: 4}
List Comprension would be { i for i in args} :{ 2, 4}

I have three solutions. If I try I can find additional solutions that all return the same dictionary : `{1: 2, 0: 4}'. They all failed.

  1. self.coefficients = dict(reversed({i: arg for i, arg in enumerate(reversed(args))}.items()))
  2. self.coefficients = {x: y for x, y in (reversed({i: arg for i, arg in enumerate(reversed(args))}.items()))}
  3. self.coefficients = {len(args) - 1 - i: arg for i, arg in enumerate(args)}

lets talk about it together as i am stuck on this step, i assume what he is saying is you are adding too much in, you only need a dict comprehension to pass

the dict is not needed put your code in this format self.coefficients = {content }

self.coefficents = {self.degree : linear for val1,val2 in enumerate(args)}  
        print(coefficents.degree)

what am i doing wrong??

From what I can tell, the answer is in the instruction:
“For example, a LinearEquation object instantiated with 2 and 4 should have the following coefficients attribute: {1: 2, 0: 4}.
My understanding is I need to use, that is program, dictionary comprehension.
below a just a few URLs defining dictionary comprehension.

[key_expression: value_expression for item in iterable if condition]

Basic Syntax:

{key_expression: value_expression for item in iterable}

{self.degree : linear for val1,val2 in enumerate(args)}

enumerate returns the iteration and the value. Short hand for looping through with a counter.
So in your case val1 would be the index of args and val2 is the value of args[index].
to create a dictionary (key, value) ; val1 is the key and val2 is the value. Or written as a dictionary {val1:val2}.

In your example self.degree value does not change, always ‘1’, and will generate duplicates.

self.coefficents = {self.degree : {0: 2, 1: 3} for val1,val2 in enumerate(args)}  

im so close its saying this hint for me You should declare an attribute named coefficients within your __init__ method.

The full code . self.coefficients = {} is declares as an empty dictionary.
The instructions provides an example:
“For example, a LinearEquation object instantiated with 2 and 4 should have the following coefficients attribute: {1: 2, 0: 4} ,”
On the other hand your code, aside from hard coding the arguments, returns
{1: {0: 2, 1: 3}} - a dictionary within a dictionary. Per instruction and correction your version should be {1: {1: 2, 0: 3}}.
More important yours nor mine pass the check.
So were are both stuck - can anyone pleeeeeaase help!

from abc import ABC, abstractmethod

class Equation(ABC):
    degree: int
    
    def __init__(self, *args):
        self.coefficients = {}
        if (self.degree + 1) != len(args):
            raise TypeError(f"'Equation' object takes {self.degree + 1} positional arguments but {len(args)} were given")
        if any(not isinstance(arg, (int, float)) for arg in args):
            raise TypeError("Coefficients must be of type 'int' or 'float'")
        if args[0] == 0:
            raise ValueError("Highest degree coefficient must be different from zero")   
        self.coefficients = {len(args) - 1 - i: arg for i, arg in enumerate(args)}  

         
    def __init_subclass__(cls):
        if not hasattr(cls, "degree"):
            raise AttributeError(
                f"Cannot create '{cls.__name__}' class: missing required attribute 'degree'"
            )
    
    @abstractmethod
    def solve(self):
        pass
        
    @abstractmethod
    def analyze(self):
        pass
        
class LinearEquation(Equation):
    degree = 1
    
    def solve(self):
        pass
    
    def analyze(self):
        pass

    
lin_eq = LinearEquation(2, 4 )
print(lin_eq.coefficients)

again the response from the check is “You should use a dictionary comprehension to store your coefficients.”
Your comment is contrary to the response. Nor did the implementation of a a list comprehension pass the check:

Sorry about the confusion, I meant a dictionary comprehension, not a list comprehension. It’s been an oversight.

By the way, your code is passing the tests on my end. Can you confirm that?
Try to reset the code for this step and write that line again if not.

Sorry but using multiple browsers the code still fails. That is chrome, Edge and Duck Duck - all failed.

It finally worked. Thanks.

1 Like