Comparador de N° numeros enteros [ESP-ENG] | Python

¡Saludos! He aquí estoy de vuelta para compartirles un poco sobre programación, en concreto, sobre un ejercicio de práctica que me asignaron en la universidad. Para esta ocasión, Python vuelve a ser el lenguaje de programación a tratar.

El enunciado de hoy es un clásico entre los ejercicios de programación. "Determine el máximo valor y el mínimo valor de N números enteros".

Greetings! Here I am back to share with you a little bit about programming, specifically, about a practice exercise I was assigned in college. For this occasion, Python is once again the programming language to be covered.

Today's statement is a classic among programming exercises. "Determine the maximum value and minimum value of N integers".


Portada post programacion, tech (1).gif

Gif Created with CANVA / Gif creado con CANVA

Education separador png.png

Recuerdo haber tratado un ejercicio muy similar en C++, solo que esa vez usamos ternarios y solo eran 3 números a comparar, en cambio, para este caso son N números, por lo que toca usar bucles y pedir datos al usuario, las veces que sean necesarias para las comparaciones.

Al leer este enunciado se me ocurrieron 2 formas de hallar la solución, por lo que decidí programar las dos. Una un poco más apegada al enunciado que la otra, pero al final, ambas cumplen con el requisito.

Para empezar hice una que comienza con la función "Max_or_Min" y se basa en retornar 0,1 o 2, dependiendo de cuál haya sido el resultado de la comparación de los dos números que exige por parámetro. Retornará 1 si n1 es mayor a n2, 2 en caso contrario y 0 si ambos son iguales.

Sigue la declaración de 3 variables, la primera es "val", con el valor "Y", que servirá de parámetro al estilo "llave" para un bucle while que sirve para repetir el proceso de comparación si el usuario responde que si quiere continuarlo, en caso contrario, termina el programa. Pero esto lo detallare mejor algunas líneas adelante.

Luego continúan "max" y "min", variables que irán cambiando según se actualice el valor máximo y mínimo a mostrar al usuario. Sigue un print para dar la bienvenida, luego se leen los datos y se entra a una serie de if-elif-else para tomar uno u otro camino según sea el valor arrojado por la antes descrita, función "Max_or_Min".

De tal forma que si el n1 ingresado es mayor a n2 o se da el caso contrario o el caso de iguales, se actualizan los valores de max y min de forma que la información suministrada en el print sea fidedigna.

Luego de esto sigue el ya mencionado bucle while, este, cuando la respuesta del usuario es afirmativa, vuelve a realizar las comparaciones, pero esta vez basado en el máximo, el mínimo y n1, dado que ya no hace falta un n2.

Una vez compara, muestra en pantalla los resultados y luego vuelve a preguntar si se quiere continuar, de tal manera que se puede cumplir el parámetro "N" números enteros, pues el usuario puede repetir el proceso cuantas veces quiera sin perder la comparación anterior.

El bucle también cuenta con la validación de que, si se ingresa un valor diferente de "Y", "y", "N" o "n", el bucle repite la pregunta, de tal manera que no es posible salir sin antes dar una respuesta que cumpla con la condición de ser "Y"/"y" para si o "N"/"n" para no.

I remember having tried a very similar exercise in C++, only that time we used ternary and there were only 3 numbers to compare, on the other hand, for this case there are N numbers, so it is necessary to use loops and ask for data to the user, as many times as necessary for the comparisons.

When I read this statement I thought of 2 ways to find the solution, so I decided to program both of them. One a little more attached to the statement than the other, but in the end, both meet the requirement.

To begin with I made one that starts with the function "Max_or_Min" and is based on returning 0, 1 or 2, depending on what was the result of the comparison of the two numbers required by parameter. It will return 1 if n1 is greater than n2, 2 otherwise and 0 if both are equal.

It follows the declaration of 3 variables, the first one is "val", with the value "Y", that will serve as parameter to the style "key" for a loop while that serves to repeat the process of comparison if the user answers that if he wants to continue it, otherwise, it finishes the program. But this I will detail it better some lines ahead.

Then follow "max" and "min", variables that will change as the maximum and minimum value to be shown to the user is updated. It follows a print to welcome, then the data is read and a series of if-elif-else is entered to take one or another way according to the value thrown by the before described function "Max_or_Min".

In such a way that if the n1 entered is greater than n2 or the opposite case or the case of equals, the values of max and min are updated so that the information provided in the print is reliable.

After this follows the already mentioned while loop, this one, when the user's answer is affirmative, performs the comparisons again, but this time based on the maximum, the minimum and n1, since n2 is no longer needed.

Once it compares, it displays the results on the screen and then asks again if the user wants to continue, so that the parameter "N" integers can be met, since the user can repeat the process as many times as he wants without losing the previous comparison.

The loop also has the validation that, if a value different from "Y", "y", "N" or "n" is entered, the loop repeats the question, so that it is not possible to exit without first giving an answer that meets the condition of being "Y"/"y" for yes or "N"/"n" for no.

Education separador png.png

image.png

image.png

Education separador png.png

Para la segunda forma, me di la libertad de agregar otra función, más algunas validaciones extra para apegarme más a la exigencia de "N" números, como mencionaba al principio.

Al inicio está la misma función que antes explique, "Max_or_Min", está copiada de la forma anterior. La novedad radica en "Imprimir_Inf", que, a partir de los resultados arrojados por "Max_or_Min" muestra en pantalla un mensaje con la información de cuál número es el mayor o el menor, de tal manera uqe puedo reducir un poco las redundancias.

Seguidamente están las declaraciones, de las cuales n1, n2, max y min cumplen las mismas funciones que en la forma 1 antes explicada. Sin embargo, aparece nrepeats para guardar la cantidad de números a comparar, de tal modo que servirá como parámetro para los condicionales que siguen. Si nrepeats es mayor que 2 entonces se sabe que no serán solo 2 números a comparar, por tanto, luego de recibir los dos primeros y mostrar la primera comparación, continúa a un bucle for que itera en un rango de (nrepeats-2) veces, recordemos que ya tomamos 2 números por lo que a N se le deben restar 2 unidades.

En dicho bucle for se compara y muestran los resultados las veces que sea necesaria según el parámetro ingresado por el usuario, apoyándose en las dos funciones antes presentadas, "Max_or_Min" e "Imprimir_inf".

En caso de que solo sean 2 números a comparar, se leen n1 y n2 para posteriormente emplear "Imprimir_inf" para dar la información de una vez, pues el proceso que hace dicha función basta para suplir ese parámetro de "nrepeats".

Finalmente, si nrepeats es menor o igual a 1, envía un mensaje de error, pues no es posible comparar un solo número si no hay ningún otro con qué hacerlo. De igual manera 0 números o menos no tendría sentido.

For the second form, I took the liberty to add another function, plus some extra validations to stick more to the requirement of "N" numbers, as I mentioned at the beginning.

At the beginning is the same function that I explained before, "Max_or_Min", it is copied from the previous form. The novelty lies in "Print_Inf", which, from the results of "Max_or_Min" shows on the screen a message with the information of which number is the largest or smallest, so that I can reduce a little the redundancies.

Next are the statements, of which n1, n2, max and min fulfill the same functions as in form 1 above. However, nrepeats appears to store the number of numbers to compare, so that it will serve as a parameter for the conditionals that follow. If nrepeats is greater than 2 then it is known that there will not be only 2 numbers to compare, therefore, after receiving the first two and displaying the first comparison, it continues to a for loop that iterates in a range of (nrepeats-2) times, remember that we already took 2 numbers so that N must be subtracted 2 units.

In this for loop the results are compared and displayed as many times as necessary according to the parameter entered by the user, relying on the two functions presented above, "Max_or_Min" and "Print_inf".

In case there are only 2 numbers to compare, n1 and n2 are read and then "Print_inf" is used to give the information at once, since the process performed by this function is enough to supply the "nrepeats" parameter.

Finally, if nrepeats is less than or equal to 1, it sends an error message, because it is not possible to compare a single number if there is no other number to compare it with. Likewise 0 numbers or less would be meaningless.

Education separador png.png

image.png

image.png

image.png

Education separador png.png

1° Program

image.png

Education separador png.png

2° Program

image.png

image.png

Education separador png.png

Y bueno... ¡Eso es todo por hoy! Poco a poco sigo avanzando en mi proceso de aprendizaje y conforme siga practicando, seguiré compartiendo contenido al respecto que pueda ser de utilidad para otros estudiantes. Si andas buscando un buen curso de este lenguaje conocido como Python, en lo personal te recomiendo este: Clica aquí.

And well... That's all for today! Little by little I continue advancing in my learning process and as I keep practicing, I will continue sharing content that may be useful for other students. If you are looking for a good course on this language known as Python, I personally recommend you this one: Click here


Redes actualizada.gif


Puedes seguirme por acá si lo deseas:
You can follow me here if you want:

Cuenta secundaria
(Dibujos, edición y juegos) | Secondary account (Drawings, editing and games)



0
0
0.000
12 comments
avatar

Interesante, aunque no conozco nada de programación, pero admiro mucho a los que la estudian y dominan.
Felicitaciones, que sigas formándote y fortaleciéndote en esta área.

SEPARADOR 3 GIRASOL.png
!PIZZA
!HUESO

0
0
0.000
avatar

Greetings from the Virtual World Community. We send you Hueso token to support your work.
Click on this banner, to be directed to the Virtual World Discord and learn more about the curation project.


Uses: 2/6
!LOL

0
0
0.000
avatar

Tu publicacion ha sido votada por el Trail de CAPYBARAEXCHANGE por contenido excepcional y formar parte de nuestra comunidad de usuarios activos.

Unete a nuestro canal de discord en dónde podrás conocer mas acerca de nuestras operaciones y servicios. registrate ingresando en capybaraexchange para disfrutar del servicio

Si quieres formar parte de nuestro trail de curación ingresa a HIVEVOTE, haciendo clic en la imagen del capybara aristocratico. Capybaraexchange tu casa de cambio, rapida, confiable y segura

0
0
0.000
avatar

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).

You may also include @stemsocial as a beneficiary of the rewards of this post to get a stronger support. 
 

0
0
0.000