2

Here in this code I am getting output differently every time I run the same code.

INPUT:

s='AABCAAADA'
st=[]
def merge_the_tools(size,k):
    n=int(len(size)/k)
    for i in range(n):
        st.append(size[i*n:(i+1)*n])
    for i in st:
        se=set(i)
        print(''.join(se))
        
print(merge_the_tools(s,3))

First OUTPUT:

AB
AC
AD
None

Another OUTPUT:

AB
CA
DA
None

Another OUTPUT:

BA
CA
DA
None

Like this I am getting different output Can anybody tell why this is happening.

And I want this OUTPUT:

AB
CA
AD
3
  • 1
    Sets in Python don't have a specific order. Commented Oct 16, 2021 at 6:46
  • So, what can we do here to get any specific order Commented Oct 16, 2021 at 6:47
  • 1
    Sort the content of the set to obtain always the same order. Commented Oct 16, 2021 at 6:49

3 Answers 3

1

Python sets have no order, so there is no guarantee that the items will be retrieved in the same order every time while joining them. Consider using a list or tuple if you would like to maintain order.

Sign up to request clarification or add additional context in comments.

Comments

1

Sets in Python are unordered and unindexed as shown in this demonstration. If you want to maintain a specific order, you can just sort the set as follows.

print(''.join(sorted(se)))

Comments

0

A set in Python is an unordered data structure, so so it does not preserve the insertion order.

You should use a list instead. Or you can sort the set. But sort return a list anyway.

Using sorted:

s='AABCAAADA'
st=[]
def merge_the_tools(size,k):
    n=int(len(size)/k)
    for i in range(n):
        st.append(size[i*n:(i+1)*n])
    for i in st:
        se=set(i)
        print(''.join(sorted(se)))
        
print(merge_the_tools(s,3))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.