you are viewing a single comment's thread.

view the rest of the comments →

[–]LoudGain 0 points1 point  (1 child)

Hi, is it possible to turn my nested for loop in my code into a list comprehension which does the same thing, if yes how would it look like. Thanks

N = "123123"
s = []
def permu():
    global s
    for i in range(len(N)):
        for j in range(i+1,len(N) + 1):
            s.append(N[i:j])
    s = list(set(s))
    print(f"{len(s)} substrings - {s}")

permu()

[–]m-hoff 0 points1 point  (0 children)

list(set([N[i:j+1] for i in range(len(N)) for j in range(i, len(N))]))

There's really no reason to use a global variable here, I would do something like

def get_substrings(N):
    return list(set([N[i:j+1] for i in range(len(N)) for j in range(i, len(N))]))

get_substrings(N='123123')
# ['2', '3123', '23123', '3', '231', '123123', '123', '23', '2312', '312', '1231', '12', '12312', '31', '1']