I have been having a problem with SymPy at the time of making a limit which would have to answer "does not exist" is returning the infinite value. The code section would be this:
x = Symbol ('x')
a = Limit ((5-x) / (x-2), x, 2, "+"). doit ()
print (a)
oo
b = Limit ((5-x) / (x-2), x, 2, "-"). doit ()
print (b)
-oo
c = Limit ((5-x) / (x-2), x, 2) .doit ()
print (c)
oo
Here is the problem as investigated and check should leave a message as the limit does not exist or return any value equal to 0.
By default, Limit ((5-x) / (x-2), x, 2) means one-sided limit from the right, so c will always be the same as a in your example.
In the current development version on GitHub, one can pass "+-" as the direction, which will compute both limits and raise ValueError if they are not the same:
>>> limit((5-x) / (x-2), x, 2, "+-")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/ubuntu/sympy/sympy/series/limits.py", line 66, in limit
% (llim, rlim))
ValueError: The limit does not exist since left hand limit = -oo and right hand limit = oo
But you probably just want a conditional like
if a != b:
print("One-sided limits are different")
elif a.is_infinite:
print("Infinite limit")
# and so on
Related
def Goods(t):
max_n = t.index(max(t))
min_n = t.index(min(t))
return max_n,min_n
t = [-125,-164,1237,809,5634,1278,8431]
Goods(t, len(t))
Hello.
I'm trying to find two values in a list and get an index tuple as the result.
The two values are the maximum and the minimum.
(6, 1)
>>> print(Goods([-125,-164,1237,809,5634,1278,8431]))
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
print(Goods([-125,-164,1237,809,5634,1278,8431]))
TypeError: Goods() missing 1 required positional argument: 'n'
I found the value. But what I want is a way to get results when I type "print(Goods([-125,-164,1237,809,5634,1278,8431]))" like this.
I would really appreciate it if you could teach me how to modify the code for the answer I want.
You didn't provide all of the arguments to your function. Should be:
def Goods(t, n):
max_n = t.index(max(t))
min_n = t.index(min(t))
print((max_n,min_n))
buff_list = [-125,-164,1237,809,5634,1278,8431];
Goods(buff_list, len(buff_list))
If you would like to print the values, you have to ask the function to return something. I.e., modify your function to:
def Goods(t, n):
max_n = t.index(max(t))
min_n = t.index(min(t))
return (min_n, max_n)
print(Goods(buff_list, len(buff_list)))
I am testing a function in Python. This is the function I wrote.
def hypotenuse(a, b):
math.sqrt(a**2 + b**2)
I used this test case.
def test_hypotenuse_1(self):
self.assertEqual(funcs.hypotenuse, 3, 4)
This assertion error came up.
======================================================================
FAIL: test_hypotenuse_1 (__main__.TestCases)
----------------------------------------------------------------------
Traceback (most recent call last):
File "funcs_tests.py", line 27, in test_hypotenuse_1
self.assertEqual(funcs.hypotenuse, 3, 4)
AssertionError: <function hypotenuse at 0x7f397f2d79d8> != 3 : 4
What did I do wrong? Sorry if this is a basic question I am a first-time coder.
You need to call the function, and then specify what the result of that call is supposed to be equal to
def test_hypotenuse_1(self):
self.assertEqual(funcs.hypotenuse(3, 4), 5)
This asserts that the hypotenuse of a triangle with sides 3 and 4 is equal to 5.
Your test will still fail because hypotenuse() doesn't return the result. It needs to be:
def hypotenuse(a, b):
return math.sqrt(a**2 + b**2)
Note that you should generally not use equality testing for a mathematical function like this. It uses floating point arithmetic, which can have roundoff error. You can use the assertAlmostEqual() function for this.
I have looked around on SO and surprisingly not found an answer to this question. I assume this is because normally inner/nested functions are used for something in particular (eg. maintaining an environment variable, factories) as opposed to something trivial like I'm trying to use them for. In any case, I can't seem to find any information on how to properly call an inner function from an outer function without having to declare inner() above outer() in the file. The problem is from this problem on HackerRank (https://www.hackerrank.com/challenges/circular-array-rotation/problem).
def circularArrayRotation(a, k, queries):
def rotateArrayRightCircular(arr: list, iterations: int) -> list:
"""
Perform a 'right circular rotation' on an array for number of iterations.
Note: function actually moves last 'iterations' elements of array to front of array.
>>>rotateArrayRightCircular([0,1,2], 1)
[2,0,1]
>>>rotateArrayRightCircular([0,1,2,3,4,5], 3)
[3,4,5,0,1,2]
>>>rotateArrayRightCircular([0,1,2,3,4,5], 6)
[0,1,2,3,4,5]
"""
return arr[-1 * iterations:] + arr[0:-1 * iterations]
k = k % len(a)
a = rotateArrayRightCircular(a, k)
res = []
for n in queries:
res.append(a[n])
return res
The code above does what I want it to, but it's somehow inelegant to me that I have to put the inner function call after the inner function definition. Various errors with different attempts:
# trying 'self.inner()'
Traceback (most recent call last):
File "solution.py", line 52, in <module>
result = circularArrayRotation(a, k, queries)
File "solution.py", line 13, in circularArrayRotation
a = self.rotateArrayRightCircular(a, k)
NameError: name 'self' is not defined
# Removing 'self' and leaving the definition of inner() after the call to inner()
Traceback (most recent call last):
File "solution.py", line 52, in <module>
result = circularArrayRotation(a, k, queries)
File "solution.py", line 13, in circularArrayRotation
a = rotateArrayRightCircular(a, k)
UnboundLocalError: local variable 'rotateArrayRightCircular' referenced before assignment
Any idea how I could include def inner() after the call to inner() without throwing an error?
As a function is executed from top to bottom, and a function is put into existence as the function is processed, what you want is just not possible.
You could put the function before the outer one, making it outer itself, possibly adding some parameters (not necessary here). (BTW, it looks so generic that other parts of the code might want to use it as well, so why not outer?)
But otherwise, you are stuck. It is essetially the same situation as in
def f():
print(a) # a doesn't exist yet, so this is an error
a = 4
Well, you could do it this way:
def circularArrayRotation(a, k, queries):
def inner_code():
k = k % len(a)
a = rotateArrayRightCircular(a, k)
# BTW, instead of the following, you could just do
# return [a[n] for n in queries]
res = []
for n in queries:
res.append(a[n])
return res
def rotateArrayRightCircular(arr: list, iterations: int) -> list:
"""
Perform a 'right circular rotation' on an array for number of iterations.
Note: function actually moves last 'iterations' elements of array to front of array.
>>>rotateArrayRightCircular([0,1,2], 1)
[2,0,1]
>>>rotateArrayRightCircular([0,1,2,3,4,5], 3)
[3,4,5,0,1,2]
>>>rotateArrayRightCircular([0,1,2,3,4,5], 6)
[0,1,2,3,4,5]
"""
return arr[-1 * iterations:] + arr[0:-1 * iterations]
return inner_code()
but I don't see that you gain anything from it.
This is not possible in Python, but is possible in other languages like Javascript and PHP. It is called function hoisting.
I have written a general bisection method to find roots of the provided function, I want to call it to solve a quadratic function. here's my generalroot.py
# generalroot.py
# determines the root of any general function
def root_bisection(f, a, b, tolerance=1.0e-6):
dx = abs(b-a)
while dx > tolerance:
x = (a+b)/2.0
if (f(a)*f(x)) < 0:
b = x
else:
a = x
dx = abs(b-a)
return
Now I am calling it to solve a quadratic function
from math import *
from generalroot import *
def function(y):
y = y**2 + 5*x - 9
return y
func = root_bisection(y, 0, 1)
print 'Found f(x) =0 at x = %0.8f +/- %0.8f' % ( func , tolerance)
and am getting the following error:
raceback (most recent call last):
File "quadfrombisectionroot.py", line 8, in <module>
func = root_bisection ( y , 0, 1)
NameError: name 'y' is not defined
Please help me fix the error, thanks
root_bisection is expecting a function as its first argument. You should probably call it like that:
func = root_bisection(function, 0, 1)
Also you are having a typo in the definition of function. Replace x with y.
As a general piece of advice: Never do from libraryXYZ import * but only import the functions you really need. This makes the code much more readable.
What is is the significance of doctest in Sphinx? Can someone help me understand its use with a simple example.
Sphinx's doctest is for testing the documentation itself. In other words, it allows for the automatic verification of the documentation's sample code. While it might also verify whether the Python code works as expected, Sphinx is unnecessary for that purpose alone (you could more easily use the standard library's doctest module).
So, a real-world scenario (one I find myself in on a regular basis) goes something like this: a new feature is nearing completion, so I write some documentation to introduce the new feature. The new docs contain one or more code samples. Before publishing the documentation, I run make doctest in my Sphinx documentation directory to verify that the code samples I've written for the audience will actually work.
I haven't used it myself but it is my understanding that it extends the functionality of doctest. For example it adds testsetup and testcleanup directives which you can put your set-up and tear-down logic in. Making it possible for Sphinx to exclude that in the documentation.
Here is a simple example (from the doctest module):
"""
This is the "example" module.
The example module supplies one function, factorial(). For example,
>>> factorial(5)
120
"""
def factorial(n):
"""Return the factorial of n, an exact integer >= 0.
If the result is small enough to fit in an int, return an int.
Else return a long.
>>> [factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> [factorial(long(n)) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> factorial(30)
265252859812191058636308480000000L
>>> factorial(30L)
265252859812191058636308480000000L
>>> factorial(-1)
Traceback (most recent call last):
...
ValueError: n must be >= 0
Factorials of floats are OK, but the float must be an exact integer:
>>> factorial(30.1)
Traceback (most recent call last):
...
ValueError: n must be exact integer
>>> factorial(30.0)
265252859812191058636308480000000L
It must also not be ridiculously large:
>>> factorial(1e100)
Traceback (most recent call last):
...
OverflowError: n too large
"""
import math
if not n >= 0:
raise ValueError("n must be >= 0")
if math.floor(n) != n:
raise ValueError("n must be exact integer")
if n+1 == n: # catch a value like 1e300
raise OverflowError("n too large")
result = 1
factor = 2
while factor <= n:
result *= factor
factor += 1
return result
if __name__ == "__main__":
import doctest
doctest.testmod()