I write this code for uri online judge(problem no.1036)...It is an Bhaskara's formula...
import cmath
A,B,C=input().split()
A = float(A)
B = float(B)
C = float(C)
D = (B*B)-(4*A*C)
if((D== -D)|(A==0)):
print("Impossivel calcular")
else:
T = cmath.sqrt(D)
x1 = (-B+T)/(2*A)
x2 = (-B-T)/(2*A)
print("R1 = %.5f" %x1)
print("R2 = %.5f" %x2)
but when i submit this program...that runtime error occured...
Traceback (most recent call last): File "Main.py", line 14, in
print("R1 = %.5f" %x1)
TypeError: can't convert complex to float
Command exited with non-zero status (1)
please help me to solve this problem.
The problem with using sqrt imported from cmath is that it outputs a complex number, which cannot be converted to float. If you are calculating a sqrt from positive number, use math library (see below).
>>> from cmath import sqrt
>>> sqrt(2)
(1.4142135623730951+0j)
>>> from math import sqrt
>>> sqrt(2)
1.4142135623730951
the problem is just that your format string is for floats and not for complex numbers. something like this will work:
print('{:#.3} '.format(5.1234 + 4.123455j))
# (5.12+4.12j)
or - more explicit:
print('{0.real:.3f} + {0.imag:.3f}i'.format(5.123456789 + 4.1234556547643j))
# 5.123 + 4.123i
you may want to have a look at the format specification mini language.
# as format specifier will not work with the old-style % formatting...
then there are more issues with your code:
if((D== -D)|(A==0)):
why not if D==0:? and for that it might be better to use cmath.isclose.
then: | is a bit-wise operator the way you use it; you may want to replace it with or.
your if statement could look like this:
if D == 0 or A == 0:
# or maybe
# if D.isclose(0) or A.isclose():
Related
I'm reading the High-Performance Python book from O'Reilly collection, in the page number 11 I found this code that works for python 2, the point here is to make one instruction that performs(by vectorizing) several at the same time
import math
def check_prime(number):
sqrt_number = math.sqrt(number)
number_float = float(number)
numbers = range(2, int(sqrt_number)+1)
for i in xrange(0, len(numbers), 5):
# the following line is not valid Python code
result = (number_float / numbers[i:(i+5)]).is_integer()
if any(result):
return False
return True
but I get this error
TypeError: unsupported operand type(s) for /: 'float' and 'list'
I've tried to change it to work on python 3 here is my try:
import math
def check_prime(number):
sqrt_number = math.sqrt(number)
number_float = float(number)
numbers = list(range(2, int(sqrt_number)+1))
for i in range(0, len(numbers), 5):
# the following line is not valid Python code
result = (number_float / numbers[i:(i+5)]).is_integer()
if any(result):
return False
return True
I changed the xrange for range and the range(2, int(sqrt_number)+1) for list(range(2, int(sqrt_number)+1)) but i did not have succeed in this. I suppose there is a special operator for sets or something like that but have no idea. if any of you people can help me I'll be so grateful whit you
I looked at the book and that line is not supposed to actually work as is; you cannot divide by a list in Python. The author uses that code as an example of what vectorization would look like. The # the following line is not valid Python code comment is in the original to indicate that.
The closest in term of functionality and semantics would probably be this code:
import math
def check_prime(number):
sqrt_number = math.sqrt(number)
number_float = float(number)
numbers = list(range(2, int(sqrt_number)+1))
for i in range(0, len(numbers), 5):
# the following line is now valid Python code, but not vectorized
result = [(number_float / n).is_integer for n in numbers[i:(i+5)]]
if any(result):
return False
return True
Note that the processing for result in this version is not done in parallel, so it's probably not what the author wanted to demonstrate. As far as I know, vectorization isn't natively available in Python, you would have to use numpy to do it. This article should be useful if you want to try it.
Try this:
import math
def check_prime(number):
sqrt_number = math.sqrt(number)
number_float = float(number)
numbers = list(range(2, int(sqrt_number)+1))
for i in range(0, len(numbers), 5):
result = [number_float % num == 0 for num in numbers[i:(i+5)]]
if any(result):
return False
return True
The following code is to convert decimal to binary.
My question is: When num becomes less than or equal to 1, python jumps to the last line i.e print(num % 2, end = '') and consequently prints out 1. But after that, why does it move to line 'decimalToBinary(num // 2)'? That line is supposed to execute only when num > 1
def decimalToBinary(num):
if num > 1:
decimalToBinary(num // 2)
print(num % 2, end='')
decimalToBinary(17)
It's because the last function in the stack finished,so it jumps to the call point of the function in the upper stack.If you add a=1 behind the print(num%2,end='') statement, you will see that a=1 gets called before the control returns to the upper function.
import numpy as np
import pandas as pd
# Read the input
s = int(input())
# Write your code below
print(format(s, 'b'))
d =dict(input('Enter a dictionary'))
sum = 0
for i in d.values():
sum +=i
print(sum)
outputs: Enter a dictionary{'a': 100, 'b':200, 'c':300}
this is the problem arises:
Traceback (most recent call last):
File "G:/DurgaSoftPython/smath.py", line 2, in <module>
d =dict(input('Enter a dictionary'))
ValueError: dictionary update sequence element #0 has length 1; 2 is required
You can't create a dict from a string using the dict constructor, but you can use ast.literal_eval:
from ast import literal_eval
d = literal_eval(input('Enter a dictionary'))
s = 0 # don't name your variable `sum` (which is a built-in Python function
# you could've used to solve this problem)
for i in d.values():
s +=i
print(s)
Output:
Enter a dictionary{'a': 100, 'b':200, 'c':300}
600
Using sum:
d = literal_eval(input('Enter a dictionary'))
s = sum(d.values())
print(s)
import json
inp = input('Enter a dictionary')
inp = dict(json.loads(inp))
sum = sum(inp.values())
print(sum)
input Enter a dictionary{"a": 100, "b":200, "c":300}
output 600
Actually the return of input function is a string. So, in order to have a valid python dict you need to evaluate the input string and convert it into dict.
One way to do this can be done using literal_eval from ast package.
Here is an example:
from ast import literal_eval as le
d = le(input('Enter a dictionary: '))
_sum = 0
for i in d.values():
_sum +=i
print(_sum)
Demo:
Enter a dictionary: {'a': 100, 'b':200, 'c':300}
600
PS: Another way can be done using eval but it's not recommended.
I would like to to use theano.scan within pymc3. I run into problems when I add more than two variables as sequences. Here is a simple example:
import numpy as np
import pymc3 as pm
import theano
import theano.tensor as T
a = np.ones(5)
b = np.ones(5)
basic_model = pm.Model()
with basic_model:
a_plus_b, _ = theano.scan(fn=lambda a, b: a + b, sequences=[a, b])
results in the following error:
Traceback (most recent call last):
File "StackOverflowExample.py", line 23, in <module>
sequences=[a, b])
File "\Anaconda3\lib\site-packages\theano\scan_module\scan.py", line 586, in scan
scan_seqs = [seq[:actual_n_steps] for seq in scan_seqs]
File "\Anaconda3\lib\site-packages\theano\scan_module\scan.py", line 586, in <listcomp>
scan_seqs = [seq[:actual_n_steps] for seq in scan_seqs]
TypeError: slice indices must be integers or None or have an __index__ method
However, when I run the same theano.scan outside a pymc model block, everything works fine:
a = T.vector('a')
b = T.vector('b')
a_plus_b, update = theano.scan(fn=lambda a, b: a + b, sequences=[a, b])
a_plus_b_function = theano.function(inputs=[a, b], outputs=a_plus_b, updates=update)
a = np.ones(5)
b = np.ones(5)
print(a_plus_b_function(a, b))
prints [2. 2. 2. 2. 2.], like it should.
In addition, the problem seems to be specific to adding more than one sequences. Everything works just fine when there is one variable in sequences and one in non-sequences. The following code works:
a = np.ones(5)
c = 2
basic_model = pm.Model()
with basic_model:
a_plus_c, _ = theano.scan(fn=lambda a, c: a + c, sequences=[a], non_sequences=[c])
a_plus_c_print = T.printing.Print('a_plus_c')(a_plus_c)
prints a_plus_c __str__ = [ 3. 3. 3. 3. 3.], as expected.
Note: I can't just use a + b instead of theano.scan because my actual function is more complex. I actually want to have something like this:
rewards = np.array([1, 1, 1, 1]) # reward (1) or no reward (0)
choices = np.array([1, 0, 1, 0]) # action left (1) or right (0)
Q_old = 0 # initial Q-value
alpha = 0.1 # learning rate
def update_Q(reward, choice, Q_old, alpha):
return Q_old + choice * alpha * (reward - Q_old)
Q_left, _ = theano.scan(fn=update_Q,
sequences=[rewards, choices],
outputs_info=[Q_old],
non_sequences=[alpha])
Turns out it was a simple mistake! Everything is working as soon as I define a and b as tensor variables. Adding those two lines did the job:
a = T.as_tensor_variable(np.ones(5))
b = T.as_tensor_variable(np.ones(5))
How would one allow the user to input a statement such as "math.sin(x)**2" and calculate the answer within python code.
In telling me the answer please explain why both exec() compile() are not producing the desired result.
import math
def getValue(function, x):
function = "val = " + function
#compile(function, '', 'exec')
exec(function)
print(val)
function = input("Enter a function f(x):\n")
getValue(function, 10)
Much Appreciated!
To answer your question, use eval:
>>> eval('math.sin(1)**2')
0.7080734182735712
exec is working, but you are not retrieving the result. Notice:
>>> val
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'val' is not defined
>>> exec('val=math.sin(1)**2')
>>> val
0.7080734182735712
So, using eval instead of exec works like so:
def getValue(function, x):
function = "{}({})".format(function, x)
print(function)
val=eval(function)
print(val)
That said -- it is considered an extreme security risk to execute arbitrary user code.
If you are building a calculator, a safer approach you might consider using SymPy or building your own parser using something like PyParsing (which is used in SymPy)
An example PyParsing calculator:
import sys
import operator
from pyparsing import nums, oneOf, Word, Literal, Suppress
from pyparsing import ParseException, Forward, Group
op_map = { '*' : operator.mul,\
'+' : operator.add,\
'/' : operator.div,\
'-' : operator.sub}
exp = Forward()
number = Word(nums).setParseAction(lambda s, l, t: int(t[0]))
lparen = Literal('(').suppress()
rparen = Literal(')').suppress()
op = oneOf('+ - * /').setResultsName('op').setParseAction(lambda s, l, t: op_map[t[0]])
exp << Group(lparen + op + (number | exp) + (number | exp) + rparen)
def processArg(arg):
if isinstance(arg, int):
return arg
else:
return processList(arg)
def processList(lst):
args = [processArg(x) for x in lst[1:]]
return lst.op(args[0], args[1])
def handleLine(line):
result = exp.parseString(line)
return processList(result[0])
while True:
try:
print handleLine(raw_input('> '))
except ParseException, e:
print >>sys.stderr,\
"Syntax error at position %d: %s" % (e.col, e.line)
except ZeroDivisionError:
print >>sys.stderr,\
"Division by zero error"
Which can easily be extended to include other functions.