Calling a list from another function in Python - python-2.7

I am trying figure out if I'm having an issue with my classes, or calling variables/lists from another function.
Below is a function I have being called from a button I press(inside a class that is my main window):
def analyzeRNA(self):
self.p = self.textbox.get("1.0", END)
protein_assignment(self.p)
self.data = primary_structure
self.databox.insert(END, self.data)
It reads from my textbox just fine. It performs my function protein_assignment on it and prints the results to the python shell as in the function does. It prints a list I make in protein_assignment that function called primary_structure. Now, how do put this information into my databox (which is also a "textbox" so to speak)
My error:
line 86, in analyzeRNA
self.data = primary_structure
NameError: global name 'primary_structure' is not defined
Protein assignment outline:
def protein_assignment(sequence):
x = 0
primary_structure = []
single_letter_assignment = []
three_letter_code = []
chemical_properties = []
while True:
blah, blah, blah adding amino acids to the list, running through sequence
"if nothing else in sequence, print lists and break"
return primary_structure #(Not sure if this is needed)
return primary_structure #(Not sure what I'm doing here either)
If more is needed, glad to help. Running off to work right now. Will respond later. Please and thank you!

primary_structure is returned by protein_assignment so to keep a reference to it in analyzeRNA you just need to do this:
def analyzeRNA(self):
self.p = self.textbox.get("1.0", END)
returned_value = protein_assignment(self.p)
self.data = returned_value
self.databox.insert(END, self.data)
or since you are just setting it to self.data anyway:
def analyzeRNA(self):
self.p = self.textbox.get("1.0", END)
self.data = protein_assignment(self.p)
self.databox.insert(END, self.data)

Related

What does does if self.transforms mean?

What does
if self.transforms:
data = self.transforms(data)
do? I don't understand the logic behind this line - what is the condition the line is using?
I'm reading an article on creating a custom dataset with pytorch based on the below implementation:
#custom dataset
class MNISTDataset(Dataset):
def __init__(self, images, labels=None, transforms=None):
self.X = images
self.y = labels
self.transforms = transforms
def __len__(self):
return (len(self.X))
def __getitem__(self, i):
data = self.X.iloc[i, :]
data = np.asarray(data).astype(np.uint8).reshape(28, 28, 1)
if self.transforms:
data = self.transforms(data)
if self.y is not None:
return (data, self.y[i])
else:
return data
train_data = MNISTDataset(train_images, train_labels, transform)
test_data = MNISTDataset(test_images, test_labels, transform)
# dataloaders
trainloader = DataLoader(train_data, batch_size=128, shuffle=True)
testloader = DataLoader(test_data, batch_size=128, shuffle=True)
thank you! i'm basically trying to understand why it works & how it applies transforms to the data.
The dataset MNISTDataset can optionnaly be initialized with a transform function. If such transform function is given it be saved in self.transforms else it will keep its default values None. When calling a new item with __getitem__, it first checks if the transform is a truthy value, in this case it checks if self.transforms can be coerced to True which is the case for a callable object. Otherwise it means self.transforms hasn't been provided in the first place and no transform function is applied on data.
Here's a general example, out of a torch/torchvision context:
def do(x, callback=None):
if callback: # will be True if callback is a function/lambda
return callback(x)
return x
do(2) # returns 2
do(2, callback=lambda x: 2*x) # returns 4

object returning memory location instead of value

So I have this class:
#!/usr/bin/python3
class MyClass(object):
def __init__(self, length):
self._list = length
def get(self, index):
try:
return self._list[index]
except IndexError:
return None
which takes in a list and returns a value, a list index I think. I am trying to get that value:
def my_function(a_list):
a_list = MyClass
for x in (10**p for p in range(1, 9)):
if a_list:
print(a_list)
def main():
length = my_function(MyClass([i for i in range(0, 543)]))
but I keep getting only the memory location of the list, I think this is supposed to return an int.
I am hoping this is a workable bit of code, but I am struggling, with the concept of passing an "object" to a class, it doesn't make any sense to me.
Here is a test I am supposed to use:
def test_large_list():
s_list = My_Class([i for i in xrange(0, 100000)])
assert len(s_list._list) == list_length(s_list)
Ok, Here is my full function that works, it is done, how od I do this so that the first line takes an argument
#!/usr/bin/python3
#def list_length(single_method_list): This is what I am supposed to work with
from single_method_list import SingleMethodList
def my_function(): # This is how I have done it and it works.
a_list = MyClass([i for i in range(0, 234589)])
for x in (10**p for p in range(1, 8)):
if a_list.get(x):
print("More than", x)
first = x
else:
print("Less than", x)
last = x
break
answer = False
while not answer:
result = (first + last)/2
result = int(round(result))
print(result)
if s_list.get(result):
first = result
print('first', result)
else:
last = result
print('last', result)
if s_list.get(result) and not s_list.get(result + 1):
answer = True
print(result + 1)
my_function()
I don't know what more I can give to explain where I am stuck, it is the OOP part of this that I don't know I need the same results here, just passing it to the function instead of creating it inside the function which I did in order to do the algorithm.
Well your class does something else.MyClass is designed to take a List at initialization, so the naming length is not a good idea.
The get() method of this class takes in a number and returns the element located at that particular index in the initialized self._list.
Your logic should be like:
def my_function(a_list):
a_list = MyClass(a_list)
...
def main():
length = my_function([i for i in range(0, 543)])
Just to clarify some misunderstanding that you might have.
Class does not return anything. It is a blueprint for creating objects.
What can return value is a method (function). For instance, if you want to write a method which returns length of some list:
def my_function(some_list):
return len(some_list)
Or in your case:
def my_function(a_list):
return len(a_list._list)
Note that you should not call your variables list. It's a built-in function in python which creates lists.
And as you can see there is another built-in function len in python which returns length of list, tuple, dictionary etc.
Hope this helps, although it's still a bit unclear what you're trying to achieve.

Generate a bunch of tkinter checkbuttons and read the status of all those radio buttons at once

I have a tkinter class which reads some data into a couple of lists. From this now i have created a dictionary for creating checkbuttons.
I'm trying to create those checkbuttons in a new window() with a button to submit and read the stutus of those. I want this data to process.
def get_data(self):
self.flags = ["one","two","three", "four"]
self.tests = ["Jack","Queen","King","Ace"]
self.value = [11,12,13,1]
self.dict1 = {k:v for k,v in enumerate(self.flags,1)}
def get_status(self):
self.selectWindow = Toplevel(root)
self.selectWindow.title("Select Test Cases")
Submit_btn = Button(selectWindow, text="Submit", command=read_status )
for testcase in self.dict1:
self.dict1[testcase] = Variable()
l = Checkbutton(self.selectWindow,text=self.dict1[testcase], variable=self.dict1[testcase])
l.pack()
def read_status(self):
pass
From here I'm not able go ahead and read the status of checkbuttons and get those are checked. I need this data for further processing on tests(not actual lists given here I have few more). How to solve? Please let me know.
Checkbutton has a built in command function that can solve this problem. Every time you press a button that function is called, and you can print out the values of the buttons (0,1)
def get_data(self):
self.flags = ["one","two","three", "four"]
self.tests = ["Jack","Queen","King","Ace"]
self.value = [11,12,13,1]
self.dict1 = {k:v for k,v in enumerate(self.flags,1)}
def get_status(self):
self.selectWindow = Toplevel(self)
self.selectWindow.title("Select Test Cases")
self.get_data()
Submit_btn = Button(self.selectWindow, text="Submit", command=read_status ) # This button should be packed
Submit_btn.pack()
for testcase in self.dict1:
self.dict1[testcase] = Variable()
l = Checkbutton(self.selectWindow,text=self.dict1[testcase], variable=self.dict1[testcase], command=self.read_status) # Note the command
l.pack()
self.selectWindow.mainloop()
# Here comes the interesting part
def read_status(self):
for i,j in self.dict1.iteritems():
print j.get()
You forgot to use self and pack method:
Submit_btn = Button(self.selectWindow, text="Submit", command=self.read_status )
Submit_btn.pack()
Checkbutton's states are (0, 1) so use IntVar() to inspect the state:
...
self.dict1[testcase] = IntVar()
...
Then use IntVar get method:
def read_status(self):
for v in self.dict1:
print self.dict1[v].get()

'list' object has no attribute 'items'

working on ubuntu 12.04, python 2.7
I have the error 'list' object has no attribute 'items' when I call the print_to_screen function.
could someone explain me please how to manage the dictionary which is created?
Thanks
class median_uniq:
def init(self):
self.median_number_list = []
def print_to_screen(self, words_dict, is_reverse = False):
words = words_dict.items()
words.sort(key = lambda(a,b):(a,b), reverse = is_reverse)
print("[Words tweeted: %d]" % len(words)).center(60,"=")
print("%-25s | %25s" % ("Words", "count"))
print BANNER
for w, c in words:
print("%-25s | %25d" % (w, c))
def Median_number(self, file_name):
file_object = open(file_name, "r")
number_word_list = []
for line in file_object:
unique_words_per_tweet = sorted(set(line.rstrip().split(" ")))
number_word_list.append(len(Counter((unique_words_per_tweet))))
self.median_number_list.append(numpy.median(numpy.array(number_word_list)))
print self.median_number_list
return self.median_number_list
to call function, I do this:
med = median_uniq() med_list = med.Median_number(input_file)
med.print_to_screen(med_list, is_reverse = False)
on command line knowing that my input_file is a .txt file. thanks
I have seen similar post, but don't well understand. An explanation with simply words would be really helpful.
Thanks
"words_dict" in your code is a list, but your attempt to use a python dictionary method (items())
I would need a working example to be able to propose a customized solution.

Pretty printing boost::unordered_map on gdb

recently I've started to use the excellent boost::unordered_map on my system, but got one drawback: I couldn't figure how to inspect its contents. Printing it on gdb gives me a table_ and a buckets_, but haven't found where are the items. Anyone has a clue about this?
For the ones that wanted a printer, I've managed to create one. Here is Code:
class BoostUnorderedMapPrinter:
"prints a boost::unordered_map"
class _iterator:
def __init__ (self, fields):
type_1 = fields.val.type.template_argument(0)
type_2 = fields.val.type.template_argument(1)
self.buckets = fields.val['table_']['buckets_']
self.bucket_count = fields.val['table_']['bucket_count_']
self.current_bucket = 0
pair = "std::pair<%s const, %s>" % (type_1, type_2)
self.pair_pointer = gdb.lookup_type(pair).pointer()
self.base_pointer = gdb.lookup_type("boost::unordered_detail::value_base< %s >" % pair).pointer()
self.node_pointer = gdb.lookup_type("boost::unordered_detail::hash_node<std::allocator< %s >, boost::unordered_detail::ungrouped>" % pair).pointer()
self.node = self.buckets[self.current_bucket]['next_']
def __iter__(self):
return self
def next(self):
while not self.node:
self.current_bucket = self.current_bucket + 1
if self.current_bucket >= self.bucket_count:
raise StopIteration
self.node = self.buckets[self.current_bucket]['next_']
iterator = self.node.cast(self.node_pointer).cast(self.base_pointer).cast(self.pair_pointer).dereference()
self.node = self.node['next_']
return ('%s' % iterator['first'], iterator['second'])
def __init__(self, val):
self.val = val
def children(self):
return self._iterator(self)
def to_string(self):
return "boost::unordered_map"
In a typical hash table implementation, the buckets contain the head of a linked list which actually contains the values corresponding to this particular hash. Thus I would bet on buckets_.
Another option: there are various python pretty printer libraries for gdb now, and I think that you could find one that works with C++0x and inspect where it looks for the values.