I was making a class for logarithims of different bases and I noticed certain numbers like log(2) and log(4) were coming up as complex
class LogBaseN:
def __init__(self,base):
self.base = base
def __call__(self,x):
y,I = sp.symbols("y I")
self.x = x
if self.x == 1:
return 0
pass
if type(self.x) == int or type(self.x) == float:
ans = sp.solve(sp.Eq(self.base,self.x**(1/y)))[0]
try:
if int(ans) == float(ans):
return int(eval(str(ans)))
else:
return float(eval(str(ans)))
return ans
except:
return(eval(str(ans)))
if type(self.x) == list:
answers = []
for num in self.x:
i = num
if i == 1:
answers.append(0)
continue
ans = sp.solve(sp.Eq(self.base,i**(1/y)))[0]
try:
if int(ans) == float(ans):
answers.append(int(eval(str(ans))))
else:
answers.append(float(eval(str(ans))))
except:
answers.append(ans)
return answers
ln = LogBaseN(e)
log2 = LogBaseN(2)
Log = LogBaseN(10)
print(Log(4))
#Output log(2)/(3.14159265359*I + log(sqrt(10)))
I tried evaluating in by using str() then evaling using eval but that didnt fix it just to make it output I had to use sympy.symbols so the "I" would not cause an error
Related
My code for now works as desired where the user can input a level 1-3 depending on how hard they would like it to be (1-3 being the amount of digits the numbers will have in the math equation), and then must solve math equations. Those math equations will output EEE if the answer is incorrect and everything works as planned if you correctly answer the question as it exits the function and adds one total_correct_answers variable at the bottom, then will prompt you with another equation. However, if you input an incorrect answer and then a correct answer, you will just be prompted with the same question over and over again without the try loop being truly broken out of and total_correct_answers not being incremented positively by 1. The incrementation block of code is at lines 61-65, and the equation code is lines 30-49.
import random
def main():
ten_questions()
def get_level():
while True:
try:
level_input = int(input("Level: "))
if level_input in [1,2,3]:
return level_input
except:
pass
def integer_generator(level):
if level == 1:
x = random.randint(0,9)
y = random.randint(0,9)
elif level == 2:
x = random.randint(10, 99)
y = random.randint(10, 99)
else:
x = random.randint(100, 999)
y = random.randint(100, 999)
return x, y
def question_generator(x, y):
real_answer = x + y
wrong_counter = 0
while True:
try:
answer_given = input(str(x) + " + " + str(y) + " = ")
if int(answer_given) == real_answer:
if wrong_counter == 0:
return True
elif int(answer_given) == real_answer and wrong_counter != 0:
break
else:
while wrong_counter < 2:
print("EEE")
wrong_counter +=1
break
else:
print(str(x) + " + " + str(y) + " = " + str(real_answer))
print("False, that was last attempt")
break
except:
print("EEE")
pass
def ten_questions():
num_of_questions = 0
total_correct_answers = 1
my_level = get_level()
correct_answers = question_generator(*integer_generator(my_level))
while num_of_questions <= 8:
question_generator(*integer_generator(my_level))
num_of_questions +=1
if correct_answers == True:
total_correct_answers +=1
print("Score: " + str(total_correct_answers))
if __name__ == "__main__":
main()
Because of your line 36:
if int(answer_given) == real_answer: happens when someone answers correctly, wether they are right or wrong. So it enters the if, and then faces if wrong_counter == 0: which discards wrong answers. So just replace those two lines with if int(answer_given) == real_answer and wrong_counter == 0: and you are good to go.
I'm taking CS50 Introduction to Programming with Python. I have problem with PSet4 (Little Professor). I don't have any problem while running, but when check50 running it keeps giving this error: "Little Professor accepts valid level timed out while waiting for program to exit." While I’m manually running the program, it accepts any level value lower than 4. But the check50 says otherwise. Here is my code:
import random
def main():
try:
level = input("Level: ")
first, second = get_level(level)
game_on(first, second, 0, 2, 0, level)
except WrongInputError:
main()
def get_level(x):
try:
x = int(x)
if 0 < x < 4:
first = generate_integer(x)
second = generate_integer(x)
return first, second
else:
raise WrongInputError
except ValueError:
raise WrongInputError
class WrongInputError(Exception):
"""You entered something wrong, try again """
def generate_integer(level):
if level == 1:
integer = random.randrange(10)
return integer
elif level == 2:
x = str(random.randrange(1, 10))
y = str(random.randrange(10))
integer = int(x + y)
return integer
elif level == 3:
x = str(random.randrange(1, 10))
y = str(random.randrange(10))
z = str(random.randrange(10))
integer = int(x + y + z)
return integer
def game_on(x , y, count, lives, score, level):
game_set = [x, y]
try:
if count < 10:
calculation = int(input(f"{x} + {y} = "))
count += 1
if calculation == sum(game_set):
score +=1
first, second = get_level(level)
game_on(first, second, count, 3, score, level)
elif calculation == sum(game_set):
print("EEE")
if lives > 0:
lives -= 1
count -= 1
game_on(x, y, count, lives, score, level)
elif lives == 0:
print(f"{x} + {y} = {sum(game_set)}")
first, second = get_level(level)
game_on(first, second, count, 2, score, level)
else:
print(f"Score: {score}")
except ValueError:
print("EEE")
if lives > 0:
lives -= 1
game_on(x, y, count, lives, score, level)
elif lives == 0:
print(f"{x} + {y} = {sum(game_set)}")
first, second = get_level(level)
game_on(first, second, count, 2, score, level)
if __name__ == "__main__":
main()
main()
import sys
import random
def main():
num = get_level()
errors = 1
score = 0
for i in range(10):
x = generate_integer(num)
for j in range(1):
y = generate_integer(num)
answer = x + y
equation = input(f"{x} + {y} = ")
if int(equation) == answer:
score += 1
while int(equation) != answer:
errors += 1
print("EEE")
equation = input(f"{x} + {y} = ")
if errors >= 3:
print(answer)
sys.exit("Score: " + str(score))
print("Score: " + str(score))
# prompt for level and reprompt if needed
def get_level():
levelChoice = input("Level: ")
if levelChoice.isalpha() or int(levelChoice) <= 0 or int(levelChoice) > 3:
input("Level: ")
else:
levelChoice = int(levelChoice)
for i in [1,2,3]:
if levelChoice == i:
return levelChoice
# generate int from level choice
def generate_integer(level):
try:
if level == 1:
return random.randint(0, 9)
elif level == 2:
return random.randint(10, 99)
elif level == 3:
return random.randint(100, 999)
except:
raise ValueError
if __name__ == "__main__":
main()
I have to get userinputs of ints and store them in a array, and print the max number in the list. But I had to create my own max function. Im not sure what steps to take to implement it into my code.
def getInt(prompt):
n = int
done = False
while not done:
try:
n = int(input(prompt))
except ValueError:
print("I was expecting a number, please try again...")
if n == 0:
done = True
return n
def maxNum(l):
maxi = [0]
for num in l:
if maxi > num:
maxi = num
return maxi
def result():
print("The maxium value is: " + maxNum(i))
def main():
num = []
i = 0
done = False
while not done:
num = getInt("Please enter an integer < 0 to finish >: ")
if num == 0:
done = True
results = maxNum(i)
The below code does exactly what you want.
def getInt(prompt):
try:
n = int(input(prompt))
return n
except ValueError:
print("I was expecting a number, please try again...")
getInt()
def maxNum(lst):
if not lst: # if list is empty
return None
max_elem = lst[0]
for x in lst:
if x > max_elem:
max_elem = x
return max_elem
def main():
nums = []
while True:
num = getInt("Please enter an integer < 0 to finish >: ")
if num == 0:
break
nums.append(num)
result = maxNum(nums)
print("The maxium value is: " + str(result))
main()
python support built-in max function
max([1,2,3]) # return 3
and Your code is totally wrong.
if you want to input array of integers, getInt may be like this.
def getInt():
array = []
while True:
x = int(input('message'))
if x == 0: break
array.append(x)
return array
and main code will be
array = getInt()
max_value = max(array)
print (max_value)
if you want your own max function, it can be
def max_func(array):
max_val = array[0]
for val in array:
if val > max_val: max_val = val
return max_val
Here is a fixed version of your maxNum function:
def maxNum(l):
if not l:
return None # or return whatever you want if user did not input anything
maxi = l[0] # it expects 'l' to be an array!
for num in l[1:]:
if maxi > num:
maxi = num
return maxi
Let's also fix your getInt function:
def getInt(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("I was expecting a number, please try again...")
Finally, your "main" function needs the following fix:
def main():
num = []
n = 1
while n != 0:
n = getInt("Please enter an integer < 0 to finish >: ") # store user input into n - do not overwrite num!
num.append(n) # append each user value to the list num
results = maxNum(num) # pass the entire *list* to maxNum
Below is part of my code. Basically what this does is when run it creates credit cards with a random number and a given currency code and credit card limit. The Credit Card is a class and the money it stores is also a class (Which I have not included here for brevity and because I think they are not relevant to my question.) What happens in my code, however, is that my cancel statement works out fine but if I have two credit cards in a list and I try to cancel the second one it will again print out NO_SUCH_CARD. The card gets deleted anyway if its in the list. My guess is that his happens because the for loop iterates through the list and it first detects a card whose number is different than the given one, which is why it prints no such card, but I have no idea how to fix this. Help would be appreciated.
PATH = 'saved_cards.txt'
creditcard_list = []
import decimal
import ast
import collections
import os
import random
def currency_dictionary():
'''Initialized at the start of the program. It finds and reads a currency.txt
file and stores those in a dictionary'''
final_dict = collections.defaultdict(list)
with open("currency.txt", 'r') as f:
currency_lines = f.readlines()
for item in currency_lines:
m = item.split(' ')
final_dict[m[0]] = [int(m[1]), decimal.Decimal(m[2])]
return final_dict
class Money():
def __init__(self, money_amount: decimal, currency_code: str):
self.m = decimal.Decimal(money_amount)
self.c = str(currency_code)
self.d = currency_dictionary()
def __repr__(self):
return 'Money({}, {})'.format(self.m, self.c)
def __eq__(self, other):
if type(other) != Money:
return False
elif self.c == other.c:
return self.m == other.m
elif self.c != other.c:
dictionary_key1 = self.d[self.c]
decimal_point1 = dictionary_key1[0]
conversion_factor1 = dictionary_key1[1]
x = self.m / conversion_factor1
dictionary_key2 = self.d[other.c]
decimal_point = dictionary_key2[0]
conversion_factor = dictionary_key2[1]
y = other.m / conversion_factor
return x == y
def __ne__(self, other):
if type(other) != Money:
return True
elif self.c == other.c:
return self.m != other.m
elif self.c != other.c:
dictionary_key1 = self.d[self.c]
decimal_point1 = dictionary_key1[0]
conversion_factor1 = dictionary_key1[1]
x = self.m / conversion_factor1
dictionary_key2 = self.d[other.c]
decimal_point = dictionary_key2[0]
conversion_factor = dictionary_key2[1]
y = other.m / conversion_factor
return x != y
def __add__(self, other):
if self.c == other.c:
return Money((self.m + other.m), self.c)
elif self.c != other.c:
dictionary_key1 = self.d[self.c]
decimal_point1 = dictionary_key1[0]
conversion_factor1 = dictionary_key1[1]
x = self.m / conversion_factor1
dictionary_key2 = self.d[other.c]
decimal_point = dictionary_key2[0]
conversion_factor2 = dictionary_key2[1]
y = other.m / conversion_factor2
total = x + y
return Money((total * conversion_factor1), self.c)
def __sub__(self, other):
if self.c == other.c:
return Money((self.m - other.m), self.c)
elif self.c != other.c:
dictionary_key1 = self.d[self.c]
decimal_point1 = dictionary_key1[0]
conversion_factor1 = dictionary_key1[1]
x = self.m / conversion_factor1
dictionary_key2 = self.d[other.c]
decimal_point = dictionary_key2[0]
conversion_factor2 = dictionary_key2[1]
y = other.m / conversion_factor2
total = x - y
return Money((total * conversion_factor1), self.c)
class Credit_Card():
def __init__(self, card_number, money_amount: Money, card_limit: int):
if type(money_amount) != Money or type(card_limit) != int:
raise TypeError('one of the types of the parameters entered is not valid')
self.number = card_number
self.amount = money_amount
self.limit = card_limit
def __repr__(self):
return 'Card#{}({}, {})'.format(self.number, self.amount, self.limit)
def user_interface():
boolean = True
while boolean:
temp_list = []
command = input()
if command.split()[0] == 'ISSUE':
if len(command.split()) == 3:
x = "%0.5d" % random.randint(0,99999)
currency_code = command.split()[1]
card_limit = int(command.split()[2])
if card_limit < 0:
print("NEGATIVE_LIMIT")
elif not currency_dictionary()[currency_code]:
print("NO_SUCH_CURRENCY")
else:
for card in creditcard_list:
temp_list.append(card.number)
if x not in temp_list and currency_dictionary()[currency_code]:
creditcard_list.append(Credit_Card(x, Money(0, currency_code), card_limit))
print('ISSUED', x)
print(creditcard_list)
else:
print("INVALID_ISSUE_COMMAND")
elif command.split()[0] == 'CANCEL':
templist2 = []
if len(command.split()) == 2:
card_number = command.split()[1]
for card in creditcard_list:
templist2.append(card)
for i, card in enumerate(templist2):
if card_number not in templist2[i].number:
print('NO_SUCH_CARD')
elif templist2[i].amount.m != 0:
print('NONZERO_BALANCE')
elif templist2[i].number == command.split()[1] and card.amount.m == 0:
del creditcard_list[i]
print('CANCELLED', card_number)
print(creditcard_list)
elif command.split()[0] == 'PURCHASE':
if len(command.split()) == 4:
card_number = command.split()[1]
currency_code = command.split()[2]
amount = int(command.split()[3])
if currency_code not in currency_dictionary().keys():
print('NO_SUCH_CURRENCY')
elif amount < 0:
print('NONPOSITIVE_AMOUNT')
else:
for i, card in enumerate(creditcard_list):
if card.number == card_number and 0 <= amount <= card.limit :
x = card.amount + Money(amount, currency_code)
creditcard_list[i] = Credit_Card(card.number, x, card.limit)
elif creditcard_list[i].number != card_number:
print('NO_SUCH_CARD')
elif amount > creditcard_list[i].limit:
print('OVER_LIMIT')
elif command.split(0) == 'PAYMENT':
print(creditcard_list)
if __name__ == '__main__':
user_interface()
My output for the cancel command basically looks like this, and I'm pretty sure once I figure this out I'll be able to deal with the rest. Bold is input, non-bold is output.
**ISSUE USD 5000**
ISSUED 50695
[Card#50695(Money(0, USD), 5000)]
**ISSUE RON 3000**
ISSUED 25282
[Card#50695(Money(0, USD), 5000), Card#25282(Money(0, RON), 3000)]
**CANCEL 25282**
[Card#50695(Money(0, USD), 5000), Card#25282(Money(0, RON), 3000)]
*NO_SUCH_CARD*
CANCELLED 25282
[Card#50695(Money(0, USD), 5000)]
Note that the lists are only printed out for me to keep track of what cards are currently in the main list, and I will eventually remove those print statements. I have italicized the output I'm having a problem with.
The problem appears to be that you're modifying creditcard_list at the same time you are iterating through it. You should first create a temporary copy of the list to iterate through while later removing items from the actual list.
Edit: Ahh, it's printing "NO_SUCH_CARD" on the first card in the list! Not on the second. So in your example, you loop through a list of two; it first visits card #50695, which is not equal to 2582, so it prints "NO_SUCH_CARD". Then it visits 25282, deletes it, and prints "CANCELED". It's doing exactly what you wrote it to do. Instead, just loop through, deleting the card if you find it and silently skipping any card that doesn't match. In the end, if the card is not found print "NO_SUCH_CARD"
Edit2: Here's an example:
found = False
for card in templist2:
if card_number == card.number:
if card.amount.m != 0:
print('NONZERO_BALANCE')
else:
del creditcard_list[i]
print('CANCELLED', card_number)
found = True
break
if not found:
print('NO_SUCH_CARD')
class Factor:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def commonFactor(self):
global cfa
cfa = self.a
cfb = self.b
while cfb:
cfa, cfb = cfb, cfa % cfb
return cfa
def simplifyIntegers(self):
self.a = int(self.a / cfa)
self.b = int(self.b / cfa)
self.c = int(self.c / cfa)
return self.c
def coefficients(self):
if self.a == 1:
coe1 = 1
coe2 = 1
else:
coe1 = self.a
coe2 = 1
return self.coe1
def getFactors(self):
positivec = abs(self.c)
global result
result = set()
for i in range(1, int(positivec ** 0.5) + 1):
div, mod = divmod(positivec, i)
if mod == 0:
result |= {i, div}
return result
def numbers(self):
if self.c < 0:
poslist = [int(x) for x in result]
neglist = [-(x) for x in poslist]
numpos = poslist[0]
numneg = neglist[-1]
for i in poslist:
number = numpos + numneg
poslist.remove(numpos)
neglist.remove(numneg)
if number == self.b:
num1 = numpos
num2 = numneg
return num1
elif len(poslist) > 0:
numpos = poslist[0]
numneg = neglist[-1]
else:
print("This equation can not be fully factored.")
if self.c > 0:
poslist1 = [int(x) for x in result]
poslist2 = [int(x) for x in result]
neglist1 = [-(x) for x in poslist1]
neglist2 = [-(x) for x in poslist1]
numpos1 = poslist1[0]
numpos2 = poslist2[-1]
numneg1 = neglist1[0]
numneg2 = neglist2[-1]
for i in poslist1:
number = numpos1 + numpos2
poslist1.remove(numpos1)
poslist2.remove(numpos2)
if number == self.b:
num1 = numpos1
num2 = numpos2
return num1
elif len(poslist1) > 0:
numpos1 = poslist1[0]
numpos2 = poslist2[-1]
else:
print("This equation can not be factored.")
for i in neglist1:
number = numneg1 + numneg2
neglist1.remove(numneg1)
neglist2.remove(numneg2)
if number == self.b:
num1 = numneg1
num2 = numneg2
return num1
elif len(neglist1) > 0:
numpos1 = neglist1[0]
numpos2 = neglist2[-1]
else:
print("This equation can not be factored.")
def factoredForm(self):
cfa = str(cfa)
coe1 = str(coe1)
num1 = str(num1)
coe2 = str(coe2)
num2 = str(num2)
equation = (cfa,"(",coe1,"x + ",num1,")(",coe2,"x + ",num2,")")
return equation
a = input("What is A?")
a = int(a)
b = input("What is B?")
b = int(b)
c = input("What is C?")
c = int(c)
e = Factor(a,b,c)
print(e.factoredForm())
I keep getting this error-
UnboundLocalError: local variable 'cfa' referenced before assignment
I have looked at quite a bit of things talking about how to fix it, but none of those seemed to have offered something to fix this. I have making the variables global, but that still doesn't work and anything else didn't work any better. This is my program I made to factor quadratics if you need to know what it is doing. Thanks to anyone that can help.
Here it looks like you are trying to create a local cfa which is a str version of the global cfa.
def factoredForm(self):
cfa = str(cfa)
You can't mix both types of access in the same scope. You should use a different name for the local variable.
Alternatively you could write the function like this
def factoredForm(self):
return map(str, (cfa, "(", coe1, "x + " ,num1, ")(", coe2, "x + " ,num2 ,")"))
These statements:
cfa = str(cfa)
coe1 = str(coe1)
num1 = str(num1)
coe2 = str(coe2)
num2 = str(num2)
suggest that you want all of these variables as instance variables (not globals). I think you have find each use and change the way you access them.