How do you get a column name and row from table? [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have to write a code where table is represented as dictionary, each key is the name of the column name and each value is the list of items in that column from top row to bottom.
I can use dictionary, list or whatever i want. So i decided to use dictionary
But when i test my code, I am getting this weird error :
>diction = {'a' : ['letter of a']}
>my_table = Table()
Traceback (most recent call last):
File "<string>", line 1, in <fragment>
builtins.TypeError: __init__() missing 3 required positional arguments: 'new_dict', 'coloumn_name', and 'coloumn_value'
Can someone help me with this?
class Table():
'''A class to represent a SQuEaL table'''
def __init__(self, new_dict, coloumn_name, coloumn_value):
self._new_dict = new_dict
self._key = coloumn_name
self._value = coloumn_value
def new_dictionary(self):
return self._new_dict
def get_coloumn_name(self):
return self._key
def get_coloumn_value(self):
return self._value
def set_dict(self, new_dict):
'''(Table, dict of {str: list of str}) -> NoneType
Populate this table with the data in new_dict.
The input dictionary must be of the form:
column_name: list_of_values
'''
# assign empty dictionary
self._new_dict = {}
# each key represents a coloumn name and each value is list of items
# that coloumn_name from top row to bottom(coloum_values)
self._new_dict += get_coloumn_name[self._key], get_coloumn_value[self._value]
return

You are getting this error because the __init__() function in your class requires 3 arguments - new_dict, coloumn_name, and coloumn_value - and you did not supply them.

Related

Sum of items of a class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed yesterday.
Improve this question
What I have to do is to create a class that counts from a giving single argument and itself make the arithmetical operation.
class Counts:
def __init__(self, value=0):
self.value = value
def newvalue(self, other):
return Counts(self.value + other)
But for every I make to the code I got any different error, either syntax or callable argument.
The idea is to get
Counts()
Expected output
0
Next
Counts.newvalue(10)
Expected output
10
Next
Counts.newvalue(40)
Expected output
50
Next
Counts.newvalue(-17)
Expected output
33
And so on.
The code that shows the expected behaviour is
class Counts:
value = 0
def __new__(self):
return self.value
#classmethod
def newvalue(cls, other):
cls.value += other
return cls.value
however this is a somewhat strange piece of code, as you are creating a class that returns a value when initialized instead of an object deriving from that class by overriding __new__, which is pretty non-standard.
also if you want to zero the value whenever Count() is called, you can add a self.value = 0 before the return self.value
Tests ->
print(Counts())
print(Counts.newvalue(10))
print(Counts.newvalue(40))
print(Counts.newvalue(-17))
returns
0
10
50
33

Using mypy to type check and i cant figure out why this errors are happening [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
So, i using mypy to learn how to code in python using type check from the beginning. I'm using this code to train:
def stars(*args: int, **kwargs: float) -> None:
for arg in args:
print(arg)
for key, value in kwargs:
print(key, value)
stars(1.3,1.3)
I'm getting this typeerror:
learning_mypy.py:6: error: Unpacking a string is disallowed
learning_mypy.py:7: error: Cannot determine type of 'key'
learning_mypy.py:7: error: Cannot determine type of 'value'
learning_mypy.py:9: error: Argument 1 to "stars" has incompatible type "float"; expected "int"
learning_mypy.py:9: error: Argument 2 to "stars" has incompatible type "float"; expected "int"
Found 5 errors in 1 file (checked 1 source file)
So my questions are:
Why error mypy.py:6 is happening?
How do i define the type the value for key and value?
Why error mypy.py:9 is hapening?
If you do the below changes, mypy does not show anything.
def stars(*args: float, **kwargs: float) -> None:
for arg in args:
print(arg)
for key, value in kwargs.items():
print(key, value)
stars(1.3,1.3)
Why error mypy.py:6 is happening?
for key, value in kwargs: for this line, you should see the kwargs as a Python dictionary. If you iterate the kwargs in the for loop, it will iterate ONLY the key of the dictionary. Look at the below code.
d = {'1': 'one', '2': 'two', '3': 'three'}
for key in d:
print(key)
The output is:
1
2
3
If you want to print the values as well, you can use dict.items method.
d = {'1': 'one', '2': 'two', '3': 'three'}
for key, value in d.items():
print(key, value)
The output is:
1 one
2 two
3 three
or, you can access the value of the key over the dictionary.
for key in d:
print(key, d[key])
In line 6, since ONLY the keys are generated and also keys are a str; you are trying to unpack a string. Consider the below code:
var1, var2 = "test_variable"
This is exactly what your second for loop does.
How do i define the type the value for key and value?
You cannot define the type of the keys for kwargs but you can define the type of the values. (You already done it: kwargs: float)
Why error mypy.py:9 is hapening?
You defined the *args as int. But you passed float.
If you change *args: float, this error will be gone.

How to change value dict out class [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I want to change dict value, but allert me a Error 'object does not support item assignment'
Full Code:
def __init__(self):
self.dict = dict()
def __getitem__(self, item):
return self.dict[item]
arr = SparseArray()
arr[0] = 1```
You to override __setitem__
def __setitem__(self, key, value):
self.dict[key] = value
Then you'll be able to assign a value using an index
# use of __setitem__
arr[0] = 1
arr["foo"] = 5
# use of __getitem__
print(arr[0]) # 1
print(arr["foo"]) # 5
Also avoid naming variable as built-in name like dict, at least you can use items or values if there is no real sense about the variable's content

Does separate method by argument? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Could you give me an opinion which A or B is better?
I sometimes get lost in the definition of method.
# Both returns same value.
# Only the arguments are difference.
# ------------------
# pattern A
def some_method_by_name(name: str):
record = <SELECT ... WHERE record_name=str>
return record
def some_method_by_id(id: int):
record = <SELECT ... WHERE record_id=id>
return record
# ------------------
# pattern B
def some_method(**kwargs):
if 'id' in kwargs:
record = <SELECT ... WHERE record_id=kwargs.get('id')>
elif 'str' in kwargs:
record = <SELECT ... WHERE record_name=kwargs.get('str')>
else:
raise Exception('wrong!')
return record
I think that 'A' is good because to separate method by arguments is easy to understand, but I think that it is verbose.
Thanks.

Why does python keep complaining that my constructor is sent one too few arguments? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I have the following class:
class Gene(object):
"""
Represents transcripts.
Called gene for convenience, but the class actually represents different transcripts of genes.
"""
def _set_start_end(strand, start_position, end_position):
if strand == '-':
return end_position, start_position
else:
return start_position, end_position
def __init__(self, transcript_name, gene_name, chromosome, strand, start_position, end_position):
self.transcript_name = transcript_name
self.gene_name = gene_name
self.chromosome = chromosome
self.strand = strand
self.start_position, self.end_position = _get_start_end(strand, start_position, end_position)
When I try to instantiate this class with refgene = Gene("NM_016166", "PIAS1", "Chr15", "-" "68346571", "68480404"), Python keeps complaining that I have one argument too few:
Traceback (most recent call last):
refgene = Gene("NM_016166", "PIAS1", "Chr15", "-" "68346571", "68480404")
TypeError: __init__() takes exactly 7 arguments (6 given)
Why? I am surely not mean to send self to the constructor?
Ps. Python 2.7.8 :: Anaconda 2.0.0 (64-bit)
You missed a comma:
Gene("NM_016166", "PIAS1", "Chr15", "-" "68346571", "68480404"),
# ^
Making that one string as Python concatenates two strings separated only by whitespace:
>>> 'foo' 'bar'
'foobar'
Add in the comma:
Gene("NM_016166", "PIAS1", "Chr15", "-", "68346571", "68480404"),
Next problem is that your _set_start_end function is not going to work; you either need to make it a method, or move it out of the class. If it is a method, you need to add self in two places; one to call it and one to receive the bound instance:
self.start_position, self.end_position = self._get_start_end(strand, start_position, end_position)
and:
def _set_start_end(self, strand, start_position, end_position):

Categories

Resources