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 4 years ago.
Improve this question
Context: Hello to anyone who looks at this question. I am a beginning python coder (2 weeks going strong!) and I believe I initially designed my classes poorly and am asking for help on a good way to re-design the fundamental one (in Locus.py).
Background: The project has 4 classes so far which can be found here (https://github.com/asriley/HalfSiblings). The very base class Locus has a tuple to represent an allele of genetic data (a,b). The next class, Individual has a list of alleles: [(a,b),(c,d),(a,e),(f,d)]. In general though, we have n individuals and l loci for each individual.
Sample Data: 7 individuals(rows) with 3 loci (cols)
1,1 5,3 4,3
1,2 4,7 3,7
2,3 3,6 5,4
2,4 7,4 4,9
3,6 8,9 3,0
6,5 4,8 0,0
7,7 7,7 7,9
I am trying to figure out how to design this class to incorporate it in other classes (Especially Individual) because eventually I have to use networkx to build graphs on the data.
A full snippet of the Locus class and the current error is given:
class Locus:
# constructor
def __init__(self):
self.alleles = ()
def get_alleles(self):
return self._alleles
def set_alleles (self,x, y):
if x and y:
self._alleles = (x,y)
alleles = property (get_alleles, set_alleles)
l1 = Locus()
l1.set_alleles(1,2)
l1.set_alleles(2,3)
print (l1.get_alleles())
Traceback (most recent call last):
File "Locus.py", line 13, in <module>
l1 = Locus()
File "Locus.py", line 4, in __init__
self.alleles = ()
TypeError: set_alleles() missing 1 required positional argument: 'y'
Can anyone assist with how I should properly handle this class?
File parsing is done in one of the other classes from the github link. So thats not an issue here. Eventually, I want to send a 2D list of Individuals (containing the genetic Locus info) to the other classes.
I see you want to use the #property decorator to get/set tuples on the Locus class, here's one possible way to do that:
class Locus:
#property
def alleles(self):
return self._alleles
#alleles.setter
def alleles(self, value):
try:
x, y = value
# ... Tuple processing goes here ...
self._alleles = (x, y)
except ValueError:
raise ValueError("(x,y) tuple expected")
l1 = Locus()
l1.alleles = (1, 2)
l1.alleles = (2, 3)
print(l1.alleles)
Related
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 1 year ago.
Improve this question
I am trying to create and use a dynamic variable in Python for the first time.
for i in range(0,len(test_data)):
globals()["test_list_{}".format(test_data[i])]=[]
globals()["test_calculation_{}".format(test_data[i])]=0
First, I created test_list_number and test_calculation_number as global variables.
Then I want to use this in for and use it for calculations.
The code I wrote here was made by simplifying the code I'm going to use.
How do I change the numbers in the two for statements below?
1
--------------Below is a code example. -------------
import pandas as pd
import numpy as np
X=list(np.random.random(100)*100)
Y=list(np.random.random(100)*100)
test_data= [2,5,7,8]
test_dict={(i,j):np.hypot(X[i]-X[j],Y[i]-Y[j]) for i in range(0,100) for j in range(0,100)}
test_df_data2={
'index' : [1,2,3],
'data1' : [3,5,6],
'data2' : [2,5,6]
}
test_df_data5={
'index' : [1,2,3],
'data1' : [8,3,1],
'data2' : [3,2,7]
}
test_df_2 =pd.DataFrame(test_df_data2)
test_df_5 =pd.DataFrame(test_df_data5)
for i in range(0,len(test_data)):
globals()["test_list_{}".format(test_data[i])]=[]
globals()["test_calculation_{}".format(test_data[i])]=0
for i in range(0, len(test_df_2 ) ):
test_list_2 .append((test_df_2 .data1[i],test_df_2 .data2 [i]))
for i in range(len(test_list_2 )):
test_calculation_2 = test_calculation_2 + test_dict[test_list_2 [i] ]
print( test_calculation_2)
Short answer, do not do this!
It is widely accepted to be a bad practice (see for example). You have a high risk of doing something difficult to debug, to overwrite existing variables, or to use the wrong namespace. In addition there are eventual pitfalls and lack of robust methods to do this.
Use a container instead.
You will have a shorter, cleaner, and easier to debug code.
Dictionaries are ideal for this:
# initialize
my_dfs = {}
# computation
for i in …:
my_dfs[f'df_computation_{i}'] = …
# access
my_dfs['df_computation_42']
As a C# programmer I'm learning python and one of the issues is what is the pythons way of handing lists back and forth. Maybe I don't know what its called so I am missing the tutorials.
I want to create a list of lists and use that in a main program but access the complexity of that creation in another file and access that as a function from the main program flow as an import.
Maybe it's a constructor of somekind? A list of Tuples? Better to do this as an array?
It seems that there are lists that are not able to iterate through, and the whole passing classes back and forth.
class TestPattern:
def __init__(self,csvFileName,chartTitle,chartName):
self.csvFileName = csvFileName
self.chartTitle = chartTitle
self.chartName = chartName
def __repr__(self):
return "{0}, {1}, {2}".format(self.csvFileName,self.chartTitle,self.chartName)
class TestPatternEntries:
def __init__(self):
self.items = []
def add(self, TestPattern):
self.items.append(TestPattern)
def __iter__(self):
return self.__items.__iter__()
patterns = TestPatternEntries()
patterns.add(TestPattern('CSVTestPatterns\Lorentz.csv','Lorentz ','Lorentz'))
patterns.add(TestPattern('CSVTestPatterns\CosineDecAmpFreqInc.csv','Cosine Dec Amp Freq Inc ','CosineDecAmpFreqInc'))
patterns.add(TestPattern('CSVTestPatterns\CosineDecAmpFreqInc.csv','Cosine Dec Amp Freq Inc ','CosineDecAmpFreqInc'))
patterns.add(TestPattern('CSVTestPatterns\ExponentialDecayTenWaves.csv','Exponential Decay ','ExponentialDecayTenWaves'))
patterns.add(TestPattern('CSVTestPatterns\ExponentialRiseTenWaves.csv','Exponential Rise ','ExponentialRiseTenWaves'))
patterns.add(TestPattern('CSVTestPatterns\LinearFall.csv','LinearFall ','LinearFall'))
patterns.add(TestPattern('CSVTestPatterns\LinearRise.csv','Linear Rise ','LinearRise'))
patterns.add(TestPattern('CSVTestPatterns\Multitone.csv','Multitone ','Multitone'))
patterns.add(TestPattern('CSVTestPatterns\Pulse10Waves.csv','Pulse ','Pulse'))
patterns.add(TestPattern('CSVTestPatterns\Pulse10WavesInverted.csv','Pulse Inverted ','Pulse10WavesInverted'))
patterns.add(TestPattern('CSVTestPatterns\RandomSamples.csv','Random Noise ','RandomSamples'))
patterns.add(TestPattern('CSVTestPatterns\SinFiveWaves.csv','Five Sin Waves ','FiveSinWaves'))
patterns.add(TestPattern('CSVTestPatterns\SinFourtyWaves.csv','Fourty Sin Waves ','SinFourtyWaves'))
patterns.add(TestPattern('CSVTestPatterns\SweepOneToFive.csv','Sweep 1:5 ','SweepOneToFive'))
patterns.add(TestPattern('CSVTestPatterns\SyncPattern.csv','Sync Pattern ','SyncPattern'))
patterns.add(TestPattern('CSVTestPatterns\TriangleTenWaves.csv','Triangle Waveform','TriangleTenWaves'))
for item in patterns.items:
print(item)
So whats the catch in what is in the code below that I am missing? Is there a good tutorial on handing lists back and forth from local code in other files? Maybe I missed it? Just want to get a full list back that one could iterate through or access by the place in the list.
I have a binary tree with 7 elements which currently looks like this:
1
5 2
7 6 4 3
I am trying to traverse it in postorder and relable the elements as I go, so that it looks like this:
7
3 6
1 2 4 5
using the following function, which is part of my Tree class:
def relable(self, h):
if self.root is not None:
self._relable(self.root, h)
def _relable(self, node, h):
if node is not None:
self._relable(node.l, h-2)
self._relable(node.r, h-1)
node = Node(h)
The rest of my Tree class is more or less the same as the one here.
I populated the tree by adding the numbers 1-7 in a loop.
However, when I call tree.relable(7), and then print the tree, the tree is the same.
I'm guessing this has something to do with how Python passes arguments (I'm a C++ programmer) but I don't know how to fix this.
The entirety of my code can be fount here.
node = Node(h) is just assigning a local variable, it doesn't have any effect on the node parameter that was passed to the function. You need to actually modify the node, i.e. node.v = h.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I am solving the following equation:
wf=1110
wt=647
wp=119000
c=300000000
e0=10983849
e1 =e0-(wp**2/(w*2+wt))
And I want "w" as a variable like from 1 to 1000 or whatever I want in a rising scale.
after I want a plot of e1 vs w
does anyone know how to do that?
One way to do this:
def solve_equation(start, end, equation):
for x in xrange(start, end):
yield equation(x)
def my_equation(x):
wt=647
wp=119000
e0=10983849
e1 =e0-(wp**2/(w*2+wt))
return e1
print solve_equation(0, 100, my_equation)
print solve_equation(500, 1000, my_equation)
This splits the solving of the equation for a range from the equation itself.
You could also look into numpy, if you are going to be doing this on a large scale. Then you would create a numpy array of the values for w and calculate them as a vector. This would boil your code down to something like this:
from numpy import arange
wt=647
wp=119000
e0=10983849
w = arange(0, 100)
e = e0-(wp**2/(w*2+wt))
This would set w to array([0, 1, 2, ..., 98, 99]) and e to:
array([-10903322, -10835873, -10768839, -10702215, -10635998, -10570184,
-10504770, -10439751, -10375125, -10310887, -10247035, -10183565,
-10120472, -10057755, -9995410, -9933433, -9871821, -9810570,
-9749679, -9689143, -9628960, -9569126, -9509638, -9450494,
-9391690, -9333224, -9275092, -9217292, -9159820, -9102675,
-9045853, -8989352, -8933169, -8877301, -8821745, -8766499,
-8711561, -8656927, -8602596, -8548564, -8494830, -8441391,
-8388244, -8335387, -8282817, -8230533, -8178532, -8126812,
-8075370, -8024204, -7973312, -7922693, -7872342, -7822259,
-7772442, -7722888, -7673595, -7624560, -7575784, -7527262,
-7478993, -7430975, -7383206, -7335685, -7288409, -7241376,
-7194584, -7148033, -7101719, -7055641, -7009797, -6964186,
-6918805, -6873654, -6828729, -6784030, -6739555, -6695302,
-6651269, -6607455, -6563858, -6520477, -6477310, -6434355,
-6391611, -6349076, -6306749, -6264628, -6222712, -6180999,
-6139488, -6098177, -6057065, -6016151, -5975432, -5934908,
-5894577, -5854438, -5814490, -5774730])
Using the excellent IPython Notebook with pylab, you can then just do:
plot(w, e)
and have a nice graph showing the result:
Plotting up to 10000 will result in a graph like this:
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I used this code to generate xyz coordinates.
from random import *
uniqcoord = [7.63, 28.05, 66.36] # my file contains 100 such list of points
for i in range(10):
i = i + 1
x,y,z = uniqcoord
x1,y1,z1 = (uniform(x[0]-3.5,x[0]+3.5), uniform(y[1]-3.5,y[1]+3.5), uniform(z[2]-3.5,z[2]+3.5))
print i, '\t', x1,y1,z1
When i run this program its showing error.
when i run this program with hole numbers it work.
how to resolve????
Your x, y, z are float, not list. So your can't have x[0] and such. You will get a no attribute or typeerror for that.
You're incorrectly using x,y,z in the x1,y1,z1 line. See what I've done below;
from random import *
uniqcoord = [7.63, 28.05, 66.36] # my file contains 100 such list of points
for i in range(10):
i=i+1
x,y,z = uniqcoord
x1,y1,z1 = (uniform(uniqcoord[0]-3.5,uniqcoord[0]+3.5), uniform(uniqcoord[1]-3.5,uniqcoord[1]+3.5), uniform(uniqcoord[2]-3.5,uniqcoord[2]+3.5))
print i, '\t', x1,y1,z1
x[0] does not exist, but uniqcoord[0] = x because uniqcoord = [x,y,z], and so on.
Result:
1 5.86941266341 29.4004245806 67.1323961576
2 6.38143060206 29.7045813689 69.4867869245
3 5.55280335095 29.9472835241 63.7388152633
4 10.5607637875 26.6269381673 69.5256503601
5 7.29826364813 28.5740308696 65.2122276564
6 8.24134391937 30.880058802 69.8445734597
7 10.246919304 27.9240839326 64.9480054046
8 8.26957559527 28.5700768795 63.996117793
9 5.88677020227 30.0621250245 63.7431176092
10 8.98100830174 27.3378753286 63.1329446911
I think this is what you are looking for.