Challenge in python. Doubt

Asked

Viewed 79 times

0

The challenge: to receive a string s and an integer k, then you must separate the string into sub-strings of length s/k and finally remove the repeated letters in each sub-string. Follows the code:

def merge_the_tools(string,k):
n=len(string)
merge= n//k
separador=[]
lista=[]
for i in range(merge):
    start= int(i*n/merge)
    end= int((i+1)*n/merge)
    separador.append(string[start:end])
for i in range(len(separador)):
    lista.append(list(separador[i]))
return lista


aux=[]
result=merge_the_tools('AABCAAADA', 3)

for i in range(len(result)):
    aux.append(list(set(result[i])))
    print(aux[i])

But when printing the output I have to have the following answer:

AB
CA
AD

And what I have is a reverse response when I use the set():

BA
AC
DA

I can’t understand why.

1 answer

1


If you check the documentation you’ll see that it says:

A set Object is an unordered Collection of distinct hashable Objects.

Free translation:

An object set (set) is an unordered collection of objects "hasheable" distinguished.

Just as the ensembles that we study in mathematics, a set is a group of elements where their order and repetition of element is not relevant.

If you access to Wiki on the concept of sets you will see that the whole A = {1, 2, 2, 1, 3, 2} is equivalent to the set A = {1, 2, 3}. And that reflects python too:

a = {1, 2, 2, 1, 3, 2}
b = {1, 2, 3}

a == b
# True

a
# {1, 2, 3}
b
# {1, 2, 3}

If you need the order to be kept in your code, you use a sequence, which is a collection where order matters. For example: lists and tuples.

PS: A while ago I read somewhere that the implementation of sets of Cpython is a "modification" of the implementation of dict, I mean, sets would be like value-less dictionaries, only keys. I confess that, although I confirmed the statement after checking the source code at the time, I can no longer find this reference. However it is relevant to leave here the information that from Python 3.7 the implementation of dict Cpython keeps the insertion order of dictionary keys (see in change log) then this information may no longer be true.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.