Python Random Equations - python

Write a function called random_equation that takes as input a single parameter, the number of operators to generate in the random equation, and returns a string representing a random math equation involving the numbers 1-10 and operators +, -, *.
def random_equation(num):
result = ""
for i in range (num):
number = random.randint(1, 10)
if number == 1:
num_gen = (" 1 ")
elif number == 2:
num_gen = (" 2 ")
elif number == 3:
num_gen = (" 3 ")
elif number == 4:
num_gen = (" 4 ")
elif number == 5:
num_gen = (" 5 ")
elif number == 6:
num_gen = (" 6 ")
elif number == 7:
num_gen = (" 7 ")
elif number == 8:
num_gen = (" 8 ")
elif number == 9:
num_gen = (" 9 ")
else:
num_gen = (" 10 ")
operator = random.randint(1,4)
if operator == 1:
op_gen = (" + ")
elif operator == 2:
op_gen = (" - ")
else:
op_gen = (" * ")
math = result + num_gen + op_gen
I don't really know where to put the [i] to get it to repeat the loop since number is an integer and num_gen is the result

There are several issues here.
Your math gets replaced every time (e.g. "" + " 2 " + " - "), thus you never get to build longer sequences. You want to make result longer in each iteration: result = result + num_gen + op_gen, instead of always creating a new math with an empty result.
You never return anything. You will want to return result when the loop is finished.
You are now generating num numbers and num operators; that will produce equations like 1 + 3 *, which are a bit unbalanced. You will want to put only num - 1 pairs, and then one more number.
There are easier ways to make a string out of a number; str(num) will do what you do in twenty lines, just without the spaces.
With operator from 1 to 4, you will be generating as many * as you do + and - combined. Intentional?

import random
question = str(random.randint(-10,100)) + random.choice(op) + str(random.randint(-10,100)) + random.choice(op) + str(random.randint(-10,100))
q_formatted = question.replace('÷','/').replace('×', '*')
answer = eval(q_formatted)
print(answer)

Related

Let py know that (input1) == (input2)

I want to let my script stop, first I ask when I want to stop it:
length = input("how many times " + str(num1) + str(" do you want to see?"))
(E.G. I say ‘3’ the length should be 3)
Then I want to ‘ask’ if length is the same as where it must be when it should finish:
if length == times (times is where my script is ATM)
This doesn’t work, but if I set times to a number it does work…
Even when I print both of them (print (times, length)) it shows the same (3, 3) in my console, but it doesn’t do something… this is my script:
length = input("how many times " + str(num1) + str(" do you want to see?"))
print("starting!")
time.sleep(2)
ORnum1 = num1
times = 1
while CalcMeth == "repeat":
if C == "Yes":
print(times, "times", ORnum1, "=", num1)
num1 = num1 + ORnum1
if length == times:
C = "no"
print("Reached End, stopping.")
else:
time.sleep(num2)
times = times + 1
elif C == "no":
time.sleep(2)
print ("stopped!")
sys.exit()
if length == times:
here in your code length is in str and times is in integer.
length = int(input("how many times " + str(num1) +" do you want to see?))

Why is function getting called without calling it in Python? [duplicate]

This question already has answers here:
mapping functions in dict
(3 answers)
Python Argument Binders
(7 answers)
Closed 1 year ago.
Below is my Code:
def addition(values):
total = 0
for i in values:
total = total + i
return total
def substract(values):
total = values[0]
print(total)
for i in range(1,len(values)):
total = total - values[i]
print(total)
return total
print("Welcome to this code")
print("This code is a simple calculator")
print("--------------------------------")
print("Please select any one")
print("1) Addition\n2) Substraction\n3) Multiplication\n4) Division\n5) Modulation")
choice = -1
while choice < 1 or choice > 5:
try:
choice = int(input("Enter your choice: "))
if choice < 1 or choice > 5:
print("Please enter value between 1 to 5")
except:
print("Enter valid input!")
option = ["Addition", "Substraction", "Multiplication", "Division", "Modulation"]
optionalias = ["add", "subtract", "multiply", "divide", "modulate"]
#print(choice)
#print("You selected " + option[choice-1])
while True:
values = list(map(float, input("Enter values to " + optionalias[choice - 1] + " separated by comma ',': ").split(',')))
if len(values) < 2:
print("Enter atleast 2 values to perform ", option[choice - 1])
continue
if (choice == 4 or choice == 5):
if len(values) > 2:
print("Please enter exactly 2 values for Division/Modulation")
continue
if values[1] == 0:
print("Divisor cannot be Zero (0) !! Please Try again!")
continue
break
operation = {
1: addition(values),
2: substract(values)
}
total = operation.get(choice)
print("Your total is ", str(total))
Please see the result below
result
I selected choice as 1, thus my code should only execute the addition function. But this code is executing even the substraction function as given above in my result. Can someone explain if I am missing something?
operation = {
1: addition(values),
2: substract(values)
}
is defining a dict where the values are the result of calling addition and substract (note: the correct spelling is subtract, no second s). You need to make the values functions to call, not the result of called functions, e.g.:
operation = {
1: addition, # No call parentheses, so it stores the function itself
2: substract
}
total = operation[choice](values) # Look up the function to call and call it

check if a number combination is found in a list of combinations

I am creating a program in Python simulating multiplication flash cards. I've gotten pretty far but I can't figure out how to not repeat combinations of numbers. How do I check if a pair of numbers has already been presented?
from __future__ import division
from itertools import combinations
import random
amountCorrect = 0
amountMissed = 0
comb = combinations([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], 2)
print("Type 0 at any time to exit and see your score.")
while True:
firstNumber = random.randint(1,12)
secondNumber = random.randint(1,12)
ans = int(input("What is " + str(firstNumber) + " x " + str(secondNumber) + ": "))
if ans == 0:
break
elif ans == firstNumber * secondNumber:
amountCorrect += 1
else:
amountMissed += 1
totalProblems = amountCorrect + amountMissed
percentCorrect = amountCorrect/totalProblems
if .9 < percentCorrect <= 1:
print("Great job, you are doing awesome!")
elif .7 <= percentCorrect <= .89:
print("You are doing well,keep it up.")
elif .5 <= percentCorrect <= .69:
print("You are half way to becoming a master.")
else:
print("Keeping practicing, you will be a master one day.")
In short, use a set to store the pairs of numbers you have already used. Here is some code. You never use combinations in your code so I removed it.
from __future__ import division
import random
amountCorrect = 0
amountMissed = 0
highestNumber = 12
print("Type 0 at any time to exit and see your score.")
used = set()
while True:
if len(used) == highestNumber ** 2:
break
while True:
firstNumber = random.randint(1,highestNumber)
secondNumber = random.randint(1,highestNumber)
pair = (firstNumber, secondNumber)
if pair not in used:
used.add(pair)
break
ans = int(input("What is " + str(firstNumber) + " x " + str(secondNumber) + ": "))
if ans == 0:
break
elif ans == firstNumber * secondNumber:
amountCorrect += 1
else:
amountMissed += 1
totalProblems = amountCorrect + amountMissed
percentCorrect = amountCorrect/totalProblems
if .9 < percentCorrect <= 1:
print("Great job, you are doing awesome!")
elif .7 <= percentCorrect <= .89:
print("You are doing well,keep it up.")
elif .5 <= percentCorrect <= .69:
print("You are half way to becoming a master.")
else:
print("Keeping practicing, you will be a master one day.")
I just created an empty set called used, and added a new inner loop. That loop test if the pair of numbers has already been used. If so, it just loops again and tries a new pair of numbers. I also added a variable to store the highest possible number, and test of the used set is full. I end the quiz if it is full. Without this, when all possibilities are tried the program will go into an infinite loop.
Note that this code will allow both 1,2 and 2,1. If you want to allow only one of those, add both (firstNumber, secondNumber) and (secondNumber, firstNumber) to the used set.

Python - Error when correct answer is inputted

When I choose question 3, even I do put in the right answer(value_c * value_d, it tells me that it is incorrect. Help?
import random
value_a = random.randint(100, 999)
value_b = random.randint(100, 999)
value_c = random.randint(21, 89)
value_d = random.randint(21, 89)
value_e = random.randint(81, 100)
value_f = random.randint(81, 100)
print('''Straight to the point. Pick an option.
1. 2 numbers with 3-digit values added.")
2. 2 numbers with 3-digit values added and then multiplied by 2.
3. 2 numbers with 2-digit values and less than 89 multiplied.
4. 2 numbers with 2-digit values and between 80 and 100 multiplied.
5. 3 random numbers added or subtracted.''')
question = int(input("Choose the type of question you want: "))
print("\n")
if question == 1:
answer = int(input(str(value_a) + " + " + str(value_b) + " : "))
if answer == value_a + value_b:
print("Dayum quicc mafs, trie again if yu wand.")
else:
print("Bed mafs.")
elif question == 2:
answer = int(input( "(" + str(value_a) + "+" + str(value_b) + ")"+ "*2" + " : "))
if answer == 2*(value_a + value_b):
print("Dayum quicc mafs.")
else:
print("Bed mafs, trie again.")
this is the part where my answer never seems to be right:
elif question == 3:
answer == int(input(str(value_c) + " * " + str(value_d) + " : "))
print(value_c, value_d)
if answer == value_c * value_d:
print("Dayum quicc mafs.")
else:
print("Bed mafs, trie again.")
In Python, a single = means assignment. You used a double == which is an equality operator. Don't confuse the two, since the answer is not being assigned. Below I have changed the == to =.
elif question == 3:
answer = int(input(str(value_c) + " * " + str(value_d) + " : "))
print(value_c, value_d)
if answer == (value_c * value_d):
print("Dayum quicc mafs.")
else:
print("Bed mafs, trie again.")

Creating a triangle of characters from a users input

For an assignment I'm suppose to make a triangle using the users input if the characters are equal to an even number. The triangle is suppose to print up to 5 lines in height and the left of it should be the left half of the string and the right side of the triangle should be the right side of the string.
Example of what the triangle is suppose to look like
The problem is I can't figure out how to divide my triangle in half without hard coding it or how to properly display the white space without a loop (were not allowed to in the assignment). Right now if I were to put in "ab" it would return:
aabb
aabbaabb
aabbaabbaabb
aabbaabbaabbaabb
aabbaabbaabbaabbaabb
Instead of:
aabb
aaaabbbb
aaaaaabbbbbb
aaaaaaaabbbbbbbb
aaaaaaaaaabbbbbbbbbb
Here's my code:
#GET Users String
userString = input("Please enter a string with a value of 7 or less characters: ")
#CALCULATE IF userString is less than or equal to 7 and is even
if len(userString) <= 7 and len(userString) % 2 == 0:
print (" " * 5 + userString)
print(" " * 4 + userString * 2)
print(" " * 3 + userString * 3)
print(" " * 2 + userString * 4)
print(" " + userString * 5)
#CALCULATE IF userString is less than 7 but and off
elif len(userString) <=7 and len(userString) % 2 == 1:
print("You are odd")
#CALCULATE IF userString is over 7 characters
else:
print ('The string is too long. \nGood-bye!')
Here's how you can do this:
def print_next(st, index):
if index < 6: # have not reached 5 - print offset and string
offset = 6-index
print ' '*offset+st
index=index+1 # increase counter
print_next((st[0:2]+st[-2:len(st)])*index,index) # recursively go next
print_next('aabb',1) # initial call with index set to 1
I think you can use a stack to save each line so you can easily get a triangle-like output. Also because you can't use loop so my suggestion would be recursive.
public_stack = []
def my_func(original_str, line_count, space_num):
if(line_count == 0):
return
times = line_count * 2
half_length = len(original_str) / 2
left_str = original_str[:half_length] * times
right_str = original_str[half_length:] * times
space_str = ' ' * space_num
complete_str = space_str + left_str + right_str
global public_stack
public_stack.append(complete_str)
space_num += len(original_str)
line_count -= 1
return my_func(original_str,line_count,space_num)
if __name__ == '__main__':
original_str = 'ab'
line_count = 5
space_num = 0
my_func(original_str,line_count,space_num)
global public_stack
for i in range(len(public_stack)):
line = public_stack.pop()
print line

Categories