Solve for x in python without Scipy, [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 5 years ago.
Improve this question
I'm trying to solve for an equation in Python without using any scipy features. c = 5 and the equation is c = 10 - 20(exp(-0.15*x) - exp(-0.5*x)).
How do I solve for x with a tolerance of .0001.
Pardon my intro level programming here guys. This is the first class I've ever taken.
from math import exp
c = 5
def x(c):
c = 10 - 20(exp*(-0.15*x) - exp*(-0.5*x))
return x(5)

You might want to have a look at SymPy. It's a dedicated algebraic symbol manipulation library for Python with a BSD license. If you're looking for a "stock"/standard library solution, then as others have mentioned you're going to have to do some homework and potentially implement your own solver.
As a closing thought, unless this is a class assignment or your boss has a pathological hatred of third-party open source libraries, there's really no good reason not to use one of the SciPy packages. IIRC, they're largely implemented as highly-optimized C binaries wrapped in Python modules, so you get blazingly fast performance and the ease-of-use of a Python API.

It seems like you want to implement this "from scratch." A few hints:
We can simplify this a bit with algebra. What you really want is to find x such that exp(-0.15*x) + exp(-0.5*x) - 0.2 = 0
For a given value of x, you know how much error you have. For example, if x = 1, then c(1) = 1.267, so your error is 1.267. You need to keep "guessing" values until your error is less than 0.0001.
Math tells us that this function is monotonically decreasing; so, there is no point checking answers to the left of 1.
Hopefully you can solve it from these hints. But this is supposed to be an answer, so here is the code:
def theFunction(x): return exp(-0.15*x) + exp(-0.5*x) - 0.2
error = 1.267
x = 1
littleBit = 1
while (abs(error) > 0.0001):
if error > 0: x += littleBit
else: x -= littleBit
oldError = error
error = theFunction(x)
if (error*oldError < 0): littleBit *= 0.5
print x
Note, the last three lines in the loop are a little bit 'clever' -- an easier solution would be to just set littleBit = 0.00001 and keep it constant throughout the program (this will be much slower, but will still do the job). As an exercise, I recommend trying to implement it this simpler way, then time how long it takes both ways, and see if you can figure out where the time savings comes in.

Related

Python function with excessive number of variables [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 20 days ago.
Improve this question
Very general question: I am attempting to write a fairly complext Python script.
#Part A: 100 lines of python code
#Part B: 500 lines of python code
#Part C: 100 lines of python code
Assume that I want "Part B" taken out of the picture for readability and debugging purposes, because I know that it is running well and I want to focus on the other parts of the code.
I would define a function like this:
def part_b():
#500 lines of python code
#Part A: 100 lines of python code
part_b()
#Part C: 100 lines of python code
The problem with this approach in my case is that there are more than twenty variables that need to be sent to "Part C". The following looks like bad practice.
def part_b():
global var1
global var2
global var3...
I am aware that I could return an object with more than twenty attibutes, but that would increase complexity and decrease readability.
In other words, is there a pythonic way of saying "execute this block of code, but move it away from the code that I am currently focusing on". This is for a Selenium automation project.
Sounds like what you're looking for is modules. Move part B into a separate file, and then import it.
import part_B
# part A here
part_B.run()
# part C here
# to access things that part B does:
do_part_C_stuff(part_B.something)

Python Function Won't Run At ALL? [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 6 years ago.
Improve this question
I am fairly new to the programming world and am wondering why the following code will not only refuse to run, but my python software won't even give me any error messages whatsoever.I'm using Pythonista, an IOS app for python. I can't get the app to run this code (and it won't give me any error messages) and was wondering if it's my code itself, or is it just the application. Any knowledge on this issue would be greatly appreciated.
def starBits():
badMatchups = [Zelda, Cloud, Ryu]
worstMatchups = [Jigglypuff, Villager, Bayonetta]
print(badMatchups)[1:2]
print(worstMatchups)[1:1]
def main():
starBits()
main()
I'm not sure what you expect from this, but it's really funky syntax.
print(badMatchups)[1:2]
print(worstMatchups)[1:1]
If those slices are subscripts for the lists, you need them inside the call to print:
print(badMatchups[1:2])
print(worstMatchups[1:1])
By the way, do you realize that [1:1] is an empty slice? The second number is the first position not included. You may need
print(badMatchups[1:3]) # two elements
print(worstMatchups[1:2]) # one element
Also, are those elements external variables, or are they supposed to be literal names? If the latter, then you have to put them in quotation marks.
badMatchups = ["Zelda", "Cloud", "Ryu"]
worstMatchups = ["Jigglypuff", "Villager", "Bayonetta"]
With this change, the code runs; I hope it's what you want.
Can't get it to run? Reality check time ...
Full code, changes made:
def starBits():
badMatchups = ["Zelda", "Cloud", "Ryu"]
worstMatchups = ["Jigglypuff", "Villager", "Bayonetta"]
print(badMatchups[1:3])
print(worstMatchups[1:2])
def main():
starBits()
main()
Output:
['Cloud', 'Ryu']
['Villager']

Optimization in Python for simple linear function

If the price charged for a crayon is p cents, then x thousand crayons
will be sold in a certain school store, where p(x)= 122-x/34 .
Using Python, calculate how many crayons must be sold to maximize
revenue.
I can solve this by hand much easily, the only problem is how can I do it using plain Python? I am using IDLE (Python GUI). I am new to Python and haven't downloaded any external libraries. Any help will be greatly appreciated.
What I've done up to this point is
import math
def f(x):
return (122-(x/34.0))
def g(x):
return x*f(x)
def h(x):
return (122-(2*x/34.0))
Use SymPy. It's simple, beautiful and powerful.
You can write down your equations with simpify(), like that:
p = simpify('122 - x/34')
And define symbols for symbolic evaluation with Symbol() and symbols().
With that you can do things like simply use solve() function for any given equation. i.e. x + 4 = 2x:
res = solve('x + 4 - 2*x')
It's pretty much the tool I use for any math work with python.
So, you should go and download an external library for this, as it's not functionality that python makes easy to implement natively. Also, if you're serious about doing mathematical computation in python I would suggest switching operating systems to something like OSX or linux, simply because compiling old FORTRAN libraries (required for much performant mathematical computing) is a huge pain on Windows.
You have to make use of the scipy library here, which has an optimize module. Specifically I would suggest using the optimize.minimize_scalar function. Docs can be found here.
>>> from scipy.optimize import minimize_scalar
>>> def g(x):
... return -(x*(122 - (x/34))) # inverse because you're minimizing.
>>> minimize_scalar(g, bounds=(1, 10000), method='bounded')
status: 0
nfev: 6
success: True
fun: -126514.0
x: 2074.0
message: 'Solution found.'

Writing word backwards

I know there are possibilities :
sampleword[::-1]
or
reverse(string)
but I wanted to write it by myself. I don't get why my code doesn't work. Could you help me?
h=input('word\n\n');
rev(h)
def rev(h):
counter=len(h);
reverse="";
while counter>0:
reverse+=h[counter];
counter=counter-1;
return reverse
#print (reverse); ?
input();
There are a couple issues with your code, I pointed them out in the comments of this adjusted script:
def rev(h):
counter=len(h) - 1 # indexes of h go from 0 to len(h) - 1
reverse=""
while counter>=0: # changed to >=0
reverse+=h[counter]
counter -= 1
return reverse
h=input('word\n\n');
revers = rev(h) # put rev(h) after the definition of rev!
print(revers) # actually print the result
# deleted your last line
In addition, you don't need to terminate lines with ; in python and you can write counter=counter-1 as counter -= 1.
You have some issues/problems in your code.
You call rev() before it is defined
Indexing starts at 0, so you need >= 0 instead of > 0
You want counter to equal len(h) - 1 because again, indexing starts at 0
You do not need semicolons at the end of your lines
Here is a much simpler and faster way using recursion:
def reverse(text):
if len(text) <= 1:
return text
return reverse(text[1:]) + text[0]
As you use Python more you will come across the concept of "Pythonic" code ... code that uses Python features well and shows good programming style.
So, you have a good answer above showing how your code can be corrected to work correctly in Python. But the issue I want to point out is that's C style programming. Someone said you can write C in any language (especially true in C++ and C#), but if you do you are probably not using the features of the language well. In Python, writing this style of function and ignoring the available built-in, implemented in C, lightning fast methods is not Pythonic.
I guarantee you that reverse(string) or string[::-1] are both faster than your rev( ) python code. Python has a ton of built in functionality and extensive library of files you can import for extra already debugged functionality. See if you can find a good way to time the execution of reverse( string ) and your rev( ) function. There is a good way, in Python.

Explain this algorithm

while solving the Palindrome problem on codechef I wrote an algorithm, which gave a TLE on test cases more than 10^6. So taking lead from people who had already solved it I wrote the following code in python.
################################################
### http://www.codechef.com/problems/TAPALIN ###
################################################
def pow(b,e,m):
r=1
while e>0:
if e%2==1:
r=(r*b)%m
e=e>>1
b=(b*b)%m
return r
def cal(n,m):
from math import ceil
c=280000002
a=pow(26, int(ceil(n/2)), m)
if(n%2==0):
return ((52*(a-1+m)%m)*c)%m
else:
return ((52*(((a-1+m)*c)%m))%m+(a*26)%m)%m
c=int(raw_input())
m=1000000007
for z in range(c):
print cal(int(raw_input()),m)
the pow function is the Right-to-left binary method. what i do not understand is:
where did the value 280000002 came from?
why do we need to perform so many mod operations?
is this some famous algorithm of which I am unaware about?
Almost every submitted code on codechef makes use of this very algorithm, but I am unable to decipher it's working. any link to the theory would be appreciated.
I am still unable to figure out what is happening in this exactly. can anyone write a pseudocode for this formula/algo? also help me understand time complexity for this code. another thing that amazes me is, if I write this code as:
################################################
### http://www.codechef.com/problems/TAPALIN ###
################################################
def modular_pow(base, exponent):
result=1
while exponent > 0:
if (exponent%2==1):
result=(result * base)%1000000007
exponent=exponent >> 1
base=(base*base)%1000000007
return result
c=int(raw_input())
from math import ceil
for z in range(c):
n=int(raw_input())
ans=modular_pow(26, int(ceil(n/2)))
if(n%2==0):
print ((52*((ans)-1+ 1000000007)%1000000007)*280000002)%1000000007
else:
print ((52*((((ans)-1+ 1000000007)*280000002)%1000000007))%1000000007+(ans*26)%1000000007)%1000000007
this improves the performance from 0.6secs to 0.4 secs. though the best code runs in 0.0 seconds. I am so much confused.
The number 280000002 is Modular Multiplicative Inverse of 25 mod 10^9 + 7, because we know 10^9 + 7 is prime so it's simply calculated using pow(25, 10^9 + 7 - 2, 10^9 + 7). Read more here: http://en.wikipedia.org/wiki/Modular_multiplicative_inverse
And we need to perform so many mod operations because we don't want to work with big numbers ;-)
Never seen this algorithm before but walking through it with some of the easier test cases starts to reveal what is happening (BTW, my guess is everyone is using it because it was the top answer on code chef and everyone is just copying it, I don't think you have to assume it's the only way to do it).
To answer your questions:
where did the value 280000002 came from?
280000002 is the modulo multiplicative inverse of 25 mod 1000000007. This means that the following congruence is true
280000002 * 25 === 1 (mod 1000000007)
why do we need to perform so many mod operations?
Probably just to not be dealing with huge numbers along the way. Although there is some extra math in there that seems to me to just be making the numbers bigger than they need to be, see my note at the end about that. Theoretically you could just do one big mod at the end and get the same result but it's possible our tiny CPUs don't like that.
is this some famous algorithm of which I am unaware about?
Again, I doubt it. This isn't really an algorithm as it is a mashed up math formula.
Speaking of math, there is some stuff in there that is questionable to me. It's been a while since I messed with this stuff but I'm pretty sure that (52*(a-1+m)%m) will always be equivalent to (52*(a-1)%m since 52m mod m = 0. Not sure why you would be adding that huge number there, you may see some performance gain if you get rid of that.

Categories