rockethon
rockethon

Reputation: 37

How can I sort tuples?

Im trying to write a program that has 2 variables (Integer) and that based on those variables print´s them joined and by order (Smaller number to Higher):

Like this:

together((0,39,100,210),(4,20))

printing the following:

(0,4,20,39,100,210)

The code:

def together(s,t):
    y = s + t
    z = 0
    if sorted(y) == y:
        print (y)
    else:
        for i in range(len(y)-1):
            if y[z] > y[z+1]:
                y[z+1] = y[z]
        return (y)
   print y

If variables are set like the following:

s=1,23,40 and t=9,90

I´m getting this:

(1, 23, 40, 9, 90)

which is out of order as you can see it should appear the following:

(1,9,23,40,90)

Upvotes: 1

Views: 61

Answers (2)

labheshr
labheshr

Reputation: 3056

T = ((0,39,100,210),(4,20))    
print tuple( sorted( reduce(tuple.__add__, T) ) )

This can combine and sort N number of tuples within a tuple, so it's not limited to two tuples

Upvotes: 0

Mureinik
Mureinik

Reputation: 311143

Why not just append both tuples and then sort them:

def together(s,t):
    return tuple(sorted(s + t))

Upvotes: 1

Related Questions