how to variate a parameter in an equation python [closed] - python

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:

Related

I want to create a dynamic variable and use it [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 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']

Binary numbers to list [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 1 year ago.
Improve this question
I have written the following program in Python:
s = []
for e in random_key:
s = str(e)
print(s)
where the list random_key is
random_key = ['0011111011100101', '0000010111111011', '0011100110110100',
'1000010101010010', '0011001011001111', '1101101101110011',
'1100001111111011', '0000100000110100', '0101111010100101',
'1001100101100001']
The output of the program is
1111011010110011
1011000110011100
0011011001100010
0000011100100001
1111111010000100
0110110101100011
1011100011000101
1011101011100010
1101101101001010
1000011110110000
which is not correct. How can I fix the code?
If I am able to read your thoughts (not sure about that ..). Would you like them to 10 based numbers?
random_key = ['0011111011100101', '0000010111111011', '0011100110110100',
'1000010101010010', '0011001011001111', '1101101101110011',
'1100001111111011', '0000100000110100', '0101111010100101',
'1001100101100001']
numbers = [int(x, 2) for x in random_key]
print(numbers)
output
[16101, 1531, 14772, 34130, 13007, 56179, 50171, 2100, 24229, 39265]
Do you mean this?
s = list()
for e in random_key:
s.append(str(e))
print(s)
Returns:
['0011111011100101', '0000010111111011', '0011100110110100', '1000010101010010', '0011001011001111', '1101101101110011', '1100001111111011', '0000100000110100', '0101111010100101', '1001100101100001']

Best Way to Design this Locus Class [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 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)

Python using multiple conditions inside a loop [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
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.
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.
Improve this question
I am trying to use multiple conditions inside an if-else expression which is as:
from datetime import date, timedelta as td, datetime
import holidays
st_dt = '1/1/2017'
en_dt = '1/5/2017'
st_year = datetime.strptime(st_dt, "%m/%d/%Y").year
en_year = datetime.strptime(en_dt, "%m/%d/%Y").year
st_mnth = datetime.strptime(st_dt, "%m/%d/%Y").month
en_mnth = datetime.strptime(en_dt, "%m/%d/%Y").month
st_date = datetime.strptime(st_dt, "%m/%d/%Y").day
en_date = datetime.strptime(en_dt, "%m/%d/%Y").day
d1 = datetime(st_year, st_mnth, st_date, 0, 0, 0)
d2 = datetime(en_year, en_mnth, en_date, 0, 0, 0)
AllHours = []
i = 0
while(d1<=d2):
AllHours.append(d1)
d1 = d1 + td(hours=1)
us_holidays = holidays.UnitedStates()
HolidayWorkingDay = ['H' if x in us_holidays else 'W' for x in AllHours]
HE = [x.hour for x in AllHours]
DayDefn = ['Type1' if (x == 'H' and y>=7 and y<=23) else 'Type2' for x in HolidayWorkingDay and for y in HE]
So, in the above I am trying to make sure that if certain location in the lists HolidayWorkingDay and HE meet certain criteria I give them name 'Type1' else they are 'Type2'
But it fails on the last line because of bad syntax. I am not sure what the right way to write multiple expression is
If you want nested loops you should write last list comprehension like this (without and):
DayDefn = ['Type1' if (x == 'H' and y>=7 and y<=23) else 'Type2'
for x in HolidayWorkingDay for y in HE]

how to assign random float number in python [closed]

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.

Categories