def test_square_root(): diff = mysqrt - math print "{:<12}\t {:<12}\t{}".format(mysqrt, math, diff) for i in range(1,10): m = mysqrt(i,x) ma = math(i) ab = abs(n-1) print "{:<12}\t{:<12}\t{}".format(m, ma, ab)
def jump(X, Y, D): if X == Y: return 0 if D < 1: return 0 else: answer = math((Y - X) / D) print(answer)
def find_values(file_name, alpha=0.05): x = read_file_2(file_name) excel_rows = [['Method', 'sample-size', 'PT. Est', 'lower CI', 'upper CI']] for i in x: method = i size = len(x[i]) t_dist = st.t.ppf(1 - (alpha / 2), size - 1) pt_est = statistics.mean(x[i]) std = statistics.stdev(x[i]) lower_ci = max(pt_est - t_dist * (std / math(size)), 0) upper_ci = pt_est + t_dist * (std / math(size)) excel_rows.append(method, size, pt_est, lower_ci, upper_ci) df = pd.DataFrame.from_records(excel_rows[1:], columns=excel_rows[0]) return df
def reflect_about(p1, p2): theta = math(p2.y - p1.y, p2.x - p1.x) m = ( rotate_about(p1.x, p1.y, -theta) * translation(0, -p1.y) * reflect_x() * translation(0, p1.y) * rotate_about(p1.x, p1.y, theta) )
def calc_interest(self): self.years = 10 if self._balance > 0: self.interest = math( self._balance * self.interest_rate * self.years) / 1000 print("Your interest is" + str(self.interest)) else: self.interest = 0 print("Your interest is 0")
def system1(): b = eval(input("Digite 1 para entrar no sistema e 0 para sair")) if b == 1: print("You are in the sys") math() else: print("\nYou quited1\nGoodbye")
def area(self): """ What comes in: -- self What goes out: Returns the area of this Triangle. Side effects: None. HINT #1: Recall Heron's formula for the area of a triangle: Area = square root of (S * (S - length of side 1) * (S - length of side 2) * (S - length of side 3)) where S = (1/2) * (perimeter of the triangle) For example: if the triangle has endpoints: a = Point(15, 35) b = Point(15, 50) c = Point(35, 45) then one can compute (** using the Point distance_from method **) that: the length of the side from a to b is (about): 15 the length of the side from b to c is (about): 20.6 the length of the side from c to a is (about): 22.4 and hence S is (about) (1/2) * (15 + 20.6 + 22.4), which is about 28.99 and so the area of the Triangle is (per the formula): 150.0 Type hints: :rtype: float """ # --------------------------------------------------------------------- # TODO: 3. # a. READ the above specification, including the Example AND HINT! # ** ASK QUESTIONS AS NEEDED. ** # ** Be sure you understand it, ESPECIALLY the Example. # b. Implement and test this method. # The tests are already written (below). # They include the Example in the above doc-string. # --------------------------------------------------------------------- s = (a + b + c) / 2 area = math(sqrt())
def start(): U_res = int(input('0:石头,1:剪刀,2:布>>>')) math(U_res)
def start(): x = int(input('请输入你的猜测(1为正,2为反):')) math(x)
def start(): year,month = map(int,input('输入年和月(逗号分隔):').split(',')) math(year,month)
import math import re def m(e): return eval( re.sub( r'math.sqrt\((.*?)\)', r'int(math.sqrt(\1))', e[:-1] ) ) print(r'sqrt\((.*)?\)') print(math('2+2=')) print(math('2+2=') == 4) print(math('(10^3-500)/(10^2)=') == 5) print(math('sqrt(28+8-9)=') == 5) print(math('75*(sqrt(82)-9)=') == 4) print(math('-5*(-5)=') == 25) print(math('5*(-5)=') == -25) print(math('(10^2)/10=') == 10)
def setup(bot): bot.add_cog(math(bot))
while indecies > 1: powerapp = np.append(powerapp, (unique[i])**indecies) #print(unique[i], indecies,(unique[i])**indecies) indecies -= 1 #print(indecies) i += 1 return powerapp k = 0 q = 0 skip = 0 while 1 == 1: num = k done = np.array([num, 1]) done = np.append(done, math(findpowers(primefac(num)))) if skip == 1000: print("----------------------------------------------------", len(done)) skip = 0 skip += 1 if len(done) > 500: print(k, "<----FOUND!") break k += q q += 1 done = np.array([num, 1]) done = np.append(done, math(findpowers(primefac(num)))) #print(done)
def calc(sum): return str(math(int(x) + int(y)))
# Naming a variable or function the same name as a module can # also be problematic. print "Ex. 2:", random.randrange(5) random = 4 print "Ex. 3:", random # Random is no longer a module; it is now a variable. #print "Error:", random.randrange(5) print print "Ex. 3:", math.e def math(): return 4 print "Ex. 4:", math() #print "Error:", math.e # This can technically be fixed by re-importing the modules, # but that would be an example of absolutely atrocious # programming, so don't do it. It is only done here since # this program is supposed to give examples of errors # anyway. import math import random print "--------" # Misspelling the methods or constant calls of the modules # also causes an error. Remember that CodeSkulptor is case # sensitive, meaning that the issue could be an incorrectly
define webscraping most likely with scrapy define storage of archived material probably with mongodb define mathematics agent(for complex math required by other fuinctions to call from) define text interface for communication between node and master agents and the user if not included define communication between nodes define MendicantBot(): Master bot, run when program starts and call from botmanager define control system that talks to BotManager call BotManager to spawn a node for a particular task that it oversees # Functions below except maybe botmanger call all from another file define BotManager(): subprocess.spawn(MendicantBotNode) #spawns MendicantBotNodes define agent type from a list of possible agents Popen. define communication between bots and MendicantBot define MendicantBotInstance(): call functions from another file define math(): here all the different types of math to do and they can all go in one function define MendicantArchive(): where data the bot has scraped is stored for recall later
def encontra_cateto(cateto, hipotenusa): return math(hipotenusa**2 - cateto**2)**(1 / 2)
# Python classes for simulating card games # By Prof. M. Colvin, UC Merced # This software is in the Public Domain for all uses # Bring in useful modules import random import math ntrials = 1000 limit = 2 player1wins = 0 for i in range(ntrials): rand1 = math(range(1, limit + 1), k=3) rand1.sort(reverse=True) rand2 = math(range(1, limit + 1), k=2) if rand2[0] == rand2[1]: continue if rand2[0] == 2 and rand2[1] == 2: player1wins = player1wins + 1 continue if rand1[0] + rand1[1] > rand2[0] + rand2[1]: player1wins = player1wins + 1 print("Fraction=", player1wins / ntrials) ################ Define Python classes for simulation ######################## # The class cell holds info about a particular card class card: def __init__(self, suit, kind, value): self.cardsuit = suit self.cardtype = kind self.cardvalue = value
{3, 4, 5, 6} >>> c = {"ewqe", 'a'} >>> s | c {0, 1, 2, 3, 4, 5, 6, 'ewqe', 'a'} >>> a = 2^10 >>> a 8 >>> 2^3 1 >>> a = math.pow(2,3) Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> a = math.pow(2,3) NameError: name 'math' is not defined >>> import math >>> a = math(2,4) Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> a = math(2,4) TypeError: 'module' object is not callable >>> a = pow(2,3) >>> a 8 >>> b = pow(2,10) >>> b 1024 >>> s = {"a":[16,21,4], "b":[32,76,81]} >>> a = {"c":[21,17], "f":[32,98], "g":3, "word":"eric"} >>> s | a Traceback (most recent call last): File "<pyshell#17>", line 1, in <module>
elif choose == 3: print("Статистический ряд относительных частот") showNumbers(arr_x, arr_n, sum_n, "x", "w") root = Tk() makePoligon(arr_x, arr_n, "X", "W", max_x, max_n, "#caf", sum_n) elif choose == 4: print("Эмпирическая функция распределения") arr_sum_n = [] makeSumArray(arr_n, arr_sum_n) showEmpFunc(arr_x, arr_sum_n, sum_n) root = Tk() makeEmpFunc(arr_x, arr_sum_n, "X", "F*(x)", max_x, 1, "#bcc", sum_n) elif choose == 5: math(arr_x, arr_n, sum_n) elif choose != 0: print("Введите корректный номер") choose = 1 elif choose == 2: arrFromFile = [] openFile("over100.txt", arrFromFile) arrFromFile[0].sort() arr_x = [] arr_n = [] separate(arrFromFile[0], arr_x, arr_n) n = int(input("Задайте количество интервалов:")) begin = [] end = [] count = [] middle = []
def main(): n = 0 m = 0 math(n,m)
return a**0.5 signs = { "+": sums, "-": subtract, "/": divide, "*": multiply, "**": power, } unary = {"s": square, "n": negate, "r": root, "l": log} token = sys.stdin.read().split() for word in token: if word in signs: b = stack.pop() a = stack.pop() math = signs[word] c = math(a, b) stack.append(c) elif word in unary: a = stack.pop() math = unary[word] c = math(a) stack.append(c) elif word == "p": print stack[len(stack) - 1] else: stack.append(float(word))
import math import sys def math(n): print 9 + int(n) math(sys.argv[1])
def banner(): print(""" \tHello, I am a basic python program that performs a couple of tasks. Such as weather reading, basic math, currency converter and web headers reading. To take advantage of either functions, simply enter a command on this same prompt window, ie 'math'\n""") banner() from tk2 import * from con import * from wea import * from sock import * while 1: cmd = raw_input("Enter Command > ") if "exit" in cmd or "quit" in cmd: print("\n\tThank you for trying me out...\n\tGood Bye!\n") sys.exit() elif "math" in cmd: math() elif "con" in cmd: convert() elif "w" in cmd: weather(MY_IP) elif "h" in cmd: help() elif "s" in cmd: sock() else: help()
def union(a, b): a = find(a) b = find(b) parent[math(a, b)] = min(a, b)
# ----------------- # module attributes # ----------------- # Don't move this to imports.py, because there's a star import. #? str() __file__ #? ['__file__'] __file__ #? str() math.__file__ # Should not lead to errors #? math() # ----------------- # with statements # ----------------- with open('') as f: #? ['closed'] f.closed for line in f: #? str() bytes() line with open('') as f1, open('') as f2: #? ['closed'] f1.closed
def __abs__(self): return math(sqrt(sum(x * x for x in self)))
def main(msg, channel, irc, name): if msg and '|math' in msg: math(msg, channel, irc)
def _uf(x,y, numpy = getattr(_numpy,ufunc), math = getattr(_math,ufunc), mathtypes = (float,int,int)): if type(x) in mathtypes and type(y) in mathtypes: return math(x,y) return numpy(x,y)
) print '{:-^6} {:-^6} {:-^6} {:-^6}'.format('', '', '', '') fmt = ' '.join(['{:6.4f}'] * 4) for i in range(0, 11, 2): x = i/10.0 print fmt.format(x, math.sinh(x), math.cosh(x), math.tanh(x)) #特殊方法 #高斯误差函数erf(-x) == -erf(x). print '{:^5} {:7}'.format('x', 'erf(x)') print '{:-^5} {:-^7}'.format('', '') for x in [ -3, -2, -1, -0.5, -0.25, 0, 0.25, 0.5, 1, 2, 3 ]: print '{:5.2f} {:7.4f}'.format(x, math.erf(x)) #使用erfc方法,避免很小的数的精度误差 print '{:^5} {:7}'.format('x', 'erfc(x)') print '{:-^5} {:-^7}'.format('', '') for x in [ -3, -2, -1, -0.5, -0.25, 0, 0.25, 0.5, 1, 2, 3 ]: print '{:5.2f} {:7.4f}'.format(x, math.erfc(x)) """ See Also: math (http://docs.python.org/library/math.html) The standard library documentation for this module. IEEE floating-point arithmetic in Python (http://www.johndcook.com/blog/2009/07/21/ieee-arithmetic-python/) Blog post by John Cook about how special values arise and are dealt with when doing math in Python. SciPy (http://scipy.org/) Open source libraries for scientific and mathematical calculations in Python. """
>>> ============================ RESTART: Shell =========================== >>> import math >>> dir(msth) Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> dir(msth) NameError: name 'msth' is not defined >>> dir(math) ['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc'] >>> help(floor) Traceback (most recent call last): File "<pyshell#7>", line 1, in <module> help(floor) NameError: name 'floor' is not defined >>> help(math(floor)) Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> help(math(floor)) NameError: name 'floor' is not defined >>> help(math.floor) Help on built-in function floor in module math: floor(x, /) Return the floor of x as an Integral. This is the largest integer <= x. >>> math.floor(-2.8) -3 >>> abs(round(-4.3))
def test_math(self, arg1, arg2, operator, result): assert math(arg1, arg2, arith_operator=operator) == result
def math(a, b, c, d): e = (a * b) c = (c + e) d = (d + a) return c, d, e overallhrs = 0 overallpoints = 0 count = 0 classes = int(input("Enter the number of courses you are taking: ")) print() for count in range(count, classes): grade = input("Enter the grade for course {:d}: ".format(count + 1)) credit = int(input("Enter the credits for course {:d}: ".format(count + 1))) print() pointscale = translate(grade) overallpoints, overallhrs, classgpa = math(credit, pointscale, overallpoints, overallhrs) gpa = overallpoints / overallhrs print("Your GPA is {0:.2f}".format(gpa))
import math __author__ = "K. Sravanthi" class math(): def fib(self): n = int(raw_input("Enter the value of n: ")) a, b = 0, 1 while n > 0: a, b = b, a + b n -= 1 print a return a def sum_of_n(self): n = int(raw_input("Upto which digit do you want to find the sum? ")) n = n * (n + 1) / 2 print n return n print("this is for git stash") print("sample avoid file text") obj1 = math() obj1.fib() obj1.sum_of_n()
>>> ascii('ओ') "'\\u0913'" >>> n='\u0913' >>> ascii(n) "'\\u0913'" >>> n 'ओ' >>> d=1 >>> callable(d) False >>> callable(any) True >>> import math >>> callable (math) False >>> math() Traceback (most recent call last): File "<pyshell#30>", line 1, in <module> math() TypeError: 'module' object is not callable >>> dir(math) ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc'] >>> callable(math.pi) False >>> callable(math.sin) True >>> for i,v in enumerate([5,6,7]): print(i,v) 0 5
print "Ex. 2:", random.randrange(5) random = 4 print "Ex. 3:", random # Random is no longer a module; it is now a variable. #print "Error:", random.randrange(5) print print "Ex. 3:", math.e def math(): return 4 print "Ex. 4:", math() #print "Error:", math.e # This can technically be fixed by re-importing the modules, # but that would be an example of absolutely atrocious # programming, so don't do it. It is only done here since # this program is supposed to give examples of errors # anyway. import math import random print "--------" # Misspelling the methods or constant calls of the modules # also causes an error. Remember that CodeSkulptor is case # sensitive, meaning that the issue could be an incorrectly # capitalized letter.