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()
Whilst attempting CS50's PSET6, I was trying to create a double-half pyramid of a size specified by the user.
The pyramid is fine but there's a random new line after the user input and before the pyramid starts. How can I fix it? Any help is appreciated :D
The code is as follows
def main():
hashHeight = height()
create(hashHeight)
# get height
def height():
h = int(input("Height: "))
if h >= 1 and h <= 8:
return h
else:
height()
#print hash
def create(x):
for i in range(x + 1):
print(" " * (x - i) + "#" * i + " " + "#" * i)
main()
def main():
hashHeight = height()
create(hashHeight)
# get height
def height():
h = int(input("Height: "))
if h >= 1 and h <= 8:
return h
else:
height()
#print hash
def create(x):
for i in range(1, x + 1):
print(" " * (x - i) + "#" * i + " " + "#" * i)
main()
So, I'm having a lot of trouble inputting my answer into the grader for the MIT Intro to CS in Python course on edX.
The specific problem ask for a program that will calculate the interest on a credit card given the monthly payment rate, interest rate, and initial balance.
I'm pretty sure my code is fine, I just can't get the grader to accept it.
I've tried changing the code to account for the names of the variables that the grader wants and removed the input prompts, function wrapper and return calls, but it still doesn't work.
Here is my initial code:
from math import *
b = float(input("balance = "))
r = float(input("annualInterestRate = "))
p = float(input("monthlyPaymentRate = "))
bval = []
def interest(b, r, p):
bal = (b - (b * p))
def update(bal, r):
balance = (bal + (r / 12.0) * bal)
return balance
if len(bval) < 12:
bval.append(update(bal, r))
return(interest(bval[-1], r, p))
elif len(bval) == 12:
return print("Remaning balance: " + "{:.2f}".format(bval[-1]))
interest(b, r, p)
And here is what it was modified to:
from math import *
bval = []
bal = (blance - (balance * monthlyPaymentRate))
def update(balance, annualInterestRate):
bal = round((balance + (annualInterestRate / 12.0) * balance), 2)
return bal
if len(bval) < 12:
bval.append(update(bal, annualInterestRate))
(interest(bval[-1], annualInterestRate, monthlyPaymentRate))
elif len(bval) == 12:
print("Remaning balance: " + "{:.2f}".format(bval[-1]))
Any help?
I'm new to Python, currently doing the MIT edX course. We had a problem to complete where we had to use the bisection method to find the lowest payment a person had to make to pay off a credit card dept in a year.We were given the balance and the annual interest rate. My code below works but it does not look correct to me. Does anyone have any insight in this? Thanks
def payment(balance, annualInterestRate):
newBalance = 0
monthlyInterest = annualInterestRate / 12
maxPaybal = (balance * (1 + monthlyInterest) ** 12) / 12
minPaybal = balance/12
while round(newBalance, 2) != 0.01 or round(newBalance, 2) != 0.00:
guess = (minPaybal + maxPaybal) / 2.0
newBalance = balance
months = 12
while months > 0:
prevBalance = newBalance - guess
uptdBalance = prevBalance + (prevBalance * monthlyInterest)
newBalance = uptdBalance
months -= 1
if round(newBalance, 2) == 0.01 or round(newBalance, 2) == 0.00:
return "Lowest Payment: ", round(guess, 2)
elif newBalance < 0.00:
maxPaybal = guess
else:
minPaybal = guess
print(payment(balance, annualInterestRate))
I just started college and I am writing this code out for my college class and it keeps sending an error. Any enlightenment will help, maybe the problem is that I'm half asleep.
here is the code
def main():
overtime = int(0)
totaloverpay = float(0)
hours = int(input('How many hours did you work? NOTE** Hours can not exceed 86 or be less than 8 '))
while hours > 86 or hours < 8:
print('ERROR: Insufficient input. Try again')
hours = int(input('How many hours did you work? NOTE** Hours can not exceed 86 or be less than 8 '))
payrate = float(input('What is the payrate per hour for this employee? NOTE** Payrate can not exceed $50.00 or be less than $7.00 '))
while payrate > 50.00 or payrate < 7.00:
print('ERROR: Insufficient input. Try again')
payrate = float(input('What is the payrate per hour for this employee? NOTE** Payrate can not exceed $50.00 or be less than $7.00 '))
workhours(hours, payrate, overtime)
def workhours(hours, payrate, overtime):
if hours > 40:
overtime = (hours - 40) * -1
else:
regtime = hours + 0
paydistribution(hours, payrate, regtime, overtime)
def paydistribution(hours, payrate, regtime, overtime):
if hours >= 40:
halfrate = float(payrate * 0.5)
overpay = halfrate + payrate
totaloverpay = float(overpay * hours)
if hours < 40:
regpay = hours * payrate
display(hours, payrate, regpay, regtime, overtime)
def display(hours, payrate, regpay, regtime, overtime):
total = float(regpay + totaloverpay)
print(' Payroll Information')
print('Payrate :', format(payrate, '0.2f'))
print('Regular Hours :', format(regtime))
print('Overtime Hours:', format(overtime))
print('Regular Pay :', format(regpay, '6.2f'))
print('Overtime Pay :', format(totaloverpay, '7.2f'))
print('Total Pay :', format(total, '7.2f'))
main()
totaloverplay is not defined in any function below main in which it is referred to, or as a global variable. If you want it to be global, define it outside of the main function's scope.
This looks like a great use-case for a class rather than relying on functional programming.
from decimal import Decimal # more precision than floating point
MINIMUM_WAGE = Decimal("7.25")
OVERTIME_RATE = Decimal("1.5")
class Employee(object):
def __init__(self,first,last,MI="",payrate=MINIMUM_WAGE):
self.first = first.capitalize()
self.last = last.capitalize()
self.MI = MI.upper()
if not MI.endswith("."): self.MI += "."
self.payrate = payrate
self.hours = 0
#property
def name(self, reversed_=False):
return "{} {} {}".format(self.first,self.MI,self.last)
#property
def alphabetize(self):
return "{}, {}".format(self.last, self.first)
def payroll(self,numweeks=1):
regularhours = min(40*numweeks,self.hours)
OThours = max(0,self.hours-regularhours)
regularpay = regularhours * self.payrate
OTpay = round(OThours * self.payrate * OVERTIME_RATE,2)
return {"reghours":regularhours,
"overtime":OThours,
"regpay":regularpay,
"OTpay":OTpay,
"total":regularpay + OTpay}
def sethoursworked(self,amt):
self.hours = amt
def display(employee):
payrollinfo = employee.payroll()
print("{:^30}".format("Payroll Information"))
print("{:>30}".format(employee.name))
print("Payrate:{:>22}".format(employee.payrate))
print("Hours:{:>24}".format(payrollinfo['reghours']))
print("Overtime Hours:{:>15}".format(payrollinfo['overtime']))
print("Regular Pay:{:>18}".format(payrollinfo['regpay']))
print("Overtime Pay:{:>17}".format(payrollinfo['OTpay']))
print("-"*30)
print("Total Pay:{:>20}".format(payrollinfo['total']))
Adam = Employee("Adam","Smith","D")
Adam.sethoursworked(51)
display(Adam)
OUTPUT:
Payroll Information
Adam D. Smith
Payrate: 7.25
Hours: 40
Overtime Hours: 11
Regular Pay: 290.00
Overtime Pay: 119.62
------------------------------
Total Pay: 409.62
You should not get in the habit of using global; it's usually a sign that you're heading in the wrong direction. Instead, pass the variables you need around explicitly, using function arguments and return statements. Also, don't pass functions arguments they don't need to do their job, and prefer default arguments or explicit constants to "magic numbers". For example:
def workhours(hours, threshold=40):
if hours > threshold:
overtime = hours - threshold
regtime = threshold
else:
overtime = 0
regtime = hours
return regtime, overtime
def paydistribution(payrate, regtime, overtime, otrate=1.5):
regpay = regtime * payrate
overpay = overtime * payrate * otrate
return regpay, overpay
Now main can call:
regtime, overtime = workhours(hours)
regpay, overpay = paydistribution(payrate, regtime, overtime)
display(hours, payrate, regpay, regtime, overtime)
This keeps the flow mostly in main while letting the other functions do just their specific bits of the task.
In your position, I would also consider having a separate function to take user input, which loops until they provide something acceptable. An appropriate definition, for example:
def user_input(prompt, min_, max_):
Here is another cleaned-up version:
from textwrap import dedent
import sys
if sys.hexversion < 0x3000000:
# Python 2.x
inp = raw_input
else:
# Python 3.x
inp = input
MIN_HOURS = 8.
MAX_HOURS = 86.
MIN_RATE = 7.
MAX_RATE = 50.
OVERTIME_CUTOFF = 40.
OVERTIME_BONUS = 0.5
def get_float(prompt, lo=None, hi=None):
while True:
try:
val = float(inp(prompt))
if lo is not None and val < lo:
print("Value must be >= {}".format(lo))
elif hi is not None and val > hi:
print("Value must be <= {}".format(hi))
else:
return val
except ValueError:
print("Please enter a number")
def main():
hours = get_float("How many hours did you work? ", MIN_HOURS, MAX_HOURS)
rate = get_float("What is the hourly payrate? ", MIN_RATE, MAX_RATE)
time = min(hours, OVERTIME_CUTOFF)
pay = time * rate
overtime = max(0., hours - OVERTIME_CUTOFF)
overpay = overtime * rate * (1. + OVERTIME_BONUS)
print(dedent("""
Payroll Information
Payrate : $ {rate:>7.2f}
Regular Hours : {time:>4.0f} h
Regular Pay : $ {pay:>7.2f}
Overtime Hours: {overtime:>4.0f} h
Overtime Pay : $ {overpay:>7.2f}
Total Pay : $ {total:>7.2f}
""").format(rate=rate, time=time, pay=pay, overtime=overtime, overpay=overpay, total=pay+overpay))
if __name__=="__main__":
main()
which runs like
How many hours did you work? 46
What is the hourly payrate? 11
Payroll Information
Payrate : $ 11.00
Regular Hours : 40 h
Regular Pay : $ 440.00
Overtime Hours: 6 h
Overtime Pay : $ 99.00
Total Pay : $ 539.00