import math
return def is_valid(filing_status, income):
"""Function determines whether the input is valid. If valid, it returns 'True'. The filing status must come from the list of options given and the income must be an integer greater than 0. If these qualifications are not met, the function will return 'False'."""
x = filing_status
y = income
def setup(x, y):
if x in ('single', 'married filing jointly', 'married filing separately', 'widow', 'head of household') and y >= 0:
print "True"
else:
print "False"
setup(x, y)
return def tax(filing_status, income):
"""Fuction displays the value of taxes that different groups of people are required to pay based on their income."""
f = filing_status
i = income
def calculation(f, i):
if f in ('single') and int(0 < i <= 9275):
print int(i*0.100)
elif 9276 <= i <= 37650:
print int((i-9276.00)*0.15 + 9275.*0.1)
elif 37651 <= i <= 91150:
print int((i-37651)*0.25 + 28375*0.15 + 9275*0.1)
elif 91151 <= i <= 190150:
print int((i-91151)*0.28 + 53500*0.25 + 28375*0.15 + 9275*0.1)
elif 190151 <= i <= 413350:
print int((i-190151)*0.33 + 99000*0.28 + 53500*0.25 + 28375*0.15 + 9275*0.1)
elif 413351 <= i <= 415050:
print int((i-413351)*0.35 + 223200*0.33 + 99000*0.28 + 53500*0.25 + 28375*0.15 + 9275*0.1)
elif i >= 415051:
print int((i-415051)*0.396 + 1700*0.35 + 223200*0.33 + 99000*0.28 + 53500*0.25 + 28375*0.15 + 9275*0.1)
calculation(f,i)
return def tax(filing_status,income):
c = filing_status
d = income
def calculation(c,d):
if c in ('widow','married filing jointly') and 0 < d <= 18550:
print int(d*0.1)
elif 18551 <= d <= 75300:
print int((d-18551)*0.15 + 18550*0.1)
elif 75301 <= d <= 151900:
print int((d-75301)*0.25 + 56750*0.15 + 18550*0.1)
elif 151901 <= d <= 231450:
print int((d-151901)*0.28 + 76600*0.25 + 56750*0.15 + 18550*0.1)
elif 231451 <= d <= 413350:
print int((d-231451)*0.33 + 79550*0.28 +76600*0.25 + 56750*0.15 + 18550*0.1)
elif 413351 <= d <= 466950:
print int((d-413351)*0.35 + 181900*0.33 + 79550*0.28 +76600*0.25 + 56750*0.15 + 18550*0.1)
elif d >= 466951:
print int((d-466951)*0.396 + 53600*0.35 + 181900*0.33 + 79550*0.28 +76600*0.25 + 56750*0.15 + 18550*0.1)
calculation(c,d)
return def tax(filing_status,income):
g = filing_status
h = income
def calculation(g,h):
if g in ('married filing separately') and 0 < h <= 9275:
print int(h*0.1)
elif 9276 <= h <= 37650:
print int((h-9276)*0.15 + 9275*0.1)
elif 37651 <= h <= 75950:
print int((h-37651)*0.25 + 28375*0.15 + 9275*0.1)
elif 75951 <= h <= 115725:
print int((h-75951)*0.28 + 38300*0.25 + 28375*0.15 + 9275*0.1)
elif 115726 <= h <= 206675:
print int((h-115726)*0.33 + 39775*0.28 +38300*0.25 + 28375*0.15 + 9275*0.1)
elif 206676 <= h <= 233475:
print int((h-206676)*0.35 + 90950*0.33 + 39775*0.28 +38300*0.25 + 28375*0.15 + 9275*0.1)
elif h >= 233476:
print int((h-233476)*0.396 + 26800*0.35 + 90950*0.33 + 39775*0.28 +38300*0.25 + 28375*0.15 + 9275*0.1)
calculation(g,h)
return def tax(filing_status,income):
m = filing_status
n = income
def calculation(m,n):
if m in ('head of household') and 0 < n <= 13250:
print int(n*0.1)
elif 13251 <= n <= 50400:
print int((n-13251)*0.15 + 13250*0.1)
elif 50401 <= n <= 130150:
print int((n-50401)*0.25 + 37150*0.15 + 13250*0.1)
elif 130151 <= n <= 210800:
print int((n-130151)*0.28 + 79750*0.25 + 37150*0.15 + 13250*0.1)
elif 210801 <= n <= 413350:
print int((n-210801)*0.33 + 80649*0.28 +79750*0.25 + 37150*0.15 + 13250*0.1)
elif 413351 <= n <= 441000:
print int((n-413351)*0.35 + 202550*0.33 + 80649*0.28 +79750*0.25 + 37150*0.15 + 13250*0.1)
elif n >= 441001:
print int((n-441001)*0.396 + 27649*0.35 + 202550*0.33 + 80649*0.28 +79750*0.25 + 37150*0.15 + 13250*0.1)
calculation(m,n)
return def percent_of_income(tax, income):
"""Function calculates the percent of income that goes to taxes."""
t = tax
s = income
def calc_percent (t, s):
print (t/s)*100
calc_percent(t, s)
return def main(filing_status,income):
"""Function brings the previous functions together to describe taxes and the percent of income of individuals based on their filing statuses"""
w = filing_status
o = income
v = tax(filing_status, income)
if w not in ('single', 'married filing jointly', 'married filing separately', 'widow', 'head of household'):
print "Invalid input. Filing status must be 'single', 'married filing jointly', 'married filing separately', 'widow', or 'head of household'. Income must be greater than or equal to zero."
if o < 0:
print "Income must be greater than or equal to zero."
else:
return ('Tax: $', str(v))
return ('Tax as % of income: $', str(percent_of_income(tax, income)) + '%')
Trying to print the tax and percent of income functions in the main. How do I reference this? I am not sure if the variables in the percent of income are documented correctly, and everytime i try to run the function, it won't print the tax value inside of the string "Tax;". I also tried concatenating that.
I think I need a little more info to help you out, but I'll try.
It looks like with this function that you are only printing if the first or second ifs are executed. If they are not, you are executing the else, which only returns a tuple without printing. Also, the second return will not be executed. Once a return is executed, the function ends.
Related
I am trying to write a code in Python to where it outputs exact change using the fewest coins and one coin type per line. The coin types are Dollars, Quarters, Dimes, Nickels, and Pennies. I also have to use singular and plural coin names as appropriate, like 1 Penny vs. 2 Pennies. When I input 45 and ran the code, I got an error saying (Your program produced no output). Here is my code:
total_change = int(input())
if total_change <= 0:
print('No change')
if total_change >= 100:
dollar = total_change//100
dollar_change = total_change % 100
if dollar == 1:
print(dollar + ' Dollar')
elif dollar > 1:
print(dollar + ' Dollars')
elif dollar_change >= 25:
quarter = dollar_change//25
quarter_change = dollar_change % 25
if quarter == 1:
print(quarter + ' Quarter')
elif quarter > 1:
print(quarter + ' Quarters')
elif quarter_change >= 10:
dime = quarter_change // 10
dime_change = quarter_change % 10
if dime == 1:
print(dime + ' Dime')
elif dime > 1:
print(dime + ' Dimes')
elif dime_change >= 5:
nickel = dime_change // 5
nickel_change = dime_change % 5
if nickel == 1:
print(nickel + ' Nickel')
elif nickel > 1:
print(nickel + ' Nickels')
elif nickel_change >= 1:
penny = nickel_change // 1
if penny == 1:
print(penny + ' Penny')
else:
print(penny + ' Pennies')
total = int(input())
if total == 0:
print("No change")
else:
denominations = [(100, "Dollar", "Dollars"), (25, "Quarter", "Quarters"), (10, "Dime", "Dimes"), (5, "Nickel", "Nickels"), (1, "Penny", "Pennies")]
for d in denominations:
coins = total // d[0]
total %= d[0]
if coins > 1:
print(f"{coins} {d[2]}")
elif coins == 1:
print(f"1 {d[1]}")
In this answer, I created a list full of tuples of all the coins and their values in cents. I then created a for loop which runs through all the tuples in the list, dividing the total removing the remainder for the number of coins
like this:
*coins = total // d[0] #returns the number of coins of the current iteration
Then, in order for the loop to continue to the next iteration and do the calculations correctly, I set the total in cents equal to the remainder of the total divided by the current iteration.
like this:
total %= d[0] #can also be written as total = total % d[0]
Then, I take the number of coins and check if the value is greater than one. If the conditional is met, it prints the number of coins followed by the corresponding "plural version" of the word.
like this:
if coins > 1:
print(f"{coins} {d[2]}")
#d[2] refers to the third item in the tuple of the current iteration
Finally, I use an else-if conditional to return 1 plus the "singular version" of the word
like this:
elif coins == 1:
print(f"1 {d[1]}")
#d[1] refers to the second item in the tuple of the current iteration
Your code has numerous problems that needed to be resolved, including the lack of a condition for input values 0 < total_change < 100, problems with indentation (the elif blocks should be aligned), unnecessary variables (you do not need variables like nickel_change and dime_change - total_change is all that matters), and you tried to print dollar + ' Dollar' even though dollar was a numeric variable.
I wanted to improve on the issues in your code and make it, well, functional, but without entirely rewriting your work. So, the basic framework of the code I'm going to provide is the same.
I used the method of recursion. I have the following function with all of your (cleaned) code:
def printCurrency(total_change):
dollar = total_change//100
dollar_change = total_change % 100
if dollar == 1:
print(str(dollar) + ' Dollar')
printCurrency(total_change-1*100)
elif dollar > 1:
print(str(dollar) + ' Dollars')
printCurrency(total_change-dollar*100)
elif dollar_change >= 25:
quarter = dollar_change//25
quarter_change = dollar_change % 25
if quarter == 1:
print(str(quarter) + ' Quarter')
printCurrency(total_change-1*25)
elif quarter > 1:
print(str(quarter) + ' Quarters')
printCurrency(total_change-quarter*25)
elif dollar_change >= 10:
dime = dollar_change // 10
dime_change = dollar_change % 10
if dime == 1:
print(str(dime) + ' Dime')
printCurrency(total_change-1*10)
elif dime > 1:
print(str(dime) + ' Dimes')
printCurrency(total_change-dime*10)
elif dollar_change >= 5:
nickel = dollar_change // 5
nickel_change = dollar_change % 5
if nickel == 1:
print(str(nickel) + ' Nickel')
printCurrency(total_change-1*5)
elif nickel > 1:
print(str(nickel) + ' Nickels')
printCurrency(total_change-nickel*5)
elif dollar_change >= 1:
penny = dollar_change // 1
if penny == 1:
print(str(penny) + ' Penny')
printCurrency(total_change-1*1)
else:
print(str(penny) + ' Pennies')
printCurrency(total_change-penny*1)
Notice how every time a line is printed, the function is ran again but after subtracting out the change we've already processed.
A few examples:
>>> printCurrency(45)
1 Quarter
2 Dimes
>>> printCurrency(101)
1 Dollar
1 Penny
>>> printCurrency(349)
3 Dollars
1 Quarter
2 Dimes
4 Pennies
And to tie this into your original framework with an input...
total_change = int(input())
if total_change <= 0:
print('No change')
if total_change >= 0:
printCurrency(total_change)
Let me know if you have any questions about the changes I've made to your code!
This is more of an answer that zybooks is looking for considering what it has taught up to this point. All that I have done here is decrement total_change each time I go down the list of coins. If there were no coins for that set then print a statement on the previous line.
total_change = int(input())
if total_change <= 0:
print('No change')
else:
dollar = total_change // 100
if dollar == 1:
print(dollar, 'Dollar')
total_change = total_change - (dollar * 100)
elif dollar <= 0:
print(end='')
else:
print(dollar, 'Dollars')
total_change = total_change - (dollar * 100)
quarter = total_change // 25
if quarter == 1:
print(quarter, 'Quarter')
total_change = total_change - (quarter * 25)
elif quarter <= 0:
print(end='')
else:
print(quarter, 'Quarters')
total_change = total_change - (quarter * 25)
dime = total_change // 10
if dime == 1:
print(dime, 'Dime')
total_change = total_change - (dime * 10)
elif dime <= 0:
print(end='')
else:
print(dime, 'Dimes')
total_change = total_change - (dime * 10)
nickel = total_change // 5
if nickel == 1:
print(nickel, 'Nickel')
total_change = total_change - (nickel * 5)
elif nickel <= 0:
print(end='')
else:
print(nickel, 'Nickels')
total_change = total_change - (nickel * 5)
penny = total_change // 1
if penny == 1:
print(penny, 'Penny')
total_change = total_change - (penny * 1)
elif penny <= 0:
print(end='')
else:
print(penny, 'Pennies')
total_change = total_change - (penny * 1)
def quadSolve(a,b,c,r):
r = list()
if a != 0:
if b**2 - 4*a*c > 0:
k1 = (-b + (b**2-4*a*c)**(1/2))/2*a
k2 = (-b - (b**2-4*a*c)**(1/2))/2*a
r.append(k1)
r.append(k2)
if b**2 - 4*a*c == 0:
k0 = -b / 2*a
r.append(k0)
if b**2 - 4*a*c < 0:
r.clear()
if a == 0 and b != 0:
k3 = -c/b
r.append(k3)
if a==0 and b == 0:
r.clear()
return r
main():
print("ax^2 + bx + c = 0")
a = input("a is?: ")
b = input("b is?: ")
c = input("c is?: ")
r = list()
answer = quadSolve(a,b,c,r)
if len(answer) == 0:
print("no roots")
else:
print("answer is", answer)
print()
Can someone point out what's wrong here??
I'm trying to make a function that solves quadratic equations using list r
I don't know what is wrong with the main code.
Look, IDK how to use the "def something ():", but this is the way that it ran for me:
My code is:
## The rules:
# function == ax2 + bx + c
# delta == b2 - 4ac
# if delta == 0: one answer
# if delta < 0: don't exist answer E R
# if delta > 0: two answers
# result is: (+/- r/delta - b)/2a
answer = 'answer ='
print('ax^2 + bx^2 + c = 0')
a = int(input('a is: '))
b = int(input('b is: '))
c = int(input('c is: '))
delta = b**2 - 4*a*c
if delta > 0:
x = (delta**(1/2) - b)/(2*a)
x2 = (-delta**(1/2) - b)/(2*a)
print(answer, x, x2)
if delta == 0:
x = (-b)/(2*a)
print(answer, x)
if delta < 0:
print("Doesn't exist Real solution.")
PyShell example:
ax^2 + bx^2 + c = 0
a is: 1
b is: -4
c is: -12
answer = 6.0 -2.0
Another way to do, based in your code is:
Look the int(input())was added and the main(): was deleted
def quadSolve(a,b,c,r):
r = list()
if a != 0:
if b**2 - 4*a*c > 0:
k1 = (-b + (b**2-4*a*c)**(1/2))/2*a
k2 = (-b - (b**2-4*a*c)**(1/2))/2*a
r.append(k1)
r.append(k2)
if b**2 - 4*a*c == 0:
k0 = -b / 2*a
r.append(k0)
if b**2 - 4*a*c < 0:
r.clear()
if a == 0 and b != 0:
k3 = -c/b
r.append(k3)
if a==0 and b == 0:
r.clear()
return r
print("ax^2 + bx + c = 0")
a = int(input("a is?: "))
b = int(input("b is?: "))
c = int(input("c is?: "))
r = list()
answer = quadSolve(a,b,c,r)
if len(answer) == 0:
print("no roots")
else:
print("answer is", answer)
print()
I have had problems with the shell saying local variable referenced before assignment and don't feel any previous answers have helped. Can I have some specific advice to this code:
Error : TotalExcessCharge = ExcessOneCharge + ExcessTwoCharge + ExcessThreeCharge + ExcessFourCharge + ExcessFiveCharge + ExcessPlusLimitCharge
UnboundLocalError: local variable 'ExcessThreeCharge' referenced before assignment
def BillingSystem(CustomerName,CustomerType,TotalGBUsed):
StandardCustomer = 1500
StandardQuota = 25
PremiumCustomer = 2500
PremiumQuota = 50
if (CustomerType == "Standard") or (CustomerType == "standard"):
if (TotalGBUsed > StandardQuota):
ExcessGB = TotalGBUsed - StandardQuota
for a in range(0, ExcessGB):
if (a <= 10):
ExcessOne = 250
ExcessOneCharge = a * ExcessOne
for b in range(0, ExcessGB):
if (b > 10) and (b <= 20):
ExcessTwo = 500
ExcessTwoCharge = b * ExcessTwo
for c in range(0, ExcessGB):
if (c > 20) and (c <= 30):
ExcessThree = 750
ExcessThreeCharge = c * ExcessThree
for d in range(0, ExcessGB):
if (d > 30) and (d <= 40):
ExcessFour = 1000
ExcessFourCharge = d * ExcessFour
for e in range(0, ExcessGB):
if (e > 40) and (e <= 50):
ExcessFive = 1250
ExcessFiveCharge = e * ExcessFive
for explus in range(0, ExcessGB):
if (explus > 50):
ExcessPlusLimit = 1500
ExcessPlusLimitCharge = explus * ExcessPlusLimit
TotalExcessCharge = ExcessOneCharge + ExcessTwoCharge + ExcessThreeCharge + ExcessFourCharge + ExcessFiveCharge + ExcessPlusLimitCharge
TotalCharge = StandardCustomer + TotalExcessCharge
print ("Total Excess Charge : " + str(TotalExcessCharge))
print ("Total Charge for this month : " + str(TotalCharge))
else:
print ("Total Excess Charge : 0")
print ("Total Charge for this month : " + str(StandardCustomer))
CName = input("[!] Customer Name : ")
CType = input("[!] Customer Type : ")
TotGB = int(input("[!] Total GB Usage : "))
BillingSystem(CName,CType,TotGB)
Obviously, at this point:
TotalExcessCharge = ExcessOneCharge + ExcessTwoCharge + ExcessThreeCharge + ExcessFourCharge + ExcessFiveCharge + ExcessPlusLimitCharge
your ExcessThreeCharge variable have not yet been assigned to, and that's because you assign to it under conditional:
for c in range(0, ExcessGB):
if (c > 20) and (c <= 30):
ExcessThree = 750
ExcessThreeCharge = c * ExcessThree
which might never be satisfied if ExcessDB is <= 20.
I'll not advise you how to fix it because, frankly, I do not understand the underlying logic of this code - it seems completely nonsensical to me.
The problem here is when your code doesn't go into the if conditions, your variables never get initiated but you have referred them at the end...So the error clearly tells you that you are calling the variable that you have never created or assigned. Always ensure that you refer the assigned variables!
And also you can make your code more easier to read like
using Excess# values directly inside the if conditions without assigning it to a variable.
using upper function on the input string and compare the value in one go..
def BillingSystem(CustomerName,CustomerType,TotalGBUsed):
StandardCustomer = 1500
StandardQuota = 25
PremiumCustomer = 2500
PremiumQuota = 50
ExcessOneCharge=0
ExcessTwoCharge=0
ExcessThreeCharge=0
ExcessFourCharge=0
ExcessFiveCharge=0
ExcessPlusLimitCharge=0
if (CustomerType.upper() == "STANDARD"):
if (TotalGBUsed > StandardQuota):
ExcessGB = TotalGBUsed - StandardQuota
for a in range(0, ExcessGB):
if (a <= 10):
ExcessOneCharge = a * 250
elif (a > 10) and (a <= 20):
ExcessTwoCharge = (a - 10) * 500
elif (a > 20) and (a <= 30):
ExcessThreeCharge = (a - 20) * 750
elif (a > 30) and (a <= 40):
ExcessFourCharge = (a - 30) * 1000
elif (a > 40) and (a <= 50):
ExcessFiveCharge = (a - 40) * 1250
elif (a > 50):
ExcessPlusLimitCharge = (a - 50) * 1500
TotalExcessCharge = ExcessOneCharge +
ExcessTwoCharge +
ExcessThreeCharge +
ExcessFourCharge +
ExcessFiveCharge +
ExcessPlusLimitCharge
TotalCharge = StandardCustomer + TotalExcessCharge
print ("Total Excess Charge : ", TotalExcessCharge)
print ("Total Charge for this month : ", TotalCharge)
else:
print ("Total Excess Charge : 0")
print ("Total Charge for this month : ", StandardCustomer)
CName = input("[!] Customer Name : ")
CType = input("[!] Customer Type : ")
TotGB = int(input("[!] Total GB Usage : "))
BillingSystem(CName,CType,TotGB)
And also instead of creating ExcessOneCharge, ExcessTwoCharge variables etc... You can do something like :
TotalExcessCharge = 0 #don't forget to initiate the variable at the beginning of the function
#then inside the if conditions
TotalExcessCharge += a*Excess#
This is just an example of how to write a cleaner code...logics you can apply as per your requirements!
Note : I'm typing everything in mobile, so pls ignore typos...
Because your definition of each of the "Excess#Charge" variables are within if statements, they seem not to be running for some reason. To fix this, I recommend defining all of the variables as 0 at the start so that if there is no excess value, it will simply be defined as 0. For example, at this at the top of the class:
ExcessOneCharge = 0
ExcessTwoCharge = 0
ExcessThreeCharge = 0
ExcessFourCharge = 0
ExcessFiveCharge = 0
ExcessPlusLimitCharge = 0
Edit: New code. Both solutions were working perfectly, but for some reason did not improve my time results and that doesn`t make sense to me just yet.
Seeing my desperation, a friend PMed me his solution, which is working fine with the time given, but somehow fails on this specific input:
9
1 2 2 3 3 4 4 5
3 6 6 7 3 8 8 9 9 10
It gives "9" instead of "5". Any ideas why that could be?
maxNum = int(0)
idxArr = []
def ReadInput():
global array
global firstNum
arr = input().split()
firstNum = int(arr[0])
while int(arr[0]) * 2 + 1 > len(arr):
tempArray = input().split()
arr = arr + tempArray
iterator = int(0)
array = [0] * int(arr[0])
for i in range(1, int(arr[0]) * 2, 2):
tempArray = [0] * 3
tempArray[0] = int(arr[i])
tempArray[1] = int(arr[i + 1])
tempArray[2] = None
array[iterator] = tempArray
iterator+=1
def SortArray(array):
array.sort(key=lambda x: x[1])
array.sort(key=lambda x: x[0])
def MergeDominos(array):
tempNum = int(0)
for item in array:
if (item[2] == None):
iterator = tempNum
counter = int(0)
tempBool = False
try:
while item == array[iterator]:
if (tempBool):
array.pop(iterator)
counter += 1
else:
iterator += 1
counter += 1
tempBool = True
except IndexError:
True == True
if (counter % 2 == 1):
item[2] = counter
tempNum += 1
else:
tempItem = item.copy()
array.insert(tempNum + 1, tempItem)
array[tempNum + 1][2] = int(1)
item[2] = counter - 1
tempNum += 1
else:
tempNum += 1
def GetLengthOfArray(array):
counter = int(0)
for item in array:
counter += item[2]
return counter
def SwitchPlaces(item):
item[0], item[1] = item[1], item[0]
def GetMaxLength(array, tempArray, left, right):
global maxNum
# print("This is temp: ", tempArray)
for i in range(len(array)):
# print("Testing: ", array[i], "Iteration: ", i)
# print("IdxArr: ", idxArr)
if (len(array) <= len(idxArr)):
#print("BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE BREAKING HERE ")
break
if (i not in idxArr):
#print("Condition:")
if (left == array[i][0]):
#print("LL")
if (i in idxArr):
break
else:
idxArr.append(i)
SwitchPlaces(array[i])
if (len(array) >= len(idxArr)):
tempArray.insert(0, array[i])
if (GetLengthOfArray(tempArray) > maxNum):
maxNum = GetLengthOfArray(tempArray)
if (len(array) >= len(idxArr)):
GetMaxLength(array, tempArray, tempArray[0][0], tempArray[len(tempArray) - 1][1])
if (left == array[i][1]):
#print("LR")
if (i in idxArr):
break
else:
idxArr.append(i)
if (len(array) >= len(idxArr)):
tempArray.insert(0, array[i])
if (GetLengthOfArray(tempArray) > maxNum):
maxNum = GetLengthOfArray(tempArray)
if (len(array) >= len(idxArr)):
GetMaxLength(array, tempArray, tempArray[0][0], tempArray[len(tempArray) - 1][1])
if (right == array[i][0]):
#print("RL")
if (i in idxArr):
break
else:
idxArr.append(i)
if (len(array) >= len(idxArr)):
tempArray.append(array[i])
if (GetLengthOfArray(tempArray) > maxNum):
maxNum = GetLengthOfArray(tempArray)
if (len(array) >= len(idxArr)):
GetMaxLength(array, tempArray, tempArray[0][0], tempArray[len(tempArray) - 1][1])
if (right == array[i][1]):
#print("RR")
if (i in idxArr):
break
else:
idxArr.append(i)
SwitchPlaces(array[i])
if (len(array) >= len(idxArr)):
tempArray.append(array[i])
if (GetLengthOfArray(tempArray) > maxNum):
maxNum = GetLengthOfArray(tempArray)
if (len(array) >= len(idxArr)):
GetMaxLength(array, tempArray, tempArray[0][0], tempArray[len(tempArray) - 1][1])
#else:
# print("No condition BIG OOOF")
ReadInput()
SortArray(array)
MergeDominos(array)
for i in range(len(array)):
#print("iter num: ", i)
tempArray = []
idxArr = []
idxArr.append(i)
tempArray.append(array[i])
if (GetLengthOfArray(tempArray) > maxNum):
maxNum = GetLengthOfArray(tempArray)
GetMaxLength(array, tempArray, tempArray[0][0], tempArray[len(tempArray) - 1][1])
print(maxNum)
E1: The input is made in this weird way, because the first item of the list gives the number of dominoes, and also, the input can come in multiple rows and then I create list item pairs.
Example input:
5 1 2
1 2
2 3
2
17
2 17
And the dominoes are:
[('1','2'),('1','2'),('2','2'),('2','17'),('2','17')]
Expected result:
5
(3,2)-(2,1)-(1,2)-(2,17)-(17-2)
The following is a rewrite of your solution with one significant change:
if maximum == len(listOfDominos) + len(tempList):
break
This prevents the code from exploring any further once it has a maximum that it knows it can't improve on. For the example input you provided, it reduced the number of searches by 20x:
def find(listOfDominos, tempList):
maximum = len(tempList)
for currentDominoIndex, domino in enumerate(listOfDominos):
if maximum == len(listOfDominos) + len(tempList):
break # we can't do any better, so why try?
remainingDominos = listOfDominos[:currentDominoIndex] + listOfDominos[currentDominoIndex+1:]
if tempList:
backwardDomino = domino[::-1]
head, tail = tempList[0], tempList[-1]
if domino[1] == head[0]:
maximum = max(find(remainingDominos, [domino] + tempList), maximum)
elif backwardDomino[1] == head[0]:
maximum = max(find(remainingDominos, [backwardDomino] + tempList), maximum)
elif domino[0] == tail[1]:
maximum = max(find(remainingDominos, tempList + [domino]), maximum)
elif backwardDomino[0] == tail[1]:
maximum = max(find(remainingDominos, tempList + [backwardDomino]), maximum)
else:
maximum = max(find(remainingDominos, [domino]), maximum)
return maximum
listOfNumbers = input().split()
numberOfDominos = int(listOfNumbers.pop(0))
while numberOfDominos * 2 > len(listOfNumbers):
listOfNumbers += input().split()
listOfDominos = list(zip(listOfNumbers[0::2], listOfNumbers[1::2]))
print(find(listOfDominos, []))
Give this a try to see if it improves performance without introducing any bugs in the process.
Try this solution:
def solution(dominoes):
if len(dominoes) == 0:
return 0
def get_sequence(d, sol=None):
if sol is None:
sol = []
if len(d) == 0:
return
for i in range(len(d)):
rest = d[:i] + d[i+1:]
d1, d2 = d[i], d[i][::-1]
if d1 == d2:
if (not sol) or (sol[-1][1] == d1[0]):
yield sol + [d1]
yield from get_sequence(rest, sol + [d1])
else:
if (not sol) or (sol[-1][1] == d1[0]):
yield sol + [d1]
yield from get_sequence(rest, sol + [d1])
if (not sol) or (sol[-1][1] == d2[0]):
yield sol + [d2]
yield from get_sequence(rest, sol + [d2])
return(len(max(get_sequence(dominoes), key=len)))
dominoes = [('1','2'),('1','2'),('2','2'),('2','17'),('2','17')]
print(solution(dominoes))
Prints:
5
I'm trying to make a factoring program, but it doesn't seem to work with negative number a-, b- and c-inputs.
from fractions import gcd
factor = -1
opp = 0
number = 1
success = 0
a = int(input("a-value: "))
b = int(input("b-value: "))
c = int(input("c-value: "))
factors = []
d = 0
e = 0
while number <= abs(a*c):
#Checking for multiples
if abs(a*c) % number == 0:
factor += 1
factors.append(number)
number += 1
while (factor-opp) >= 0:
#Checking for actual factors
d = int(factors[factor])
e = int(factors[opp])
if (abs(d+e) or abs(d-e)) == abs(b):
success += 1
break
else:
factor -= 1
opp += 1
if success > 0:
if (d+e) == b:
e = e
elif (d-e) == b:
e -= 2*e
elif (e-d) == b:
d -= 2*d
elif (-d-e) == b:
d -= 2*d
e -= 2*e
#Figuring out the equation
if d % a == 0:
d /= a
f = 1
else:
f = a/gcd(d,a)
d /= gcd(d,a)
if e % a == 0:
e /= a
g = 1
else:
g = a/gcd(e,a)
e /= gcd(e,a)
#Displaying the answer
if d >= 0:
d = str("+" + str(int(d)))
if e >= 0:
e = str("+" + str(int(e)))
elif e < 0:
e = str(int(e))
else:
d = str(int(d))
if e >= 0:
e = str("+" + str(int(e)))
elif e < 0:
e = str(int(e))
if f == 1:
if g == 1:
print ("(x" + d + ")(x" + e + ")")
else:
g = str(int(g))
print ("(x" + d + ")(" + g + "x" + e + ")")
elif g == 1:
f = str(int(f))
print ("(" + f + "x" + d + ")(x" + e + ")")
else:
f = str(int(f))
g = str(int(g))
print ("(" + f + "x" + d + ")(" + g + "x" + e + ")")
else:
print("This equation cannot be factored into integers.")
More specifically, the problem is somewhere within this block, I think. I've tested it out with print statements:
while (factor-opp) >= 0:
#Checking for actual factors
d = int(factors[factor])
e = int(factors[opp])
if (abs(d+e) or abs(d-e)) == abs(b):
success += 1
break
else:
factor -= 1
opp += 1
I've searched everywhere: my programming textbook, online searches about inputting negatives, everything. What am I doing wrong here?
Ok I am able to reproduce your issue for a simple testcase like - a=1 , b=0, c=-4 .
The issue is in the line -
if (abs(d+e) or abs(d-e)) == abs(b):
This does not check whether abs(b) is equal to abs(d+e) or abs(d-e) , instead it first evaluates the result of (abs(d+e) or abs(d-e)) , which would return the first non-zero result , and then compare that against abs(b) , so for negative numbers this does not evaluate the result correctly. Change that condition to -
if abs(d+e) == abs(b) or abs(d-e) == abs(b):
or you can also use a set -
if abs(b) in {abs(d+e), abs(d-e)}: #Though I doubt if using set would give any performance improvement because of the overhead of creating a set.
Demo after changes -
a-value: 1
b-value: 0
c-value: -4
(x+2)(x-2)
a-value: 1
b-value: -1
c-value: -6
(x-3)(x+2)
One more thing, there is something you have not considered , when a=-1 , b=-4 , c=-4 , the result should come to -(x+2)(x+2) , but the current program results in (x+2)(x+2) .