python: comparing equivalent coordinates - python

I am doing a maths quiz for my coursework based around differentiation and integration using python 3. I'm finding it difficult to check if the answer, typed in by the user, is correct. I'm currently using the code below. However, if the user types in answer but in a different order it is treated as incorrect. for example if the answer was (2,4) but I typed in (4/2,4) it would be treated as incorrect despite both answers being correct. I've tried using sympify but it isnt working. How would I overcome this issue?
def Question4(self):
QID = 109
conn = mysql.connector.connect(user="root", password = "", host = "")
mycursor = conn.cursor()
#mysql query
query = """
SELECT
QText, QAnswer, Marks
FROM
QuestionInfo.Question
WHERE
QID = %s
"""
mycursor.execute(query, (QID, ))
Question4, Answer4, Mark4 = mycursor.fetchone()
self.Answer4 = str(Answer4)
self.Mark4 = Mark4
self.next_question.clicked.connect(self.HandleQuestion4)
def HandleQuestion4(self):
#for validation
reply = QtGui.QMessageBox.question(self, 'Message',
"Are you sure this is your final answer?", QtGui.QMessageBox.Yes |
QtGui.QMessageBox.No, QtGui.QMessageBox.Yes)
#get users answer in a sympy state
self.UAnswer4 = self.Answer.text().replace("^", "**")
if reply == QtGui.QMessageBox.Yes:
if sympify(self.UAnswer4) == sympify(self.Answer4):
self.score = self.score + self.Mark4
else:
self.score = self.score + 0
self.Question5()

If you are expecting only numbers then you can use S (short for sympify) on the string. Otherwise you might need parse_expr and/or other string processing to to handle additional syntax like implied multiplication and "^" for exponentiation (see sympy.parsing.sympy_parser):
>>> S('4/2,2')
(2, 2)

Related

Incorrect Number of bindings supplied error

def login():
loggedIn = False
userInput = input("please enter your username: ")
pwdInput = input("please enter your password: ")
searchUser = hashlib.md5(userInput.encode()).hexdigest()
searchPwd = hashlib.md5(pwdInput.encode()).hexdigest()
query = """SELECT * FROM Users
WHERE Username =?;"""
cursor.execute(query, searchUser)
record = cursor.fetchone()
if record:
print("found")
Sorry the indenting is bad but isn't in the actual thing
I have this code set up to take in inputs and then hash them, I want to search the table "Users" to find the "Username". But it keeps saying "Incorrect number of bindings supplied. The current statement uses 1 and there are 32 supplied.
I tried combining the query and variables into 1 line and it still didnt work
You need to provide a tuple (or other sequence) of query parameters, even if there's only one:
cursor.execute(query, (searchUser,))
By passing searchUser on its own, without wrapping it, you're telling the cursor to treat the individual characters of searchUser as separate query parameters.

MessageBox in DearPyGui

I am using the DearPyGui library for creating a user interface in python.
In a function that runs my algorithm, the algorithm needs some input from the user (yes/no question). Is it possible to easily implement such a messagebox in DearPyGui without braking the flow of the function?
Something like this:
def runAlgorithm():
a = 2 + 2
user_choice = dpg.messageBox("Do you want to add or subtract the values", ["add", "subtract"]
if user_choice == "add":
a = a + a
else:
a = a - a
print("The user has selected %s and the result is %d"%(user_choice, a)
As I understand DearPyGui until now, this is not possible and I have to write something like this, which is quite bulky and unreadable and especially in algorithms that might need some user input greatly disrupts their readability.
def choiceAdd(sender, app_data, user_data):
a = user_data[0]
print("The user has selected %s and the result is %d"%("add", a + a)
def choiceSub(sender, app_data, user_data):
a = user_data[0]
print("The user has selected %s and the result is %d"%("subtract", a - a)
def runAlgorithm():
a = 2 + 2
with dpg.window():
dpg.add_button("add", callback = choiceAdd, user_data = [a])
dpg.add_button("subtract", callback = choiceSub, user_data = [a]
user_choice = dpg.messageBox("Do you want to add or subtract the values", ["add", "subtract"]
if user_choice == "add":
a = a + a
else:
a = a - a
print("The user has selected %s and the result is %d"%(user_choice, a)
Any help is recommended.
Thank you in advance

If-Else statement not asking for input in Python

I am trying to write a basic Twitter scraper in Python and while I have it so that it can scrape for hard coded terms, I'm trying to set it to take the search term from user input.
While my if/else statement accepts input when asked, it then fails to run stating that rawinput is not defined. The rawinput is within the if statement I've included my code below
I should mention I'm fairly new to Python.
I've tried removing the rawinput from the if/else and kept it separate but the same issue happens.
userinp = input("Select search type. 1 = tweets. 2 = people")
if userinp == 1:
entry = rawinput
query = u'q='
elif userinp == 2:
entry = rawinput
query = u'f=users&vertical=default&q='
searchurl = baseurl + query + entry
The expected result is that the user selects option 1 or 2 then is asked to enter their search term.
Results are:
Select search type. 1 = tweets. 2 = people1
Traceback (most recent call last):
File "Scrape.py", line 22, in <module>
userentry = rawinput('enter search term')
NameError: name 'rawinput' is not defined
Thanks in advance for any help given.
Use input() instead and don't forget the parentheses!
Additionally, input() converts your input to a string, so your if condition will never be met if it uses integers. Consider replacing with if userinp == '1': and elif userinp == '2':.
It should be raw_input() not rawinput. so your code should be like this...
userinp = input("Select search type. 1 = tweets. 2 = people")
if userinp == 1:
entry = raw_input()
query = u'q='
elif userinp == 2:
entry = raw_input()
query = u'f=users&vertical=default&q='
searchurl = baseurl + query + entry

How to prevent printing from previous function in current function?

I'm currently writing a test function for class to test provided cases on provided solution code. However I'm running into an issue where a print statement is executing when I don't want it to.
This is the provided solution that I'm testing:
def alphapinDecode(tone):
phone_num = ''
if checkTone(tone): #or checkTone2
while len(tone) > 0:
# retrieve the first tone
next_tone = tone[0:2]
tone = tone[2:]
# find its position
cons = next_tone[0]
vow = next_tone[1]
num1 = consonants.find(cons)
num2 = vowels.find(vow)
# reconstruct this part of the number -
# multiply (was divided) and add back
# the remainder from the encryption division.
phone = (num1 * 5) + num2
# recreate the number
# by treating it as a string
phone = str(phone)
# if single digit, not leading digit, add 0
if len(phone) == 1 and phone_num != '':
phone = '0' + phone
phone_num = phone_num + phone
# but return in original format
phone_num = int(phone_num)
else:
print('Tone is not in correct format.')
phone_num = -1
return phone_num
Here's the (partially done) code for the test function I have written:
def test_decode(f):
testCases = (
('lo', 43),
('hi', 27),
('bomelela', 3464140),
('bomeluco', 3464408),
('', -1),
('abcd', -1),
('diju', 1234),
)
for i in range(len(testCases)):
if f(testCases[i][0]) == testCases[i][1] and testCases[i][1] == -1:
print('Checking '+ f.__name__ + '(' + testCases[i][0] + ')...Tone is not in correct format.')
print('Its value -1 is correct!')
return None
When executing test_decode(alphapinDecode), I get this:
Tone is not in correct format.
Checking alphapinDecode()...Tone is not in correct format.
Its value -1 is correct!
Tone is not in correct format.
Checking alphapinDecode(abcd)...Tone is not in correct format.
Its value -1 is correct!
As you can see, because of the print statement in alphapinDecode(I think), it is printing an extra "Tone is not in correct format." above the print statement I have written.
How would I prevent this print statement from executing, and why is it printing if the print statement I wrote in my test function doesn't ask for the result of alphapinDecode?
We are not allowed to alter the code of the given solution.
I'm fairly new to stackOverflow, so sorry for any formatting issues. Thank you!
Edit: Fixed the idents of the test_decode function
One easy solution would be to pass an extra parameter say, a boolean variable debug to the function. That would go something like this.
def func1(var1, debug):
if debug:
print("Printing from func1")
# Do additional stuff
Now when you call it. You now have the option of setting the debug variable.
func1("hello", debug=True) # will print the statement
func1("hello", debug=False) # will not print statement.
If you cannot modify the called function. Then you can follow this method. explained by #FakeRainBrigand here.
import sys, os
# Disable
def blockPrint():
sys.stdout = open(os.devnull, 'w')
# Restore
def enablePrint():
sys.stdout = sys.__stdout__
print 'This will print'
blockPrint()
print "This won't"
enablePrint()
print "This will too"

function not working using sql and tkinter (quiz)

On the function, confirmAnswer, it updates the question but doesn't display to the user whether their answer is correct or inccorrect which makes me think it is skipping straight to this line, if self.Qn < self.recordNum['text']: on the same function.
I only have two questions in the database at the moment allowing testing to be easier and when the question updates, the submit button doesnt work when an answer is inputted when really the quiz should end and display the score which is in the same function.
I included this much code as I thought it would make more sense to understand the code so sorry if it is too much and sorry if it comes across confusing. Thank you for your help!
def quiz(self):
self.newf.pack_forget()
self.head['text'] = 'Welcome to the psychology revision quiz'
self.quizf.pack()
self.quizScore = 0
self.correctAnswer = '' # <-- create it at start (and use better name)
self.Qn = 1
self.update_question()# <-- get new question
self.update_question_number()
def update_question_number(self):
# Get question's number
query = "SELECT MAX(qnumber) FROM questions"
c.execute(query)
row = c.fetchone()
self.recordNum['text'] = row[0]
def update_question(self):
# Get new question
query = "SELECT * FROM questions WHERE qnumber=?"
c.execute(query, (self.Qn,))
row = c.fetchone()
self.question['text'] = row[1]
self.answer1['text'] = row[2]
self.answer2['text'] = row[3]
self.answer3['text'] = row[4]
self.answer4['text'] = row[5]
self.correctAnswer = row[6]
def confirmAnswer(self):
self.rightOrWrong = self.enterAnswer
if self.enterAnswer == self.correctAnswer:
self.rightOrWrong['text'] = "Correct"
self.quizScore += 1
self.update_question()
else:
self.rightOrWrong['text'] = "Incorrect"
if self.Qn < self.recordNum['text']:
self.Qn += 1 # <-- get new question
self.update_question() # <-- get new question
else:
self.rightOrWrong['text'] = "Quiz Complete! Your score was: {}".format(self.quizScore)

Categories