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
Related
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))
I need to compare 2 numbers,
if they have the same sign (positive or negative), print "same sign".
If they have a different sign, print "different sign"
The catch is, I need to do it without the use of < or > (greater than or less than) and only using addition and subtraction of num1 and num2. You can also use 0 (no other numbers).
Here is what it looks like with the <>s:
num1 = int(input("enter num1: "))
num2 = int(input("enter num2: "))
if num1 < 0 and num2 < 0: print("same sign")
if num1 > 0 and num2 > 0: print("same sign")
if num1 > 0 and num2 < 0: print("different sign")
if num1 < 0 and num2 > 0: print("different sign")
You can check whether two numbers x and y have the same sign by validating the following:
same_sign = abs(x) + abs(y) == abs(x + y)
Well, mb not the prettiest solution, but have a check
#!/usr/bin/env python3
num1 = 10
num2 = 2
if ((num1 & 0x800000) == (num2 & 0x800000)):
print('same sign')
else:
print('different sign')
the trick here, that int type in Python takes 24 bits = 3 bytes. Signed types have 1 in the most significant position. 0x800000 = 1000 0000 0000 0000 0000 0000b. If both nums have this bit - same sign, otherwise - different.
A little late here, but this is what I figured out.
def sameSign(x, y)
if (x*y > 0):
print("same sign")
else:
print("different sign")
Negative times negative and positive time positive both always give positive. Negative time positive gives negative. If you pass in zero, you always get false, so you could add a check.
You can use subtract the number by itself and if the result equal to zero in the two numbers or non equal to zero is the two numbers then it is the same sign, else different sign, here is the code:
num1 = int(input("enter num1: "))
num2 = int(input("enter num2: "))
if num1 + 0 - num1 == 0 and num2 + 0 - num2 == 0: print("same sign") # +
elif num1 + 0 - num1 != 0 and num2 + 0 - num2 != 0: print("same sign") # -
else: print("different sign")
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
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
So I'm trying to solve a puzzle and I came across this code. I can't figure out what the output would be and any attempts to run it result in a "reached the maximum amount of recursion" error. Sorry in advance for the goofy variable names.
How can I modify this to achieve the same output, without the recursion error? The initial numbers I'm passing are 13379446(arg 1) and 5(arg 2).
import sys
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
def doot(num1, num2):
print num1
print num2
doritos = 0
if num2 > num1:
pass
else:
if num2 == 0:
print "if"
doritos = 1
else:
if num2 == num1:
doritos = 1
else:
wew = doot(num1 - 1, num2 - 1)
doritos = wew
wew = doot(num1 -1, num2)
doritos = doritos + wew
print doritos
Let me get you started. I'm assuming that doritos is supposed to be the return value, that is, that the code should say return dortitos instead of print doritos. Also, I'm completely ignoring the line print if.
Now what do we know? Looking at the code we see that
doot(x,y) = 0 if y > x
doot(x,0) = 1
doot(x,x) = 1 and
doot(x,y) = doot(x-1,y-1) + doot(x-1,y) otherwise
So we want to figure out the value of doot(x+h,x) where h > 0. Start with the simplest case, h=1. We already know that doot(1,0)=1, so
doot(2,1) = doot(1,0)+doot(1,1) = 1+1 = 2
doot(3,2) = doot(2,1)+doot(2,2) = 2+1 = 3
and now it's easy to guess that
doot(x+1,x)=x+1 for all x>= 0.
t's also easy to prove this by induction, if you're so inclined.
So now, work out some examples when h=2, and figure out the formula for doot(x+2,x). Then figure out the formula for doot(x+3,x) and so on, until you're ready to guess the the formula for doot(x+h,x)
Okay, I overhauled your code to use a dictionary (values) and a queue.
import sys
num1 = int(raw_input("num1: "))
num2 = int(raw_input("num2: "))
def doot(num1, num2):
print num1
print num2
doritos = 0
n1 = num1
n2 = num2
values = {}
queue = [(num1,num2)]
while queue:
num1,num2 = queue.pop()
#print queue
#print values
if (num1,num2) not in values:
if num1 >= num2:
if num2 == 0:
#print "if"
#doritos = 1
values[(num1,num2)] = 1
else:
if num2 == num1:
#doritos = 1
values[(num1,num2)] = 1
else:
#wew = doot(num1 - 1, num2 - 1)
#doritos = wew
#wew = doot(num1 -1, num2)
#doritos = doritos + wew
if (num1-1,num2-1) in values and (num1-1,num2) in values:
values[(num1,num2)] = values[(num1-1,num2-1)] + values[(num1-1,num2)]
else:
queue.append((num1,num2))
if (num1-1,num2) not in values:
queue.append((num1-1,num2))
if (num1-1,num2-1) not in values:
queue.append((num1-1,num2-1))
#print values
doritos = values[(n1,n2)]
print doritos
return doritos
doot(num1,num2)
In essence, I use the queue to keep track of the sums I don't have yet. If both of the descendants of (num1,num2) are in the dictionary, then I put it in the dictionary with the sum of their values. Otherwise, I put either or both descendant that's not in the dictionary on the queue along with itself. The other times that I don't put (num1,num2) back on the queue are when num1 == num2 or num2 == 0, in which cases I put them in the dictionary with value 1. At the end, I return the value in the dictionary that corresponds to the original inputted numbers.
Now, a word of caution: this code is horribly inefficient. I just had to reboot my computer because I tried the inputs you gave in the question, and it gobbled up all of the available RAM. So, you should instead consider what exactly is being done with the recursion, and figure out how to work forwards from the base cases instead of backwards from the input. That task, I will leave to you.
Your code is a recursive implementation of a combination function, which calculates the number of combinations of k distinct elements that can be drawn from a set of n elements.
A tidied up version of your function would look like this (note I have removed all the print statements and ensured that the function returns something - otherwise it won't work at all).
def doot(n, k):
if n < k:
return 0
if k == 0 or n == k:
return 1
return doot(n - 1, k - 1) + doot(n - 1, k)
This works fine for small values of n and k. A faster version that doesn't rely on recursion uses factorials, as shown in this answer.
import math
def nCr(n, r):
f = math.factorial
return f(n) / f(r) / f(n - r)
However, calculating the factorial of 13379446 still takes a long time and may not be accurate because the result is so huge. My system hangs when I try it. The other answer to the same question appears to work better.