<?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 Pavangowdats on Medium]]></title>
        <description><![CDATA[Stories by Pavangowdats on Medium]]></description>
        <link>https://medium.com/@pavangowdats10?source=rss-b32544704c1c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ghvquWSKp5tK9PEp</url>
            <title>Stories by Pavangowdats on Medium</title>
            <link>https://medium.com/@pavangowdats10?source=rss-b32544704c1c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 23:43:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pavangowdats10/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[Building a JSON Parser]]></title>
            <link>https://medium.com/@pavangowdats10/building-a-json-parser-f99d7a453ba4?source=rss-b32544704c1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f99d7a453ba4</guid>
            <category><![CDATA[python-coding-challenges]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[json-parse]]></category>
            <dc:creator><![CDATA[Pavangowdats]]></dc:creator>
            <pubDate>Thu, 02 Apr 2026 15:56:01 GMT</pubDate>
            <atom:updated>2026-04-02T15:56:01.244Z</atom:updated>
            <content:encoded><![CDATA[<p>Thank you for Coding Challenges for amazing questions: <a href="https://codingchallenges.fyi/challenges/challenge-json-parser">https://codingchallenges.fyi/challenges/challenge-json-parser</a></p><p>Project Solution:- <a href="https://github.com/pavants09/Coding-Challenges/tree/main/buildJsonParser">https://github.com/pavants09/Coding-Challenges/tree/main/buildJsonParser</a></p><p>This challenge is to build your own JSON parser.</p><p>Have you ever wondered how programs understand and process JSON data? In this guide, we’ll build a <strong>JSON parser from scratch</strong>, progressing from the simplest case (recognizing empty objects) to handling complex nested structures. This is a practical journey into <strong>compiler design and parsing techniques</strong>— skills that apply far beyond JSON!</p><p><strong>What is Parsing?</strong></p><p>Parsing is the process of converting raw text into a structured, meaningful format that a program can understand.</p><blockquote>Step Zero: Environment Setup</blockquote><p>Follow as the question says</p><blockquote>Step One : The Simplest Parser — Recognizing</blockquote><p>Validate empty JSON objects</p><pre>import sys<br><br>def extract_token(data):<br>    tokens = []<br>    if not data.strip():<br>        return None<br>    <br>    for ch in data:<br>        if ch == &#39;{&#39;:<br>            tokens.append(&#39;{&#39;)<br>        elif ch == &#39;}&#39;:<br>            tokens.append(&#39;}&#39;)<br>        elif ch.isspace():<br>            continue<br>        else:<br>            return None<br>    <br>    return tokens<br>    <br>def parse_json(token):<br>    if token[0] == &quot;{&quot; and token[-1] == &quot;}&quot;:<br>        return True<br>    return False<br><br><br>def main():<br>    if len(sys.argv) &lt; 2:<br>        print(&quot;Usage: python jsonparser.py &lt;file&gt;&quot;)<br>        sys.exit(1)<br>    <br>    try :<br>        with open(sys.argv[1],&#39;r&#39;) as f:<br>            content = f.read()<br>    except:<br>        print(&quot;Error reading file&quot;)<br>        sys.exit(1)<br>    <br>    <br>    token = extract_token(content)<br>    <br>    if token is None:<br>        print(&quot;Invalid JSON&quot;)<br>        sys.exit(1)     <br><br>    if parse_json(token):<br>        print(&quot;Valid JSON&quot;)<br>        sys.exit(0)<br>    else:<br>        print(&quot;Invalid JSON&quot;)   <br>        sys.exit(1)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>How It Works</p><p>1. <strong>Skip whitespace:</strong> Remove all spaces, tabs, and newlines</p><p>2. <strong>Extract tokens: </strong>Create a list with `{` and `}.`</p><p>3. <strong>Validate:</strong> Check that the first token is `{` and the last is `}.`</p><p>Example</p><p>Input file: “{ }”</p><p>Step 1: tokens = [‘{‘, ‘}’]</p><p>Step 2: Validate: First is ‘{‘ ✓, Last is ‘}’ ✓</p><p>Output: “Valid JSON” (exit code 0)</p><blockquote>Step Two: Adding String Keys and Values</blockquote><p>Parse objects with string key-value pairs</p><pre>import sys<br><br>def extract_token(data):<br>    token = []<br>    <br>    i = 0<br><br>    while i &lt; len(data):<br>        ch = data[i].strip()<br><br>        if ch in [&#39;{&#39;, &#39;}&#39;, &#39;:&#39;,&#39;,&#39;] :<br>            token.append(ch)<br>        <br>        elif ch.isspace():<br>            pass<br>        <br>        elif ch == &#39;&quot;&#39;:<br>            i += 1<br>            starting = i<br><br>            while i &lt; len(data) and data[i] != &#39;&quot;&#39;:<br>                i += 1<br>            <br>            if i &gt;= len(data):<br>                return None<br>            <br>            token.append(data[starting:i])<br>        <br>        i += 1<br>    return token<br><br><br>def parse_json(token):<br>    if not token or token[0] != &#39;{&#39; or token[-1] != &#39;}&#39;:<br>        return False<br>    <br>    i = 1<br><br>    while i &lt; len(token) - 1:<br>        if not isinstance(token[i],str) or token[i] in [&#39;{&#39;, &#39;}&#39;, &#39;:&#39;,&#39;,&#39;]:<br>            return False<br>        i += 1<br><br>        if token[i] != &#39;:&#39;:<br>            return False<br>        i += 1<br><br>        if not isinstance(token[i],str) or token[i] in [&#39;{&#39;, &#39;}&#39;, &#39;:&#39;,&#39;,&#39;]:<br>            return False<br>        i += 1<br><br>        if token[i] == &#39;,&#39; :<br>            i += 1<br>        elif token[i] == &#39;}&#39;:<br>            i += 1<br>        else:<br>            return False<br>    return True<br><br>def main():<br>    if len(sys.argv) &lt; 2 :<br>        print(&quot;Usage: python ccwc.py &lt;file&gt;&quot;)<br>        sys.exit(1)<br>    <br>    try :<br>        with open(sys.argv[1],&#39;r&#39;) as f:<br>            content = f.read()<br>    except:<br>        print(&quot;Error reading file&quot;)<br>        sys.exit(1)<br><br>    token = extract_token(content)<br><br>    if token is None:<br>        print(&quot;Invalid JSON&quot;)<br>        sys.exit(1) <br>    if parse_json(token):<br>        print(&quot;Valid JSON&quot;)<br>        sys.exit(0)<br>    else:<br>        print(&quot;Invalid JSON&quot;)<br>        sys.exit(1) <br><br>if __name__ == &quot;__main__&quot; :<br>    main()</pre><p>Example Flow :</p><p>Input: {“name”: “Alice”, “age”: 30}</p><p>Tokens: [‘{‘, ‘name’, ‘:’, ‘Alice’, ‘,’, ‘age’, ‘:’, ‘30’, ‘}’]</p><p>Parser checks:</p><p>✓<em> Starts with {</em></p><p><em>✓ ‘name’ is a string (key)</em></p><p><em>✓ Followed by :</em></p><p><em>✓ ‘Alice’ is a string (value)</em></p><p><em>✓ Followed by ,</em></p><p><em>✓ ‘age’ is a string (key)</em></p><p><em>✓ Followed by :</em></p><p><em>✓ ‘30’ is a string (value)</em></p><p><em>✓ Followed by }</em></p><p><em>✓ Valid JSON!</em></p><blockquote>Step Three : Supporting Multiple Data Types</blockquote><p>Parse objects with diverse value types</p><pre>import sys<br><br>def extract_token(data):<br>    tokens = []<br>    i = 0<br><br>    while i &lt; len(data):<br>        ch = data[i]<br><br>        if ch in [&#39;{&#39;, &#39;}&#39;, &#39;:&#39;, &#39;,&#39;]:<br>            tokens.append(ch)<br><br>        elif ch.isspace():<br>            pass<br><br>        elif ch == &#39;&quot;&#39;:<br>            i += 1<br>            start = i<br><br>            while i &lt; len(data) and data[i] != &#39;&quot;&#39;:<br>                i += 1<br>            <br>            if i &gt;= len(data):<br>                return None<br>            <br>            tokens.append((&quot;STRING&quot;, data[start:i]))<br><br>        # true<br>        elif data[i:i+4] == &quot;true&quot;:<br>            tokens.append((&quot;BOOLEAN&quot;, True))<br>            i += 3<br><br>        # false<br>        elif data[i:i+5] == &quot;false&quot;:<br>            tokens.append((&quot;BOOLEAN&quot;, False))<br>            i += 4<br><br>        # null<br>        elif data[i:i+4] == &quot;null&quot;:<br>            tokens.append((&quot;NULL&quot;, None))<br>            i += 3<br><br>        # invalid (case-sensitive)<br>        elif data[i:i+5] == &quot;False&quot;:<br>            return None<br><br>        # number<br>        elif ch.isdigit():<br>            start = i<br>            while i &lt; len(data) and data[i].isdigit():<br>                i += 1<br>            <br>            tokens.append((&quot;NUMBER&quot;, int(data[start:i])))<br>            i -= 1<br><br>        else:<br>            return None<br><br>        i += 1<br><br>    return tokens<br><br><br>def parse_json(tokens):<br>    if not tokens or tokens[0] != &#39;{&#39; or tokens[-1] != &#39;}&#39;:<br>        return False<br>    <br>    i = 1<br><br>    while i &lt; len(tokens) - 1:<br>        if not isinstance(tokens[i], tuple) or tokens[i][0] != &quot;STRING&quot;:<br>            return False<br>        i += 1<br><br>        if tokens[i] != &#39;:&#39;:<br>            return False<br>        i += 1<br><br>        if not isinstance(tokens[i], tuple) or tokens[i][0] not in [&quot;STRING&quot;, &quot;NUMBER&quot;, &quot;BOOLEAN&quot;, &quot;NULL&quot;]:<br>            return False<br>        i += 1<br><br>        if tokens[i] == &#39;,&#39;:<br>            i += 1<br>        elif tokens[i] == &#39;}&#39;:<br>            return True<br>        else:<br>            return False<br><br>    return True<br><br><br>def main():<br>    if len(sys.argv) &lt; 2:<br>        print(&quot;Usage: python step3jsonparser.py &lt;file&gt;&quot;)<br>        sys.exit(1)<br><br>    try:<br>        with open(sys.argv[1], &#39;r&#39;) as f:<br>            content = f.read()<br>    except:<br>        print(&quot;Error reading file&quot;)<br>        sys.exit(1)<br><br>    tokens = extract_token(content)<br><br>    if tokens is None:<br>        print(&quot;Invalid JSON&quot;)<br>        sys.exit(1)<br><br>    if parse_json(tokens):<br>        print(&quot;Valid JSON&quot;)<br>        sys.exit(0)<br>    else:<br>        print(&quot;Invalid JSON&quot;)<br>        sys.exit(1)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Example Flow :</p><p>Input: {“active”: true, “count”: 42, “data”: null}</p><p>Tokens: [‘{‘, (‘STRING’, ‘active’), ‘:’, (‘BOOLEAN’, True), ‘,’,</p><p>(‘STRING’, ‘count’), ‘:’, (‘NUMBER’, 42), ‘,’,</p><p>(‘STRING’, ‘data’), ‘:’, (‘NULL’, None), ‘}’]</p><p>Parser checks:</p><p><em>✓ ‘active’ is STRING (key)</em></p><p><em>✓ Followed by :</em></p><p><em>✓ True is BOOLEAN (valid value)</em></p><p><em>✓ Followed by ,</em></p><p><em>✓ ‘count’ is STRING (key)</em></p><p><em>✓ Followed by :</em></p><p><em>✓ 42 is NUMBER (valid value)</em></p><p><em>✓ Followed by ,</em></p><p><em>✓ ‘data’ is STRING (key)</em></p><p><em>✓ Followed by :</em></p><p><em>✓ null is NULL (valid value)</em></p><p><em>✓ Followed by }</em></p><p><em>✓ Valid JSON!</em></p><blockquote>Step Four: Supporting Nested Objects and Arrays</blockquote><p>Parse complex JSON with nesting</p><pre>import sys<br><br>def extract_token(data):<br>    tokens = []<br>    i = 0<br><br>    while i &lt; len(data):<br>        ch = data[i]<br><br>        if ch in [&#39;{&#39;, &#39;}&#39;, &#39;:&#39;, &#39;,&#39;, &#39;[&#39;, &#39;]&#39;]:<br>            tokens.append(ch)<br><br>        elif ch.isspace():<br>            pass<br><br>        elif ch == &#39;&quot;&#39;:<br>            i += 1<br>            start = i<br>            while i &lt; len(data) and data[i] != &#39;&quot;&#39;:<br>                i += 1<br>            if i &gt;= len(data):<br>                return None<br>            tokens.append((&quot;STRING&quot;, data[start:i]))<br><br>        elif data[i:i+4] == &quot;true&quot;:<br>            tokens.append((&quot;BOOLEAN&quot;, True))<br>            i += 3<br><br>        elif data[i:i+5] == &quot;false&quot;:<br>            tokens.append((&quot;BOOLEAN&quot;, False))<br>            i += 4<br><br>        elif data[i:i+4] == &quot;null&quot;:<br>            tokens.append((&quot;NULL&quot;, None))<br>            i += 3<br><br>        elif ch.isdigit():<br>            start = i<br>            while i &lt; len(data) and data[i].isdigit():<br>                i += 1<br>            tokens.append((&quot;NUMBER&quot;, int(data[start:i])))<br>            i -= 1<br><br>        else:<br>            return None<br><br>        i += 1<br><br>    return tokens<br><br><br>def parse_value(tokens, i):<br>    tok = tokens[i]<br><br>    if isinstance(tok, tuple):<br>        return i + 1<br><br>    if tok == &#39;{&#39;:<br>        return parse_object(tokens, i)<br><br>    if tok == &#39;[&#39;:<br>        return parse_array(tokens, i)<br><br>    return None<br><br><br>def parse_object(tokens, i):<br>    if tokens[i] != &#39;{&#39;:<br>        return None<br><br>    i += 1<br>    if tokens[i] == &#39;}&#39;:<br>        return i + 1<br><br>    while True:<br>        if not isinstance(tokens[i], tuple) or tokens[i][0] != &quot;STRING&quot;:<br>            return None<br>        i += 1<br><br>        if tokens[i] != &#39;:&#39;:<br>            return None<br>        i += 1<br><br>        i = parse_value(tokens, i)<br>        if i is None:<br>            return None<br><br>        if tokens[i] == &#39;,&#39;:<br>            i += 1<br>        elif tokens[i] == &#39;}&#39;:<br>            return i + 1<br>        else:<br>            return None<br><br><br>def parse_array(tokens, i):<br>    if tokens[i] != &#39;[&#39;:<br>        return None<br><br>    i += 1<br><br>    if tokens[i] == &#39;]&#39;:<br>        return i + 1<br><br>    while True:<br>        i = parse_value(tokens, i)<br>        if i is None:<br>            return None<br><br>        if tokens[i] == &#39;,&#39;:<br>            i += 1<br>        elif tokens[i] == &#39;]&#39;:<br>            return i + 1<br>        else:<br>            return None<br><br><br>def parse_json(tokens):<br>    if not tokens:<br>        return False<br><br>    i = parse_object(tokens, 0)<br>    return i == len(tokens)<br><br><br>def main():<br>    if len(sys.argv) &lt; 2:<br>        print(&quot;Usage: python step4jsonparser.py &lt;file&gt;&quot;)<br>        sys.exit(1)<br><br>    try:<br>        with open(sys.argv[1], &#39;r&#39;) as f:<br>            content = f.read()<br>    except:<br>        print(&quot;Error reading file&quot;)<br>        sys.exit(1)<br><br>    tokens = extract_token(content)<br><br>    if tokens is None:<br>        print(&quot;Invalid JSON&quot;)<br>        sys.exit(1)<br><br>    if parse_json(tokens):<br>        print(&quot;Valid JSON&quot;)<br>        sys.exit(0)<br>    else:<br>        print(&quot;Invalid JSON&quot;)<br>        sys.exit(1)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Example Flow :</p><p>Input: {</p><p>“user”: {“name”: “Alice”},</p><p>“tags”: [“a”, “b”]</p><p>}</p><p>1. Start parse_object → sees {</p><p>2. Read key “user”</p><p>3. Read : and call parse_value</p><p>4. parse_value sees { → call parse_object recursively</p><p>5. Inner object: “name”: “Alice”</p><p>6. Return from inner object</p><p>7. Read , and continue</p><p>8. Read key “tags”</p><p>9. Read : and call parse_value</p><p>10. parse_value sees [ → call parse_array</p><p>11. Array: “a”, “b”</p><p>12. Return from array</p><p>13. Close outer object</p><p>Result: Valid JSON</p><h3><strong>Exit Codes Matter</strong></h3><p><em># Standard practice for CLI tools</em></p><p><em>exit 0 # Success</em></p><p><em>exit 1 # Failure (or 1–255 for different errors)</em></p><p>You’ve now seen how to build a <strong>complete JSON parser </strong>from scratch! The journey from recognizing `{}` to handling complex nested structures demonstrates powerful software engineering principles:</p><p>- <strong>Incremental development: </strong>Add features one at a time</p><p>- <strong>Separation of concerns:</strong> Keep tokenization and parsing separate</p><p>- <strong>Recursion:</strong> Let problems solve themselves naturally</p><p>- <strong>Testing:</strong> Validate against known good/bad examples</p><p>These lessons apply far beyond JSON — they’re fundamental to compiler design, configuration parsing, query languages, and much more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f99d7a453ba4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Your Own wc Tool: A Complete Implementation Guide]]></title>
            <link>https://medium.com/@pavangowdats10/building-your-own-wc-tool-a-complete-implementation-guide-01656fc623fc?source=rss-b32544704c1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/01656fc623fc</guid>
            <category><![CDATA[file-io]]></category>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[text-processing]]></category>
            <category><![CDATA[unix-tools]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Pavangowdats]]></dc:creator>
            <pubDate>Wed, 01 Apr 2026 18:11:08 GMT</pubDate>
            <atom:updated>2026-04-01T18:11:08.125Z</atom:updated>
            <content:encoded><![CDATA[<p>Thank you for Coding Challenges for amazing questions <a href="https://codingchallenges.fyi/challenges/challenge-wc">https://codingchallenges.fyi/challenges/challenge-wc</a></p><p>Project Solution :- <a href="https://github.com/pavants09/Coding-Challenges/tree/main/buildWC">https://github.com/pavants09/Coding-Challenges/tree/main/buildWC</a></p><p>This challenge is to build your own version of the Unix command line tool wc!</p><p>Building a clone of the Unix `wc` (word count) tool is a fantastic exercise in software engineering fundamentals. Through this challenge, I learn about file I/O, command-line argument parsing, text processing, and how elegant tools can solve complex problems through simplicity. This article documents my complete solution, walking through each step of the journey.</p><blockquote>Step Zero: Environment Setup</blockquote><p>Before diving into the code, I prepared my development environment:</p><p>1.<strong>Created the project structure</strong> with `ccwc.py` as the main executable script</p><p>2. <strong>Downloaded test data</strong> and saved it as `test.txt` (a 342,190-byte file with 7,145 lines and 58,164 words)</p><p>3. <strong>Set up testing methodology</strong> to compare outputs with the system’s `wc` command</p><p>This step emphasizes the importance of:</p><blockquote>- Having proper test fixtures</blockquote><blockquote>- Establishing clear acceptance criteria</blockquote><blockquote>- Creating a reproducible development environment</blockquote><blockquote>Step One: Counting Bytes with `-c` Flag</blockquote><p>The Challenge : Create a simple version that counts the number of bytes in a file using the `-c` option.</p><pre>import sys<br><br>def count_bytes(filepath):<br>    with open(filepath, &quot;rb&quot;) as f:<br>        return len(f.read())<br><br><br>def main():<br>    if len(sys.argv) != 3:<br>        print(&quot;Usage: python ccwc.py -c &lt;filename&gt;&quot;)<br>        sys.exit(1)<br>    <br>    option = sys.argv[1]<br>    filename = sys.argv[2]<br>    <br>    if option != &quot;-c&quot;:<br>        print(&quot;Error: Invalid option. Only -c is supported in this version.&quot;)<br>        sys.exit(1)<br>    <br>    try:<br>        byte_count = count_bytes(filename)<br>        print(f&quot;{byte_count} {filename}&quot;)<br>        <br>    except FileNotFoundError:<br>        print(f&quot;Error: File &#39;{filename}&#39; not found.&quot;)<br>        sys.exit(1)<br>    except Exception as e:<br>        print(f&quot;Error: {e}&quot;)<br>        sys.exit(1)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Testing :</p><pre>python ccwc.py -c test.txt</pre><p>Output : 342190 test.txt</p><p><strong>Result:</strong> Matches the expected output exactly</p><p><strong>Key Decisions:</strong></p><blockquote>- Open file in <strong>binary mode</strong> (`”rb”`) to accurately count bytes</blockquote><blockquote>- Read entire file and measure its length</blockquote><blockquote>- Output format: `&lt;byte_count&gt; &lt;filename&gt;` to match Unix `wc` output</blockquote><p>Key Learnings</p><blockquote>- File size ≠ character count (especially with multi-byte encodings)</blockquote><blockquote>- Binary mode is essential for accurate byte counting</blockquote><blockquote>- Simple file I/O with Python’s context managers (`with` statement) ensures proper file closure’</blockquote><blockquote>Step Two: Counting Lines with `-l` Flag</blockquote><p>The Challenge : Support the `-l` option to count the number of lines in a file.</p><pre>import sys<br><br>def count_lines(filepath):<br>    count = 0<br>    with open(filepath, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>        for _ in f:<br>            count += 1<br>    return count<br><br>def main():<br>    if len(sys.argv) != 3:<br>        print(&quot;Usage: python ccwc.py -l &lt;filename&gt;&quot;)<br>        sys.exit(1)<br>    <br>    option = sys.argv[1]<br>    filename = sys.argv[2]<br>    <br>    # Validate option<br>    if option != &quot;-l&quot;:<br>        print(&quot;Error: Invalid option. Supported -l (lines)&quot;)<br>        sys.exit(1)<br>    <br>    try:<br>        line_count = count_lines(filename)<br>        print(f&quot;{line_count} {filename}&quot;)<br>        <br>    except FileNotFoundError:<br>        print(f&quot;Error: File &#39;{filename}&#39; not found.&quot;)<br>        sys.exit(1)<br>    except UnicodeDecodeError:<br>        print(f&quot;Error: Could not decode file &#39;{filename}&#39; as UTF-8.&quot;)<br>        sys.exit(1)<br>    except Exception as e:<br>        print(f&quot;Error: {e}&quot;)<br>        sys.exit(1)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><pre>python ccwc.py -l test.txt</pre><p>Output : 7145 test.txt</p><p><strong>Result: </strong>Exactly matches `wc -l` output</p><p><strong>Key Decisions:</strong></p><blockquote>- Open file in <strong>**text mode**</strong> (`”r”`) for proper line handling</blockquote><blockquote>- Use UTF-8 encoding for international character support</blockquote><blockquote>- Iterate through file directly; Python treats each line as a logical unit</blockquote><p>Key Learnings</p><blockquote>- Text mode file iteration abstracts away byte-level newline handling</blockquote><blockquote>- Line counting is locale-independent</blockquote><blockquote>- Memory efficiency comes from streaming (line-by-line) rather than loading entire files</blockquote><blockquote>Step Three: Counting Words with `-w` Flag</blockquote><p>The Challenge : Support the `-w` option to count the number of words in a file.</p><pre>import sys<br><br>def count_words(filepath):<br>    count = 0<br>    with open(filepath, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>        for line in f:<br>            count += len(line.split())<br>    return count<br><br>def main():<br>    if len(sys.argv) != 3:<br>        print(&quot;Usage: python ccwc.py -w &lt;filename&gt;&quot;)<br>        sys.exit(1)<br>    <br>    option = sys.argv[1]<br>    filename = sys.argv[2]<br>    <br>    if option != &quot;-w&quot;:<br>        print(&quot;Error: Invalid option. Supported -w (words)&quot;)<br>        sys.exit(1)<br>    <br>    try:<br>        word_count = count_words(filename)<br>        print(f&quot;{word_count} {filename}&quot;)<br>        <br>    except FileNotFoundError:<br>        print(f&quot;Error: File &#39;{filename}&#39; not found.&quot;)<br>        sys.exit(1)<br>    except UnicodeDecodeError:<br>        print(f&quot;Error: Could not decode file &#39;{filename}&#39; as UTF-8.&quot;)<br>        sys.exit(1)<br>    except Exception as e:<br>        print(f&quot;Error: {e}&quot;)<br>        sys.exit(1)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><pre>python ccwc.py -w test.txt</pre><p>Output : 58164 test.txt</p><p><strong>Result: </strong>Perfect match with `wc -w`</p><p><strong>Key Decisions:</strong></p><blockquote>- Use `split()` without arguments (smarter than `split(‘ ‘)`)</blockquote><blockquote>- `split()` handles multiple consecutive spaces gracefully</blockquote><blockquote>- Maintains memory efficiency with line-by-line processing</blockquote><p>Key Learnings</p><blockquote>- `str.split()` vs `str.split(‘ ‘)`: The former is more robust</blockquote><blockquote>- Understanding what constitutes a “word” (whitespace-delimited tokens)</blockquote><blockquote>- Combining line-based iteration with token counting is both efficient and elegant</blockquote><blockquote>Step Four: Counting Characters with `-m` Flag</blockquote><p>The Challenge : Support the `-m` option to count multibyte characters (not bytes). This is locale-dependent.</p><pre>import sys<br><br>def count_chars(filepath):<br>    count = 0<br>    with open(filepath, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>        while True:<br>            chunk = f.read(1024)<br>            if not chunk:<br>                break<br>            count += len(chunk)<br>    return count<br><br>def main():<br>    if len(sys.argv) != 3:<br>        print(&quot;Usage: python ccwc.py -m &lt;filename&gt;&quot;)<br>        sys.exit(1)<br>    <br>    option = sys.argv[1]<br>    filename = sys.argv[2]<br>    <br>    if option != &quot;-m&quot;:<br>        print(&quot;Error: Invalid option. Supported options: -c (bytes), -l (lines), -w (words), -m (characters)&quot;)<br>        sys.exit(1)<br>    <br>    try:<br>        char_count = count_chars(filename)<br>        print(f&quot;{char_count} {filename}&quot;)<br>        <br>    except FileNotFoundError:<br>        print(f&quot;Error: File &#39;{filename}&#39; not found.&quot;)<br>        sys.exit(1)<br>    except UnicodeDecodeError:<br>        print(f&quot;Error: Could not decode file &#39;{filename}&#39; as UTF-8.&quot;)<br>        sys.exit(1)<br>    except Exception as e:<br>        print(f&quot;Error: {e}&quot;)<br>        sys.exit(1)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><pre>python ccwc.py -m test.txt</pre><p>Output : 339292 test.txt</p><p><strong>Result:</strong> Matches the expected output exactly</p><p><strong>Key Decisions:</strong></p><blockquote>- Open in <strong>**text mode**</strong> with UTF-8 encoding to properly decode multibyte sequences</blockquote><blockquote>- Use chunked reading for memory efficiency with very large files</blockquote><blockquote>- Python’s `len()` on a string counts Unicode characters, not bytes</blockquote><p>Key Learnings</p><blockquote>- Character count vs. byte count: Important distinction in international text</blockquote><blockquote>- UTF-8 encoding: 1–3 bytes per character depending on the character</blockquote><blockquote>- Chunked reading prevents memory overflow on large files</blockquote><blockquote>- Python handles Unicode transparently in text mode</blockquote><blockquote>Step Five: Default Behavior (All Three Counts)</blockquote><p>The Challenge : When no option is provided, output line count, word count, and byte count (equivalent to `-l -w -c`).</p><p><strong>Key Implementation Details:</strong></p><p>1. <strong>Line count: </strong>Count newline characters with `count(“\n”)`</p><p>2. <strong>Word count: </strong>Use `split()` on entire data</p><p>3. <strong>Byte count:</strong>Use `.encode()` to convert to bytes, then count</p><p>4. <strong>Character count:</strong> Use `len()` on the string directly</p><p>5. <strong>No filename output:</strong> When reading from stdin, omit the filename in output</p><pre>import sys<br><br><br>def count_bytes(filepath):<br>    with open(filepath, &quot;rb&quot;) as f:<br>        return len(f.read())<br><br><br>def count_lines(filepath):<br>    count = 0<br>    with open(filepath, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>        for _ in f:<br>            count += 1<br>    return count<br><br><br>def count_words(filepath):<br>    count = 0<br>    with open(filepath, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>        for line in f:<br>            count += len(line.split())<br>    return count<br><br><br>def main():<br>    if len(sys.argv) != 2:<br>        print(&quot;Usage: python ccwc.py &lt;filename&gt;&quot;)<br>        print(&quot;  Outputs: &lt;lines&gt; &lt;words&gt; &lt;bytes&gt; &lt;filename&gt;&quot;)<br>        sys.exit(1)<br>    <br>    filename = sys.argv[1]<br>    <br>    try:<br>        lines = count_lines(filename)<br>        words = count_words(filename)<br>        bytes_count = count_bytes(filename)<br>        print(f&quot;{lines} {words} {bytes_count} {filename}&quot;)<br>        <br>    except FileNotFoundError:<br>        print(f&quot;Error: File &#39;{filename}&#39; not found.&quot;)<br>        sys.exit(1)<br>    except UnicodeDecodeError:<br>        print(f&quot;Error: Could not decode file &#39;{filename}&#39; as UTF-8.&quot;)<br>        sys.exit(1)<br>    except Exception as e:<br>        print(f&quot;Error: {e}&quot;)<br>        sys.exit(1)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><pre>python ccwc.py test.txt</pre><p>7145 58164 342190 test.txt</p><p><strong>Result: </strong>Matches `wc test.txt` exactly</p><blockquote>Step Six: Reading from Standard Input</blockquote><p>The Challenge : Support reading from stdin when no filename is specified (e.g., `cat test.txt | ccwc -l`).</p><p><em>This step is easy! Try implementing it yourself first before reading the solution below. You’ve already learned all the concepts you need — just apply them to reading from `sys.stdin` instead of a file!</em></p><p>Code Reference</p><p>The complete implementation is available in `ccwc.py`. Feel free to run experiments, add enhancements, or use this as a template for other Unix tool clones (try `cat`, `grep`, or `sort` next!).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01656fc623fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a Scalable System for a URL Shortener]]></title>
            <link>https://medium.com/@pavangowdats10/how-we-built-the-design-system-behind-shortenr-ur-0ac7c6a5e93d?source=rss-b32544704c1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ac7c6a5e93d</guid>
            <category><![CDATA[learn-design]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[url-shorteners]]></category>
            <dc:creator><![CDATA[Pavangowdats]]></dc:creator>
            <pubDate>Wed, 25 Mar 2026 17:49:12 GMT</pubDate>
            <atom:updated>2026-03-25T17:54:34.261Z</atom:updated>
            <content:encoded><![CDATA[<h3>Problem Statement :</h3><p>Design a system for creating a URL shortening service similar to TinyURL. This service will generate concise aliases that redirect to the original, longer URLs.</p><h3><strong>Example :</strong></h3><p>Have you ever noticed this? You paste a long URL like:</p><p><strong>https://github.com/pavants09/GenAI/blob/main/my-model/.ipynb_checkpoints/config-checkpoint.json</strong></p><p>But when it appears on LinkedIn, it becomes something like:<br><a href="https://lnkd.in/gCrmgQ3V"><strong>https://lnkd.in/gCrmgQ3V</strong></a></p><p>So… what’s happening behind the scenes?</p><h3><strong>Two Ways to Build a URL Shortener</strong></h3><blockquote>1 : Algorithm-Based (Encoder Algorithms) :</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*8FgeAjOT6Vn-I0QdqVQs5g.png" /></figure><blockquote>URL Shortening Flow :</blockquote><p>Step 1 : User submits a long URL to the server.</p><p>Step 2 : The server generates a <strong>unique numeric ID</strong> for the URL.</p><p>The ID is passed to the <strong>Base62 Encoder</strong>, which converts it into a short string.</p><p>Step 3 : The server stores the mapping in the database:</p><blockquote><strong><em>ID ↔ Original URL</em></strong></blockquote><p>Step 4 : The server returns the final short URL to the user:</p><p><a href="https://short.ly/cb"><em>https://short.ly/cb</em></a></p><blockquote>Redirection Flow</blockquote><p>Step 1 : User clicks the short URL (/cb).</p><p>Step 2 : The request reaches the server, which sends the code to the <strong>Base62 Decoder</strong>.</p><p>Step 3 : The decoder converts the short code back into the original numeric ID.</p><p>Step 4 : The server queries the database using this ID to fetch the original URL.</p><p>Step 5 : The server responds with an HTTP redirect (<strong>302 Redirect</strong>) and forwards the user to the original URL.</p><p>Advantages :</p><blockquote>High Performance</blockquote><blockquote>Simple to Implement</blockquote><blockquote>Minimal Storage Dependency</blockquote><p>Disadvantages :</p><blockquote>Predictable URLs (Security Risk)</blockquote><blockquote>Limited Scalability</blockquote><blockquote>No Built-in Analytics</blockquote><blockquote>2 : Database + Scalable System (Real-World Approach)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*xTW-m7AwZUK3zKnMrSL9Ag.png" /></figure><blockquote>URL Shortening Flow</blockquote><p>Step 1 : User submits a long URL to the server.</p><p>Step 2 : The request first goes through a <strong>Load Balancer</strong>, which distributes traffic to available servers.</p><p>Step 3 : The backend server generates a <strong>unique short code</strong> (random string or encoded ID).</p><p>Step 4 : The server stores the mapping in the database:</p><blockquote><strong><em>Short Code ↔ Original URL</em></strong></blockquote><p>Step 5 : (Optional but important) The mapping is also stored in a <strong>cache (e.g., Redis)</strong> for faster access.</p><p>Step 6 : The server returns the short URL to the user:</p><blockquote><a href="https://short.ly/abc123"><em>https://short.ly/abc123</em></a></blockquote><blockquote>Redirection Flow</blockquote><p>Step 1 : User clicks the short URL (/abc123).</p><p>Step 2 : Request goes through the <strong>Load Balancer</strong> to an available server.</p><p>Step 3 :</p><p>The server first checks the <strong>cache</strong>:</p><ul><li>If found → return URL immediately ⚡</li><li>If not → query database</li></ul><p>Step 4 : The database returns the original URL.</p><p>Step 5 : The server may update the cache for future requests.</p><p>Step 6 : The server responds with an HTTP redirect (<strong>302/301</strong>) to the original URL.</p><p>Advantages :</p><blockquote>Highly Scalable</blockquote><blockquote>Fast Redirection (with Cache)</blockquote><blockquote>Better Security</blockquote><p>Disadvantages :</p><blockquote>Higher Infrastructure Cost</blockquote><blockquote>Cache Consistency Problems</blockquote><blockquote>Slight Latency Overhead</blockquote><p><em>Building a URL shortener may seem simple at first, but designing it for real-world scale introduces challenges like performance, scalability, and security. While Base62 encoding helps understand the core idea, production systems rely on distributed architectures with caching and load balancing to handle millions of users efficiently.</em></p><blockquote><em>Focus on clear thinking, step-by-step design, and scalability to impress in system design interviews.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ac7c6a5e93d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Placement Story: Lessons Beyond the Offer Letter (Only for tier-3 College Students)]]></title>
            <link>https://medium.com/@pavangowdats10/my-placement-story-lessons-beyond-the-offer-letter-only-for-tier-3-college-students-5fa11beb9b0e?source=rss-b32544704c1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fa11beb9b0e</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[pes-college]]></category>
            <category><![CDATA[placement]]></category>
            <dc:creator><![CDATA[Pavangowdats]]></dc:creator>
            <pubDate>Wed, 25 Feb 2026 20:03:25 GMT</pubDate>
            <atom:updated>2026-02-25T20:07:27.829Z</atom:updated>
            <content:encoded><![CDATA[<p>Placement season teaches you more about yourself than any classroom ever can. For me, it was not just about getting an offer letter — it was about failure, self-realization, growth, and a strong comeback.</p><p>This is my story as a Tier-3 college student.</p><p>Companies started visiting our campus at the beginning of my 7th semester. I was excited and confident. I believed I was prepared.</p><p>More than 40 companies visited in 2025. I applied to almost all of them.</p><p>One by one, I got rejected. Not a single offer letter.</p><p>Watching everyone get selected while I stayed behind was painful. At first, I blamed the placement process. I thought:</p><blockquote>The process is unfair.<br> Shortlisting is random.<br> On-campus placements are unpredictable.</blockquote><p>But after multiple failures, I asked myself one honest question:</p><p>Is the process wrong… or am I preparing the wrong way?</p><p>That question changed everything.</p><blockquote>I reached the final round of Infosys. Almost 95% of the students were getting selected in that conversation round. I felt confident.</blockquote><p>This was my moment.</p><p><strong><em>But I got rejected.</em></strong></p><p>That rejection hurt more than the previous 40, because this time, I was so close.</p><p>For a few days, I felt completely broken. But instead of blaming luck, I analyzed myself:</p><blockquote>Was my communication clear enough?<br> Did I structure my answers properly?<br> Was I truly confident, or just memorizing answers?</blockquote><p>That rejection transformed me.</p><blockquote>Earlier, I was preparing to become industry-ready before getting selected. But after repeated failures, I shifted my focus to just clearing rounds</blockquote><p>In 2026, things changed.</p><p>I got 3+ opportunities up to February — and this time, I cracked all three.</p><p>What changed? Not luck. Not the process.</p><p>My preparation and my mindset.</p><p>Today, I hold:</p><blockquote>Cognizant — GenC Role<br> TCS — Digital Role<br> HashedIn by Deloitte — SDE 1 Role</blockquote><p>The same student who couldn’t get a single offer in 2025 secured multiple strong offers in 2026.</p><p>Failure didn’t stop me. It rebuilt me.</p><p>5 Things You Must Have Before 7th Semester</p><ol><li>Maintain a CGPA of 9+</li></ol><p>I missed major opportunities because my CGPA was 8.9, just below the 9.0 cutoff. Sometimes you don’t even get a chance to sit for the company if you don’t meet the eligibility criteria.</p><p>2. Be Strong in Basic Aptitude</p><p>Aptitude is the first elimination round in most companies. If you cannot clear aptitude, your technical skills won’t matter. Practice consistently and focus on speed and accuracy.</p><p>3. Develop Good Communication Skills</p><p>Communication is not optional. Interviews test how clearly and confidently you can express your thoughts. Even if you know the answer, poor communication can cost you the opportunity.</p><p>4. Solve Normal-Level DSA Questions</p><p>You don’t need to solve the hardest problems online. But you must be comfortable with basic to medium-level DSA questions and understand core concepts clearly.</p><p>5. Have Strong CS Fundamentals</p><p>Be clear in subjects like OOPS, DBMS, Operating Systems, and Computer Networks. Strong fundamentals make interviews feel like discussions rather than stress sessions.</p><p>Final Words</p><p>Placement is not just about getting an offer letter. It is about handling rejection, accepting mistakes, improving strategically, and developing mental strength.</p><p>If you are failing right now, remember:</p><p>Your current result is not your final result.</p><p>Your comeback is being prepared through your discipline.</p><p>And when you finally receive your offer letter, you will realize — the biggest achievement was not getting the offer letter, but becoming strong enough to earn it…</p><p>Definitely, this will not stop me — it will give me the courage to think bigger and achieve much more.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fa11beb9b0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>