<?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 Karthik Dev on Medium]]></title>
        <description><![CDATA[Stories by Karthik Dev on Medium]]></description>
        <link>https://medium.com/@sri.dev?source=rss-6cf356616d39------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*75Cx1UTuxvdKWQOuUANMlA.jpeg</url>
            <title>Stories by Karthik Dev on Medium</title>
            <link>https://medium.com/@sri.dev?source=rss-6cf356616d39------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 18:07:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sri.dev/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[Exploring AI-Powered Test Automation: Journey with DeepSeek and Selenium]]></title>
            <link>https://medium.com/@sri.dev/exploring-ai-powered-test-automation-journey-with-deepseek-and-selenium-fde266e1daef?source=rss-6cf356616d39------2</link>
            <guid isPermaLink="false">https://medium.com/p/fde266e1daef</guid>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Karthik Dev]]></dc:creator>
            <pubDate>Thu, 30 Jan 2025 01:06:43 GMT</pubDate>
            <atom:updated>2026-09-28T21:54:24.519Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s fast pace of software development, <strong>test automation</strong> is essential for maintaining quality, scalability, and efficiency. As someone who is passionate about both <strong>Artificial Intelligence </strong>and <strong>Quality Assurance</strong>, I have been curious to explore how AI can change the way we approach test automation.</p><p>My goal is to use <strong>DeepSeek</strong>, to auto-generate UI test cases based on specific prompts. The prompts could range from simple text descriptions of test scenarios to providing URLs as direct inputs. However, there’s a catch - basic AI models usually do not have direct access to external resources like URLs. So, we need to provide the AI with the necessary context such as the DOM structure of a webpage or visual representations in order to generate accurate and relevant test cases.</p><p>In this particular example, although I have used Selenium, this simple solution pretty much fits any other UI automation tool of your choice, be it Playwright, Cypress etc.,</p><p>Here is how it can be achieved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IOMIxN1SplPrXJHMbRMzvg.png" /><figcaption>Workflow</figcaption></figure><p>Here’s a step-by-step breakdown of how you can approach this :</p><h4>Step 1 : Getting API key</h4><p>First step to communicate with DeepSeek APIs is to login to Open platform <a href="https://platform.deepseek.com/">here</a> where you purchase API subscription. Create an API key for your device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*CLWtnKBnSdDOvOa8dfDdRw.jpeg" /><figcaption>Authentication setup</figcaption></figure><h4>Step 2: Setting Up Selenium</h4><p>On your local, before we make API calls, setup the project structure, have the required browser drivers ready for <strong>Selenium WebDriver</strong> to automate browser interactions.</p><pre>WebDriver driver = new ChromeDriver(options);<br>driver.get(&quot;https://www.pizzahut.com/&quot;);<br>System.out.println(&quot;Launched browser&quot;);<br></pre><h4>Step 3: Extracting the page source</h4><p>Next step is to get the HTML DOM structure using selenium’s in-built methods and prepare the text for sending it via REST calls.</p><p>This is a critical step, as we need to limit the number of input tokens. By sending the entire page results in exceeding the threshold of 65,536 tokens for this model. To address this, we need to preprocess the page source to eliminate certain redundant elements. This way, we will stay within the token limit while still providing enough information to DeepSeek.</p><pre>String pageSource = driver.getPageSource();<br>String sanitizedPageSource = sanitizeString(pageSource);<br><br>private static String sanitizeString(String pageSource) {<br>    pageSource = pageSource.replaceAll(&quot;(?s)&lt;script.*?&lt;/script&gt;&quot;, &quot;&quot;)<br>                .replaceAll(&quot;(?s)&lt;style.*?&lt;/style&gt;&quot;, &quot;&quot;)<br>                .replaceAll(&quot;&lt;!--.*?--&gt;&quot;, &quot;&quot;);<br><br>// Remove redundant whitespace<br>pageSource = pageSource.replaceAll(&quot;\\s+&quot;, &quot; &quot;);<br>}</pre><h4>Step 4: Making the API call</h4><p>Using the API key generated, we make an authentication to call the endpoint <a href="https://api.deepseek.com/v1/chat/completions">https://api.deepseek.com/v1/chat/completions</a></p><p>Prompt is the critical step, where we specify ‘how’ we desire the response to be generated.</p><p>Tweak the parameters in the request body as needed. Important consideration relies on the model being used — either <strong>deepseek-chat</strong> or the smarter (and pricier) <strong>deepseek-reasoner</strong> model.</p><p>Refer the API documentation <a href="https://api-docs.deepseek.com/api/deepseek-api">here</a> for additional information.</p><pre>String model = &quot;deepseek-chat&quot;;<br>String apiKey = &quot;&lt;your_api_key&gt;&quot;;<br>String userMessage = &quot;Here is the page source, generate a Selenium Java TestNG test case for this page: &quot; + sanitizedPageSource;<br><br>JSONObject requestBodyJson = new JSONObject();<br>JSONArray messagesArray = new JSONArray();<br>JSONObject message = new JSONObject();<br>message.put(&quot;role&quot;, &quot;user&quot;);<br>message.put(&quot;content&quot;, userMessage);<br>messagesArray.put(message);<br><br>requestBodyJson.put(&quot;messages&quot;, messagesArray);<br>requestBodyJson.put(&quot;model&quot;, model);<br>requestBodyJson.put(&quot;frequency_penalty&quot;, 0);<br>requestBodyJson.put(&quot;max_tokens&quot;, 4196);<br>requestBodyJson.put(&quot;presence_penalty&quot;, 0);<br>requestBodyJson.put(&quot;temperature&quot;, 1);<br>requestBodyJson.put(&quot;top_p&quot;, 1);<br><br>String requestBody = requestBodyJson.toString();<br><br>// Send the request to DeepSeek API<br>HttpClient client = HttpClient.newHttpClient();<br>HttpRequest request = HttpRequest.newBuilder()<br>        .uri(URI.create(&quot;https://api.deepseek.com/v1/chat/completions&quot;))<br>        .header(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>        .header(&quot;Authorization&quot;, &quot;Bearer &quot; + apiKey)<br>        .POST(HttpRequest.BodyPublishers.ofString(requestBody))<br>        .build();<br><br>HttpResponse&lt;String&gt; response = client.send(request, HttpResponse.BodyHandlers.ofString());</pre><h4>Step 5: Reading the response</h4><pre>System.out.println(&quot;API Response Code &quot; + response.statusCode());<br><br>if (response.statusCode() == 200) {<br>    JSONObject jsonResponse = new JSONObject(response.body());<br>    String content = jsonResponse.getJSONArray(&quot;choices&quot;)<br>            .getJSONObject(0)<br>            .getJSONObject(&quot;message&quot;)<br>            .getString(&quot;content&quot;);<br><br>    System.out.println(&quot;API response body: &quot; + content);<br>} else {<br>    System.out.println(&quot;API request failed with status code: &quot; + response.statusCode());<br>}</pre><h4>And here is the exact response from DeepSeek API — 👍</h4><pre>import org.openqa.selenium.By;<br>import org.openqa.selenium.WebDriver;<br>import org.openqa.selenium.WebElement;<br>import org.openqa.selenium.chrome.ChromeDriver;<br>import org.testng.Assert;<br>import org.testng.annotations.AfterClass;<br>import org.testng.annotations.BeforeClass;<br>import org.testng.annotations.Test;<br><br>public class PizzaHutHomePageTest {<br>    private WebDriver driver;<br><br>    @BeforeClass<br>    public void setUp() {<br>        // Set the path to your ChromeDriver executable<br>        System.setProperty(&quot;webdriver.chrome.driver&quot;, &quot;path/to/chromedriver&quot;);<br>        driver = new ChromeDriver();<br>        driver.manage().window().maximize();<br>    }<br><br>    @Test(priority = 1)<br>    public void testHomePageTitle() {<br>        driver.get(&quot;https://www.pizzahut.com/&quot;);<br>        String expectedTitle = &quot;Pizza Hut | Delivery &amp; Carryout - No One OutPizzas The Hut!&quot;;<br>        String actualTitle = driver.getTitle();<br>        Assert.assertEquals(actualTitle, expectedTitle, &quot;Page title does not match expected title.&quot;);<br>    }<br><br>    @Test(priority = 2)<br>    public void testHeroImagePresence() {<br>        WebElement heroImage = driver.findElement(By.cssSelector(&quot;div[data-testid=&#39;homepage-hero-card&#39;]&quot;));<br>        Assert.assertTrue(heroImage.isDisplayed(), &quot;Hero image is not displayed.&quot;);<br>    }<br><br>    @Test(priority = 3)<br>    public void testFindDealsButton() {<br>        WebElement findDealsButton = driver.findElement(By.cssSelector(&quot;div[data-testid=&#39;findDeals&#39;]&quot;));<br>        Assert.assertTrue(findDealsButton.isDisplayed(), &quot;Find Deals button is not displayed.&quot;);<br>        findDealsButton.click();<br>        // Add assertions or further actions after clicking the button if needed<br>    }<br><br>    @Test(priority = 4)<br>    public void testSidekickLinks() {<br>        WebElement sidekickLink = driver.findElement(By.cssSelector(&quot;a[data-testid=&#39;homepage-sidekick_0-link&#39;]&quot;));<br>        Assert.assertTrue(sidekickLink.isDisplayed(), &quot;Sidekick link is not displayed.&quot;);<br>        sidekickLink.click();<br>        // Add assertions or further actions after clicking the link if needed<br>    }<br><br>    @Test(priority = 5)<br>    public void testMarketingBanners() {<br>        WebElement marketingBanner = driver.findElement(By.cssSelector(&quot;a[data-testid=&#39;homepage-mkt_banner_1-link&#39;]&quot;));<br>        Assert.assertTrue(marketingBanner.isDisplayed(), &quot;Marketing banner is not displayed.&quot;);<br>        marketingBanner.click();<br>        // Add assertions or further actions after clicking the banner if needed<br>    }<br><br>    @AfterClass<br>    public void tearDown() {<br>        if (driver != null) {<br>            driver.quit();<br>        }<br>    }<br>}</pre><p>While this was a great starting point, there are still a lot of improvements that can be done.</p><p>Firstly, this solution fits well for simple use cases. For real time, enterprise level applications, scaling up might be challenging. Integrating <strong>RAGs ( Retrieval Augmented Generation)</strong> will improve the <strong>relevance </strong>of the generated content making it more accurate.</p><p>To do this, we would need to setup a vector database that serves as a Retrieval System. We embed the page source and query into a vector space for similarity search. Then, the relevant information such as best practices, existing test cases, or other domain specific knowledge is retrieved which serves as a context. This information is then fed to DeepSeek API thus making the solution more flexible and provide domain-specific.</p><p>There are still challenges to overcome, but for now the results look promising.</p><p>Thanks for reading! Share your comments below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fde266e1daef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Commonly Used Algorithms and When to Use Them]]></title>
            <link>https://medium.com/@sri.dev/10-commonly-used-algorithms-and-when-to-use-them-2a269b6b8083?source=rss-6cf356616d39------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a269b6b8083</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Karthik Dev]]></dc:creator>
            <pubDate>Tue, 10 Jan 2023 04:50:10 GMT</pubDate>
            <atom:updated>2026-09-28T21:45:31.838Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Simplest tricks to remember and master 10 commonly used Algorithms !</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gUR5lauTESNOV1Tm" /><figcaption>Photo by <a href="https://unsplash.com/it/@pablogamedev?utm_source=medium&amp;utm_medium=referral">Pablo Arroyo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>An <a href="https://www.freecodecamp.org/news/what-is-an-algorithm-definition-for-beginners/">algorithm</a> is a set of instructions used in computer science that are intended to solve a particular problem or complete a certain activity.</p><p>Algorithms have a wide range of uses, from straightforward computations to intricate data processing and machine learning operations.</p><p>We’ll look at 10 frequently used algorithms in this blog post, along with when to utilize each one.</p><h3>Algorithm #1: Bubble Sort</h3><blockquote>Bubble sort is a simple and intuitive sorting algorithm that is easy to understand and implement. It works by repeatedly comparing adjacent elements in a list and swapping them if they are in the wrong order. This process is repeated until the list is sorted. The time complexity of bubble sort is O(n²), which means that it is not very efficient for sorting large lists.</blockquote><p>However, it is a good choice to use when the list is small or almost sorted, as it performs well in these cases.</p><p>Cool way to remember :</p><p><em>Bubble sort is like trying to get to the top of a mountain by bouncing up one step at a time. It’s not the most efficient way to get to the top, but it gets the job done eventually! Just keep bouncing up and up and eventually you’ll reach the top… or your legs will give out and you’ll have to start all over again. But hey, at least you’ll have a good workout!</em></p><p>Here is an example of how to implement bubble sort in <a href="https://www.python.org/">Python</a>:</p><pre>def bubble_sort(lst):<br>    for i in range(len(lst) - 1):<br>        for j in range(len(lst) - 1 - i):<br>            if lst[j] &gt; lst[j + 1]:<br>                lst[j], lst[j + 1] = lst[j + 1], lst[j]<br>    return lst</pre><p>To use this function, you can pass in a list of numbers that you want to sort, and it will return a new list that is sorted in ascending order. For example:</p><pre>sorted_list = bubble_sort([3, 1, 4, 2])<br>print(sorted_list)  # Output: [1, 2, 3, 4]</pre><h3>Algorithm #2: Selection Sort</h3><blockquote>Selection sort is another simple sorting algorithm that works by repeatedly selecting the smallest element from the unsorted portion of the list and placing it at the end of the sorted portion. Like bubble sort, it has a time complexity of O(n²) and is not very efficient for sorting large lists.</blockquote><p>However, it can be a good choice to use when the list is small or when the elements are already partially sorted.</p><p>Cool way to remember</p><p><em>Selection sort is like trying to pick out the best outfit for a fancy party. You go through your closet and try on one outfit after another, comparing each one to see if it’s the best one. You keep trying on different outfits until you find the perfect one that makes you look and feel your best. Just like selection sort, it might take a while to find the right choice, but in the end, it’s worth it!</em></p><p>Here is an example of how to implement selection sort in Python:</p><pre>def selection_sort(lst):<br>    for i in range(len(lst)):<br>        min_index = i<br>        for j in range(i + 1, len(lst)):<br>            if lst[j] &lt; lst[min_index]:<br>                min_index = j<br>        lst[i], lst[min_index] = lst[min_index], lst[i]<br>    return lst</pre><p>To use this function, you can pass in a list of numbers that you want to sort, and it will return a new list that is sorted in ascending order. For example:</p><pre>sorted_list = selection_sort([3, 1, 4, 2])<br>print(sorted_list)  # Output: [1, 2, 3, 4]</pre><h3>Algorithm #3: Insertion Sort</h3><blockquote>Insertion sort is a simple sorting algorithm that works by building up a sorted list one element at a time. It starts with the first element in the list, and then repeatedly compares each subsequent element to the ones that come before it until it finds the correct position to insert it. Insertion sort has a time complexity of O(n²) and is not very efficient for sorting large lists.</blockquote><p>However, it is a good choice to use when the list is small or when the elements are already partially sorted. It is also a good choice to use when the list is expected to be almost sorted, as it performs well in this case.</p><p>Cool way to remember</p><p><em>Insertion sort is like organizing a deck of cards. You start with a few cards in your hand, and then you go through the deck one card at a time, inserting each card into the right spot in your hand. It’s a bit of a slow process, but in the end, you end up with a perfectly organized hand of cards that you can use to win all your games! Just like insertion sort, it takes a little bit of time to get everything in order, but it’s worth it in the end.</em></p><p>Here is an example of how to implement insertion sort in Python:</p><pre>def insertion_sort(lst):<br>    for i in range(1, len(lst)):<br>        j = i<br>        while j &gt; 0 and lst[j] &lt; lst[j - 1]:<br>            lst[j], lst[j - 1] = lst[j - 1], lst[j]<br>            j -= 1<br>    return lst</pre><p>To use this function, you can pass in a list of numbers that you want to sort, and it will return a new list that is sorted in ascending order. For example:</p><pre>sorted_list = insertion_sort([3, 1, 4, 2])<br>print(sorted_list) # Output: [1, 2, 3, 4]</pre><h3>Algorithm #4: Merge Sort</h3><blockquote>Merge sort is a divide and conquer sorting algorithm that works by recursively dividing the list into smaller and smaller pieces until each piece is only one element long, and then merging the pieces back together in a sorted order. It has a time complexity of O(n*log(n)), which makes it more efficient than the O(n²) algorithms we have seen so far, such as bubble sort and selection sort.</blockquote><p>Merge sort is a good choice to use when you need to sort a large list, as it can handle large lists more efficiently. It is also a good choice to use when you need a stable sort, meaning that the relative order of elements with equal values is preserved.</p><p>Cool way to remember</p><p><em>Merge sort is like dividing a big pile of laundry into smaller and smaller piles until each pile is just one sock. Then you start combining the piles two at a time, making sure to match up all the socks as you go. It’s a bit of a tedious process, but in the end, you end up with a perfectly organized pile of socks that are all paired up and ready to be put away. Just like merge sort, it takes a little bit of time to get everything sorted out, but it’s worth it in the end!</em></p><p>Here is an example of how to implement merge sort in Python:</p><pre>def merge_sort(lst):<br>    if len(lst) &lt;= 1:<br>        return lst<br>    mid = len(lst) // 2<br>    left = merge_sort(lst[:mid])<br>    right = merge_sort(lst[mid:])<br>    return merge(left, right)<br><br><br>def merge(left, right):<br>    result = []<br>    while left and right:<br>        if left[0] &lt; right[0]:<br>            result.append(left.pop(0))<br>        else:<br>            result.append(right.pop(0))<br>    if left:<br>        result.extend(left)<br>    if right:<br>        result.extend(right)<br>    return result</pre><p>To use this function, you can pass in a list of numbers that you want to sort, and it will return a new list that is sorted in ascending order. For example:</p><pre>sorted_list = merge_sort([3, 1, 4, 2])<br>print(sorted_list) # Output: [1, 2, 3, 4]</pre><h3>Algorithm #5: Quick Sort</h3><blockquote>Quick sort is another divide and conquer sorting algorithm that works by selecting a pivot element from the list and partitioning the list into two sublists based on whether the elements are less than or greater than the pivot. The sublists are then recursively sorted using the same process.</blockquote><blockquote>Quick sort has a time complexity of O(n*log(n)), which makes it more efficient than the O(n²) algorithms we have seen so far, such as bubble sort and selection sort.</blockquote><p>It is a good choice to use when you need to sort a large list, as it can handle large lists very efficiently. It is also a good choice to use when you do not need a stable sort, as it is not a stable sort.</p><p>Cool way to remember:</p><p><em>Quick sort is like trying to find the perfect seat on a crowded bus. You start by choosing a seat and then you compare it to all the other seats on the bus. If you find a better seat, you switch with it. You keep doing this until you find the best seat on the bus. Just like quick sort, it might take a little bit of time to find the perfect spot, but once you do, you can sit back and relax for the rest of the ride!</em></p><p>Here is an example of how to implement quick sort in Python:</p><pre>def quick_sort(lst):<br>    if len(lst) &lt;= 1:<br>        return lst<br>    pivot = lst[0]<br>    left = [x for x in lst[1:] if x &lt; pivot]<br>    right = [x for x in lst[1:] if x &gt;= pivot]<br>    return quick_sort(left) + [pivot] + quick_sort(right)</pre><p>To use this function, you can pass in a list of numbers that you want to sort, and it will return a new list that is sorted in ascending order. For example:</p><pre>sorted_list = quick_sort([3, 1, 4, 2])<br>print(sorted_list)  # Output: [1, 2, 3, 4]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xALMQnS9_7yBElKT" /><figcaption>Photo by <a href="https://unsplash.com/de/@evgenit?utm_source=medium&amp;utm_medium=referral">Evgeni Tcherkasski</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Algorithm #6: Linear Search</h3><blockquote>Linear search is a simple search algorithm that works by iterating through a list of elements and comparing each element to the target value until it is found or the end of the list is reached. It has a time complexity of O(n), which means that it takes longer to run as the list gets larger.</blockquote><p>Linear search is a good choice to use when you have a small list and you do not need to search the list frequently. It is also a good choice to use when you do not have a sorted list and you do not want to spend the time to sort it.</p><p>Here is an example of how to implement linear search in Python:</p><pre>def linear_search(lst, target):<br>    for i in range(len(lst)):<br>        if lst[i] == target:<br>            return i<br>    return -1</pre><p>To use this function, you can pass in a list of elements and a target value that you want to search for, and it will return the index of the first occurrence of the target value in the list. If the target value is not found, it will return -1. For example:</p><pre>index = linear_search([3, 1, 4, 2], 4)<br>print(index)  # Output: 2<br> <br>index = linear_search([3, 1, 4, 2], 5)<br>print(index)  # Output: -1</pre><h3>Algorithm #7: Binary Search</h3><blockquote>Binary search is a search algorithm that works by repeatedly dividing the list in half and comparing the target value to the middle element. If the target value is less than the middle element, it searches the left half of the list. If the target value is greater than the middle element, it searches the right half of the list. This process is repeated until the target value is found or it is determined that the target value is not in the list.</blockquote><blockquote>Binary search has a time complexity of O(log(n)), which means that it is much faster than linear search for large lists.</blockquote><p>However, it requires that the list be sorted, so you may need to spend some time sorting the list first if it is not already sorted.</p><p>Here is an example of how to implement binary search in Python:</p><pre>def binary_search(lst, target):<br>    left = 0<br>    right = len(lst) - 1<br>    while left &lt;= right:<br>        mid = (left + right) // 2<br>        if lst[mid] == target:<br>            return mid<br>        elif lst[mid] &lt; target:<br>            left = mid + 1<br>        else:<br>            right = mid - 1<br>    return -1</pre><p>To use this function, you can pass in a sorted list of elements and a target value that you want to search for, and it will return the index of the first occurrence of the target value in the list. If the target value is not found, it will return -1. For example:</p><pre>index = binary_search([1, 2, 3, 4], 3)<br>print(index)  # Output: 2<br> <br>index = binary_search([1, 2, 3, 4], 5)<br>print(index)  # Output: -1</pre><h3>Algorithm #8: Depth-First Search (DFS)</h3><blockquote>Depth-first search (DFS) is a graph traversal algorithm that works by exploring as far as possible along each branch before backtracking. It starts at the root node and explores each branch as far as possible before backtracking and exploring the next branch. This process continues until all nodes have been visited.</blockquote><blockquote>DFS has a time complexity of O(n), which means that it takes longer to run as the number of nodes in the graph increases.</blockquote><p>It is a good choice to use when you want to explore all the nodes in a graph, especially if the graph is not too large. It is also a good choice to use when you want to find a path between two nodes in a graph.</p><p>Here is an example of how to implement DFS in Python using a recursive approach:</p><pre>def dfs(graph, node, visited):<br>    if node not in visited:<br>        visited.add(node)<br>        for neighbor in graph[node]:<br>            dfs(graph, neighbor, visited)<br><br><br>def depth_first_search(graph, start_node):<br>    visited = set()<br>    dfs(graph, start_node, visited)<br>    return visited</pre><p>To use this function, you can pass in a graph represented as a dictionary and a start node, and it will return a set of nodes that were visited during the DFS. For example:</p><pre>graph = {<br>    &#39;A&#39;: [&#39;B&#39;, &#39;C&#39;],<br>    &#39;B&#39;: [&#39;A&#39;, &#39;D&#39;, &#39;E&#39;],<br>    &#39;C&#39;: [&#39;A&#39;, &#39;F&#39;],<br>    &#39;D&#39;: [&#39;B&#39;],<br>    &#39;E&#39;: [&#39;B&#39;, &#39;F&#39;],<br>    &#39;F&#39;: [&#39;C&#39;, &#39;E&#39;],<br>}<br>visited = depth_first_search(graph, &#39;A&#39;)<br>print(visited)  # Output: {&#39;A&#39;, &#39;B&#39;, &#39;D&#39;, &#39;E&#39;, &#39;C&#39;, &#39;F&#39;}</pre><h3>Algorithm #9: Breadth-First Search (BFS)</h3><blockquote>Breadth-first search (BFS) is a graph traversal algorithm that works by exploring the neighbors of a node before exploring the children of those neighbors. It starts at the root node and explores all the neighbors before moving on to the next level of nodes. This process continues until all nodes have been visited.</blockquote><blockquote>BFS has a time complexity of O(n), which means that it takes longer to run as the number of nodes in the graph increases.</blockquote><p>It is a good choice to use when you want to explore all the nodes in a graph, especially if the graph is not too large. It is also a good choice to use when you want to find the shortest path between two nodes in a graph.</p><p>Here is an example of how to implement BFS in Python using a queue:</p><pre>from collections import deque<br><br><br>def breadth_first_search(graph, start_node):<br>    visited = set()<br>    queue = deque([start_node])<br>    while queue:<br>        node = queue.popleft()<br>        if node not in visited:<br>            visited.add(node)<br>            for neighbor in graph[node]:<br>                queue.append(neighbor)<br>    return visited</pre><p>To use this function, you can pass in a graph represented as a dictionary and a start node, and it will return a set of nodes that were visited during the BFS. For example:</p><pre>graph = {<br>    &#39;A&#39;: [&#39;B&#39;, &#39;C&#39;],<br>    &#39;B&#39;: [&#39;A&#39;, &#39;D&#39;, &#39;E&#39;],<br>    &#39;C&#39;: [&#39;A&#39;, &#39;F&#39;],<br>    &#39;D&#39;: [&#39;B&#39;],<br>    &#39;E&#39;: [&#39;B&#39;, &#39;F&#39;],<br>    &#39;F&#39;: [&#39;C&#39;, &#39;E&#39;],<br>}<br>visited = breadth_first_search(graph, &#39;A&#39;)<br>print(visited)  # Output: {&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;}</pre><h3>Algorithm #10: Dijkstra’s Algorithm</h3><blockquote>Dijkstra’s algorithm is a graph search algorithm that works by finding the shortest path between two nodes in a graph. It uses a priority queue to prioritize nodes that are closer to the starting node, and it updates the distance to each node as it explores them.</blockquote><blockquote>Dijkstra’s algorithm has a time complexity of O(n*log(n)), which means that it is more efficient than a brute force search for large graphs.</blockquote><p>It is a good choice to use when you want to find the shortest path between two nodes in a graph and the edge weights are non-negative.</p><p>Here is an example of how to implement Dijkstra’s algorithm in Python using a priority queue:</p><pre>from heapq import heappop, heappush<br><br><br>def dijkstra(graph, start, end):<br>    distances = {node: float(&quot;inf&quot;) for node in graph}<br>    distances[start] = 0<br>    queue = [(0, start)]<br>    while queue:<br>        distance, node = heappop(queue)<br>        if node == end:<br>            return distance<br>        if distance &gt; distances[node]:<br>            continue<br>        for neighbor, cost in graph[node]:<br>            new_distance = distance + cost<br>            if new_distance &lt; distances[neighbor]:<br>                distances[neighbor] = new_distance<br>                heappush(queue, (new_distance, neighbor))<br>    return float(&quot;inf&quot;)</pre><p>To use this function, you can pass in a graph represented as a dictionary, a starting node, and an ending node, and it will return the shortest distance between the two nodes. If there is no path between the two nodes, it will return infinity. For example:</p><pre>graph = {<br>    &#39;A&#39;: [(&#39;B&#39;, 10), (&#39;C&#39;, 3)],<br>    &#39;B&#39;: [(&#39;D&#39;, 2)],<br>    &#39;C&#39;: [(&#39;D&#39;, 8), (&#39;E&#39;, 2)],<br>    &#39;D&#39;: [(&#39;E&#39;, 7)],<br>    &#39;E&#39;: [],<br>}<br>distance = dijkstra(graph, &#39;A&#39;, &#39;D&#39;)<br>print(distance)  # Output: 8</pre><h3>Conclusion</h3><p>In this blog post, we covered 10 commonly used algorithms in computer science and when to use them:</p><ol><li>Bubble sort</li><li>Selection sort</li><li>Insertion sort</li><li>Merge sort</li><li>Quick sort</li><li>Linear search</li><li>Binary search</li><li>Depth-first search (DFS)</li><li>Breadth-first search (BFS)</li><li>Dijkstra’s algorithm</li></ol><p>Although there are many other algorithms used in computer science, these are some of the most widely used and crucial ones to understand. Understanding these algorithms can help you tackle a wide range of problems more effectively, whether you are a novice learning computer science or an experienced developer trying to brush up on your expertise.</p><p>I sincerely hope this blog post was helpful.</p><p>Please share and feel free to leave any questions or comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a269b6b8083" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>