Welcome, guest | Sign In | My Account | Store | Cart

A one line code to do that...

Python, 37 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#features:
#oneliner to reverse,sort,extend a string /tuple/list
#can also pass user defined func in sort
#string or tuple or list can be extended to list,tuple
#for None returns 0

op=lambda o,f,p='',t=type:t(o) in [t(()),t(''),t([])] and eval("lambda o,l,t,p:[l.extend(o),l.%s(%s),%s(l)][2]"%(f,['p',''][f=='reverse' or not p],[["''.join","tuple"][t(o)==t(())],''][t(o)==t([])]))(o,[],t,p)

#if u want that faster versions
#then use this as it creates three lambdas and returns them
#so that they may be used later
reverse,extend,sort = map(lambda a:eval("lambda o,%sl=[[]],t=type:t(o) in [t(()),t(''),t([])] \
                           and [l.pop(0),l.append(list(o)),l[0].%s, t(o)==t('') and ''.join(l[0])\
                           or t(o)==t(()) and tuple(l[0]) or l[0]][3]"%(a[0],a[1])),
            [['','reverse()'],['o1=[],','extend(o1)'],['f=cmp,','sort(f)']])


#if you are wondering whats happening above....
#the basic approach is to convert tuple/string to list
#do operation and reconvert it to tuple/string
#may be recipe
#http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119029
#will help u to understand that

#test code
obj=(2,1,3)
print 'sort',obj,op(obj,'sort')
print 'extend',obj,op(obj,'extend',obj)
print 'reverse',obj,op(obj,'reverse')
obj='anurag'
print 'sort',obj,op(obj,'sort',lambda a,b:cmp(b,a))
print 'extend',obj,op(obj,'extend',' uniyal')
print 'reverse',obj,op(obj,'reverse')
obj=[6,2,5]
print 'sort',obj,op(obj,'sort')
print 'extend',obj,op(obj,'extend','abc')
print 'reverse',obj,op(obj,'reverse')

Thanks to H. Krekel who asked me to lambda-ise his recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119596

Any person willing to use not-in-place list type operations on tuples/strings in practical applications may use recipe:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/120203

Created by anurag uniyal on Mon, 8 Apr 2002 (PSF)
Python recipes (4591)
anurag uniyal's recipes (12)

Required Modules

  • (none specified)

Other Information and Tasks