#23. ¿Puedo ahorrar otros periodos de tiempo?
Tu banco quiere permitirte ahorrar en nuevos intérvalos de tiempo que tú eleijas, agrega la funcionalidad a tu calculadora de interés compuesto de poner una cantidad de meses de ahorro variable
#24. ¿Puedo ahorrar en otros bancos?
Te llegó un correo de un banco rival diciéndote que ellos te ofrecen un 3% de interés plus un 7% extra año con año
¿¿Cuál de los dos bancos te conviene más para un año de ahorro?¿Cuál para 2?¿Cuál para 3?
#24. ¿Puedo ahorrar en otros bancos? en Python 😃
menu='''CALCULADORA DE INTERES COMPUESTO INGRESA EL MONTO DE CAPITAL INICIAL EN BOLIVIANOS Bs Y LA TASA DE INTERES EN PORCENTAJE EJ: "4" QUE SERA 4%''' print(menu) defrun(): capital=int(input('Ingresa tu mont en Bs: ')) interes=4 meses=36 intanual=0 banco='A' calcular_interes(capital,interes,meses,intanual,banco) interes=3 intanual=7/100 banco='B' calcular_interes(capital,interes,meses,intanual,banco) defcalcular_interes(capital,interes,meses,intanual,banco):for mes in range(meses): capital=capital+capital*interes/100if mes==11or mes==23or mes==35: capital=capital+intanual*capital capital=round(capital, 2) print(f'Tu ganancia a {int((mes+1)/12)} años a un interes de {interes}% es de {capital} Bs en el banco {banco} con el interes plus de {intanual}') else: passif __name__ == "__main__": run()```
Reto 23 en Java ☕️ ☕️ 😃
public class CalculadoraInteresCompuestoV2 { public static void main(String[] args) { DecimalFormat df = new DecimalFormat("#.00");System.out.println("Calculadora de capital final (considerando un interes del 4%)"); Scanner scanner = new Scanner(System.in);System.out.println("Ingresa tu captial incial");int cInicial = scanner.nextInt();double cFinal;System.out.println("Ingresa los meses");int meses = scanner.nextInt(); cFinal = Math.pow(1.04, (meses * 0.08333333333)) * cInicial;System.out.println("El capital final en " + meses + " meses" + " sería de: " + df.format(cFinal)); } }
Resultado de la ejecución

""" Programa para calcular interés compuesto mensual recibiendo como parámetros el capital inicial, el interés mensual y el número de meses. Program to calculate monthly compound interest receiving as parameters the initial capital, the monthly interest and the number of months. """import re defmonthly_compound_interest(initial_capital, interest, months): final_capital = round(initial_capital * ((1 + (interest/100))**months), 2) return final_capital defreceive_values(): initial_capital = input('Please enter your initial capital: $') dollar_pattern = re.compile(r'[0-9]*[.]?[0-9]{1,2}') whilenot dollar_pattern.fullmatch(initial_capital): initial_capital = input(' Invalid value. Please enter a dollar numeric value: $') interest = input('Please enter your monthly interest: %') interest_pattern = re.compile(r'[0-9]*[.]?[0-9]+') whilenot interest_pattern.fullmatch(interest): interest = input(' Invalid value. Please enter an interest numeric value: %') months = input('Please insert the number of months you want to calculate: ') whilenot months.isdigit(): months = input(' Invalid value. Please insert a positive integer: ') return float(initial_capital), float(interest), int(months) if __name__ == "__main__": print('COMPOUND INTEREST CALCULATOR!!!') initial_capital, interest, months = receive_values() final_capital = monthly_compound_interest(initial_capital, interest, months) print('Your mount (${}) with %{} interest in {} months will be: ${}' .format(initial_capital, interest, months, final_capital))
Reto 24 en JavaScript:
//¿Puedo ahorrar en otros bancos? en JavaScript//FuncionfunctionahorroFinal(capital, meses, banco) { let ahorroFinal = capital let interesActual = banco.interes let aumentoInteres = banco.interesPlus while (meses / 12 >= 1) { ahorroFinal *= Math.pow((1 + interesActual), 12) //C = c(1 + r)^t interesActual += aumentoInteres meses -= 12 } ahorroFinal *= Math.pow((1 + interesActual), meses) return ahorroFinal } //Datos de bancosconst BANCO_1 = { //Datos del reto 22interes: 0.04, //4% mensualinteresPlus: 0 } const BANCO_2 = { //Datos del reto 24interes: 0.03, //3% mensualinteresPlus: 0.07//7%+ cada año } //Datos del usuarioconst AHORRO_INICIAL = 1000const TIEMPOS = [1, 2, 3] //años//Resultados TIEMPOS.forEach(tiempo => { let meses = tiempo * 12let ahorroFinal_Banco1 = ahorroFinal(AHORRO_INICIAL, meses, BANCO_1) let ahorroFinal_Banco2 = ahorroFinal(AHORRO_INICIAL, meses, BANCO_2) mejorBanco = ahorroFinal_Banco1 > ahorroFinal_Banco2 ? 1 : 2console.log(`En el banco 1 se ahorra $${ahorroFinal_Banco1.toFixed(2)}`) console.log(`En el banco 2 se ahorra $${ahorroFinal_Banco2.toFixed(2)}`) console.log(`Para un tiempo de ${tiempo} año(s) conviene más el banco ${mejorBanco}`) }); // Consola:// En el banco 1 se ahorra $1601.03// En el banco 2 se ahorra $1425.76// Para un tiempo de 1 año(s) conviene más el banco 1// En el banco 1 se ahorra $2563.30// En el banco 2 se ahorra $4474.65// Para un tiempo de 2 año(s) conviene más el banco 2// En el banco 1 se ahorra $4103.93// En el banco 2 se ahorra $29443.49// Para un tiempo de 3 año(s) conviene más el banco 2
Reto 22 adaptado al reto 23 en Java:
PD: no sabia del interes compuesto antes de este reto, muy curioso me hizo considerar un plan de ahorros.
public class InterestCalculator { private static DecimalFormat decimalFormat = new DecimalFormat("#.##"); private Scanner scan = new Scanner(System.in);/** * Reto #22, Calculadora de interes compuesto */ public void calculateInterest() { double savings = 0;System.out.println("Please enter the amount to save monthly:");double amount = scan.nextDouble();System.out.println("Please enter the number of intervals:");int intervals = scan.nextInt();int[] months = monthlyIntervals(intervals);for (int i = 0; i < months.length; i++) { savings += (amount * months[i]) * 1.04;System.out.println("Months: " + i + "\nTotal Savings: " + decimalFormat.format(savings)); } } /** * Reto #23, Recive el numero de intervalos deseados y * devulve un arreglo con los meses en dichos intervalos * * @param intervals * @return int[] */ public int[] monthlyIntervals(int intervals) { int[] months = new int[intervals];for (int i = 0; i < months.length; i++) {System.out.println("This is the interval No. " + (i + 1));System.out.println("Please enter the number of months: "); months[i] = scan.nextInt(); } return months; } }
JavaScript - Dia 23
const meses = prompt('Cuantos meses quieres ahorrar?') functioninterest(money, perc, period) { let ganancia = (money*(perc/100)) + money if(period <= 0) { meses2 = prompt('Introduce un valor mayor a 0:') interest(100, 4, meses2) } else { for(i = 1; i < period; i++) { ganancia += (ganancia*(perc/100)) } } alert(`Esto generaste en ${i} meses: $ ${ganancia.toFixed(2)}`) } interest(100, 4, meses)
Reto 24 en Java ☕️ ☕️ 😃
public class CalculadoraInteresCompuestoV3 { public static void main(String[] args) { DecimalFormat df = new DecimalFormat("#.00");System.out.println("Calculadora de capital final (considerando un interes del 4%)"); Scanner scanner = new Scanner(System.in);System.out.println("Ingresa tu captial incial");int cInicial = scanner.nextInt();double cFinal;System.out.println("Ingresa los meses");int meses = scanner.nextInt();double cFinalB; cFinal = Math.pow(1.04, (meses * 0.08333333333)) * cInicial;//Interés del 4% cFinalB = Math.pow(1.03, (meses * 0.08333333333)) * cInicial;//Interés del 3%System.out.println("El capital final con el banco A en " + meses + " meses" + " sería de: " + df.format(cFinal));System.out.println("El capital final con el banco B en " + meses + " meses" + " sería de: " + df.format(cFinalB)); } }
Respuesta del reto 23:
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Ahorros en otros periodos</title></head><style> * { margin: 0; } .contenedor { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; } .section { padding: 2rem; } .inputs { display: inherit; flex-direction: column; justify-content: center; align-items: center; } .btn { border: 2px solid black; border-radius: 6px; cursor: pointer; height: 50%; } #newFrase { padding: 020px; text-align: justify; } </style><body><divclass="contenedor"><h1>Ingresa el monto que vas a Ahorrar con una tasa de 4% a tu favor</h1><divclass="inputs"><divstyle="display: flex; flex-direction: row; justify-content: center; align-items: center;"><sectionclass="section"> Monto: <inputid="monto"/></section><buttononclick="calcular()"class="btn">Calcular...</button></div><h4style="margin-bottom: 16px;">Cuantos meses deseas ahorrar? <inputid='meses'></input></h4><h4>Tendrías un ahorro de $ <spanid='ahorro'></span></h4></div></div><script>functioncalcular(){ let monto = parseFloat(document.getElementById('monto').value) const meses = parseInt(document.getElementById('meses').value) const ahorro = document.getElementById('ahorro') for (let i = 1; i <= meses; i++){ monto = monto + (monto*0.04) } ahorro.innerHTML = monto.toFixed(2) } </script></body></html>
El resultado del reto 24:
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>Ahorros en otros periodos</title></head><style> * { margin: 0; } .contenedor { display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; } .section { padding: 2rem; } .inputs { display: inherit; flex-direction: column; justify-content: center; align-items: center; } .btn { border: 2px solid black; border-radius: 6px; cursor: pointer; height: 50%; } #newFrase { padding: 020px; text-align: justify; } </style><body><divclass="contenedor"><h1>Ingresa el monto que vas a Ahorrar</h1><divclass="inputs"><divstyle="display: flex; flex-direction: row; justify-content: center; align-items: center;"><sectionclass="section"> Monto: <inputid="monto"/></section><buttononclick="calcular()"class="btn">Calcular...</button></div><h4style="margin-bottom: 16px;">En tu banco al 4%, en un año ahorraras $ <spanid='año4'>0</span></h4><h4style="margin-bottom: 16px;">En tu banco al 4%, en dos años ahorraras $ <spanid='dosAños4'>0</span></h4><h4style="margin-bottom: 16px;">En tu banco al 4%, en tres años ahorraras $ <spanid='tresAños4'>0</span></h4><br><h4style="margin-bottom: 16px;">En el banco rival al 3% + 7% año a año, en un año ahorraras $ <spanid='año3'>0</span></h4><h4style="margin-bottom: 16px;">En el banco rival al 3% + 7% año a año, en dos años ahorraras $ <spanid='dosAños3'>0</span></h4><h4style="margin-bottom: 16px;">En el banco rival al 3% + 7% año a año, en tres años ahorraras $ <spanid='tresAños3'>0</span></h4><h3style="display: none;"id='resultado'>En el primer año te conviene <spanid='primerAño'></span>, en el segundo año te conviene <spanid='segundoAño'></span>, y en el tercer año te conviene <spanid='tercerAño'></span>!</h3></div></div><script>functioncalcular(){ let monto = parseFloat(document.getElementById('monto').value) let calculo4 = monto let calculo3 = monto const año4 = document.getElementById('año4') const dosAños4 = document.getElementById('dosAños4') const tresAños4 = document.getElementById('tresAños4') const año3 = document.getElementById('año3') const dosAños3 = document.getElementById('dosAños3') const tresAños3 = document.getElementById('tresAños3') for (let i = 1; i <= 36; i++){ calculo4 = calculo4 + (calculo4 * 0.04) calculo3 = calculo3 + (calculo3 * 0.03) if (i === 12 || i === 24 || i === 36){ calculo3 = calculo3 + (calculo3 * 0.07) } switch (i){ case12: año4.innerHTML = calculo4.toFixed(2) año3.innerHTML = calculo3.toFixed(2) if (calculo4 > calculo3) { document.getElementById('primerAño').innerHTML = 'tu banco actual' } else { document.getElementById('primerAño').innerHTML = 'el banco rival' } document.getElementById('resultado').style = 'display: block;'breakcase24: dosAños4.innerHTML = calculo4.toFixed(2) dosAños3.innerHTML = calculo3.toFixed(2) if (calculo4 > calculo3) { document.getElementById('segundoAño').innerHTML = 'tu banco actual' } else { document.getElementById('segundoAño').innerHTML = 'el banco rival' } document.getElementById('resultado').style = 'display: block;'breakcase36: tresAños4.innerHTML = calculo4.toFixed(2) tresAños3.innerHTML = calculo3.toFixed(2) if (calculo4 > calculo3) { document.getElementById('tercerAño').innerHTML = 'tu banco actual' } else { document.getElementById('tercerAño').innerHTML = 'el banco rival' } document.getElementById('resultado').style = 'display: block;'breakdefault: break } } } </script></body></html>
Reto 23 en JavaScript y en Python
//¿Puedo ahorrar otros periodos de tiempo? en JavaScriptfunctionfinalAmount(capital, time, rate) { return capital * Math.pow(1 + rate, time) //C = c(1 + r)^t } //Pedido de datosconst capital = 1000const tiempo = parseInt(prompt('¿Por cuantos meses vas a ahorrar?')) const interes = 4/100//4% alert(`En ${tiempo} mes(es) vas a ahorrar $${finalAmount(capital, tiempo, interes).toFixed(2)}`)
#¿Puedo ahorrar otros periodos de tiempo? en PythondeffinalAmount(capital, time, rate):return capital * (1 + rate)**time # C = c(1 + r)^t#Pedido de datos capital = 1000 tiempo = int(input('¿Por cuantos meses vas a ahorrar?: ')) interes = 4/100# 4% print('En {} mes(es) vas a tener ${}'.format(tiempo, round(finalAmount(capital, tiempo, interes), 2)))
#PlatziCodingChallenge Día 24 - Solución al reto con JavaScript
Repo:
https://github.com/pahoalapizco/PlatziCodingChallenge
Código

Implementación

Resultado

El reto en JS, C y C++.
https://github.com/ceporro/PlatziCodingChallenge/tree/master/Day 22-24
Reto 23: ¿Puedo ahorrar otros periodos de tiempo?
Repositorio del reto: PlatziCodingChallengeRepo
GitHub pages: PlatziCodingChallengePages
Reto 24: ¿Puedo ahorrar en otros bancos?
Repositorio del reto: PlatziCodingChallengeRepo
GitHub pages: PlatziCodingChallengePages
#23. ¿Puedo ahorrar otros periodos de tiempo? en Python 😃
menu='''CALCULADORA DE INTERES COMPUESTO INGRESA EL MONTO DE CAPITAL INICIAL EN BOLIVIANOS Bs Y LA TASA DE INTERES EN PORCENTAJE EJ: "4"QUE SERA 4%''' print(menu) capital=int(input('Ingresa tu mont enBs: ')) interes=int(input('Ingresa tu interes: ')) month=int(input('Ingresa a cuantos meses deseas calcular el interes: ')) meses=25 for mes inrange(meses): ganancia=capital*((1+interes/100)**mes) ganancia=round(ganancia, 2) if mes==month: print(f'Tu ganancia a {mes} meses para un capital de {capital} Bs a un interes de {interes}% es de {ganancia} Bs') else: pass```
Challenge 23: 🐍🐍
definteres(monto, meses): monto_con_intereses = monto for _ in range(meses): interes = monto_con_intereses * 0.04 monto_con_intereses += interes monto_con_intereses = round(monto_con_intereses, 2) return monto_con_intereses defrun(): ahorro_inicial = float(input('¿Con qué cantidad iniciarás tus ahorros?: ')) meses = int(input('¿Por cuántos meses ahorrarás tu dinero?: ')) ahorro_con_intereses = interes(ahorro_inicial, meses) print(f"""\nAl comenzar a ahorrar hoy ${ahorro_inicial} tendrás en: {meses} meses: ${ahorro_con_intereses} """) if __name__ == "__main__": run()
En Python:
24. ¿Puedo ahorrar en otros bancos?
""" Programa para calcular interés compuesto mensual recibiendo como parámetros el capital inicial, el interés mensual y anual y el número de meses. Program to calculate monthly compound interest receiving as parameters the initial capital, the monthly and anual interest and the number of months. """import re defmonthly_anual_interest(initial_capital, monthly_interest, months): anual_monthly_capital = initial_capital * ((1 + (monthly_interest/100))**months) return anual_monthly_capital deffinal_anual_interest(anual_monthly_capital, anual_interest): final_anual_capital = anual_monthly_capital * (1 + (anual_interest/100)) return final_anual_capital defmonthly_compound_interest_plus(initial_capital, monthly_interest, anual_interest, months): anios = int(months/12) final_anual_capital = 0for anio in range(1, anios+1): anual_monthly_capital = monthly_anual_interest(initial_capital, monthly_interest, 12) final_anual_capital = final_anual_interest(anual_monthly_capital, anual_interest) initial_capital = final_anual_capital remaining_months = months - (anios*12) final_capital = monthly_anual_interest(initial_capital, monthly_interest, remaining_months) return round(final_capital,2) defreceive_values(): initial_capital = input('Please enter your initial capital: $') dollar_pattern = re.compile(r'[0-9]*[.]?[0-9]{1,2}') whilenot dollar_pattern.fullmatch(initial_capital): initial_capital = input(' Invalid value. Please enter a dollar numeric value: $') monthly_interest = input('Please enter your monthly interest: %') interest_pattern = re.compile(r'[0-9]*[.]?[0-9]+') whilenot interest_pattern.fullmatch(monthly_interest): monthly_interest = input(' Invalid value. Please enter an interest numeric value: %') anual_interest = input('Please enter your anual interest: %') whilenot interest_pattern.fullmatch(anual_interest): anual_interest = input(' Invalid value. Please enter an interest numeric value: %') months = input('Please insert the number of months you want to calculate: ') whilenot months.isdigit(): months = input(' Invalid value. Please insert a positive integer: ') return float(initial_capital), float(monthly_interest), float(anual_interest), int(months) if __name__ == "__main__": print('COMPOUND INTEREST CALCULATOR!!!') initial_capital, monthly_interest, anual_interest, months = receive_values() total_final_capital = monthly_compound_interest_plus(initial_capital, monthly_interest, anual_interest, months) print('Your inital mount (${}) with %{} monthly interest and %{} anual interest in {} months will be: ${}' .format(initial_capital, monthly_interest, anual_interest, months, total_final_capital))
Para los 3 casos (1, 2 y 3 años) es mejor el banco actual:

Reto 24 en Python:
defrun(): CO = int(input('Ingresa el importe que deseas ahorrar: ')) tiempo = int(input('Escoge el número de meses para ahorrar: ')) tasa = 4 calculo_de_ahorro(tiempo, CO, tasa) tasa = 3 calculo_de_ahorro(tiempo, CO, tasa) defcalculo_de_ahorro(tiempo,CO, tasa): I_ganado = round( (CO * ( (pow(1 + (tasa/100), tiempo) ) - 1)),2 ) print('') print(' -- RESUMEN DE ESTADO -- ') print('Importe ahorrado (USD): {} '. format(CO)) print('Interés ganado (USD): {}'. format(I_ganado)) print('Total ganado (USD): {}'. format(CO + I_ganado)) print('Periodo de ahorro: {} meses'. format(tiempo)) print('Tasa: {} %'. format(tasa)) if __name__ == '__main__': run() print('Banco Alternativo')
Listo, en Python:
tasa = 4defrun(): print('Este banco te ofrece lo siguientes ahorros:') CO = int(input('Ingresa el importe que deseas ahorrar: ')) tiempo = int(input('Escoge el número de meses para ahorrar: ')) calculo_de_ahorro(tiempo, CO) defcalculo_de_ahorro(tiempo,CO): I_ganado = round( (CO * ( (pow(1 + (tasa/100), tiempo) ) - 1)),2 ) print('') print(' -- RESUMEN DE ESTADO -- ') print('Importe ahorrado (USD): {} '. format(CO)) print('Interés ganado (USD): {}'. format(I_ganado)) print('Total ganado (USD): {}'. format(CO + I_ganado)) print('Periodo de ahorro: {} meses'. format(tiempo)) print('Tasa: {} %'. format(tasa)) if __name__ == '__main__': run()```