How to take greatest value - python

Enter 10 for first input
enter 500 for second input
enter 20 for third input
I was wondering if there is a way where I can get the maximum profit and show it without the user having to go through and read every single line?
MP=abs(int(input("Enter the minimum number of passengers:")))
print(MP)
max_passengers=int(input("Enter the maximum number of passengers:"))
while(max_passengers <= MP):
print("\n")
max_passengers=int(input("You must enter a number that is greater than the minimum ammount of passengers:"))
print(max_passengers)
TP=float(input("Enter the ticket price"))
print(TP)
increment=10
fixed_cost=2500
print("\n")
for numberpass in range(MP,max_passengers+10,increment):
discount=.5
ticketcost = TP - (((numberpass - MP) /10) * discount)
gross=numberpass*ticketcost
profit=gross-fixed_cost
print(numberpass,"\t",ticketcost,"\t",gross,"\t",fixed_cost,
"\t",profit)

Save every profit in a list, then take the maximum value of that list:
# rest of you code above...
profits = [] # create the list to store the every profit
for numberpass in range(MP,max_passengers+10,increment):
discount=.5
ticketcost = TP - (((numberpass - MP) /10) * discount)
gross=numberpass*ticketcost
profit=gross-fixed_cost
print(numberpass,"\t",ticketcost,"\t",gross,"\t",fixed_cost,"\t",profit)
profits.append(profit) # store each profit
max_profit = max(profits)
print("Maximum profit: {}".format(max_profit))

Related

Trying to print correct element corresponding to value

def main():
rain = [] # empty list awaiting user input
MONTH = ["January", "February"] # parallel to the rain?
SIZE = 2 # array size
getRain(rain,SIZE) # ask user to input each month rainfall amount
highest = findHigh(rain, SIZE, MONTH)
displayValues(SIZE, highest, rain)
# get input and add to list
def getRain(rain, SIZE):
index = 0
while (index <= SIZE - 1):
print('Enter rainfall for month', index + 1)
rainInput = int(input('Enter rainfall: '))
rain.append(rainInput)
index = index + 1
# finding the highest value in the array and printing the highest value with month
def findHigh(rain, SIZE, MONTH):
highest = rain[0]
index = 1
while (index <= SIZE - 1):
if (rain[index] > highest):
highest = rain[index]
else:
index = index + 1
print("The highest month is:", MONTH[index - 1]) # not too sure if I need this here
return highest
# display the values
def displayValues(SIZE, highest, rain):
print("--------------------------------")
print("The highest value is:", highest)
# run code
main()
Hi, I am trying to figure out how to get it so then my output would print the right month in correlation to the amount of rainfall each month has (for example: january has 50 and february has 40)
Output: The highest month is: January
I've tried making another condition thing or another module to try to check the values, but I cannot compare strings to int in the list. I have also tried moving the print values but I feel like another module would be needed to find the right month unless I am just printing it in the wrong area
If you don't want to change the rest of the code, you can modify findHigh to track and print the month with the highest value:
def findHigh(rain, SIZE, MONTH):
highest = 0
index = 1
while (index <= SIZE - 1):
if (rain[index] > rain[highest]):
highest = index
else:
index = index + 1
print("The highest month is:", MONTH[highest]) # not too sure if I need this here
return rain[highest]
or slightly more pythonic:
def findHigh(rain, SIZE, MONTH):
highest = 0
for index in range(SIZE):
if rain[index] > rain[highest]:
highest = index
print("The highest month is:", MONTH[highest]) # not too sure if I need this here
return rain[highest]
It may be better to move both the prints to displayValues:
def main():
rain = [] # empty list awaiting user input
MONTH = ["January", "February"] # parallel to the rain?
SIZE = 2 # array size
getRain(rain,SIZE) # ask user to input each month rainfall amount
highest = findHigh(rain, SIZE)
displayValues(SIZE, highest, rain, MONTH)
# get input and add to list
def getRain(rain, SIZE):
index = 0
while (index <= SIZE - 1):
print('Enter rainfall for month', index + 1)
rainInput = int(input('Enter rainfall: '))
rain.append(rainInput)
index = index + 1
# finding the highest value in the array and printing the highest value with month
def findHigh(rain, SIZE):
highest = 0
for index in range(SIZE):
if rain[index] > rain[highest]:
highest = index
return highest
# display the values
def displayValues(SIZE, highest, rain, MONTH):
print("The highest month is:", MONTH[highest]) # not too sure if I need this here
print("--------------------------------")
print("The highest value is:", rain[highest])

what is the mistake in the while/for loop?

This is the output using the wrong for/while-loop operation:
current value is 60
current value is 120
total value is 120
This is what I would like it to be:
current value is 10
current value is 30
total value is 30
prices = [10, 20, 30]
total = 0
steps = 0
step_limit = 2
while steps < step_limit:
steps +=1
for i in prices:
total += i
print(f'current value is {total}')
print(f'total value is {total}')
If you want to add each element from the list, the problem that arises here is in the following part of your code:
for i in prices:
total += i
This means that you iterate through each element inside the list and add it to the total (10+20+30). This is done 2 times, so the total will be 120.
You have to replace that part of the code with something that accesses only one element at a time. For instance:
total += prices[steps]
If you desire to add the last element and display the total straight away with it, you can add the last price outside of the while loop right before the message display at the end:
total += prices[steps]
print(f'total value is {total}')

algorithm that calculates a minimum amount to be paid to pay off a balance in 12 months

I'm struggling with a problem that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. By a fixed monthly payment, I mean a single number which does not change each month, but instead is a constant amount, multiple of 10 and the same for all months, that will be paid each month. ( it is possible for the balance to become negative using this payment scheme, which is OK)
So as input I have
original_balance = 3329
annualInterestRate = 0.2
From this I'm calculating the followings :
after_12_months_interest = original_balance
monthlyInterestRate = round(annualInterestRate/12.0,2)
monthly_payment = 10
total_paid = 0
for i in range(0,12):
after_12_months_interest = after_12_months_interest + (annualInterestRate/12.0)*after_12_months_interest
while total_paid < after_12_months_interest:
new_balance = 0
unpaid_balance = original_balance - monthly_payment
total_paid = 0
for i in range(0, 13):
total_paid = total_paid + monthly_payment
if total_paid < after_12_months_interest:
monthly_payment = monthly_payment + 10
print "Lowest Payment: ", monthly_payment
My problem I have is that I end up having a monthly_payment just a little more than I should have it. In this case the return for the monthly_payment is 320 instead of 310. For all use cases I've tried the monthly_payment it's slightly more than it should be.
Anyone can give me a hint or an idea on what I'm doing wrong please. Thank you
Mandatory one-liner
from itertools import count
print(next(payment for payment in count(0, 10)
if sum(payment*(1+monthly)**i for i in range(12)) > original_balance*(1+annual)))
What this does:
next takes the first element of an iterator.
count tries values from 0 to infinity (only each time next is called, and only until a value is returned)
sum(payment*(1+monthly)**i for i in range(12)) That's the combined value of the payments. Each payment is worth itself plus all the saved interests (the earlier you repay, the less interest you'll owe later)
original_balance*(1+annual) is indeed the total value if nothing is repayed.
Alternative
print(next(payment for payment in count(0, 10)
if reduce(lambda x,_:(x - payment)*(1+monthly), range(12), original_balance) <= 0))
This one computes the combined remainder of the debt by reduceing the original_balance 12 times.

in python, i have an int and want to substract it from a list

In python: how do I divide an int received by a user from a list while every time it runs in the for loop I need to divide the value I received from the round before in the next round?
This is my code:
a = input('price: ')
b = input('cash paid: ')
coin_bills = [100, 50, 20, 10, 5, 1, 0.5]
if b >= a:
for i in coin_bills:
hef = b - a
print (hef / i), '*', i
else:
print 'pay up!'
Example: a=370 b=500 ---> b-a=130
Now in the loop I will receive (when i=100) 1, and (when i=50) I will receive 2 but I want in the second round (when i=50) to divide 30 (130[=b-a]- 100[=answer of round 1*i]) by 50.
What do I need to change in the code?
Thanks!
You just need to subtract the amount of change you give back at each step from the total amount of change you're returning. It's much easier to see if you change your variable names to something meaningful:
price= int(raw_input('price: ')) # Use int(raw_input()) for safety.
paid= int(raw_input('cash paid: '))
coin_bills=[100,50,20,10,5,1,0.5]
if paid >= price:
change = paid - price
for i in coin_bills:
# Use // to force integer division - not needed in Py2, but good practice
# This means you can't give change in a size less than the smallest coin!
print (change // i),'*',i
change -= (change // i) * i # Subtract what you returned from the total change.
else:
print 'pay up!'
You could also clear up the output a bit by only printing the coins/bills that you actually return. Then the inner loop might look something like this:
for i in coin_bills:
coins_or_bills_returned = change // i
if coins_or_bills_returned: # Only print if there's something worth saying.
print coins_or_bills_returned,'*',i
change -= coins_or_bills_returned * i
OK, I'm assuming that you're trying to calculate change for a transaction using a number of types of bills.
The problem is that you need to keep a running tally of how much change you have left to pay out. I used num_curr_bill to calculate how many of the current bill type you're paying out, and your hef I changed to remaining_change (so it would mean something to me) for the remaining change to pay.
a= input('price: ')
b= input('cash paid: ')
coin_bills=[100,50,20,10,5,1,0.5]
if b>=a:
# Calculate total change to pay out, ONCE (so not in the loop)
remaining_change = b-a
for i in coin_bills:
# Find the number of the current bill to pay out
num_curr_bill = remaining_change/i
# Subtract how much you paid out with the current bill from the remaining change
remaining_change -= num_curr_bill * i
# Print the result for the current bill.
print num_curr_bill,'*',i
else:
print 'pay up!'
So, for a price of 120 and cash paid 175, the output is:
price: 120
cash paid: 175
0 * 100
1 * 50
0 * 20
0 * 10
1 * 5
0 * 1
0.0 * 0.5
One bill for 50 and one for 5 add up to 55, the correct change.
Edit: I'd go more sparingly on the comments in my own code, but I added them here for explanation so that you could more clearly see what my thought process was.
Edit 2: I would consider removing the 0.5 in coin_bills and replacing 1 with 1.0, since any fractional amounts will wind up being fractions of 0.5 anyway.

Python: smarter way to calculate loan payments

How to calculate the monthly fee on a loan?
Given is:
a: an amount to loan.
b: the loan period (number of months).
c: the interest rate p.a. (interests is calculated and added every month, 1/12 of the interest is added. So if the interest is on 12%, 1% interest is added every month).
d: the amount of money owed after the end of the period.
This problem is a bit different than the usual since, the goal is not to have the loan payed after the loan period has ended, but to still owe an amount that is given. I have been able to find an algorithm so solve the problem if I wanted to pay the entire amount, but it will of course not work for this problem where the goal is to end up owing a given amount rather than not owing anything.
I managed to make a solution to this problem by starting with an guess and then keep on improving that guess until it was close enough. I wondered however, if there is a better way to simply calculate this, rather than just guessing.
Edit: Here's how I'm doing it now.
def find_payment(start, end, months, interest):
difference = start
guess = int(start / months * interest)
while True:
total = start
for month in range(1, months + 1):
ascribe = total * interest / 12
total = total + ascribe - guess
difference = total - end
# See if the guess was good enough.
if abs(difference) > start * 0.001:
if difference < 0:
if abs(difference) < guess:
print "payment is %s" % guess
return evolution(start, guess, interest, months)
else:
mod = int(abs(difference) / start * guess)
if mod == 0:
mod = 1
guess -= mod
else:
mod = int(difference / start * guess)
if mod == 0:
mod = 1
guess += mod
else:
print "payment is %s" % guess
return evolution(start, guess, interest, months)
evolution is just a function that displays how the loan would look like payment for payment and interest for interest, summing up total amount of interest paid etc.
An example would be if I wanted to find out the monthly payments for a loan starting with $100k and ending at $50k with an interest of 8% and a duration of 70 months, calling
>>> find_payment(100000, 50000, 70, 0.08)
payment is 1363
In the above case I would end up owing 49935, and I went through the loop 5 times. The amount of times needed to go through the loop depends on how close I want to get to the amount and it varies a bit.
This is a basically a mortgage repayment calculation.
Assuming that start is greater than end, and that interest is between 0 and 1 (i.e. 0.1 for 10% interest)
First consider the part of the payment you want to pay off.
Principal = start - end
The monthly payment is given by:
pay_a = (interest / 12) / (1 - (1+interest/12) ^ (-months))) * Principal
You then need to consider the extra interest. Which is just equal to the remaining principal times the monthly interest
pay_b = interest / 12 * end
So the total payment is
payment = (interest / 12) * (1 / (1 - (1+interest/12) ^ (-months))) * Principal + end)
On the example you gave of
Start: 100000
End: 50000
Months: 70
Interest: 8%
pay_a = 896.20
pay_b = 333.33
Payment = 1229.54
When I tested these values in Excel, after 70 payments the remaing loan was 50,000. This is assuming you pay the interest on the notional before the payment is made each month.
Perhaps the easiest way to think about this is to split the loan in two parts, one part which is to be repaid in full and another part where you don't pay off anything. You have already computed the monthly fee for the first part.
You can keep paying the interest of every month; then, you will alway owe the same amont.
Owe_1 = a
Int_2 = Owe_1*(InterestRate/12)
Pay_2 = Int_2
Owe_2 = Owe_1 + Int_2 - Pay_2 # ==> Owe_1 + Int_2 - Int_2 = Owe_1
Int_3 = Owe_2*(InterestRate/12)
Pay_3 = Int_3
Owe_3 = Owe_2 + Int_3 - Pay_3 # ==> Owe_2 + Int_3 - Int_3 = Owe_2 = Owe_1
python code to calculate emi
class EMI_CALCULATOR(object):
# Data attributes
# Helps to calculate EMI
Loan_amount = None # assigning none values
Month_Payment = None # assigning none values
Interest_rate = None #assigning none values
Payment_period = None #assigning none values
def get_loan_amount(self):
#get the value of loan amount
self.Loan_amount = input("Enter The Loan amount(in rupees) :")
pass
def get_interest_rate(self):
# get the value of interest rate
self.Interest_rate = input("Enter The Interest rate(in percentage(%)) : ")
pass
def get_payment_period(self):
# get the payment period"
self.Payment_period = input("Enter The Payment period (in month): ")
pass
def calc_interest_rate(self):
# To calculate the interest rate"
self.get_interest_rate()
if self.Interest_rate > 1:
self.Interest_rate = (self.Interest_rate /100.0)
else:
print "You have not entered The interest rate correctly ,please try again "
pass
def calc_emi(self):
# To calculate the EMI"
try:
self.get_loan_amount() #input loan amount
self.get_payment_period() #input payment period
self.calc_interest_rate() #input interest rate and calculate the interest rate
except NameError:
print "You have not entered Loan amount (OR) payment period (OR) interest rate correctly,Please enter and try again. "
try:
self.Month_Payment = (self.Loan_amount*pow((self.Interest_rate/12)+1,
(self.Payment_period))*self.Interest_rate/12)/(pow(self.Interest_rate/12+1,
(self.Payment_period)) - 1)
except ZeroDivisionError:
print "ERROR!! ZERO DIVISION ERROR , Please enter The Interest rate correctly and Try again."
else:
print "Monthly Payment is : %r"%self.Month_Payment
pass
if __name__ == '__main__':# main method
Init = EMI_CALCULATOR() # creating instances
Init.calc_emi() #to calculate EMI
for more info visit : https://emilgeorgejames.wordpress.com/2015/07/29/python-emi-equated-monthly-installment-calculator/
This rather a detailed way but will give the whole payment as well
# Mortgage Loan that gives the balance and total payment per year
# Function that gives the monthly payment
def f1 (principle,annual_interest_rate,duration):
r = annual_interest_rate/1200
n = duration*12
a=principle*r*((1+r)**n)
b= (((1+r)**n)- 1)
if r > 0 :
MonthlyPayment = (a/b)
else :
MonthlyPayment = principle/n
return MonthlyPayment
# Function that gives the balance
def f2 (principle,annual_interest_rate,duration,number_of_payments):
r = annual_interest_rate/1200
n = duration*12
a= ((1+r)**n)
b= ((1+r)**number_of_payments)
c= (((1+r)**n)-1)
if r > 0 :
RemainingLoanBalance = principle*((a-b)/c)
else :
RemainingLoanBalance = principle*(1-(number_of_payments/n))
return RemainingLoanBalance
# Entering the required values
principle=float(input("Enter loan amount: "))
annual_interest_rate=float(input("Enter annual interest rate (percent): "))
duration=int(input("Enter loan duration in years: "))
# Output that returns all useful data needed
print ("LOAN AMOUNT:",principle,"INTEREST RATE (PERCENT):",annual_interest_rate)
print ("DURATION (YEARS):",duration,"MONTHLY PAYMENT:",int(f1(principle,annual_interest_rate,duration)))
k=duration+1
BALANCE=principle
total=0
for i in range (1,k):
TOTALPAYMENT= f1(BALANCE,annual_interest_rate,k-i)*12
total+= TOTALPAYMENT
BALANCE= f2(principle,annual_interest_rate,duration,12*i)
print("YEAR:",i,"BALANCE:",int(BALANCE),"TOTAL PAYMENT",int(total))
How about this?
def EMI_calc(principle, rate, time, frequency):
return (principle / ((1-((1+(rate/frequency))**(-1*(time*frequency))))/(rate/frequency)))
print("""
----- Welcome to EMI programe for Python -----
""")
print("\n You have chosen to know the EMI for Loan.\n")
input('\nTo Continue Press ENTER --- to ABORT Press ctrl+c > \n')
print("\nPlease Enter amount of Loan to be taken: >\n")
principle = int(input())
print("\nEnter rate of interst (%): >\n")
rate = float(input())/100
print("\nEnter Term (Years): >\n")
time = float(input())
print("\nPlease enter the frequency of installments) : >\n")
frequency = int(input())
EMI = round(EMI_calc(principle, rate, time, frequency),0)
print("""
---------------------------------------------------------------------
""")
print(f"""
The EMI for Loan of Rs.{principle};
at interest rate of {rate*100} % for {time} years;
would be: Rs.""", EMI)
print("""
---------------------------------------------------------------------
""")
Here is a code snippet using numpy functions. This shows you the payment, principal, interest, instalment and total_amount each month. Run it and see the output. You can also check the syntax for Excel "IPMT()" and "PPMT()" functions for more explanation of the arguments.
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.pmt.html#numpy.pmt
import math
import numpy as np
rate = 0.08
start_amount = 100000.0
end_amount = 50000.0
diff_amount = start_amount - end_amount
# nr_years = 4
payment_frequency = int (12)
nr_months = 70 # = nr_years * payment_frequency
per_np = np.arange (nr_months) + 1 # +1 because index starts with 1 here
pay_b = rate / payment_frequency * end_amount
ipmt_np = np.ipmt (rate / payment_frequency, per_np, nr_months, diff_amount) - pay_b
ppmt_np = np.ppmt (rate / payment_frequency, per_np, nr_months, diff_amount)
for payment in per_np:
idx = payment - 1
principal = math.fabs (ppmt_np [idx])
start_amount = start_amount - principal
interest = math.fabs (ipmt_np [idx])
instalment = principal + interest
print payment, "\t", principal, "\t", interest, "\t\t", instalment, "\t\t", start_amount
print np.sum (ipmt_np)

Categories

Resources