Changing from int to int32 in Python - python

so I am doing an exercise from SPOJ, and it's a simple calculator. Everytime I try to submit an answer I get an NZEC error, and I wonder if it's because it should be defined as int32.
Here's my code:
import sys
n = input()
n = int(n)
i = 0
while n > i:
znak, num1, num2 = input().split()
num1 = int(num1)
num2 = int(num2)
if znak == "+":
b = num1 + num2
print(b)
elif znak == "-":
b = num1 - num2
print(b)
elif znak == "*":
b = num1 * num2
print(b)
elif znak == "/":
b = num1 / num2
print(b)
elif znak == "%":
b = num1 % num2
print(b)
i += 1
sys.exit(0)
I've tried a some "solutions" for this NZEC error, but nothing worked.

If the result should be an integer, you should use operator.floordiv, i.e. a // b, not a / b 1:
from operator import add, sub, mul, floordiv, mod
op = {'+': add, '-': sub, '*': mul, '/': floordiv, '%': mod}
for i in range(int(input())):
znak, *nums = input().split()
print(op[znak](*map(int, nums)))
By the way, the code above does exactly the same as yours, but it's around two times shorter!
How?
why check if znak is equal to something with tons of if/else statements, if you could put all the math operators in a dictionary op, and get the operator you need with op[znak]?
you're on Python 3, so you can use that nice a, *b = iterable syntax which extracts the first item of iterable into a and puts other items into a list b, which looks super nice
each op[znak] is a function that accepts two arguments, so you convert nums to integers with map(int, nums) and then pass them as separate arguments with the asterisk: *map(int, nums)
last, but not least, why use this C-style while loop index incrementing if there's the Pythonic way to do it - with range(start, stop, [step])?
finally, you don't really need the variable n, so you can plug it into range right away
Pssst, dude, feeling in need of some craziness? Take a look at how you can squeeze all this into two lines:
from operator import*
sum(0for _ in map(print,((lambda znak,*nums:{'+':add,'-':sub,'*':mul,'/':floordiv,'%':mod}[znak](*map(int,nums)))(*input().split())for _ in range(int(input())))))
Or only one line:
sum(0for _ in map(print,((lambda znak,*nums:{'+':lambda a,b:a+b,'-':lambda a,b:a-b,'*':lambda a,b:a*b,'/':lambda a,b:a//b,'%':lambda a,b:a%b}[znak](*map(int,nums)))(*input().split())for _ in range(int(input())))))
These work exactly as the first version. Now, this is just for fun, to show how powerful Python is and how messy it can be. Don't try this at home :D
1 True division vs Floor division: 1 / 10 == 0.1, but 1 // 10 == 0.

A simple solution: The idea is to split input charter into tokens preserving their orders . in our case tokens are operators and numbers so it very simple using regular expressions. [+-/*] match any of those operators or any number of digits using \d+
n = input()
import re
while n>0:
expression = input()
operator,num1,num2 = re.findall('[+-/*]|\d+',expression)
if operator == '+': print(int(num1) + int (num2))
if operator == '-': print(int(num1) - int (num2))
if operator == '*': print(int(num1) * int (num2))
if operator == '%': print(int(num1) % int (num2))
if operator == '/': print(int(num1) // int (num2))
n = n - 1

Related

how to store a value to a variable while in a for loop

I'm programming a calculator.
For example, I have the following:
result = 0
splitted_calculation = ["2", "+", "2"]
for thing in splited_calculation:
if thing == "+":
result = result + number
else:
number = int(thing)
print(result)
I want that, if the variable in the for loop is an integer, then that value is stored such that I can add the previous integer to the next integer currently in the for loop. However, when I run the code, I always get 0. It seems that the "number = int(thing)" isn't working. Any tips to solve this?
The issue with your code (besides the typo) is that the last digit is ignored. Step through it - in your head, on paper, or with a debugger.
Iterations of the loop. For this example, change it to ['2','+','3'] for clarity:
SIteration
thing
Action
number
result
1
2
assign it to number
2
0
2
+
add number to result
2
2
3
3
assign it to number
3
2
After the loop, the last digit is just hanging out in number but was never added to result. So result ends up at 2 not 5.
If the format is always "number operator number" there is no need for a loop. Access the values directly from the list:
splitted_calculation = ["2", "+", "2"]
left_number = int(splitted_calculation[0])
right_number = int(splitted_calculation[2])
operator = splitted_calculation[1]
if operator == '+':
result = left_number + right_number
elif operator == '-'
result = left_number - right_number
# repeat for others.
If the formulas are more complex ("2 + 2 + 2" for example) you can modify the loop to store the last operator and do the math on the numbers:
splitted_calculation = ["-5", "+", "2", "-", "3"]
result = 0
last_op = "+"
for n in splitted_calculation:
if n in "+-*/":
last_op = n
else:
if last_op == '+': result += int(n)
elif last_op == '-': result -= int(n)
elif last_op == '*': result *= int(n)
elif last_op == '/': result /= int(n)
Output:
-6
Find Modified Code Below:
result = 0
splited_calculation = ["2", "+", "2"]
for thing in splited_calculation:
if thing != "+":
result += int(thing)
print(result)

A faster way to have two random numbers that always divisible?

today I wrote a simple math game that I can practice mental math. My concerns is to make sure two number are always divisible. I have tried the while loop to add 1 until it divisible but it took too long:
import random
import operator
def random_problem():
operators = {
'+': operator.add,
'-': operator.sub,
'x': operator.mul,
':': operator.truediv
};
num1 = random.randint(1000,9999)
num2 = random.randint(num1,9999)
operation = random.choice(list(operators.keys()))
if operation == ':':
while num1 % num2 != 0:
num2 += 1
answer = (operators.get(operation)(num1, num2))
print(f'What is {num1} {operation} {num2}')
return answer
So any ideas to make this process faster? Thanks for your answers.
A simple approach would be:
Generate a random first number (n1)
Generate a random multiplier (m)
Use the product of the first number and the multiplier as the second number (n2 = n1 * m)
IIUC:
Your current code will only work when num1 == num2 for all other values of num2 the denominator is always greater than the numerator so the modulus will never be 0, so you would get an infinite loop.
Instead try generating the numerator from the denominator like:
Code:
import random
import operator
def random_problem():
operators = {
# '+': operator.add,
# '-': operator.sub,
# 'x': operator.mul,
':': operator.truediv
}
num2 = random.randint(1000, 2000)
num1 = num2 * random.randint(1, int(9999/num2))
operation = random.choice(list(operators.keys()))
if operation == ':':
while num1 % num2 != 0:
num2 += 1
answer = (operators.get(operation)(num1, num2))
print(f'What is {num1} {operation} {num2}')
return answer
print(random_problem())
Output:
What is 4136 : 1034
4.0

Calculation program with arithmetic operators

Defining the function (x,y,ops) where x and y are 2 numbers to be input into the function and ops is a variable that indicates which of the arithmetic operator (+, - , / *) is used.
I am stuck with how to define the ops.
This is what I have so far and I am stuck :(
x=eval(input("x= "))
y=eval(input("y= "))
def func(x, y, ops):
return x+y if ops==1
elif return x-y is ops==1
print(func(x, y, ops))
You can have the user just enter the symbol. You can compare it as a string.
def func(x, y, ops):
if ops == '+':
return x+y
elif ops == '-':
return x-y
elif ops == '*':
return x*y
elif ops == '/':
return x/y
else:
raise ValueError("Unknown op " + ops)
x = float(input('x= '))
y = float(input('y= '))
op = input('op [+,-,*,/]: ')
print(func(x, y, op))
You can create a dictionary of functions, which gives you quite a bit of flexibility in adding or changing operations.
oper_dict = {
"*": lambda x,y:x*y,
"+": lambda x,y:x+y,
"-": lambda x,y:x-y,
"/": lambda x,y:x/y if y !=0 else 'div by zero'
}
x = float(input("x= "))
y = float(input("y= "))
oper = input("operation (*, +, -, /): ")
answer = oper_dict.get(oper, lambda x,y: 'unkown operation')(x, y)
This presents a good opportunity to dig deeper into Python's fantastic standard libraries. In this case the operator library can be used to peform the desired calculator operations. Using a dictionary you can use operation symbols as keys and the operations themselves as the values:
from operator import mul, add, sub, truediv
op_mapper = {"*": mul, "+": add, "-": sub, "/": truediv}
x = float(input("x= "))
y = float(input("y= "))
op = input("operator [*, +, -, /]: ")
print(op_mapper[op](x, y))

python3 algebraic expression solve for x

I'm relatively new to python, and decided to make a calculator. Unfortunately I cant solve for x. The error is:
SyntaxError: can use starred expression only as assignment target.
I can't figure out any way around this as I want to have the person enter in the problem, and then it prints x.
Please help, And thanks for any help in advance.
My code:
import random
from datetime import datetime
import time
def ints(x,y):
x = int(x)
y = int(y)
now = datetime.now()
def solve(c, z):
c = (*z)
print(now.year)
time.sleep(1)
print("WELCOME TO THE JERAXXUS SOFTWARE")
time.sleep(2)
math = True
if math == True:
user_input = input("My name is jeraxxus, please put in 2 numbers followed by a operator, *, /, +, -, **, or %. No commas please")
user_input = str.split(user_input)
a_list = [user_input]
n1 = user_input[0]
n2 = user_input[1]
operate = user_input[2]
algebra = input("does your mathmatical equation contain algebraic values?")
if algebra == 'no':
if operate == '*':
n1 = int(n1)
n2 = int(n2)
print(n1 * n2)
elif operate == '/':
n1 = int(n1)
n2 = int(n2)
print(n1 / n2)
elif operate == '+':
n1 = int(n1)
n2 = int(n2)
print(n1 + n2)
elif operate == '-':
n1 = int(n1)
n2 = int(n2)
print(n1 - n2)
elif operate == '**':
n1 = int(n1)
n2 = int(n2)
print(n1 ** n2)
elif operate == '%':
n1 = int(n1)
n2 = int(n2)
print(n1 % n2)
elif operate != '%' and operate!= '**' and operate != '-' and operate != '+' and operate != '/' and operate != '*':
print("SHAME YOU SHOULD HAVE FOLLOWED MY COMMANDS")
math = False
elif algebra == 'yes':
problem = input("please state your algebraic problems with spaces after each operation and number, the order is crucial please have only 1 variable and have it first.")
problem = str.split(problem)
lop = problem[0]
b_list = [problem]
sovle(lop, b_list)
here are a few thing about your code:
the function ints do nothing in the end because you don't return any value, the error that you get come from c=(*z) you can't do that in a assignation, but you can do it in a function call like this fun(*argument_list).
The variable math as used there is useless because you assign it True and check it for that same value, so you enter in that if block unconditionally meaning that that if math == True is unneeded, maybe you mean while math that way you repeat that block while the variable math is true.
What is the reason of the variable a_list?, you don't use it.
In the block if algebra == 'no' you can put int conversions first and then check the operate so to avoid repeat the same code over and over again, speaking of operate the last elif is redundant because if you get there it is because it fail the other comparisons so no need to check again against every possibility, change it for a simple else.
with that little revisions you code will look like this
import random
from datetime import datetime
import time
def solve(c, z):
raise NotImplementedError("In process of programming") # an error because there is still no code for this
now = datetime.now()
print(now.year)
time.sleep(1)
print("WELCOME TO THE JERAXXUS SOFTWARE")
time.sleep(2)
math = True
while math:
user_input = input("My name is jeraxxus, please put in 2 numbers followed by a operator, *, /, +, -, **, or %. No commas please")
user_input = str.split(user_input)
#a_list = [user_input]
n1 = user_input[0]
n2 = user_input[1]
operate = user_input[2]
algebra = input("does your mathematical equation contain algebraic values?")
if algebra == 'no':
n1 = int(n1)
n2 = int(n2)
if operate == '*':
print(n1 * n2)
elif operate == '/':
print(n1 / n2)
elif operate == '+':
print(n1 + n2)
elif operate == '-':
print(n1 - n2)
elif operate == '**':
print(n1 ** n2)
elif operate == '%':
print(n1 % n2)
else:
print("SHAME YOU SHOULD HAVE FOLLOWED MY COMMANDS")
math = False
elif algebra == 'yes':
problem = input("please state your algebraic problems with spaces after each operation and number, the order is crucial please have only 1 variable and have it first.")
problem = str.split(problem)
lop = problem[0]
b_list = [problem]
solve(lop, b_list)
The no algebra part work fine, you need now figure the solve x part, if you need help with this too, just ask :)
Simple calculator
After quick search, making a simple calculator in python is easy with the use of eval, like this
def calculator():
exp = input("x= ")
print("x=", eval(exp) )
with this you can procesate any valid python expression as if you were in the IDLE.
But if for academics reason you don't want to use it, then as I tell you before, you have to make a parser of mathematical expressions, that identificate what operator is in there and arrange them according to its precedence and finally solve the expresion

prefix notation parsing in python

Right off the bat - no, this is NOT homework.
I would like to write a prefix notation parser in python (for sums presently)... for example
if given: + 2 2 it would return: 4
ideas?
Prefix notation can be very easily evaluated recursively. You basically see the first token and if it is a '+' you evaluate the sub-expressions that follow to get the values to be added and just add them up. If it is a number, you just return the number.
The following code assumes that the input is nicely formatted and is a valid expression.
#! /usr/bin/env python
from collections import deque
def parse(tokens):
token=tokens.popleft()
if token=='+':
return parse(tokens)+parse(tokens)
elif token=='-':
return parse(tokens)-parse(tokens)
elif token=='*':
return parse(tokens)*parse(tokens)
elif token=='/':
return parse(tokens)/parse(tokens)
else:
# must be just a number
return int(token)
if __name__=='__main__':
expression="+ 2 2"
print parse(deque(expression.split()))
Here's what I worked up. It keeps a stack of the operators. As it receives sufficient numbers it pops an operator and evaluates the sub-expression.
# Bring in the system module to get command line parameters
import sys
# This function takes in some binary operator, which is just an arbitrary
# string, and two values. It looks up the method associated with the
# operator, passes the two values into that method, and returns the
# method's result.
def eval_expression(operator, value_one, value_two):
if operator == "+":
return value_one + value_two
elif operator == "-":
return value_one - value_two
elif operator == "*":
return value_one * value_two
elif operator == "/":
return value_one / value_two
# Add new operators here. For example a modulus operator could be
# created as follows:
# elif operator == "mod":
# return value_one % value_two
else:
raise Exception(operator, "Unknown operator")
# This function takes in a string representing a prefix equation to
# evaluate and returns the result. The equation's values and
# operators are space delimited.
def calculate( equation ):
# Gather the equation tokens
tokens = equation.split( " " )
# Initialize the evaluation stack. This will contain the operators
# with index 0 always containing the next operator to utilize. As
# values become available an operator will be removed and
# eval_expression called to calculate the result.
eval_stack = [ ]
total = None
# Process all the equation tokens
for token in tokens:
if token.isdigit():
# Save the first value. Subsequent values trigger the evaluation
# of the next operator applied to the total and next values
token = int(token)
if total is None:
total = token
else:
total = eval_expression(eval_stack.pop(0), total, token)
else:
# Save the new operator to the evaluation stack
eval_stack.insert(0, token)
# Done! Provide the equation's value
return total
# If running standalone pass the first command line parameter as
# an expression and print the result. Example:
# python prefix.py "+ / 6 2 3 - 6"
if __name__ == '__main__':
print calculate( sys.argv[1] )
I like MAK's recursive function too.
Reverse the tokens and use a stack machine like the following:
def prefix_eval(tokens):
stack = []
for t in reversed(tokens):
if t == '+': stack[-2:] = [stack[-1] + stack[-2]]
elif t == '-': stack[-2:] = [stack[-1] - stack[-2]]
elif t == '*': stack[-2:] = [stack[-1] * stack[-2]]
elif t == '/': stack[-2:] = [stack[-1] / stack[-2]]
else: stack.append(t)
assert len(stack) == 1, 'Malformed expression'
return stack[0]
>>> prefix_eval(['+', 2, 2])
4
>>> prefix_eval(['-', '*', 3, 7, '/', 20, 4])
16
Note that stack[-1] and stack[-2] are reversed with respect to a normal stack machine. This is to accommodate the fact that it's really a prefix notation in reverse.
I should explain the several Python idioms I've used:
stack = []: There is no built-in stack object in Python, but lists are easily conscripted for the same purpose.
stack[-1] and stack[-2]: Python supports negative indices. stack[-2] refers to the second-last element of the list.
stack[-2:] = ...: This assignment combines two idioms in addition to negative indexing:
Slicing: A[x:y] refers to all the elements of A from x to y, including x but excluding y (e.g., A[3:5] refers to elements 3 and 4). An omitted number implies either the start or the end of the list. Therefore, stack[-2:] refers to every element from the second-last to the end of the list, i.e., the last two elements.
Slice assignment: Python allows you to assign to a slice, which has the effect of splicing a new list in place of the elements referred to by the slice.
Putting it all together, stack[-2:] = [stack[-1] + stack[-2]] adds together the last two elements of the stack, creates a single-element list from the sum, and assigns this list to the slice comprising the two numbers. The net effect is to replace the two topmost numbers on the stack with their sum.
If you want to start with a string, a simple front-end parser will do the trick:
def string_eval(expr):
import re
return prefix_eval([t if t in '+-*/' else int(t)
for t in re.split(r'\s+', expr)])
>>> string_eval('/ 15 - 6 3')
5
Here is example with lambda functions
ops = {
"+": (lambda a, b: a + b),
"-": (lambda a, b: a - b),
"*": (lambda a, b: a * b),
"/": (lambda a, b: a / b)
}
def eval(expression):
tokens = expression.split()
stack = []
for token in tokens:
if token in ops:
arg2 = stack.pop()
arg1 = stack.pop()
result = ops[token](arg1, arg2)
stack.append(result)
else:
stack.append(int(token))
return stack.pop()
regex that ish:
import re
prefix_re = re.compile(r"(+|-|*|/)\s+(\d+)\s+(\d+)")
for line in get_lines_to_parse():
match = prefix_re.match(line)
if match:
operand = match.group(1)
if operand == '+':
return int(match.group(2))+int(match.group(3))
elif operand == '-':
return int(match.group(2))-int(match.group(3))
#etc...
Based on other answers, but with less logic.
import operator
def eval_prefix(tokens):
operators = {'+': operator.add, '-': operator.sub, '/': operator.truediv,
'*': operator.mul, '%': operator.mod}
stack = []
for i in reversed(tokens):
if i in operators:
stack[-2] = operators[i](int(stack[-1]), int(stack[-2]))
del stack[-1]
else:
stack.append(i)
return stack[0]
This is another way to do it. I have added an "#" switcher on a, b, and c that returns b if a is positive and returns c if a is negative. I know it is a bit lengthy and inefficient but I wanted it to be universal for all operations.
def operatorhelper(index, answer):
del currentsplitline[index + 2]
del currentsplitline[index + 1]
del currentsplitline[index]
currentsplitline.insert(index, answer)
infilelines = ["+ 2 3", " - 3 2", "* 2 3", "# 1 3 4"]
for line in infilelines:
currentsplitline = line.split(" ")
for i in range(len(currentsplitline)):
try:
currentsplitline[i] = int(currentsplitline[i])
except:
continue
operatorindexes = [int(i) for i,x in enumerate(currentsplitline) if not type(x) == int]
operatorindexes = operatorindexes[::-1]
for index in operatorindexes:
answer = 0
if(isinstance(currentsplitline[index + 1], int) and isinstance(currentsplitline[index + 2], int)):
operator = currentsplitline[index]
nextnum = currentsplitline[index + 1]
secondnum = currentsplitline[index + 2]
if(operator == "+"):
answer = nextnum + secondnum
operatorhelper(index, answer)
elif(operator == "-"):
answer = nextnum - secondnum
operatorhelper(index, answer)
elif(operator == "*"):
answer = nextnum * secondnum
operatorhelper(index, answer)
elif(operator == "#"):
if(isinstance(currentsplitline[index + 3], int)):
thirdnum = currentsplitline[index + 3]
del currentsplitline[index + 3]
if(nextnum >= 0):
answer = secondnum
else:
answer = thirdnum
operatorhelper(index, answer)
print(currentsplitline[0])
def prefix(input):
op, num1, num2 = input.split(" ")
num1 = int(num1)
num2 = int(num2)
if op == "+":
return num1 + num2
elif op == "*":
return num1 * num2
else:
# handle invalid op
return 0
print prefix("+ 2 2")
prints 4, also included a multiplication operator just to show how to expand it.

Categories

Resources