I-NOZex Posted February 23, 2013 at 09:59 PM Report #496790 Posted February 23, 2013 at 09:59 PM Ando aqui um bocado as cabeçadas com este exercicio: Problem 2: Paying Debt Off In a Year : 15.0 pointsNow write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. By a fixed monthly payment, we mean a single number which does not change each month, but instead is a constant amount that will be paid each month. In this problem, we will not be dealing with a minimum monthly payment rate. The following variables contain values as described below: balance - the outstanding balance on the credit card annualInterestRate - annual interest rate as a decimal The program should print out one line: the lowest monthly payment that will pay off all debt in under 1 year, for example: Lowest Payment: 180 Assume that the interest is compounded monthly according to the balance at the end of the month (after the payment for that month is made). The monthly payment must be a multiple of $10 and is the same for all months. Notice that it is possible for the balance to become negative using this payment scheme, which is okay. A summary of the required math is found below: Monthly interest rate = (Annual interest rate) / 12.0 Monthly unpaid balance = (Previous balance) - (Minimum monthly payment) Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance) Confesso que nao entendo muito bem na teorica o que eles pedem, quanto mais na pratica, eu fiz aqui este codigo, mas tenho a sensação que nao tem nada a haver :\ #saldo da conta balance = 3329 #taxa anual annualInterestRate = 0.2 initial_bal = balance #O que tenho de pagar por mes de taxa payment = (balance * (1 + annualInterestRate/12)**12) total = 0 for month in range(1,13): # % taxa mensal monthly_rate = (annualInterestRate) / 12.0 #min_month_pay = (monthly_rate) * (balance) #total += min_month_pay month_unpaid_bal = (balance) - (payment) balance = (month_unpaid_bal) + (monthly_rate * month_unpaid_bal) print('Month rate: %f' % monthly_rate) print('month_unpaid_bal: %f' % month_unpaid_bal) print('balance: %f' % balance) print('payment: %f' % payment) #print('min_month_pay: %f' % min_month_pay) #print('total: %f' % (total/12)) se alguem me puder dar uma ajuda com isso, isso tem ai alguns comentarios e tal que meti para me orientar, mas tou tipo a zeros do que fazer :S e nada de usar bibliotecas que nao a default :\ Tenho alguma urgencia em quem conseguir ajudar, tenho que entregar isso ate 3aFeira as 2h da manha... é que depois tenho um outro exercicio que vai ser um pouco com base nesse :S basicamente nao consigo encontrar a logica de pensamento para realizar o codigo... nao tou a pedir que ninguem me de codigo, tou a pedir que me tentem explicar o que exactamente pedem, e que passos seguir ate la chegar... eles dizem que as operações matematicas sao estas: Monthly interest rate = (Annual interest rate) / 12.0 Monthly unpaid balance = (Previous balance) - (Minimum monthly payment) Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance) mas creio serem precisas mais, e tambem ja vi na discuçao que a resoluçao é simples e nao devemos dificultar, que é apenas "guess and check" mas tou completamente nas brancas :S B2R » Beat2Revolution v3.0b | Regista e divulga-nos beat2revolution.net
ffunenga Posted February 24, 2013 at 10:58 AM Report #496824 Posted February 24, 2013 at 10:58 AM Não percebi mt bem o enunciado. A frase chave é esta: "the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months" mas fiquei na mesma. De qq das formas, no que toca a implementação (se o objectivo for mesmo implementar um ciclo que passe por todos os meses) eu trocava umas coisas no teu código: - No ciclo for, em vez de "for month in range(1,13)" simplificava para "for month in range(12)". Não vale a pena estares a indexar de 1 a 12 porque depois se precisares de usar a variável "month" para acederes a um índice de uma lista, tens que tar com truques a subtrair um valor. - Antes do ciclo, inicializava várias listas e em cada iteração utilizava o metodo append para introduzir valores nas listas. Algo do género: # definição de constantes balances, month_unpaid_balances = [],[] for month in range(12): month_unpaid_balances.append(balances[-1]-payment) balances.append(month_unpaid_balances[-1]+(monthly_rate * month_unpaid_balances[-1])) # e depois no fim logo tratava de analisar as listas e apresentar resultados Nota: em python, para acederes ao último item de uma lista, utiliza-se o índice -1.
I-NOZex Posted February 24, 2013 at 11:42 AM Author Report #496827 Posted February 24, 2013 at 11:42 AM (edited) pois é a tal cena eu tambem nao entendi bem o que o enunciado pedia. vou analisar melhor o que diseste e tentar algo daqui a pouco quando for mexer nisso, se tiver mais duvidas digo algo entretanto se alguem entendeu melhor o que se pede, e me puder explicar. a minha dificuldade está mesmo mais em intrepertar exactamente o que é pretendido e de que forma dá pa la chegar. ja agora tambem ha assim uns "tip's" e "hit's" que eles dao mas mesmo assim nao entendo.... sao estes: Hint: How to think about this problem? Start with $10 payments per month and calculate whether the balance will be paid off in a year this way (be sure to take into account the interest accrued each month). If $10 monthly payments are insufficient to pay off the debt within a year, increase the monthly payment by $10 and repeat. Hint: A way of structuring your code If you are struggling with how to structure your code, think about the following:Given an initial balance, what code would compute the balance at the end of the year? Now imagine that we try our initial balance with a monthly payment of $10. If there is a balance remaining at the end of the year, how could we write code that would reset the balance to the initial balance, increase the payment by $10, and try again (using the same code!) to compute the balance at the end of the year, to see if this new payment value is large enough. I'm still confused! A good way to implement this problem will be to use a loop structure. You may want to refresh your understanding of while loops. Think hard about how the program will know when it has found a good minimum monthly payment value - when a good value is found, the loop can terminate. [*]Be careful - you don't want to overwrite the original value of balance. You'll need to save that value somehow for later reference! cumpz Edited February 24, 2013 at 11:44 AM by I-NOZex B2R » Beat2Revolution v3.0b | Regista e divulga-nos beat2revolution.net
I-NOZex Posted February 25, 2013 at 03:45 PM Author Report #496947 Posted February 25, 2013 at 03:45 PM mais ninguem? :\ B2R » Beat2Revolution v3.0b | Regista e divulga-nos beat2revolution.net
Pedro C. Posted February 25, 2013 at 06:40 PM Report #496966 Posted February 25, 2013 at 06:40 PM (edited) I-NOZex posso dizer-te o que entendi do enunciado. Tenho um balanço cartão de crédito (seja 3329, por exemplo - atenção que isto é a divida). Tenho um pagamento fixo mensal (não varia portanto) e o que tenho de actualizar de mês para mês é: *) o balanço do mês anterior menos o que estou a pagar este mês mais o juro (seja o 0.2/12 que usaste no teu código) do resultado desta conta. A ideia é tentar minimizar o problema, ou melhor, chegar à solução na qual, utilizando múltiplos de 10 como pagamento, ficas após 12 meses com balanço zero (resultado ideal) ou negativo (se o zero não for possível que seja o negativo mais próximo possível, mas tem de ser negativo, caso contrário não foi paga a divida após 12 meses). Em termos de código: from __future__ import division balance = 3329 month_payment = 10 anual_interest = 0.2 month_interest = anual_interest/12 def debt(balance,month_payment,month_interest): for i in xrange(12): balance = (balance - month_payment)+month_interest*(balance - month_payment) return balance for i in xrange(1,40): print 'MONTLHY PAYMENT: ',i*month_payment,' -> FINAL BALANCE: ', debt(balance,month_payment*i,month_interest) O resultado do código acima foi: ...MONTHLY PAYMENT: 280 -> FINAL BALANCE: 312.153191468 MONTHLY PAYMENT: 290 -> FINAL BALANCE: 178.324629676 MONTHLY PAYMENT: 300 -> FINAL BALANCE: 44.4960678838 MONTHLY PAYMENT: 310 -> FINAL BALANCE: -89.3324939084 MONTHLY PAYMENT: 320 -> FINAL BALANCE: -223.161055701 MONTHLY PAYMENT: 330 -> FINAL BALANCE: -356.989617493 MONTHLY PAYMENT: 340 -> FINAL BALANCE: -490.818179285 ... Se não me enganei na interpretação do problema será isto o pretendido. Já agora a minimização do problema, embora acho que pode ser feita analiticamente, está a ser feita a partir de um loop tal como indicado no "Hint". Eles falam também em guarda o valor inicial do balanço (coisa que não fiz mas é uma questão de se criar um nova variável) e também darem um critério de paragem (um if a perguntar se o balança atingiu zero ou negativo é suficiente penso eu). Edited February 25, 2013 at 06:57 PM by Pedro C. 1 Report
I-NOZex Posted February 25, 2013 at 06:48 PM Author Report #496969 Posted February 25, 2013 at 06:48 PM (edited) exacto 🙂 obrigado pela explicação, era isto que andava a tentar entender mas fiquei com uma duvida: xrange(1,40) porque 40? EDIT: ja fiz as alterações necessarias, e para estar totalmente correcto ficou assim: #alternei com outros valores de balanço balance = 4773 month_payment = 10 annualInterestRate = 0.2 month_interest = annualInterestRate/12 def debt(balance,month_payment,month_interest): for i in xrange(12): balance = (balance - month_payment)+month_interest*(balance - month_payment) return balance final_bal = 0 i = 0 while final_bal >=0: final_bal = debt(balance,month_payment*i,month_interest) month_pay = i*month_payment i += 1 print 'Lowest Payment: '+str(month_pay) Mesmo muito obrigado, eu sozinho não estava a chegar lá xD agora tenho de "refazer" o exercicio com o algoritmo "bisection search", penso que agora ja chego la sozinho, é que sem este feito era impossivel fazer o outro. De novo, obrigado Pedro 😉 Edited February 25, 2013 at 07:07 PM by I-NOZex B2R » Beat2Revolution v3.0b | Regista e divulga-nos beat2revolution.net
Pedro C. Posted February 25, 2013 at 06:51 PM Report #496970 Posted February 25, 2013 at 06:51 PM (edited) Porque não sabia qual era o valor certo e não tinha critério de paragem (só reparei que se podia meter um depois de já ter escrito o código). Limitei-me a experimentar todos os múltiplos de 10 até um número redondo como 40 (podia ser 50 mas 40 pareceu-me suficiente) e verificar na lista de saida onde aparecia um zero ou o primeiro negativo. EDIT: ah, mas se o problema for o número que tu dás podes até nem dar nenhum fazendo um ciclo while enquanto uma flag qualquer for verdadeira. E ele corre até atingir o critério de paragem. Edited February 25, 2013 at 06:57 PM by Pedro C. 1 Report
I-NOZex Posted February 25, 2013 at 07:13 PM Author Report #496974 Posted February 25, 2013 at 07:13 PM (edited) Porque não sabia qual era o valor certo e não tinha critério de paragem (só reparei que se podia meter um depois de já ter escrito o código). Limitei-me a experimentar todos os múltiplos de 10 até um número redondo como 40 (podia ser 50 mas 40 pareceu-me suficiente) e verificar na lista de saida onde aparecia um zero ou o primeiro negativo. EDIT: ah, mas se o problema for o número que tu dás podes até nem dar nenhum fazendo um ciclo while enquanto uma flag qualquer for verdadeira. E ele corre até atingir o critério de paragem. ya, foi mesmo isso que eu fiz, um while, engloba logo a paragem, e o loop, tinha feito 1º com um break, mas depois é que entendi melhor o que era aquele loop Obrigado mesmo Pedro 👍 Edited February 25, 2013 at 07:13 PM by I-NOZex B2R » Beat2Revolution v3.0b | Regista e divulga-nos beat2revolution.net
schwartz Posted February 25, 2013 at 10:35 PM Report #496998 Posted February 25, 2013 at 10:35 PM Olá, esse problema é do EDX né, será que você poderia postar os outros dois para que eu possa comparar com os meus ? Obrigado!
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now