making a basic multiplication program in python - python

The goal of the program is for it to multiply two random numbers less than 12 and for the user to guess the answer. So far i have this . . .
import random
g=0
while g<10:
variable_1 = random.randint (0,13)
variable_2 = random.randint (0,13)
answer = variable_1 * variable_2
guess = input("What is 'variable_1' x 'variable_2'?")
if guess == answer:
print "Correct!"
else:
print "Incorrect!"
The problem is the input box literally says "What is Variable_1 x Variable_2?". But, i want it to have the value of the variables in the input box. Is there a way to do this?

Try this instead:
guess = input("What is %d x %d?" % (variable_1, variable_2))

querystr="What is "+str(variable_1)+" x "+str(variable_2)+"?";
Then you can
guess=input(querystr);

from random import randint
def val(lo=1, hi=12):
return randint(lo, hi)
def main():
right = 0
reps = 10
for rep in range(reps):
v1, v2 = val(), val()
target = v1 * v2
guess = int(raw_input("What is {} * {}?".format(v1, v2)))
if guess==target:
print("Very good!")
right += 1
else:
print("Sorry - it was {}".format(target))
print("You got {} / {} correct.".format(right, reps))

Related

Better way to code this ? Set multiple variables as values for one str(key) in a dictionary

I wrote the following function. The output values should be used as part of parameters in a api request
def zeitraum():
x = input("How many month? Choose between 1 and 24 \n")
y = []
z = {'a string key':y}
for i in range(1,int(x)+1):
if int(x) > 24:
x = input("Choose between 1 and 24. \n")
if i <= 12:
x = f'year1month{i}'
y.append(x)
else:
x = f'year2month{i-12}'
y.append(x)
return z
d = zeitraum()
print (d)
** Output **
How many month? Choose between 1 and 24
13
{'a string key': ['year1month1', 'year1month2', 'year1month3', 'year1month4', 'year1month5', 'year1month6', 'year1month7', 'year1month8', 'year1month9', 'year1month10', 'year1month11', 'year1month12', 'year2month1']}
Is there a better way to code this?
EDIT: With Yevhens,VPfB and zwers comments I rewrote the code:
def zeitraum():
while True:
x = input("How many month? Choose between 1 and 24 \n")
if 1 <= int(x) <= 24:
break
else:
print ("Wrong input! \n")
return {'a key': [f"year{m//12+1}month{m%12+1}" for m in range(int(x))]}
I'm posting just the core
This will work for any positive integer x:
return {'a key': [f"year{m//12+1}month{m%12+1}" for m in range(x)]}
You can greatly simplify this by generating the whole list in one go, something like:
def zeitraum():
x = input("How many months? Choose between 1 and 24 \n")
y = ['year{}month{}'.format(m // 12 + 1, m % 12 + 1) for m in range(int(x))]
z = {'a string key': y}
return z
You don't even need to limit it to just 24 months—integer division with 12 will always return the year number and modulo with 12 will always give you the exact month of the year.

Which data structure to store inputted numbers?

Which data structure is best for calculating average of inputted numbers ?
I used an array, but it feels clumsy.
Is there a more standard way to do this?
import os
def getGrades():
g = input("How many tests?")
numGrades = int(g)
grades = []*numGrades
for x in range(numGrades):
t = int(input("Enter Grade #" + str(x+1) + ": "))
grades.append(t)
avgGrades(grades)
def avgGrades(a):
total = 0
count = 0
for t in a:
total = total + t
count = count + 1
avg = total / count
print (f"average is: {avg}")
getGrades()
There is a statistics module which you can use:
import statistics
def get_grades_avg():
g = input("How many tests?")
num_grades = int(g)
grades = [] * num_grades
for x in range(num_grades):
grades.append(int(input("Enter Grade #" + str(x + 1) + ": ")))
return statistics.mean(grades)
avg = get_grades_avg()
print('avg: {}'.format(avg))
Using Python list is well. Maybe trying some built-in functions for getting average grade would be more easily.
Assume grades is a list store some grade.
sum(grades) / len(grades)
You can use something like this:
def average_factory():
count_numbers = 0
sum_numbers = 0
def wrapper(number):
nonlocal count_numbers
nonlocal sum_numbers
sum_numbers += number
count_numbers += 1
return sum_numbers / count_numbers
return wrapper
def get_number(message):
str_number = input(message)
try:
return int(str_number)
except (ValueError, TypeError):
print('Invalid number, please try again')
return get_number(message)
def get_average_of_all_tests():
count_tests = get_number('How many tests? ')
get_average = average_factory()
average = 0
for test_number in range(1, count_tests + 1):
number = get_number('Enter Grade #{test_number}: '.format(test_number=test_number))
average = get_average(number)
return average
Yes this solution seems a little complex with average factory. But I think storing all value just for calculating average is not so good idea. Storing only count and sum of grades is better.
If you have any question about solution feel free to ask me about it.
numpy or scipy offer good facilities for this.
store your numbers in an numpy.array([]).
To obtain your mean, numpy.mean(<yourarray>)
Your code would look like:
import numpy
import os
def getGrades():
g = input("How many tests?")
numGrades = int(g)
grades = []*numGrades
for x in range(numGrades):
t = int(input("Enter Grade #" + str(x+1) + ": "))
grades.append(t)
yourArray = numpy.array(grades)
return numpy.mean(yourArray)

How can I iterate through a list of letters to assign float values to create a polynomial?

I am trying to integrate a polynomial function via the Trapezoidal Method (I can change to a more accurate method later). My code isn't perfect, and I'd like to understand exactly why it doesn't work. One problem I have is that the while loop does not end. My code thus far is as follows.
def Integrate_Trapezoidal(x_LoBound,x_HiBound,N):
"""
INPUT :
x_LoBound -- lower bound of integral
x_HiBound -- upper bound of integral
N -- number of slices (N --> inf ==> integral)
OUTPUT :
-- approximate value of integral
"""
## CREATE ALPHABET
alphabet = [chr(i) for i in range(ord('a'),ord('z')+1)]
## alphabet = ['a','b','c',...,'z'] ##
## WOULD LOVE TO TRY FLOATING INPUTS VIA ARRAY COMPREHENSION
a = float(input("What is the coefficient of the lowest order term: "))
CoeffList = []
CoeffNumList = []
LengthCoeffList = [] ## [1,2,3,...,max] where max = coefficient of highest-order term
for letter in alphabet:
AddOne = int(1)
AddOne += int(1)
for i in range(int(1),int(AddOne)):
letter = alphabet[int(i)]
while letter in alphabet:
CoeffList.append(letter)
LengthCoeffList.append(len(CoeffList))
# alphabet[i]
# i = i + 1
letter = float(input("What is the coefficient of the next-order term: ")) ## GO FROM a = ___ TO b = ___ TO c = ___ ...
CoeffNumList.append(letter)
if float(input("What is the coefficient of the next-order term: ")) == '0':
print("Type 'Y for YES and 'N' for NO")
YESorNO = str(input("Is that the last term of the polynomial: "))
endterm = YESorNO[-1] ## look at last character of string
if endterm == 'N' or endterm == 'n' or endterm == 'no' or endterm == 'NO' or endterm == 'No':
pass
elif endterm == 'Y' or endterm == 'y' or endterm == 'YES' or endterm == 'yes' or endterm == 'Yes':
break
def f(x):
"""
INPUT :
x -- variable of function
EX: x = x_LoBound OR x = x_HiBound
OUTPUT :
function -- f(x) = a x^0 + b x^1 + ...
EX: f(x_LoBound) OR f(x_HiBound)
"""
for expval in LengthCoeffList and CoeffNum in CoeffNumList:
# function = 0
function += CoeffNum * x**expval
return function
letter = alphabet[int(i+1)] ## GO FROM a TO b TO c ...
## TRAPEZOIDAL RULE
# def f(x):
# return x**4 - 2*x + 1
ht = (x_HiBound - x_LoBound) / N
ss = 0.5 * f(x_LoBound) + 0.5 * f(x_HiBound)
for num in range(1,N):
ss += f(x_LoBound + num*ht)
return ht*ss
checkanswer = Integrate_Trapezoidal(0,2,10)
print(checkanswer)
I've had a go at looking over your code and found something that I think works, checking against a couple of college handouts I downloaded. As you have said in the comments, there were a lot of extra lists which aren't necessary, so I've cut back the code a lot there.
In particular, if the presumption if that each coefficient is added in sequence from lowest to highest order, and 0 is added for any that aren't there, all you need is the number of the element in the list to know the power of x.
I also moved the definition of f() to create the helper function solve_point() which works the same I think. In particular, sum and enumerate are built in, with enumerate iterating through coeff_list and also returning a count to give the power (0 upwards).
get_coefficients() was from your old Integrate_Trapezoidal() but more focused on just one thing - which is why it then returns CoeffList to be finally processed at the end.
def solve_point(x, coeff_list):
return sum(coeff * x**e for e, coeff in enumerate(coeff_list))
def get_coefficients():
CoeffList = []
while True:
# GO FROM a = ___ TO b = ___ TO c = ___ ...
coeff = float(input("What is the coefficient of the next-order term: "))
CoeffList.append(coeff)
if coeff == 0:
YESorNO = raw_input("Is that the last term of the polynomial: [Y/N] ")
if YESorNO.upper() == 'Y':
return CoeffList[:-1]
lo, hi, n = 0, 2, 6
coeff_list = get_coefficients()
ht = (hi - lo) / float(n)
ss = 0.5 * solve_point(lo, coeff_list) + 0.5 * solve_point(hi, coeff_list)
for num in range(1,n):
ss += solve_point(lo + num*ht, coeff_list)
checkanswer = ht*ss
print(checkanswer)
I think its right - I have done a couple of checks. Hopefully it may be of help for your rewrite! If you have any examples that don't work, it would be good to know, or any errors you can see...

How to reverse an int in python?

I'm creating a python script which prints out the whole song of '99 bottles of beer', but reversed. The only thing I cannot reverse is the numbers, being integers, not strings.
This is my full script,
def reverse(str):
return str[::-1]
def plural(word, b):
if b != 1:
return word + 's'
else:
return word
def line(b, ending):
print b or reverse('No more'), plural(reverse('bottle'), b), reverse(ending)
for i in range(99, 0, -1):
line(i, "of beer on the wall")
line(i, "of beer"
print reverse("Take one down, pass it around")
line(i-1, "of beer on the wall \n")
I understand my reverse function takes a string as an argument, however I do not know how to take in an integer, or , how to reverse the integer later on in the script.
Without converting the number to a string:
def reverse_number(n):
r = 0
while n > 0:
r *= 10
r += n % 10
n /= 10
return r
print(reverse_number(123))
You are approaching this in quite an odd way. You already have a reversing function, so why not make line just build the line the normal way around?
def line(bottles, ending):
return "{0} {1} {2}".format(bottles,
plural("bottle", bottles),
ending)
Which runs like:
>>> line(49, "of beer on the wall")
'49 bottles of beer on the wall'
Then pass the result to reverse:
>>> reverse(line(49, "of beer on the wall"))
'llaw eht no reeb fo selttob 94'
This makes it much easier to test each part of the code separately and see what's going on when you put it all together.
Something like this?
>>> x = 123
>>> str(x)
'123'
>>> str(x)[::-1]
'321'
best way is
x=12345
a=str(x)[::-1]\\ In this process i have create string of inverse of integer (a="54321")
a=int(a) \\ Here i have converted string a in integer
or
one line code is
a=int(str(x)[::-1]))
def reverse(x):
re = 0
negative = x < 0
MAX_BIG = 2 ** 31 -1
MIN_BIG = -2 ** 31
x = abs(x)
while x != 0:
a = int(x % 10)
re = re * 10 + a
x = int(x // 10)
reverse = -1 * re if negative else re
return 0 if reverse < MIN_BIG or reverse > MAX_BIG else reverse
this is for 32 - bit integer ( -2^31 ; 2^31-1 )
def reverse_number(n):
r = 0
while n > 0:
r = (r*10) + (n % 10)
print(r)
r *=10
n //= 10
return r
print(reverse_number(123))
You can cast an integer to string with str(i) and then use your reverse function.
The following line should do what you are looking for:
def line(b, ending):
print reverse(str(b)) or reverse('No more'), plural(reverse('bottle'),reverse(str(b))), reverse(ending)
Original number is taken in a
a = 123
We convert the int to string ,then reverse it and again convert in int and store reversed number in b
b = int("".join(reversed(str(a))))
Print the values of a and b
print(a,b)
def reverse_number(n):
r = 0
while n > 0:
r *= 10
r += n % 10
n /= 10
return r
print(reverse_number(123))
This code will not work if the number ends with zeros, example 100 and 1000 return 1
def reverse(num):
rev = 0
while(num != 0):
reminder = num % 10
rev = (rev * 10 ) + reminder
num = num // 10
print ("Reverse number is : " , rev )
num=input("enter number : ")
reverse(int(num))
#/ always results into float
#// division that results into whole number adjusted to the left in the number line
I think the following code should be good to reverse your positive integer.
You can use it as a function in your code.
n = input() # input is always taken as a string
rev = int(str(n)[::-1])
If you are having n as integer then you need to specify it as str here as shown. This is the quickest way to reverse a positive integer
import math
def Function(inputt):
a = 1
input2 = inputt
while(input2 > 9):
input2 = input2/10
a = a + 1
print("There are ", a, " numbers ")
N = 10
m = 1
print(" THe reverse numbers are: ")
for i in range(a):
l = (inputt%N)/m
print(math.floor(l), end = '')
N = N*10
m = m*10
print(" \n")
return 0
enter = int(input("Enter the number: "))
print(Function(enter))
More robust solution to handle negative numbers:
def reverse_integer(num):
sign = [1,-1][num < 0]
output = sign * int(str(abs(num))[::-1])
An easy and fast way to do it is as follows:
def reverse(x: int|str) -> int:
reverse_x = int(''.join([dgt for dgt in reversed(num:=str(x)) if dgt != '-']))
if '-' in num:
reverse_x = -reverse_x'
return reverse_x
First we create a list (using list comprehension) of the digits in reverse order. However, we must exclude the sign (otherwise the number would turn out like [3, 2, 1, -]). We now turn the list into a string using the ''.join() method.
Next we check if the original number had a negative sign in it. If it did, we would add a negative sign to reverse_x.
Easily you can write this class:
class reverse_number:
def __init__(self,rvs_num):
self.rvs_num = rvs_num
rvs_ed = int(str(rvs_num)[::-1])
print(rvs_ed)
You can use it by writing:
reverse_number(your number)
I have written it in a different way, but it works
def isPalindrome(x: int) -> bool:
if x<0:
return False
elif x<10:
return True
else:
rev=0
rem = x%10
quot = x//10
rev = rev*10+rem
while (quot>=10):
rem = quot%10
quot = quot//10
rev = rev*10+rem
rev = rev*10+quot
if rev==x:
return True
else:
return False
res=isPalindrome(1221)

Python. displaying items in a random order

I'm a beginner at python and i've got this code for a flash card game that I have wrote. The following code is only a small part of it.
remove = 0
while remove < 2:
a = random.choice(list(key))
if (a) == line27:
print(a)
x = input(random.choice(defi))
x = input(random.choice(defi))
x = input(line28)
if x == ('c'):
remove = remove + 1
print('you got it right')
score = (score + 1)
print('score =', score)
if x == ('b', 'a'):
print('thats wrong')
print()
t = t + 1
if remove == 2:
key.remove(line27)
I have to be able to display this :
x = input(random.choice(defi))
x = input(random.choice(defi))
x = input(line28)
in a random order every time it displays. so the two random choices have to display in different positions and so does the line 28.
the two random choices are in a list and the line 28 is in another list if that is any help.
Would something like this be sufficient? It seems like this is what you are asking for, but I don't really know...
def randomInput(list):
randIdx = random.randint(0, len(list)-1)
in = input(list[randIdx])
list.remove(randIdx)
return in, list
inputs = [random.choice(defi), random.choice(defi), line28]
x, inputs = randomInput(inputs)
x, inputs = randomInput(inputs)
x, inputs = randomInput(inputs)
Also, as Burhan Khalid said, x is never going to be equal to the tuple ('b', 'a')... I suppose what you meant was
x == 'b' or x == 'a'

Categories

Resources