Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to choose between writing compact but complicated code AND easy-to-follow but longer code in Python?

While doing this challenge on Hackerrank ( https://www.hackerrank.com/challenges/merge-the-tools/problem), I came across this high-vote answer written by a user. It's nice to be compact but I find it VERY difficult to follow.

def merge_the_tools(string, k):
    S, N = input(), int(input()) 
    for part in zip(*[iter(S)] * N):
        d = dict()
        print(''.join([ d.setdefault(c, c) for c in part if c not in d ]))

Here's how I coded:

def merge_the_tools(string, k):
    # s1. cut string into list of substrings
    t=[]
    start=0
    k=int(k)
    end=k
    while(end<len(string)+1):
        t.append(string[start:end])
        start+=k
        end+=k
    #test: print(t)

    #s2. strip repeating char from t_i by iterating thru
    for ti in t:
        si=""
        for char in ti:
            if char not in si:
                si+=char
        print(si)

By the Python standards, which answer demonstrates a better practice? I skimmed PEP8 and didn't find an answer to my question.

like image 921
Schwinn Zhang Avatar asked Jan 08 '19 20:01

Schwinn Zhang


People also ask

What makes Python readable?

Indeed, a high level of readability is at the heart of the design of the Python language, following the recognized fact that code is read much more often than it is written. One reason for the high readability of Python code is its relatively complete set of Code Style guidelines and “Pythonic” idioms.


1 Answers

It all depends on your intended audience and the intended use for your code. If the code is just for you, do it how you best understand it. Compact code is often, but not always more efficient, because you have to write less and there is less to look through if there are errors. If you intend for other people to be looking at your code and learning from it, definitely go for the longer more readable code, give room for them to figure out shortcuts so they can feel accomplished and proud of their work, but back to the question. There is no right or wrong way (in reference to compact vs. readable), to do it, it all depends on situation.

like image 103
Aaron D. Rodriguez Avatar answered Oct 25 '22 00:10

Aaron D. Rodriguez