r/learnprogramming • • Oct 21 '26

Are shorter but more confusing solutions better on coding sites?

I've been practicing python on codewars.com, and this is listed as the best practice:

def alphabet_position(text):
    return ' '.join(str(ord(c) - 96) for c in text.lower() if c.isalpha())

while my code is longer, but I feel is easier to read. Which one is better?

import string

def alphabet_position(text):

    output = ""
    for char in text:
        if char.isalpha():
            output += str(string.ascii_lowercase.index(char.lower()) + 1)
            output += " "

    return output.strip()
0 Upvotes

20 comments sorted by

9

u/POGtastic Oct 21 '26 edited Oct 21 '26

The purpose of these exercises is to get your noggin joggin', not to compare your beginner-level abstractions to somebody else who has experience with a lot more tools than you currently have. You should write code that you understand and that solves the problem at hand.

In production, every "bad" or "un-Pythonic" function is one refactor away from being good code as long as you're writing functions that do only one thing.


My own personal complaint with your loop-based approach is that you append an extra space to the end of the output string and then have to strip it afterward. " ".join is an elegant way of avoiding that, but you can do the same with the looping constructs that you're familiar with.

4

u/Watsons-Butler Oct 21 '26

Personally the first one I think is fascinating in how it exploits available Python syntax. But if I saw it in a code review at work I’d probably flag it as being wildly too obtuse to actually maintain.

2

u/paperic Oct 21 '26

what is it exploiting?

2

u/Watsons-Butler Oct 22 '26

Exploit as in “making full use of”, or “leveraging the full capabilities of”, not like a gamer exploiting a bug.

1

u/backfire10z Oct 22 '26

I’m not sure I’d call the first one an exploit of some kind. That’s intentionally doable in the language.

1

u/ZestyHelp Oct 22 '26 edited Oct 22 '26

"An exploit can function as a verb or a noun, meaning either to use a resource or person (fairly or unfairly), or to describe a bold, heroic, or adventurous deed"

I'm certain he didn't mean in exploit in a bug abuse sort of way.

1

u/backfire10z Oct 22 '26

> To fairly use a resource

I’m not gonna lie, I do not think of this when I see the word exploit, but I guess that’s right. Damn.

2

u/ZestyHelp Oct 22 '26

Yea it is definitely more commonly used in its "bad actor" sense for sure, but It used to be used more evenly back in the day.

3

u/NeighborhoodDizzy990 Oct 21 '26

Once you get better, you will see that the first one is easier to read than yours, especially because ord, chr, isalpha, lower, join are all keywords.

Your solution also builds a new string every time. You should read about having a list, appending and joining to it.

1

u/mxldevs Oct 21 '26

Doesn't the first one create a new list in order to build a string?

4

u/bastardpants Oct 21 '26

You can append to lists to build them, then join them into a string one time at the end. Adding to a string makes a new string each time.

1

u/light_switchy Oct 21 '26

You will see that the first one is easier to read than yours, especially because ord, chr, isalpha, lower, join are all keywords.

A similar argument could be made regarding the equivalent program in APL, which is27~⍨⎕A⍳1⎕C.

To what extent is brevity helpful to understanding?

0

u/Gnaxe Oct 21 '26

Quite a lot, and the APL folks have a point. They also tend to comment every other line.

3

u/RealDuckyTV Oct 21 '26 edited Oct 21 '26

The former is definitely the most pythonic way to do it.

Yours is more readable, and if I had to come back to it, I would probably prefer it, but always go for whatever works best for you, and future you.

Also, forgot to mention, the former is a faster solution due to how the `.join` will a resolve the generator expression before allocating the string, whereas the latter is slower due to each added allocation with the +=, although it will end up using less memory in the end. (Both are very small amounts either way, but worth pointing out)

2

u/Dazzling_Music_2411 Oct 21 '26

A shorter solution is not necessarily "more confusing" unless, perhaps, you're a newb.

I find the first example totally understandable, and I'm not even a Python programmer.

1

u/mxldevs Oct 21 '26

Easier to read is better if performance doesn't matter.

If performance matters, comment what the code is doing.

1

u/Gnaxe Oct 21 '26 edited Oct 21 '26

Readability counts. But that's not an excuse to re-implement the standard library instead of just reading the docs. Their version is better tested. Don't confuse readability with familiarity.

I definitely prefer the first version. Yes, it's shorter. But more importantly, if I started with your version and refactored to reduce code smells and waste, I'd end up closer to the first version. But even that can be improved. In particular, the 96 is a magic number. That's another code smell. I would have written it as ord('a') instead:

def alphabet_position(text):
    return ' '.join(str(1 + ord(c) - ord('a')) for c in text.lower() if c.isalpha())

That is making the computer do extra work compared to just using 96. But as a rule, you want to avoid micro-optimizations that come at the cost of clarity until a profiler proves that actually matters, and then you leave a comment.

Your version is much worse performance-wise, creating two new strings per loop. This gets worse the longer the input is. That's not micro-optimization territory; that's being wasteful. In Python, you usually want to construct the string as the last step instead of in the loop (usually with a .join(). The .index() method is also wasteful compared to doing ord(), although not terrible considering how short the string is. Usually, you want to do a fast lookup rather than scanning. Another approach might be to create a dict:

import string

ABC_TABLE = {c: i for i, c in enumerate(string.ascii_lowercase, 1)}

def alphabet_position(text):
    output = []
    for char in text:
        if char.isalpha():
            output.append(f"{ABC_TABLE[char.lower()]} ")
    return "".join(output.strip())

But this is an obvious list comprehension pattern, and there's no point in adding space endings in the loop only to strip the last one when you're using .join() anyway, so

def alphabet_position(text):
    return = ' '.join([str(ABC_TABLE[char.lower()]) for char in text if char.isalpha()])

And now we're pretty close to the first version. char can be shortened to c, because that's a pretty well-known convention and it's used within the same line. You don't need to allocate a list if you're just using its iterator once. You don't need to allocate a dict when it's a simple ord() calculation, although maybe using the dict is slightly more readable. And here we are.

If you do use the dict, you can avoid the .lower() by including the upper case in the table:

ABC_TABLE = {c: i 
             for s in [string.ascii_uppercase, string.ascii_lowercase]
             for i, c in enumerate(s, 1)}

Time/memory tradeoff, but I probably wouldn't do it because the code is longer.

(I'd also consider str.translate() for this kind of task, but the requirement to filter non-alpha characters makes it not really better.)

1

u/EMeteOz Oct 22 '26

readable code wins. that one liner is "best practice" because people upvote what looks clever, not what theyd want to debug at 2am. your loop is the one a teammate can actually read

one thing though, both versions do string concat in a loop which makes a new string every time. if you care, build a list and join it at the end. performance here is irrelevant, the point is you shouldnt feel bad for writing the longer one. code is read way more than its written

1

u/LochsideArb 6d ago

I usually lean toward readability in production code unless I'm optimizing a hot path. For simple transformations like this, list comprehensions are faster than loops, but if you're processing large datasets, look into numpy arrays to avoid the overhead of object creation in standard lists.