How can I learn to write simpler code?

valeriahhdez

Valeria writes docs

Posted on December 22, 2023

How can I learn to write simpler code?

I'm taking Harvard's CS50 Introduction to Python Programming course and I'm shocked by how ugly my code is.

I'm a beginner and assume that everyone goes through this stage where your code is overcomplicated. But how can I speed up my learning curve and write cleaner, simpler code?

When solving coding problems, I always write my own code first and after I'm sure it does what it needs to do, I go to Bard and ask it to improve it. What I've learned from comparing my code to Bard's version is that my algorithms are too complicated.

With all the shame I have, I will present an example.

Ashamed dog

The following code is part of a function that takes a string entered by a user and checks if the string complies with five different conditions. For the sake of simplicity, I will present the code for only one of these conditions. The condition is: the string can't have numbers in the middle and the leading number can't be a zero.

This is the code I wrote to check this condition:

if any(char.isdigit() for char in input_str):  
        for i in range(len(input_str)):
            if input_str[i].isdigit():
                if input_str[i] == '0':
                    break
                else:
                    number_index= i
                    contains_number = input_str[number_index:]
                    if contains_number[0] != 0 and all(char.isdigit() for char in contains_number):
                        condition_met += 1
                        condition_list.append(6)
                break
    else:
        condition_met += 1
        condition_list.append(6)
Enter fullscreen mode Exit fullscreen mode

and this is Bard's version:

digits = "".join(char for char in input_str if char.isdigit())
    if not digits:  
        condition_met += 1
        condition_list.append(5)
    else:
        if digits[0] != '0' and digits == input_str[-len(digits):]:
            condition_met += 1
            condition_list.append(5)
Enter fullscreen mode Exit fullscreen mode

My code has 15 lines and Bard's code has 8. A lot more concise.

So my question for more experienced programmers is, how can I improve my solving-problem thinking?

I am enjoying a lot learning to code precisely because it teaches you to break down problems into small tasks but I'm shocked to realize that my solutions are complicated and that I can do better at making them simpler. How can I learn to create simpler code?

💖 💪 🙅 🚩
valeriahhdez
Valeria writes docs

Posted on December 22, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

testing python code
programming testing python code

June 3, 2024

How can I learn to write simpler code?
programming How can I learn to write simpler code?

December 22, 2023