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.
Related
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
my answer for finding the number of combinations given drawing 3 cards out of 52 is off by a spot. Like 0 cards from 52 should = 1, 1 should = 52, 2 = 1326 and so on. but I have 0 = 1, 1 = 1, 2 = 52 and so on. What would I modify to reach the desired result? I think the error is in def factorial() but I can not seem to fix/ find the issue, no matter what I try.
def factorial(num):
i = 2
if num == 0:
num = 1
print(num)
elif num > 1:
for i in range(i, num):
num = num * i
return num
def combinations(n,r):
l = n-r
nn = factorial(n)
rn = factorial(r)
ln = factorial(l)
result = nn / (rn * ln)
print(result)
return result
def main():
h = 52
a = 0
while a<4:
combinations(h,a)
a = a + 1
You're printing extra stuff in factorial which may lead to the confusion. I suggest you print out your final result with comparison to your a variable at the end of the combinations function like so:
print("For a=" + str(r) + ", result=" + str(result))
Here is the overall edited code:
def factorial(num):
if num == 0:
num = 1
elif num > 1:
for i in range(2, num): # Setting i=2 at the start is redundant
num = num * i
return num
def combinations(n,r):
l = n-r
nn = factorial(n)
rn = factorial(r)
ln = factorial(l)
result = nn / (rn*ln)
print("For a=" + str(r) + ", result=" + str(result))
return
h = 52
a = 0
while a<4:
combinations(h,a)
a = a + 1
from informedSearch import *
from search import *
class EightPuzzleProblem(InformedProblemState):
"""
Inherited from the InformedProblemState class. To solve
the eight puzzle problem.
"""
def __init__(self, myList, list = {}, operator = None):
self.myList = list
self.operator = operator
def __str__(self):
## Method returns a string representation of the state.
result = ""
if self.operator != None:
result += "Operator: " + self.operator + ""
result += " " + ' '.join(self.myList[0:3]) + "\n"
result += " " + ' '.join(self.myList[3:6]) + "\n"
result += " " + ' '.join(self.myList[6:9]) + "\n"
return result
def illegal(self):
## Tests whether the state is illegal.
if self.myList < 0 or self.myList > 9: return 1
return 0
def equals(self, state):
## Method to determine whether the state instance
## and the given state are equal.
return ' '.join(self.myList) == ' '.join(state.myList)
## The five methods below perform the tree traversing
def move(self, value):
nList = self.myList[:] # make copy of the current state
position = nList.index('P') # P acts as the key
val = nList.pop(position + value)
nList.insert(position + value, 'P')
nList.pop(position)
nList.insert(position, val)
return nList
def moveleft(self):
n = self.move(-1)
return EightPuzzleProblem(n, "moveleft")
def moveright(self):
n = self.move(1)
return EightPuzzleProblem(n, "moveright")
def moveup(self):
n = self.move(-3)
return EightPuzzleProblem(n, "moveup")
def movedown(self):
n = self.move(+3)
return EightPuzzleProblem(n, "movedown")
def operatorNames(self):
return ["moveleft", "moveright", "moveup", "movedown"]
def enqueue(self):
q = []
if (self.myList.index('P') != 0) and (self.myList.index('P') != 3) and (self.myList.index('P') != 6):
q.append(self.moveleft())
if (self.myList.index('P') != 2) and (self.myList.index('P') != 5) and (self.myList.index('P') != 8):
q.append(self.moveright())
if self.myList.index('P') >= 3:
q.append(self.moveup())
if self.myList.index('P') >= 5:
q.append(self.movedown())
def applyOperators(self):
return [self.moveleft(), self.moveright(), self.moveup(), self.movedown()]
def heuristic():
counter = 0
for i in range(len(self.myList)):
if ((self.myList[i] != goal.myList[i]) and self.myList[i] != 'P'):
## Position of current:
current = goal.myList.index(self.myList[i])
if current < 3: goalRow = 0
elif current < 6: goalRow = 1
else: goalRow = 2
if i < 3: initRow = 0
elif i < 6: initRow = 1
else: startRow = 2
initColumn = i % 3
goalColumn = current % 3
counter += (abs(goalColumn - initColumn) + abs(goalRow - initRow))
return counter
#Uncomment to test the starting states:
init = ['1','3','P','8','2','4','7','6','5'] #A
#init = ['1','3','4','8','6','2','P','7','5'] #B
#init = ['P','1','3','4','2','5','8','7','6'] #C
#init = ['7','1','2','8','P','3','6','5','4'] #D
#init = ['8','1','2','7','P','4','6','5','3'] #E
#init = ['2','6','3','4','P','5','1','8','7'] #F
#init = ['7','3','4','6','1','5','8','P','2'] #G
#init = ['7','4','5','6','P','3','8','1','2'] #H
goal = ['1','2','3','8','P','4','7','6','5'] #goal state
InformedSearch(EightPuzzleProblem(init), EightPuzzleProblem(goal))
I run it and it shows error
line 34, in __str__ result += " " + ' '.join(self.myList[0:3]) + "\n"
TypeError: unhashable type: 'slice'
Any Ideas?
You're setting the "list" to a dictionary as a default value: list = {} in:
def __init__(self, myList, list = {}, operator = None):
and then assigning it to myList with:
self.myList = list
A dictionary cannot be sliced like a list. So when you try to slice it:
self.myList[0:3]
it fails.
firstly, i want to make a program for this formula:
"Capacity of all nodes X 4 X node_type X node_feature X 1.aspect_count
this is what i have so far:
import math
node_type = 1
node_feature = 1
aspect_count = 0
capacity = 0
def capacity():
capcaity = int(input("input the capacity of your node: "))
def aspect_count():
aspect_count = int(input("input the number of aspects that their are: ")) / 10 + 1
def node_type():
node_type = raw_input("input the type of node you have e.g. pale/bright/normal: ")
def node_feature():
node_feature = raw_input("input the feature of your node e.g. hungry/pure/normal:")
def which_node_type():
if node_type == pale:
node_type = 1.1
elif node_type == bright:
node_type = 1.5
else:
node_type = 1.3
def which_node_feature():
if node_feature == hungry:
node_feature = 5
elif node_feature == sinister:
node_feature = 3
elif node_feature == pure:
node_feature = 4
else:
node_feature = 2.5
def price():
price = capacity * 4 * which_node_type * which_node_feature * aspect_count
well, that is what i have so far but it throws issues about elif being a syntax error, i just wondered if anyone could help me out with this? Thanks in advance!
Edit: Now i have changed the elif lines, i get this error:
Traceback (most recent call last):
File "", line 40, in
File "", line 38, in price
TypeError: unsupported operand type(s) for *: 'function' and 'int'
any help on the above?
You are writing your elif statements incorrectly. Everything like this:
elif:
node_feature == sinister:
needs to be written like this:
elif node_feature == sinister:
In other words, the condition to evaluate goes just after the elif keyword.
Also note that you are not actually calling the functions in price() - should be
def price():
price = capacity() * 4 * which_node_type() * which_node_feature() * aspect_count()
and your functions are not returning values; you need to return like so:
def capacity():
return int(input("input the capacity of your node: "))
Finally, your code is kind of unstructured; I would rewrite it as a class, like so:
# assumes Python 2.x
def get_int(prompt):
while True:
try:
return int(raw_input(prompt))
except ValueError:
pass
def get_one_of(prompt, values):
while True:
result = raw_input(prompt).strip()
if result in values:
return result
else:
print(" (must enter one of [{}])".format(", ".join(values)))
class Node(object):
node_type_values = {"pale": 1.1, "normal": 1.3, "bright": 1.5}
node_types = sorted(node_type_values.keys())
node_feature_values = {"normal": 2.5, "sinister": 3, "pure": 4, "hungry": 5}
node_features = sorted(node_feature_values.keys())
#classmethod
def from_prompt(cls):
capacity = get_int("Enter the node's capacity: ")
node_type = get_one_of("Enter the node's type: ", cls.node_types)
node_feature = get_one_of("Enter the node's feature: ", cls.node_features)
num_aspects = get_int("Enter the node's aspect count: ")
return cls(capacity, node_type, node_feature, num_aspects)
def __init__(self, capacity, node_type, node_feature, num_aspects):
self.capacity = capacity
self.node_type = node_type
self.node_feature = node_feature
self.num_aspects = num_aspects
def price(self):
return 4 * self.capacity * Node.node_type_values[self.node_type] * Node.node_feature_values[self.node_feature] * (1. + 0.1 * self.num_aspects)
def main():
n = Node.from_prompt()
print("Price is ${:0.2f}.".format(n.price()))
if __name__=="__main__":
main()
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')