예제 #1
0
def Calculator():
    print("************MAIN MENU**************")
    print()

    choice = int(
        input("""
                      1: Addition
                      2: Subtraction
                      3: Division
                      4: Multiplication
                      5: Remainder
                      6: Quit/log out
                      
                      Please enter your choice: """))
    if choice == 1:
        add()
    elif choice == 2:
        subtract()
    elif choice == 3:
        divide()
    elif choice == 4:
        multiply()
    elif choice == 5:
        modulus()
    elif choice == 6:
        sys.exit
    else:
        print("You must only select either 1,2,3,4,5, or 6.")
        print("Please try again")
        Calculator()
예제 #2
0
파일: main.py 프로젝트: kirawrath/RP
def main():
	imgname1='imgs/porta1pb.pnm'
	imgname2='imgs/larapiopb.pnm'
	if len(argv)>2:
		imgname1=argv[1]
		imgname2=argv[2]

	thresh_factor = 65
	min_size = 10 #(minimum w and h to be not considered noise)



	print 'Subtracting...'
	subtract(imgname1, imgname2)
	print 'Thresholding...'
	threshold('subtracted_image.png', 65)
	print 'Eroding...'
	k=open('kernel', 'w')
	k.write('''1 1 1 1 1
	1 1 1 1 1
	1 1 1 1 1''')
	k.close()
	erode('thresholded_image.png')
	print 'Dilating...'
	dilate('eroded_image.png')

	#Dilating to merge pieces, then erode to get back to the original size

	print 'Merging pieces...',
	k=open('kernel', 'w')
	for i in range(10):
		k.write('1 1 1 1 1 1 1 1 1 1\n')
	k.close()
	dilate('dilated_image.png', outfile='result0.png')
	print 'halfway done...'
	erode('result0.png', outfile = 'result.png')

	#Using opencv to calculate the bounding box to figure out what we found

	img = cv2.imread('result.png', cv2.CV_LOAD_IMAGE_GRAYSCALE)
	contours, hierarchy = cv2.findContours(img,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

	noise=0
	for cnt in contours:
		b_box = cv2.boundingRect(cnt)
		w,h = b_box[2], b_box[3]
		#print w,h
		if w > min_size and h > min_size:
			#Found something...
			if w > h:
				print 'Found a dog!'
			else:
				print 'Found an intruder!'
		else:
			noise+=1
	print 'Found',str(noise),'noise(s).'
예제 #3
0
def karat(a, b):
    '''
    Implementation of the
    :param a: (int) or list reverse order
    :param b: (int) or list reverse order
    :return: a reversed list of the product a * b
    '''
    if (type(a) == int):
        a, b = create_reverse_lists(a, b)
    if len(a) == 1 and len(b) == 1:
        d, e = create_reverse_lists(a[0] * b[0], 0)
        return d
    if (len(a) > len(b)):
        b = b + [0] * (len(a) - len(b))
    if (len(b) > len(a)):
        a = a + [0] * (len(b) - len(a))
    k = len(a) // 2

    A2 = a[:k]
    A1 = a[k:]
    B2 = b[:k]
    B1 = b[k:]

    a1b1 = karat(A1, B1)
    a12b12 = karat((add(A1, A2)), (add(B1, B2)))
    a2b2 = karat(A2, B2)
    # print(a12b12)
    # print('k: ' + str(k) + '\n')
    # print ('a1b1: ' + str(a1b1))
    stepone = power(a1b1, 2 * k)
    # print('stepone: ' + str(stepone) + '\n')
    # stepone = (a1b1 * (10 ** (2 * k)))

    # print ('a12b12: ' + str(a12b12))
    steptwo = subtract(a12b12, a1b1)
    # print('steptwo: ' + str(steptwo) + '\n')
    # steptwo = (a12b12) - a1b1

    # print ('a2b2: ' + str(a2b2))
    stepthree = subtract(steptwo, a2b2)
    # print('stepthree: ' + str(stepthree) + '\n')
    # stepthree = steptwo - a2b2

    stepfour = power(stepthree, k)
    # print('stepfour: ' + str(stepfour))
    # stepfour = (10 ** k)

    stepfive = add(stepone, stepfour)
    # print('stepfive: ' + str(stepfive))

    stepsix = add(stepfive, a2b2)
    # print('stepsix: ' + str(stepsix))

    return stepsix
예제 #4
0
def multiply(multiplicand, multiplier, accumulator, c_multiplier, circ,
             cl_index):
    """
    Multiply two numbers stored in QuantumRegisters multiplicand and 
    multiplier using repeated fourier transform based
    addition.

    """
    try:
        from qiskit import QuantumRegister, ClassicalRegister, \
            QuantumCircuit, execute
        from qiskit import Aer
    except ImportError:
        raise QForestMathError("Please install qiskit! " +
                               "You can install it using the pip tool:" +
                               " pip install qiskit.")

    if isinstance(multiplicand, QuantumRegister) and \
            isinstance(multiplier, QuantumRegister) and \
            isinstance(accumulator, QuantumRegister) and \
            isinstance(c_multiplier, ClassicalRegister) and \
            isinstance(cl_index, int) and \
            isinstance(circ, QuantumCircuit):
        pass
    else:
        raise QForestMathError(
            "Expected three QuantumRegister" +
            " objects, one ClassicalRegister object, one " +
            "QuantumCircuit object and an integer! Please check the objects passed"
            + " to the multiply() function.")

    if len(c_multiplier) < len(multiplier):
        raise RegisterError(
            "Expected ClassicalRegister of same" +
            " or greater length than associated QuantumRegister!" +
            " Passed Register objects have lengths " + str(len(multiplier)) +
            " and " + str(len(c_multiplier)) + ".")

    d = QuantumRegister(1)
    circ.add(d)
    circ.x(d[0])

    multiplier_str = '1'

    while (int(multiplier_str) != 0):
        add.add(accumulator, multiplicand, circ)
        subtract.subtract(multiplier, d, circ)
        for i in range(len(multiplier)):
            circ.measure(multiplier[i], c_multiplier[i])
        result = execute(circ,
                         backend=Aer.get_backend('qasm_simulator'),
                         shots=2).result()
        counts = result.get_counts("qc")
        multiplier_str = list(counts.keys())[0].split()[cl_index]
예제 #5
0
def subtract_multi(arguments):
    
    #Performs subtraction of supplied experiment from the current experiment (Used for background sub) MULTIPROCESSING VERSION
    global completed_tasks
    control_RT = arguments[0]
    control_list_of_spectra = arguments[1]
    analyte_RT = arguments[2]
    analyte_list_of_spectra = arguments[3]
    start_time = arguments[4]
    end_time = arguments[5]
    proc_num = arguments[6]
    tol_window = arguments[7]
    time_window = arguments[8]
    scaling_factor = arguments[9]
    
    
    try:
        a_spec = sub.subtract(analyte_RT, analyte_list_of_spectra, control_RT, control_list_of_spectra, tol_window, time_window, scaling_factor, start_time, end_time, proc_num)
    except:
        print "Unexpected error:", sys.exc_info()[0]
        raise
        
    
    start_index = sub.find_index(analyte_RT,start_time)
    end_index = sub.find_index(analyte_RT,end_time)
    sliced_rt = analyte_RT[start_index:end_index]
    sliced_spectra = a_spec[start_index:end_index]
    for i,series in enumerate(sliced_spectra):
        s = series[:,1]
        s[s<0] = 0
    
    completed_tasks.value = completed_tasks.value+1
    print "Completed Tasks , Process number " + str(completed_tasks.value) + "," + str(proc_num)
    
    return (sliced_rt, sliced_spectra)
예제 #6
0
def divide(dividend, divisor, accumulator,
           c_dividend, circ, cl_index):
    """
    Divide QuantumRegister dividend by QuantumRegister divisor, and store the
    product in QuantumRegister accumulator.

    """
    try:
        from qiskit import QuantumRegister, ClassicalRegister, \
            QuantumCircuit
        from qiskit import Aer, execute
    except ImportError:
        install = """Please install qiskit! You can install it using the 
                     pip tool: pip install qiskit."""
        raise QForestMathError(install)

    if isinstance(divisor, QuantumRegister) and \
            isinstance(dividend, QuantumRegister) and \
            isinstance(accumulator, QuantumRegister) and \
            isinstance(c_dividend, ClassicalRegister) and \
            isinstance(cl_index, int) and \
            isinstance(circ, QuantumCircuit):
        pass
    else:
        raise QForestMathError("Expected three QuantumRegister" +
                               " objects, one ClassicalRegister object, one " +
                               "QuantumCircuit object and an integer! Please check the objects passed" +
                               " to the multiply() function.")

    d = QuantumRegister(1)
    circ.add(d)
    circ.x(d[0])

    c_dividend_str = '0'

    while c_dividend_str[0] == '0':
        subtract.subtract(dividend, divisor, circ)
        add.add(accumulator, d, circ)
        for i in range(len(dividend)):
            circ.measure(dividend[i], c_dividend[i])
        result = execute(circ, backend=Aer.get_backend('qasm_simulator'),
                         shots=2).result()
        counts = result.get_counts("qc")
        c_dividend_str = list(counts.keys())[0].split()[cl_index]

    subtract.subtract(accumulator, d, circ)
예제 #7
0
def factorial(n):
    m = subtract(n, 1)

    #while loop to iteratively calculate factorial
    while m > 0:
        #uncomment line 16 when multiplication function has been completed
        #rename function call as appropriate
        #comment out line 17
        n = multiply(n, m)
        #n *= m
        #uncomment line 21 when subtraction function has been completed
        #rename/modify function call as appropriate
        #comment out line 22
        m = subtract(m, 1)

    #return calculated factorial
    return n
예제 #8
0
def main():
    print("\n\nWelcome to My Math!\n")
    a = int(input("Enter your first whole number: "))
    b = int(input("Enter your second whole number: "))
    print("\n{} + {} = {}".format(a, b, add(a, b)))
    print("\n{} - {} = {}".format(a, b, subtract(a, b)))
    print("\n{} * {} = {}".format(a, b, multiply(a, b)))
    print("\n{} / {} = {}".format(a, b, divide(a, b)))
    print("\n{} % {} = {}".format(a, b, remainder(a, b)))
    print("\n{} ^ {} = {}".format(a, b, exponent(a, b)))
예제 #9
0
def calculator(operator, operands, verbosity):

    n1, n2 = operands.split(',')
    n1 = int(n1)
    n2 = int(n2)

    if operator == "+":
        result = add.add(n1, n2)
    elif operator == "-":
        result = subtract.subtract(n1, n2)

    if verbosity:
        print("Operator:", operator, end="***")
        print("Operands:", operands, end="***")

    print("Result:", result)
예제 #10
0
def calculator():
    operator = input("Enter the operator (+/-):")
    operands = input("Enter the operands (comma separated): ")

    n1,n2 = operands.split(',')
    n1 = int(n1)
    n2 = int(n2)

    if operator == "+":
        result = add.add(n1,n2)
    elif operator == "-":
        result = subtract.subtract(n1,n2)
        
    print("Operator:",operator)
    print("Operands:",operands)
    print("Result:", result)
예제 #11
0
def createCG3(circ, args, anc_cl, n, reg, reg2, pie, anc, a_cl):
    """
    Creates a CompositeGate cgate with a series of instructions controlled
    by ClassicalRegister anc_cl holding the value 3. 
    Parameters:
    circ: QuantumCircuit
    args: List containing (Register, index) pairs that the CompositeGate
          will affect.
    reg, reg2, anc: QuantumRegisters
    anc_cl, a_cl: ClassicalRegisters
    n: integer
    pie: float representing pi (3.14..)
    Returns:
    cgate: CompositeGate     
    """
    cgate = CompositeGate("cl_" + str(3), [pie], args, circuit=circ)
    #Compute (reg - reg2)/2
    cgate = subtract.subtract(circ, n, pie, reg, reg2, cgate, -1, anc_cl, 3)
    cgate = divideBy2(cgate, n, circ, reg, anc_cl, 3, anc, a_cl)
    return cgate
예제 #12
0
from add import add
from subtract import subtract
from multiply import multiply
from divide import divide

a = 10
b = 7

print("Result from add method: ", add(a,b))
print("Result from subtract method: ", subtract(a,b))
print("Result from multiply method: ", multiply(a,b))
print("Result from divide method: ", divide(a,b))
예제 #13
0
from add import add
from subtract import subtract
from multiply import multiplication
import sys

print("Choose Valid Option\n1.Addition\n2.Subtraction\n3.Multiplication")
a = int(sys.argv[3])

if(a>=1 and a<=3):
	b=int(sys.argv[1])
	c=int(sys.argv[2])

	if(a==1):
		add(b,c)
	elif(a==2):
		subtract(b,c)
	else:
		multiplication(b,c)
else:
	print("Choose valid option")
예제 #14
0
        else:
            print('Enter the right value')
            continue

        num1 = int(
            input('Enter the first number to do {} : '.format(operation)))
        num2 = int(
            input('Enter the second number to do {} : '.format(operation)))
    except ValueError:
        print('Please enter an appropriate input to the place')
        continue

    if operation.lower() == 'addition':
        print(add(num1, num2))
    elif operation.lower() == 'subtraction':
        print(subtract(num1, num2))
    elif operation.lower() == 'multiplication':
        print(multiply(num1, num2))
    elif operation.lower() == 'division':
        print(divide(num1, num2))

    try:
        again = input("Do you want to do another calculation? (Y or N): ")
        if again.lower() != 'y' or again.lower() != 'y':
            print(
                'Your answer must be either Y or N. It is note case sensetive.'
            )
            print('Starting the progress again. Please enter the right value')
            continue
    except:
        print('There was an error try again')
예제 #15
0
from add import add
from divide import divide
from multiply import multiply
from subtract import subtract
print("Welcome to Simple Calculator")
print("1. Addition")
print("2. Subtraction ")
print("3. Multliply")
print("4. Divide")
ch = input("Enter Operation: ")
if ch == '1':
    add()
elif ch == '2':
    subtract()
elif ch == '3':
    multiply()
elif ch == '4':
    divide()
else:
    print("Error")
def test_subtract_negative():
    return_value = subtract(-1, 2)
    print(type(return_value))
    assert return_value == -3
def test_subtract_characters():
    return_value = subtract("2", "1")
    print(type(return_value))
    assert return_value == 3
def test_subtract():
    assert subtract(4, 2) == 2
예제 #19
0
 def test_2by2(self):
     a = [[1, 2], [4, 5]]
     b = [[1, 2], [3, 4]]
     c = subtract(a, b)
     self.assertEqual(c, [[0, 0], [1, 1]])
예제 #20
0
 def test_rectange(self):
     a = [[1, 2], [4, 5], [7, 6]]
     b = [[1, 2], [3, 4], [6, 7]]
     c = subtract(a, b)
     self.assertEqual(c, [[0, 0], [1, 1], [1, -1]])
예제 #21
0
 def test_3by3(self):
     a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
     b = [[1, 2, 3], [6, 5, 4], [9, 8, 7]]
     c = subtract(a, b)
     self.assertEqual(c, [[0, 0, 0], [-2, 0, 2], [-2, 0, 2]])
예제 #22
0
    print(i)


def b():
    global i
    print('B')
    i = i + 1
    print(i)


def c():
    global i
    print('C')
    i = i + 1
    print(i)


a()
b()
c()

#ans = sub.subtract(5,2)
ans = subtract(5, 2)

df = pd.DataFrame()
df['col1'] = [1, 2, 3]
df['col2'] = [2, 3, 4]

print(ans)

format_report(df)
예제 #23
0
def test_subtract(a,b,expected):
    from subtract import subtract
    result = subtract(a,b)
    assert result == pytest.approx(expected)
예제 #24
0
def test_subtract():
    from subtract import subtract
    answer = subtract(20, 10)
    expected = 10
    assert answer == expected
def test_subtract_float():
    return_value = subtract(1.5, 2)
    print(type(return_value))
    assert return_value == 3.5
def test_subtract_space():
    return_value = subtract("", "")
    print(type(return_value))
    assert return_value == ""
def test_subtract_null():
    return_value = subtract(null, null)
    print(type(return_value))
    assert return_value == null
def test_subtract_high_school():
    assert subtract(8000600, 6405006) == 1595594
def test_subtract_elementary():
    assert subtract(2, 1) == 1
예제 #30
0
def test_subtract():
    c = subtract(4, 5)
    assert (c == -1)
예제 #31
0
user_ingang = (input(
    "calc programina hosgeldiniz devam etmek icin 'Y' cikmak icin 'N' tusuna basin"
))
user_ingang = user_ingang.lower()
while user_ingang == "y":
    try:  #''' kullanicidan girdiler alinir. hata ayiklamasi icin try except blogunda '''
        user_kies = input("islem sec:")
        sayi1 = float(input("sayi gir: "))
        sayi2 = float(input("sayi gir:"))

        if user_kies == "+":
            print(total(sayi1, sayi2))
        if user_kies == "-":
            print(
                subtract(sayi1, sayi2)
            )  #kosullar karsilandiginda ilgili modulden fonksiyon cgrilir islem yapilir,
        if user_kies == "x":
            print(multiplication(sayi1, sayi2))
        if user_kies == "/":
            print(division(sayi1, sayi2))
        else:
            print('lutfen (+,-,x,/) isaretlerini kullanin'
                  )  #kullanici isaret yanlis girdigi durumlarda
        user_ingang = (
            input('yeniden hesaplamak icin "Y" tusuna basin cikmak icin "N" ')
        )  #islem sonrasi tekrar kullaniciya sorulur.
        user_ingang = user_ingang.lower()
        if user_ingang == "n":
            print("programdan cikiliyor...")
예제 #32
0
	def test_subtract(self):
		self.assertEqual(subtract(1, 2), -1)
		self.assertEqual(subtract(1, 2), 0)
		self.assertEqual(subtract(2, 1), 1)