<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alberto Márquez on Medium]]></title>
        <description><![CDATA[Stories by Alberto Márquez on Medium]]></description>
        <link>https://medium.com/@bbetoben122?source=rss-6d34be8d8641------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*y5hR2-UyNYYiE7X4</url>
            <title>Stories by Alberto Márquez on Medium</title>
            <link>https://medium.com/@bbetoben122?source=rss-6d34be8d8641------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 04:06:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bbetoben122/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[River Crossing]]></title>
            <link>https://medium.com/@bbetoben122/river-crossing-e13f87385083?source=rss-6d34be8d8641------2</link>
            <guid isPermaLink="false">https://medium.com/p/e13f87385083</guid>
            <dc:creator><![CDATA[Alberto Márquez]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 04:42:37 GMT</pubDate>
            <atom:updated>2024-10-09T04:42:37.371Z</atom:updated>
            <content:encoded><![CDATA[<p>River Crossing</p><p><a href="https://www.codingame.com/training/medium/river-crossing">Exercise</a></p><p><strong>Goal</strong></p><p>There is a farmer, a wolf, a goat and a cabbage.<br>They need to cross a river with the following restrictions:</p><p>* The farmer can move from one side to the other freely, and can optionally carry one other entity<br>* The wolf can’t be on the same side with the goat without the farmer<br>* The goat can’t stay at the same side with the cabbage without the farmer</p><p>The river has two sides <strong>L</strong> for Left and <strong>R</strong> for Right.</p><p>You are given the initial positions and the target positions, in the following order <strong>Farmer, Wolf, Goat, Cabbage</strong>. For example you may be given the positions like so</p><p><strong>L L L R</strong> which would mean that the farmer, wolf, and goat are on the left side and the cabbage is on the right side.</p><p>Without breaking the restrictions, print out the minimum legal states starting at the initial state to get to the target state and including the target state.</p><p><strong>FOR MULTIPLE SOLUTIONS</strong><br>If there are multiple solutions with the same length, <strong>return the one that is alphabetically first</strong>.</p><p><strong>Example Input</strong></p><pre>L L L R<br>L L L L</pre><p><strong>Desired Output</strong></p><pre>L L L R<br>R L R R<br>L L R L<br>R L R L<br>L L L L</pre><p><strong>Explanation</strong></p><pre>L L L R // Starting State<br>R L R R // Farmer takes goat to right<br>L L R L // Farmer takes cabbage left<br>R L R L // Farmer returns to goat<br>L L L L // Farmer takes goat to left</pre><p><strong>Input</strong></p><p><strong>Line 1:</strong> 4 letters representing the initial state<br><strong>Line 2:</strong> 4 letters representing the target state</p><p><strong>Output</strong></p><p><strong>Lines: S</strong>olution states, starting with the initial state and ending in the target state</p><p><strong>Constraints</strong></p><p>All problems have a solution, and each solution has fewer than 20 transition states</p><p><strong>Example</strong></p><p><strong>Input</strong></p><pre>L L L L<br>R L R L</pre><p>Output</p><pre>L L L L<br>R L R L</pre><p><strong>Entendiedo el Problema</strong></p><p>Un granjero, un lobo, una cabra y un repollo deben cruzar un río, pero hay restricciones sobre cómo pueden estar juntos en cada lado. El granjero puede moverse libremente y llevar a uno de los otros. No se pueden dejar el lobo con la cabra ni la cabra con el repollo sin la supervisión del granjero.</p><p>Dado un estado inicial y un estado objetivo, debes encontrar la secuencia mínima de movimientos legales desde el estado inicial hasta el estado objetivo, incluyendo ambos.</p><p><strong>Proceso</strong></p><p>se crea la función valido(estado), esta verifica si un estado dado es válido. El estado se descompone en las variables F , L , O y C. La función retorna False si el lobo está en el mismo lado que la cabra sin la presencia del granjero (L == O and F != O) o si la cabra está en el mismo lado que el repollo sin el granjero (O == C and F != C). En todos los demás casos, retorna True, indicando que el estado es válido.</p><pre>def valido(estado):<br>    F, L, O, C = estado<br>    if (L == O and F != O) or (O == C and F != C):<br>        return False<br>    return True</pre><p>Se define una función estados(estado), esta lo que hace es generar todos los estados posibles a partir del estado actual. Utiliza un diccionario llamado lados para alternar entre los lados izquierdo (&#39;L&#39;) y derecho (&#39;R&#39;). Para cada entidad en el estado, si se encuentra en el mismo lado que el granjero (pos == F), el programa crea un nuevo estado donde el granjero y esa entidad cruzan al otro lado. Luego, verifica si el nuevo estado es válido mediante la función valido. Si es así, lo añade a la lista de estados válidos, que finalmente se retorna.</p><pre>def estados(estado):<br>    lados = {&#39;L&#39;: &#39;R&#39;, &#39;R&#39;: &#39;L&#39;}<br>    F, L, O, C = estado<br>    siguientes_estados = []<br>    for i, pos in enumerate(estado):<br>        if pos == F:<br>            nuevo_estado = list(estado)<br>            nuevo_estado[0] = lados[nuevo_estado[0]]<br>            if i &gt; 0:<br>                nuevo_estado[i] = lados[nuevo_estado[i]]<br>            nuevo_estado_tup = tuple(nuevo_estado)<br>            if valido(nuevo_estado_tup):<br>                siguientes_estados.append(nuevo_estado_tup)<br>    return siguientes_estados</pre><p>Después de implementa la función visita(inicio, objetivo), que utiliza una búsqueda en anchura (BFS) para encontrar el camino más corto desde el estado inicial hasta el objetivo. Se inicializa una cola con el estado inicial y un camino que contiene solo este estado. Además, se mantiene un conjunto de estados visitados para evitar ciclos. Mientras haya estados en la cola, se toma el estado actual y el camino asociado. Si el estado actual coincide con el objetivo, la función retorna el camino. Para cada siguiente estado generado, si no ha sido visitado, se agrega a la cola junto con el camino actualizado. Esto asegura que los estados se procesen en orden alfabético.</p><pre>def visita(inicio, objetivo):<br>    cola = deque([(inicio, [inicio])])<br>    visitados = {inicio}<br>    while cola:<br>        actual, camino = cola.popleft()<br>        if actual == objetivo:<br>            return camino<br>        for siguiente_estado in sorted(estados(actual)):<br>            if siguiente_estado not in visitados:<br>                visitados.add(siguiente_estado)<br>                cola.append((siguiente_estado, camino + [siguiente_estado]))<br>    return []</pre><p>Finalmente, el programa lee el estado inicial y el estado objetivo desde la entrada estándar, llama a la función visita para encontrar la solución y luego imprime cada estado en la solución, separando los elementos con un espacio.</p><pre>inicio = tuple(input().split())<br>objetivo = tuple(input().split())<br><br>solucion = visita(inicio, objetivo)<br>for estado in solucion:<br>    print(&#39; &#39;.join(estado))</pre><p>Código completo:</p><pre>import sys<br>import math<br>from collections import deque<br><br>def valido(estado):<br>    F, L, O, C = estado<br>    if (L == O and F != O) or (O == C and F != C):<br>        return False<br>    return True<br><br>def estados(estado):<br>    lados = {&#39;L&#39;: &#39;R&#39;, &#39;R&#39;: &#39;L&#39;}<br>    F, L, O, C = estado<br>    siguientes_estados = []<br>    for i, pos in enumerate(estado):<br>        if pos == F:<br>            nuevo_estado = list(estado)<br>            nuevo_estado[0] = lados[nuevo_estado[0]]<br>            if i &gt; 0:<br>                nuevo_estado[i] = lados[nuevo_estado[i]]<br>            nuevo_estado_tup = tuple(nuevo_estado)<br>            if valido(nuevo_estado_tup):<br>                siguientes_estados.append(nuevo_estado_tup)<br>    return siguientes_estados<br><br>def visita(inicio, objetivo):<br>    cola = deque([(inicio, [inicio])])<br>    visitados = {inicio}<br>    while cola:<br>        actual, camino = cola.popleft()<br>        if actual == objetivo:<br>            return camino<br>        for siguiente_estado in sorted(estados(actual)):<br>            if siguiente_estado not in visitados:<br>                visitados.add(siguiente_estado)<br>                cola.append((siguiente_estado, camino + [siguiente_estado]))<br>    return []<br><br>inicio = tuple(input().split())<br>objetivo = tuple(input().split())<br><br>solucion = visita(inicio, objetivo)<br>for estado in solucion:<br>    print(&#39; &#39;.join(estado))</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e13f87385083" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UNARY]]></title>
            <link>https://medium.com/@bbetoben122/unary-b63397f22383?source=rss-6d34be8d8641------2</link>
            <guid isPermaLink="false">https://medium.com/p/b63397f22383</guid>
            <dc:creator><![CDATA[Alberto Márquez]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 04:28:06 GMT</pubDate>
            <atom:updated>2024-10-09T04:28:06.819Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>UNARY</strong></p><p><a href="https://www.codingame.com/training/easy/unary">Exercise</a></p><p><strong>The Goal</strong></p><p>Binary with 0 and 1 is good, but binary with only 0, or almost, is even better!</p><p>Write a program that takes an incoming message as input and displays as output the message encoded using this method.</p><p><strong>Rules</strong></p><p>Here is the encoding principle:</p><ul><li>The input message consists of ASCII characters (7-bit)</li><li>The encoded output message consists of blocks of 0</li><li>A block is separated from another block by a space</li><li>Two consecutive blocks are used to produce a series of same value bits (only 1 or 0 values):</li><li>- First block: it is always 0 or 00. If it is 0, then the series contains 1, if not, it contains 0<br>- Second block: the number of 0 in this block is the number of bits in the series</li></ul><p><strong>Example</strong></p><p>Let’s take a simple example with a message which consists of only one character: Capital C. C in binary is represented as 1000011, so with this method, this gives:</p><ul><li>0 0 (the first series consists of only a single 1)</li><li>00 0000 (the second series consists of four 0)</li><li>0 00 (the third consists of two 1)</li></ul><p>So C is coded as: 0 0 00 0000 0 00</p><p>Second example, we want to encode the message CC (i.e. the 14 bits 10000111000011) :</p><ul><li>0 0 (one single 1)</li><li>00 0000 (four 0)</li><li>0 000 (three 1)</li><li>00 0000 (four 0)</li><li>0 00 (two 1)</li></ul><p>So CC is coded as: 0 0 00 0000 0 000 00 0000 0 00</p><p><strong>Game Input</strong></p><p>Input</p><p><strong>Line 1: </strong>the message consisting of N ASCII characters (without carriage return)</p><p>Output</p><p>The encoded message</p><p>Constraints</p><p>0 &lt; N &lt; 100</p><p><strong>Example</strong></p><pre>Input<br>C</pre><pre>Output<br>0 0 00 0000 0 00</pre><p><strong>Entendiendo el Próblema</strong></p><p>Se pide realizar un programa que tome un mensaje como entrada y muestre a la salida el mensaje codificado en numeros vinarios solo con 0</p><pre>Entrada<br>C</pre><p>esta en binario seria <strong>1000011</strong></p><p>en binario de solo 0 seria</p><pre>0 0 00 0000 0 000 00 0000 0 00</pre><p><strong>Proceso</strong></p><p>primero se crea una variable mensaje, la cual pedirá la entrada de un texto. Luego, se crea una cadena binary_messageen esta seconvierte cada carácter del mensaje a su representación binaria de 7 bits utilizando una comprensión de listas. La función ord(c) obtiene el valor ASCII del carácter c, y f&#39;{ord(c):07b}&#39; formatea ese valor como una cadena binaria de 7 bits.</p><pre>message = input()<br>binary_message = &#39;&#39;.join(f&#39;{ord(c):07b}&#39; for c in message)</pre><p>Después de crea una lista result que se utilizará para almacenar las partes codificadas del mensaje. Y se señala una variable i que se establece igual a 0</p><pre>result = []<br>i = 0</pre><p>se crea un blucle while ipara recorrer cada bit en binary_message . En cada iteración, se guarda el valor del bit actual en la variable bit y se inicializa un contador count en 1.</p><pre>while i &lt; len(binary_message):<br>    bit = binary_message[i]<br>    count = 1</pre><p>Se crea otro bucle while que se utiliza para contar cuántos bits consecutivos son iguales al bit actual. Este bucle se detiene cuando se encuentra un bit diferente o se alcanza el final de la cadena. Una vez que se cuenta el número de bits consecutivos, se genera una cadena codificada para esos bits y se agrega a la lista result. Si el bit es &#39;1&#39;, se añade &#39;0 &#39; seguido de &#39;0&#39; repetido count veces; si el bit es &#39;0&#39;, se añade &#39;00 &#39; seguido también de &#39;0&#39; repetido count veces. Después de procesar un bit, se incrementa el índice i en 1 para continuar con el siguiente bit.</p><pre>while i &lt; len(binary_message):<br>    bit = binary_message[i]<br>    count = 1<br>    while i + 1 &lt; len(binary_message) and binary_message[i + 1] == bit:<br>        count += 1<br>        i += 1<br>    result.append((&#39;0 &#39; if bit == &#39;1&#39; else &#39;00 &#39;) + &#39;0&#39; * count)<br>    i += 1</pre><p>Y por ultimo, el programa imprime el mensaje codificado, uniendo todos los elementos de la lista result con un espacio.</p><pre><br>print(&#39; &#39;.join(result))</pre><p><strong>Código Completo</strong></p><pre>import sys<br>import math<br><br>message = input()<br>binary_message = &#39;&#39;.join(f&#39;{ord(c):07b}&#39; for c in message)<br><br>result = []<br>i = 0<br>while i &lt; len(binary_message):<br>    bit = binary_message[i]<br>    count = 1<br>    while i + 1 &lt; len(binary_message) and binary_message[i + 1] == bit:<br>        count += 1<br>        i += 1<br>    result.append((&#39;0 &#39; if bit == &#39;1&#39; else &#39;00 &#39;) + &#39;0&#39; * count)<br>    i += 1<br><br>print(&#39; &#39;.join(result))</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b63397f22383" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DEFIBRILLATORS]]></title>
            <link>https://medium.com/@bbetoben122/defibrillators-1ab0d2f0f715?source=rss-6d34be8d8641------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ab0d2f0f715</guid>
            <dc:creator><![CDATA[Alberto Márquez]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 04:02:22 GMT</pubDate>
            <atom:updated>2024-10-09T04:02:22.082Z</atom:updated>
            <content:encoded><![CDATA[<p>DEFIBRILLATORS</p><p><a href="https://www.codingame.com/training/easy/defibrillators">Exercise</a></p><h3>The Goal</h3><p>The city of Montpellier has equipped its streets with defibrillators to help save victims of cardiac arrests. The data corresponding to <a href="http://data.montpellier3m.fr/dataset/d%C3%A9fibrillateurs-de-montpellier">the position of all defibrillators</a> is available online.</p><p>Based on the data we provide in the tests, write a program that will allow users to find the defibrillator nearest to their location using their mobile phone.</p><h3>Rules</h3><p>The input data you require for your program is provided in text format.<br>This data is comprised of lines, each of which represents a defibrillator. Each defibrillator is represented by the following fields:</p><ul><li>A number identifying the defibrillator</li><li>Name</li><li>Address</li><li>Contact Phone number</li><li>Longitude (degrees)</li><li>Latitude (degrees)</li></ul><p>These fields are separated by a semicolon (;).</p><p><strong><em>Beware</em></strong><em>: the decimal numbers use the comma (,) as decimal separator. Remember to turn the comma (,) into dot (.) if necessary in order to use the data in your program.</em></p><p><strong>DISTANCE</strong></p><p>The distance d between two points A and B will be calculated using the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*KWVz5mLz3iKBH2kamLODiQ.png" /></figure><p><em>Note: In this formula, the latitudes and longitudes are expressed in </em><strong><em>radians</em></strong><em>. 6371 corresponds to the radius of the earth in km.</em></p><p>The program will display the name of the defibrillator located the closest to the user’s position. This position is given as input to the program.</p><p><strong>Game Input</strong></p><p><strong>Input</strong></p><p><strong>Line 1: </strong>User’s longitude (in degrees)</p><p><strong>Line 2: </strong>User’s latitude (in degrees)</p><p><strong>Line 3: </strong>The number N of defibrillators located in the streets of Montpellier</p><p><strong>N next lines: </strong>a description of each defibrillator</p><p>Output</p><p>The name of the defibrillator located the closest to the user’s position.</p><p>Constraints</p><p>0 &lt; N &lt; 10000</p><p><strong>Example</strong></p><pre>Input<br>3,879483<br>43,608177<br>3<br>1;Maison de la Prevention Sante;6 rue Maguelone 340000 Montpellier;;3,87952263361082;43,6071285339217<br>2;Hotel de Ville;1 place Georges Freche 34267 Montpellier;;3,89652239197876;43,5987299452849<br>3;Zoo de Lunaret;50 avenue Agropolis 34090 Mtp;;3,87388031141133;43,6395872778854</pre><pre>Output<br>Maison de la Prevention Sante</pre><p><strong>Entendiendo el código</strong></p><p>El objetivo es encontrar el defibrilador más cercano a la ubicación del usuario, basada en la longitud y latitud proporcionadas. Los datos de los defibriladores incluyen su identificación, nombre, dirección, número de contacto, longitud y latitud.</p><p><strong>Proceso</strong></p><p>Primero, se define una función llamada a_radianes, que convierte las coordenadas de grados a radianes. Esta función toma un valor en grados, lo convierte a un número de punto flotante y utiliza math.radians para convertirlo a radianes.</p><pre>def a_radianes(grado):<br>    return math.radians(float(grado.replace(&#39;,&#39;, &#39;.&#39;)))</pre><p>Luego, se crea la función calcular_distancia, que utiliza la fórmula de distancia entre dos puntos en la superficie de la Tierra, considerando la curvatura de la misma. Esta función recibe las longitudes y latitudes de dos puntos (A y B) y calcula la distancia entre ellos en kilómetros, usando el radio de la Tierra</p><pre>def calcular_distancia(lonA, latA, lonB, latB):<br>    x = (lonB - lonA) * math.cos((latA + latB) / 2)<br>    y = latB - latA<br>    return math.sqrt(x**2 + y**2) * 6371</pre><p>se solicita la entrada de la longitud y latitud, las cuales tambien se convertiran a radianes utilizando la función a_radianes. Y tambien se pide el número de desfibriladores disponibles.</p><pre>lon = a_radianes(input())<br>lat = a_radianes(input())<br>n = int(input())</pre><p>Se crean dos variables defibrilador_cercano y distancia_minima . defibrilador_cercano, que almacenará el nombre del desfibrilador más cercano y distancia_minima, que se inicializa en infinito para asegurar que cualquier distancia calculada será menor en comparación.</p><pre>defibrilador_cercano = None<br>distancia_minima = float(&#39;inf&#39;)</pre><p>Despues en un blucle for en un rango (n) . El programa recorre cada desfibrilador proporcionado en la entrada. Para cada desfibrilador, se divide la línea de entrada en campos usando el punto y coma como separador. Se extraen las coordenadas (longitud y latitud) del desfibrilador y se convierten a radianes. Luego, se calcula la distancia entre la ubicación del usuario y el desfibrilador utilizando la función calcular_distancia. Si la distancia calculada es menor que la distancia mínima almacenada, se actualiza distancia_minima con la nueva distancia y se guarda el nombre del desfibrilador en defibrilador_cercano. Y para finalizar el programa imprime el nombre del desfibrilador más cercano a la ubicación del usuario.</p><pre>for i in range(n):<br>    defibrilador = input().split(&#39;;&#39;)<br>    defibrilador_lon = a_radianes(defibrilador[4])<br>    defibrilador_lat = a_radianes(defibrilador[5])<br>    distancia = calcular_distancia(lon, lat, defibrilador_lon, defibrilador_lat)<br>    <br>    if distancia &lt; distancia_minima:<br>        distancia_minima = distancia<br>        defibrilador_cercano = defibrilador[1]<br><br>print(defibrilador_cercano)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ab0d2f0f715" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DOLBEAR’S LAW]]></title>
            <link>https://medium.com/@bbetoben122/dolbears-law-f7c020aa307f?source=rss-6d34be8d8641------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7c020aa307f</guid>
            <dc:creator><![CDATA[Alberto Márquez]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 03:44:40 GMT</pubDate>
            <atom:updated>2024-10-09T03:44:40.957Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>DOLBEAR’S LAW</strong></p><p><a href="https://www.codingame.com/training/easy/dolbears-law">Exercise</a></p><h4>Goal</h4><p><strong>Dolbear’s law</strong> states the relationship between the <strong>air temperature</strong> and the <strong>rate at which crickets chirp</strong> (source: Wikipedia).</p><p>Dolbear expressed the relationship as the following formula, which provides a way to estimate the temperature <strong>TC</strong> in degrees Celsius from the number of chirps per minute, called N60:<br><strong>TC</strong> = 10 + (N60–40) / 7.</p><p>Another method is to count the number of chirps in <strong>8</strong> seconds, called N8, and add 5<br>(this is fairly accurate between 5 and 30°C):<br><strong>TC</strong> = N8 + 5.</p><p>We are in August and it is very hot.<br>With the help of Jiminy Cricket, you want to estimate the air temperature while staying cool at home.<br>You then take a stopwatch, a pencil and a paper, and every 4 seconds, you note the number of chirps of Jiminy.</p><p>For example, if you noted the following series: <strong>3 2 3</strong>, then Jiminy chirped <strong>3</strong> times in the first 4 seconds, then <strong>2</strong> times in the next 4 seconds, and finally <strong>3</strong> times in the last 4 seconds.</p><p>In order to have a good estimate of the air temperature, you take a lot of measurements: one measure every 4 seconds during M minutes.</p><p>Once you’re done with the measurements, you can compute the estimated temperature using the correct formula!<br>Unfortunately, Jiminy chirps whenever he wants, driving you crazy and distorting your calculations… so do not take your results too seriously!</p><p><strong>Input</strong></p><p><strong>Line 1</strong>: an integer M for the number of minutes your measurements lasted.<br><strong>Next</strong> M <strong>lines</strong>: series of 15 integers separated by a <strong>space</strong>, each integer representing the number of times that Jiminy has chirped in 4 seconds (each line thus represents 1 minute).</p><p>Output</p><p>On the <strong>first line</strong>, you must return the <strong>average</strong> of the estimates calculated every minute using the N60 <strong>formula</strong>.</p><p>On the <strong>second line</strong>, if the result on the first line is <strong>between</strong> 5 and 30 (inclusive), then return the <strong>average</strong> of the estimates calculated every 8 seconds using the N8 <strong>formula</strong>. If your total number of measurements is <strong>odd</strong>, then <strong>ignore the very last measure</strong> because it makes the total duration of your measurements non-divisible by 8 seconds.</p><p>The results must be printed <strong>rounded</strong> with <strong>1</strong> decimal place:<br><strong>16.0</strong> and <strong>16.1</strong> are <strong>valid</strong> outputs.<br><strong>16</strong> and <strong>16.12</strong> are <strong>invalid</strong> outputs.</p><p><strong>Constraints</strong></p><p>1 ≤ M ≤ 60<br>For every measure, 0 ≤ <strong>measure</strong> ≤ 20</p><p><strong>Example</strong></p><pre>Input<br>2<br>8 8 6 3 2 4 8 6 9 5 2 1 5 2 8<br>8 3 3 6 7 2 8 1 7 4 5 4 2 3 9</pre><pre>Output<br>14.9<br>14.9</pre><p><strong>Entendiendo el problema</strong></p><p>El objetivo es estimar la temperatura usando los chirridos de un grillo con dos fórmulas basadas en cuántas veces chirría en intervalos de tiempo. la primera es para chirridos por minuto (N60) y la otra para cada 8 segundos. luego se debe calcular el promedio de las estimaciones con la fórmula de chirridos por minuto y si el promedio está entre 5 y 30, también calcular el promedio con la fórmula de cada 8 segundos</p><p><strong>Proceso</strong></p><p>Primero, se define una función llamada Calcular_Entrada, que toma una lista de chirridos por minuto. En esta función, se calcula el número total de chirridos en un minuto, Luego, se estima la temperatura en grados Celsius usando la fórmula: TC = 10 + (N60 - 40) / 7 . Para finalizar la funcion devuelve la listas de chirridos y la temperatura calculada.</p><pre>def Calcular_Entrada():<br>    Total_Minutos_Chirridos = Lista<br>    N60 = sum(Total_Minutos_Chirridos)<br>    TC = 10 + (N60 - 40) / 7<br>    return Total_Minutos_Chirridos, TC</pre><p>luego se crean 3 listas Total_Estimaciones, Total_Chirridos , Estimaciones_8_segundosy una petición m</p><pre>Total_Estimaciones = []<br>Total_Chirridos = []<br>Estimaciones_8_segundos = []<br>m = int(input())</pre><p>Y se crea un ciclo for donde, para cada minuto de entrada, se toma una lista de números que representan los chirridos y se calcula la temperatura usando la función Calcular_Entrada. Los chirridos de cada minuto se agregan a una lista Total_Chirridos , y las temperaturas estimadas se guardan en la lista Total_Estimaciones. Después de recopilar todas las estimaciones, se calcula el promedio de estas temperaturas y se imprime con un decimal.</p><pre>for i in range(m):<br>    Lista = list(map(int,input().split()))<br>    Total_Minutos_Chirridos, TC = Calcular_Entrada()<br>    Total_Chirridos.extend(Lista)<br>    Total_Estimaciones.append(TC)<br><br>Minutos_Promedio = sum(Total_Estimaciones) / len(Total_Estimaciones)<br>print(f&quot;{Minutos_Promedio:.1f}&quot;)</pre><p>Si el promedio de las temperaturas calculadas está entre 5 y 30 grados, se define una nueva función llamada Temperatura_Extacta. Esta función toma la lista de chirridos, verifica que tenga un número par de elementos y luego agrupa los chirridos en pares de 8 segundos. Por cada par, se calcula una nueva estimación de temperatura sumando los chirridos y agregando 5. Las estimaciones resultantes se almacenan en la lista Estimaciones_8_segundos, y si la lista contiene datos, se calcula su promedio y se imprime.</p><pre>if 5 &lt;= Minutos_Promedio &lt;= 30:<br><br>    def Temperatura_Extacta(Total_Chirridos):<br><br>        if len(Total_Chirridos) % 2 != 0:<br>            Total_Chirridos = Total_Chirridos[:-1]<br><br>        for i in range(0, len(Total_Chirridos), 2):<br>            N8 = Total_Chirridos[i] + Total_Chirridos[i + 1]<br>            TC_8 = N8 + 5<br>            Estimaciones_8_segundos.append(TC_8)<br><br>        if Estimaciones_8_segundos:<br>            Promedio_8_segundos = sum(Estimaciones_8_segundos) / len(Estimaciones_8_segundos)<br>            print(f&quot;{Promedio_8_segundos:.1f}&quot;)<br><br>    Temperatura_Extacta(Total_Chirridos)</pre><p><strong>codigo completo</strong></p><pre>import sys<br>import math<br><br><br>def Calcular_Entrada():<br>    Total_Minutos_Chirridos = Lista<br>    N60 = sum(Total_Minutos_Chirridos)<br>    TC = 10 + (N60 - 40) / 7<br>    return Total_Minutos_Chirridos, TC<br><br>Total_Estimaciones = []<br>Total_Chirridos = []<br>Estimaciones_8_segundos = []<br>m = int(input())<br><br>for i in range(m):<br>    Lista = list(map(int,input().split()))<br>    Total_Minutos_Chirridos, TC = Calcular_Entrada()<br>    Total_Chirridos.extend(Lista)<br>    Total_Estimaciones.append(TC)<br><br>Minutos_Promedio = sum(Total_Estimaciones) / len(Total_Estimaciones)<br>print(f&quot;{Minutos_Promedio:.1f}&quot;)<br><br><br>if 5 &lt;= Minutos_Promedio &lt;= 30:<br><br>    def Temperatura_Extacta(Total_Chirridos):<br><br>        if len(Total_Chirridos) % 2 != 0:<br>            Total_Chirridos = Total_Chirridos[:-1]<br><br>        for i in range(0, len(Total_Chirridos), 2):<br>            N8 = Total_Chirridos[i] + Total_Chirridos[i + 1]<br>            TC_8 = N8 + 5<br>            Estimaciones_8_segundos.append(TC_8)<br><br>        if Estimaciones_8_segundos:<br>            Promedio_8_segundos = sum(Estimaciones_8_segundos) / len(Estimaciones_8_segundos)<br>            print(f&quot;{Promedio_8_segundos:.1f}&quot;)<br><br>    Temperatura_Extacta(Total_Chirridos)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7c020aa307f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Death First Search — Episode 1]]></title>
            <link>https://medium.com/@bbetoben122/death-first-search-episode-1-1fed10b46089?source=rss-6d34be8d8641------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fed10b46089</guid>
            <dc:creator><![CDATA[Alberto Márquez]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 03:17:33 GMT</pubDate>
            <atom:updated>2024-10-09T03:17:33.003Z</atom:updated>
            <content:encoded><![CDATA[<h4>Death First Search — Episode 1</h4><p><a href="https://www.codingame.com/ide/puzzle/death-first-search-episode-1">Exercise</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*KEOC-1x3A1X38JvU5LuZCw.png" /></figure><p><strong>The Goal</strong></p><p>Your virus has caused a backdoor to open on the Bobnet network enabling you to send new instructions in real time.</p><p>You decide to take action by <strong>stopping Bobnet from communicating on its own internal network</strong>.</p><p>Bobnet’s network is divided into several smaller networks, in each sub-network is a Bobnet agent tasked with transferring information by moving from node to node along links and <strong>accessing gateways leading to other sub-networks.</strong></p><p>Your mission is to reprogram the virus so it will <strong>sever links </strong>in such a way that the Bobnet Agent is unable to access another sub-network thus preventing information concerning the presence of our virus to reach Bobnet’s central hub.</p><h4>Rules</h4><p>For each test you are given:</p><ul><li>A map of the network.</li><li>The position of the exit gateways.</li><li>The starting position of the Bobnet agent.</li></ul><p><strong>&gt;&gt;&gt; Nodes can only be connected to up to a single gateway. &lt;&lt;&lt;</strong></p><p>Each game turn:</p><ul><li>First off, you sever one of the given links in the network.</li><li>Then the Bobnet agent moves from one Node to another accessible Node.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*UgWQVxJQqYnBS93sfi7dYA.png" /><figcaption><em>Bobnet agent</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*9kRumhG3SLIPV0-ctAEeOw.png" /><figcaption><em>Gateway</em></figcaption></figure><p>Example</p><pre>4 4 1<br>0 1<br>0 2<br>1 3<br>2 3<br>3</pre><p><strong>Initialization input</strong></p><p>Text representation of the network used in this example. There are 4 nodes, 4 links and 1 gateway. The next 4 lines describe the links. The last integer is the index of the exit node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*VtIO4IzCih_Domm9yahsBg.png" /><figcaption><strong>Turn 1</strong></figcaption></figure><p>The Bobnet agent starts at node 0 (SI = 0). Our virus cut the link between the nodes 1 and 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*HEVPJcewByn56ItCPogMAQ.png" /><figcaption><strong>Turn 2</strong></figcaption></figure><p>The Bobnet agent moves to node 2 (SI = 2). Our virus cut the link between the nodes 2 and 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*NVaVLl3hvJu3KQsbokhi-g.png" /><figcaption><strong>Turn 3</strong></figcaption></figure><p>The Bobnet agent has been cut off from the exit, you have won !</p><p><strong>Note</strong></p><p>The tests provided are similar to the validation tests used to compute the final score but remain different.</p><h4>Game Input</h4><p>The program must first read the initialization data from standard input. Then, <strong>within an infinite loop</strong>, read the data from the standard input related to the current state of the Bobnet agent and provide to the standard output the next instruction.</p><p><strong>Initialization input</strong></p><p><strong>Line 1: </strong>3 integers N L E<br>- N, the total number of nodes in the level, including the gateways.<br>- L, the number of links in the level.<br>- E, the number of exit gateways in the level.</p><p><strong>Next </strong>L<strong>lines: </strong>2 integers per line (N1, N2), indicating a link between the nodes indexed N1and N2in the network.</p><p><strong>Next </strong>E<strong>lines: </strong>1 integer EIrepresenting the index of a gateway node.</p><p><strong>Input for one game turn</strong></p><p><strong>Line 1: </strong>1 integer SI, which is the index of the node on which the Bobnet agent is positioned this turn.</p><p>Output for one game turn</p><p>A <strong>single line </strong>comprised of two integers C1 and C2separated by a space. C1and C2are the indices of the nodes you wish to sever the link between.</p><p><strong>Constraints</strong></p><p>2 ≤ N≤ 500<br>1 ≤ L ≤ 1000<br>1 ≤ E≤ 20<br>0 ≤ N1, N2&lt; N<br>0 ≤ SI&lt; N<br>0 ≤ C1, C2&lt; N<br>Response time per turn ≤ 150ms</p><p><strong>Entendiendo el problema</strong></p><p>El objetivo es impedir que el agente de Bobnet acceda a otras subredes cortando enlaces en la red. Cada nodo en la red puede estar conectado a otros nodos y a puertas de salida que permiten al agente transferir información a otras subredes. Si el agente puede acceder a una puerta de salida, se pierde. Si se logra cortarle el acceso a todas las puertas de salida, se gana.</p><p><strong>Entrada</strong></p><p>Se recibe la configuración de la red, que incluye el número total de nodos N, el número de enlaces Ly el número de puertas de salida E. Luego, se leen los pares de nodos que están conectados entre sí y las posiciones de las puertas de salida.</p><p><strong>Proceso</strong></p><p>Se reciben tres números enteros n, l, y e estos son el numero total de los nodos, enlace y puerta, estos se guardan en una lista llamada conexion .</p><pre>n, l, e = [int(i) for i in input().split()]<br>conexion=[]</pre><p>se crea un bucle for este se repetirá en un rango de L (L es el numero de conexiones). en cada iteración se lee una linea de entrada que contiene dos números n1 y n2 estos son los nodos conectados por un enlace, estos dos se agrupan en un mismo objeto y se agregan a la lista conexiones . se crea una lista vacía llamada gateways .</p><pre>for i in range(l):<br>    n1, n2 = [int(j) for j in input().split()]<br>    conexion.append((n1,n2))<br>gateways =[]</pre><p>Se crea un bucle for que se repetirá en una rango de E (E es el número de puertas de salida ). En cada iteración, se lee un número entero ei, que representa el índice de un nodo que actúa como puerta de salida en la red. Este valor se agrega a la lista gateways, que almacena todos los nodos que son puertas de salida.</p><pre>for i in range(e):<br>    ei = int(input())  <br>    gateways.append(ei)</pre><p>Se crea un bucle while True se lee un número entero si, que representa la posición actual del agente Bobnet y se crea una variablelink_to_cut en None . Luego, el programa recorre la lista conexion, que contiene los pares de nodo (c1, c2), se verifica si uno de los nodos esta en la lista gatewaysy si el otro nodo coincide con la posición actual del agente (si). Si ambos criterios se cumplen, se guarda el enlace entre c1 y c2 en link_to_cut, y se interrumpe el ciclo for, indicando que este es el enlace que se debe cortar.</p><pre>while True:<br>    si = int(input())  <br>    link_to_cut = None<br><br>    for c1, c2 in conexion:<br>        if c1 in gateways or c2 in gateways:<br>            if si == c1 or si == c2:<br>                link_to_cut = (c1, c2)<br>                break</pre><p>si la variable link_to_cut no es None, se imprime el par de nodos link_to_cut[0] y link_to_cut[1], lo que indica que se cortará ese enlace específico. Si no se ha encontrado un enlace adecuado se selecciona el primer enlace en la lista conexion, y se cortan los nodos representados por conexion[0] .</p><pre> if link_to_cut:<br>        print(link_to_cut[0], link_to_cut[1])<br>    else:<br>        c1, c2 = conexion[0]<br>        print(c1, c2)</pre><p><strong>Codigo completo</strong></p><pre>import sys<br>import math<br><br>n, l, e = [int(i) for i in input().split()]<br>conexion=[]<br>for i in range(l):<br>    n1, n2 = [int(j) for j in input().split()]<br>    conexion.append((n1,n2))<br>gateways =[]<br>for i in range(e):<br>    ei = int(input())  <br>    gateways.append(ei)<br># game loop<br>while True:<br>    si = int(input())  <br>    link_to_cut = None<br><br>    for c1, c2 in conexion:<br>        if c1 in gateways or c2 in gateways:<br>            if si == c1 or si == c2:<br>                link_to_cut = (c1, c2)<br>                break<br><br>    if link_to_cut:<br>        print(link_to_cut[0], link_to_cut[1])<br>    else:<br>        c1, c2 = conexion[0]<br>        print(c1, c2)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fed10b46089" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Personal Best]]></title>
            <link>https://medium.com/@bbetoben122/personal-best-d3fb398b98b6?source=rss-6d34be8d8641------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3fb398b98b6</guid>
            <dc:creator><![CDATA[Alberto Márquez]]></dc:creator>
            <pubDate>Tue, 08 Oct 2024 20:08:09 GMT</pubDate>
            <atom:updated>2024-10-08T20:08:09.234Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://www.codingame.com/training/easy/personal-best">Exercise</a></p><p><strong>The Goal</strong></p><p>The puzzle input provides one or more gymnasts’ names and competition categories, for example “Simone Biles” and “bars”, following which will be a set of competition records. Each record contains a gymnast’s name and the points they scored on the bars, the balance beam, and for floor work. There may be more than one competition record per gymnast.</p><p>The puzzle requires that you read through all the records, and find the highest score for each of the given gymnast/s in the given category/categories.</p><p><strong>Input</strong></p><p><strong>Line 1:</strong> The name of one or more gymnasts for whom to provide a personal best<br><strong>Line 2:</strong> One or more categories for which to find the personal best; these can be “bars”, “beam”, or “floor”<br><strong>Line 3:</strong> An integer Nfor the number of competition records provided<br><strong>Next </strong><strong>Nlines:</strong> One string and three floating point values, separated by commas, representing a gymnast and the number of points they scored in each category. These values represent a gymnast’s name, and their score on the bars, beam, and floor work in a competition.</p><p><strong>Output</strong></p><p>One or more lines, each one a comma-separated list of the maximum points for the given gymnasts for the requested categories, in the same order.</p><p>For example, given the input:<br>Paris Berelc,Ariana Berlin<br>bars,floor</p><p>Then the order of the output would be:<br>bars score for Paris Berelc,floor score for Paris Berelc<br>bars score for Ariana Berlin,floor score for Ariana Berlin</p><p><strong>Constraints</strong></p><p>1 ≤ N≤ 40<br>6 ≤ bars, beam, floor &lt; 10</p><p>Each of the gymnasts in gymnasts will always have their nameincluded in the competition records.<br>Points scores (bars, beam, floor) will have between 0 and 2 decimal places, sometimes mixed.</p><p><strong>Example</strong></p><pre>Input<br>Simone Biles<br>floor<br>1<br>Simone Biles,8,7,9</pre><pre>Output<br>9</pre><p><strong>Entendiendo el problema</strong></p><p>la entrada proporciona los nombres de uno o más gimnastas y las categorías de la competencia y se recibe los resultados de la competencia.</p><pre>entrada<br>Simone Biles<br>floor<br>1<br>Simone Biles,8,7,9</pre><p><strong>Proceso</strong></p><p>Se crea un diccionario puntuación que asocia las categorías de la competencia a un numero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*rgiidgFLNVgaGwJgLp2duQ.png" /></figure><p>Se crea un diccionario gimnastas donde cada clave es el nombre de un gimnasta y su valor es una lista de tres elementos inicializados en0.0 que representa la puntuación de las categorías. tambien lee la entrada de nombre y los separa con una , .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*TeOmUkCgBfugcO0_jwnHRg.png" /></figure><p>Se crea una lista llamadacategorias que contiene los índices de las categorías seleccionadas, utiliza el dicionnario puntuaje para convertir los nombres de las categorrias a numeros,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*p-lyB8XXAQxTobb49p_Sxw.png" /></figure><p>Se almacenan en la variable N el numero entero de cuantos registros de competencia se van a procesar. Se crea un bucle for que se repetirá en un rango de N vece</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*wCEVxgUcmhQgRwGniiPOUg.png" /></figure><p>Se almacenan en datos los registros de puntuaciones de los gimnastas. Se verifica si el gimnasta está en el diccionario gimnastas , Si es así, se actualizan sus puntuaciones en un bucle que itera tres veces, asignando el valor máximo entre su puntuación actual y la nueva entrada convertida a float.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*XaXn7Ouo5-UVpPeSAzRYvA.png" /></figure><p>Se revisan las puntuaciones de cada gimnasta. Para cada uno, se muestra sus puntuaciones en las categorías elegidas. Si una puntuación es un número entero, se muestra sin decimales, si no, se muestra como está.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qwiG8NLt-nuhM0nSxkODNA.png" /></figure><p><strong>Código Completo</strong></p><pre>import sys<br>import math<br><br>puntaje = {&quot;bars&quot;: 0, &quot;beam&quot;: 1, &quot;floor&quot;: 2}<br><br>gimnastas = {nombre: [0.0, 0.0, 0.0] for nombre in input().split(&#39;,&#39;)}<br>categorias = [puntaje[nombre] for nombre in input().split(&#39;,&#39;)]<br><br>N = int(input())<br>for _ in range(N):<br>    datos = input().split(&#39;,&#39;)<br>    if datos[0] in gimnastas:<br>        for j in range(3):<br>            gimnastas[datos[0]][j] = max(gimnastas[datos[0]][j], float(datos[j + 1]))<br><br>for gimnasta in gimnastas.values():<br>    print(&#39;,&#39;.join(str(int(gimnasta[categoria])) if gimnasta[categoria].is_integer() else str(gimnasta[categoria]) for categoria in categorias))</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3fb398b98b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Horse-racing Duals]]></title>
            <link>https://medium.com/@bbetoben122/horse-racing-duals-06c2811cb2c7?source=rss-6d34be8d8641------2</link>
            <guid isPermaLink="false">https://medium.com/p/06c2811cb2c7</guid>
            <dc:creator><![CDATA[Alberto Márquez]]></dc:creator>
            <pubDate>Tue, 08 Oct 2024 06:18:55 GMT</pubDate>
            <atom:updated>2024-10-08T06:18:55.917Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://www.codingame.com/training/easy/horse-racing-duals">Exercise</a></p><p><strong>The Goal</strong></p><p>Casablanca’s hippodrome is organizing a new type of horse racing: duals. During a dual, only two horses will participate in the race. In order for the race to be interesting, it is necessary to try to select two horses with similar strength.</p><p>Write a program which, using a given number of strengths, identifies the two closest strengths and shows their difference with an integer (≥ 0).</p><p><strong>Game Input</strong></p><p><strong>Input</strong></p><p><strong>Line 1: </strong>Number Nof horses</p><p><strong>The </strong>N<strong> following lines: </strong>the strength Piof each horse. Piis an integer.</p><p><strong>Output</strong></p><p>The difference Dbetween the two closest strengths. D is an integer greater than or equal to 0.</p><p>Constraints</p><p>1 &lt; N&lt; 100000<br>0 &lt; Pi ≤ 10000000</p><p>Example</p><pre>Input<br>3<br>5<br>8<br>9</pre><pre>Output<br>1</pre><p><strong>Entendiendo el problema</strong></p><p>Para resolver el problema, se necesita identificar las dos fuerzas mas cercanas de un grupo de caballos y calcular la diferencia entre estas, esta diferencia debe ser un numero entero mayor o igual a 0 (≥ 0).</p><p><strong>Entrada</strong></p><p>se recibe un numero total de caballos N y sus fortalezas Pi</p><pre>Entrada<br>3<br>5<br>8<br>9</pre><p><strong>Proceso</strong></p><p>Entrada de datos: Se obtiene el número total de caballos, que se representa con N. Este se lee mediante un input(), el cual convierte un entero utilizando una función int().</p><p>Después se crea una lista vacía llamada Fuerza la cual va a almacenar la fortaleza de cada caballo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*L6I0SLupcNBaYyIigKX1_w.png" /></figure><p>Se inicia un bucle for que se repite en un rango N. En cada uno de estos bucles se resibe la fuerza de un caballo y se convierte en enteroPi=int(input()) . Luego esta se añade a la lista de fuerza y una vez terminado esta se organiza en orden ascendente.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*AL6N4LH3GwS8hpNPldrlow.png" /></figure><p>Se crea una variable diferencia en este se inicializa con float(&#39;inf&#39;) que representa el infinito positivo. Esto permite que cualquier diferencia calculada entre las fortalezas de los caballos sea menor que este valor inicial. Al hacer esto se puede encontrar facilmente la menor diferencia entre las fortalezas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*reDKPtIni7Jtz9l_oJpbmA.png" /></figure><p>Se inicia un buble for que va en un rango de (n-1), de cada bucle se calcula la diferencia entre las fortalezas de dos caballos dentro de la lista fuerza. Despues se evalia si esta diferencia es menor a la diferencia actual, si es asi se actualiza diferancia, actualizando asi la menor diferencia encontrada en la fortaleza.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*KNDxlwlmD_RJrb9J-JFF6Q.png" /></figure><p>Finalmente, se imprime el valor de diferencia, que representa la diferencia entre las dos fortalezas más cercanas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*2TnQBKldlwsm93km15ou2g.png" /></figure><p>Este bloque de código es clave para identificar la menor diferencia entre las fortalezas de los caballos de manera eficiente.</p><p><strong>Codigo completo</strong></p><pre>import sys<br>import math<br><br><br>n = int(input())<br>fuerza=[]<br><br>for i in range(n):<br>    pi = int(input())<br>    fuerza.append(pi)<br>fuerza.sort()<br><br>diferencia = float(&#39;inf&#39;)<br><br>for i in range(n - 1):<br>    dif_fu = fuerza[i + 1] - fuerza[i]<br>    if dif_fu &lt; diferencia:<br>        diferencia = dif_fu<br><br>print(diferencia)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06c2811cb2c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TEMPERATURE]]></title>
            <link>https://medium.com/@bbetoben122/temperature-234e07a75a41?source=rss-6d34be8d8641------2</link>
            <guid isPermaLink="false">https://medium.com/p/234e07a75a41</guid>
            <dc:creator><![CDATA[Alberto Márquez]]></dc:creator>
            <pubDate>Wed, 02 Oct 2024 05:27:37 GMT</pubDate>
            <atom:updated>2024-10-09T01:49:40.109Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://www.codingame.com/training/easy/temperatures">Exercise</a></p><p><strong>The Goal</strong></p><p>In this exercise, you have to analyze records of temperature to find the closest to zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/0*bRbSb13Y6z7CyGz_" /><figcaption><strong>Sample temperatures</strong></figcaption></figure><p>Here, -1 is the closest to 0.</p><p><strong>Rules</strong></p><p>Write a program that prints the temperature closest to 0 among input data. <strong>If two numbers are equally close to zero, positive integer has to be considered closest to zero</strong> (for instance, if the temperatures are -5 and 5, then display 5).</p><p><strong>Game Input</strong></p><p>Your program must read the data from the standard input and write the result on the standard output.</p><p><strong>Input</strong></p><p><strong>Línea 1: </strong>N, the number of temperatures to analyze</p><p><strong>Línea 2: </strong>A string with the Ntemperatures expressed as integers ranging from -273 to 5526</p><p><strong>Output</strong></p><p>Display 0 (zero) if no temperatures are provided. Otherwise, display the temperature closest to 0.</p><p><strong>Constraints</strong></p><p>0 ≤ N&lt; 10000</p><p>Example</p><pre>input<br>5<br>1-2-845</pre><pre>output<br>1</pre><p><strong>Entendiendo el problema</strong></p><p>Para resolver el problema, se necesita identificar cual es la temperatura más cercana a 0 a partir de una lista de temperaturas dadas. Si hay dos números con la misma distancia al 0 como puede ser el -3 y el 3 (<strong>-3</strong>, -2, -1, 0, 1, 2, <strong>3</strong>), se debe escoger el número positivo.</p><p><strong>Entrada</strong></p><p>Se recibe una lista de temperatura y se identifica la más cercana a 0.</p><pre>Temperatura<br>1<br>-2<br>-8<br>4<br>5</pre><p><strong>Proceso</strong></p><p>Entrada de datos: Se obtiene el numero de temperaturas, que se representa con n. Si nes 0, se imprime 0 ya que no hay temperatura.</p><p>Temperatura: Después, se recibe una lista de temperaturas y se compara cada una con la más cercana a 0, llamada temp. Si algún valor de las temperaturas es el más cercano a 0, se actualiza guardando el valor en temp; si dos temperaturas están a la misma distancia, se escoge la positiva.</p><pre>n = int(input())  <br><br>if n == 0:<br>    print (0)</pre><p>Se leemos el número de temperaturas que vamos a procesar. Si n es igual a 0, se muestra <strong>0</strong>.</p><pre>else:<br>    temp = None <br>    for i in input().split():<br>        t = int(i)</pre><p>Si n es diferente de 0, se utilizara la variable temp para almacenar la temperatura más cercana, donde esta es inicialmente None porque no hay aun alguna temperatura. luego se lee las temperaturas de la entrada, las separamos y las convertimos en enteros.</p><pre>if temp is None or abs(t) &lt; abs(temp) or (abs(t) == abs(temp) and t &gt; temp):<br>            temp = t<br>    print(temp)</pre><p>Aquí se verifica si se debe actualizar la variable temp, dado el caso de que si temp es None, si el valor absoluto de t esta mas cerca de 0 que el valor absoluto de temp y si t tiene la misma distancia que temp , pero t es positivo, se elige t . Finalmente se imprimirá la temperatura mas cercana a 0 almacenada en temp</p><p><strong>Código completo</strong></p><pre>import sys<br>import math<br><br>n = int(input())  <br><br>if n == 0:<br>    print (0)<br>else:<br>    temp = None <br>    for i in input().split():<br>        t = int(i)<br>        if temp is None or abs(t) &lt; abs(temp) or (abs(t) == abs(temp) and t &gt; temp):<br>            temp = t<br>    print(temp)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=234e07a75a41" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>