Re: how to sort a list of tuples with custom function

2017-08-04 Thread Ho Yeung Lee
On Friday, August 4, 2017 at 10:08:56 PM UTC+8, Ho Yeung Lee wrote:
> i had changed to use kmeans
> 
> https://gist.github.com/hoyeunglee/2475391ad554e3d2b2a40ec24ab47940
> 
> i do not know whether write it correctly
> but it seems can cluster to find words in window, but not perfect
> 
> 
> On Wednesday, August 2, 2017 at 3:06:40 PM UTC+8, Peter Otten wrote:
> > Glenn Linderman wrote:
> > 
> > > On 8/1/2017 2:10 PM, Piet van Oostrum wrote:
> > >> Ho Yeung Lee  writes:
> > >>
> > >>> def isneighborlocation(lo1, lo2):
> > >>>  if abs(lo1[0] - lo2[0]) < 7  and abs(lo1[1] - lo2[1]) < 7:
> > >>>  return 1
> > >>>  elif abs(lo1[0] - lo2[0]) == 1  and lo1[1] == lo2[1]:
> > >>>  return 1
> > >>>  elif abs(lo1[1] - lo2[1]) == 1  and lo1[0] == lo2[0]:
> > >>>  return 1
> > >>>  else:
> > >>>      return 0
> > >>>
> > >>>
> > >>> sorted(testing1, key=lambda x: (isneighborlocation.get(x[0]), x[1]))
> > >>>
> > >>> return something like
> > >>> [(1,2),(3,3),(2,5)]
> > 
> > >> I think you are trying to sort a list of two-dimensional points into a
> > >> one-dimensiqonal list in such a way thet points that are close together
> > >> in the two-dimensional sense will also be close together in the
> > >> one-dimensional list. But that is impossible.
> > 
> > > It's not impossible, it just requires an appropriate distance function
> > > used in the sort.
> > 
> > That's a grossly misleading addition. 
> > 
> > Once you have an appropriate clustering algorithm
> > 
> > clusters = split_into_clusters(items) # needs access to all items
> > 
> > you can devise a key function
> > 
> > def get_cluster(item, clusters=split_into_clusters(items)):
> > return next(
> > index for index, cluster in enumerate(clusters) if item in cluster
> > )
> > 
> > such that
> > 
> > grouped_items = sorted(items, key=get_cluster)
> > 
> > but that's a roundabout way to write
> > 
> > grouped_items = sum(split_into_clusters(items), [])
> > 
> > In other words: sorting is useless, what you really need is a suitable 
> > approach to split the data into groups. 
> > 
> > One well-known algorithm is k-means clustering:
> > 
> > https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.vq.kmeans.html
> > 
> > Here is an example with pictures:
> > 
> > https://dzone.com/articles/k-means-clustering-scipy


i use number of clusters = 120

https://gist.github.com/hoyeunglee/2475391ad554e3d2b2a40ec24ab47940
https://drive.google.com/file/d/0Bxs_ao6uuBDUZFByNVgzd0Jrdm8/view?usp=sharing

using my previous is not suitable for english words
but using kmeans is better, however not perfect to cluster words, 
some words are missing
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to sort a list of tuples with custom function

2017-08-04 Thread Ho Yeung Lee
i had changed to use kmeans

https://gist.github.com/hoyeunglee/2475391ad554e3d2b2a40ec24ab47940

i do not know whether write it correctly
but it seems can cluster to find words in window, but not perfect


On Wednesday, August 2, 2017 at 3:06:40 PM UTC+8, Peter Otten wrote:
> Glenn Linderman wrote:
> 
> > On 8/1/2017 2:10 PM, Piet van Oostrum wrote:
> >> Ho Yeung Lee  writes:
> >>
> >>> def isneighborlocation(lo1, lo2):
> >>>  if abs(lo1[0] - lo2[0]) < 7  and abs(lo1[1] - lo2[1]) < 7:
> >>>  return 1
> >>>  elif abs(lo1[0] - lo2[0]) == 1  and lo1[1] == lo2[1]:
> >>>  return 1
> >>>  elif abs(lo1[1] - lo2[1]) == 1  and lo1[0] == lo2[0]:
> >>>  return 1
> >>>  else:
> >>>  return 0
> >>>
> >>>
> >>> sorted(testing1, key=lambda x: (isneighborlocation.get(x[0]), x[1]))
> >>>
> >>> return something like
> >>> [(1,2),(3,3),(2,5)]
> 
> >> I think you are trying to sort a list of two-dimensional points into a
> >> one-dimensiqonal list in such a way thet points that are close together
> >> in the two-dimensional sense will also be close together in the
> >> one-dimensional list. But that is impossible.
> 
> > It's not impossible, it just requires an appropriate distance function
> > used in the sort.
> 
> That's a grossly misleading addition. 
> 
> Once you have an appropriate clustering algorithm
> 
> clusters = split_into_clusters(items) # needs access to all items
> 
> you can devise a key function
> 
> def get_cluster(item, clusters=split_into_clusters(items)):
> return next(
> index for index, cluster in enumerate(clusters) if item in cluster
> )
> 
> such that
> 
> grouped_items = sorted(items, key=get_cluster)
> 
> but that's a roundabout way to write
> 
> grouped_items = sum(split_into_clusters(items), [])
> 
> In other words: sorting is useless, what you really need is a suitable 
> approach to split the data into groups. 
> 
> One well-known algorithm is k-means clustering:
> 
> https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.vq.kmeans.html
> 
> Here is an example with pictures:
> 
> https://dzone.com/articles/k-means-clustering-scipy

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to sort a list of tuples with custom function

2017-08-03 Thread Ho Yeung Lee
I remove red line 
and capture another version

https://gist.github.com/hoyeunglee/99bbe7999bc489a79ffdf0277e80ecb6

it can capture words in windows, but since window words some are black
and some gray, some are not exactly black, 
so I only choose notepad , since it is using black words

but some words are splitted, I have already sorted by x[0] and x[1]

can it improver to a consecutively a few words

"檔案" <- File is succeed
but "另存新檔"  failed since words are splitted

On Thursday, August 3, 2017 at 3:54:13 PM UTC+8, Ho Yeung Lee wrote:
> https://gist.github.com/hoyeunglee/3d340ab4e9a3e2b7ad7307322055b550
> 
> I updated again
> 
> how to do better because some words are stored in different files
> 
> On Thursday, August 3, 2017 at 10:02:01 AM UTC+8, Ho Yeung Lee wrote:
> > https://gist.github.com/hoyeunglee/f371f66d55f90dda043f7e7fea38ffa2
> > 
> > I am near succeed in another way, please run above code
> > 
> > when so much black words, it will be very slow
> > so I only open notepad and maximum it without any content
> > then capture screen and save as roster.png
> > 
> > and run it, but I discover it can not circle all words with red rectangle
> > and only part of words
> > 
> > 
> > On Wednesday, August 2, 2017 at 3:06:40 PM UTC+8, Peter Otten wrote:
> > > Glenn Linderman wrote:
> > > 
> > > > On 8/1/2017 2:10 PM, Piet van Oostrum wrote:
> > > >> Ho Yeung Lee  writes:
> > > >>
> > > >>> def isneighborlocation(lo1, lo2):
> > > >>>  if abs(lo1[0] - lo2[0]) < 7  and abs(lo1[1] - lo2[1]) < 7:
> > > >>>  return 1
> > > >>>  elif abs(lo1[0] - lo2[0]) == 1  and lo1[1] == lo2[1]:
> > > >>>  return 1
> > > >>>  elif abs(lo1[1] - lo2[1]) == 1  and lo1[0] == lo2[0]:
> > > >>>  return 1
> > > >>>  else:
> > > >>>  return 0
> > > >>>
> > > >>>
> > > >>> sorted(testing1, key=lambda x: (isneighborlocation.get(x[0]), x[1]))
> > > >>>
> > > >>> return something like
> > > >>> [(1,2),(3,3),(2,5)]
> > > 
> > > >> I think you are trying to sort a list of two-dimensional points into a
> > > >> one-dimensiqonal list in such a way thet points that are close together
> > > >> in the two-dimensional sense will also be close together in the
> > > >> one-dimensional list. But that is impossible.
> > > 
> > > > It's not impossible, it just requires an appropriate distance function
> > > > used in the sort.
> > > 
> > > That's a grossly misleading addition. 
> > > 
> > > Once you have an appropriate clustering algorithm
> > > 
> > > clusters = split_into_clusters(items) # needs access to all items
> > > 
> > > you can devise a key function
> > > 
> > > def get_cluster(item, clusters=split_into_clusters(items)):
> > > return next(
> > > index for index, cluster in enumerate(clusters) if item in cluster
> > > )
> > > 
> > > such that
> > > 
> > > grouped_items = sorted(items, key=get_cluster)
> > > 
> > > but that's a roundabout way to write
> > > 
> > > grouped_items = sum(split_into_clusters(items), [])
> > > 
> > > In other words: sorting is useless, what you really need is a suitable 
> > > approach to split the data into groups. 
> > > 
> > > One well-known algorithm is k-means clustering:
> > > 
> > > https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.vq.kmeans.html
> > > 
> > > Here is an example with pictures:
> > > 
> > > https://dzone.com/articles/k-means-clustering-scipy

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to sort a list of tuples with custom function

2017-08-03 Thread Ho Yeung Lee
https://gist.github.com/hoyeunglee/3d340ab4e9a3e2b7ad7307322055b550

I updated again

how to do better because some words are stored in different files

On Thursday, August 3, 2017 at 10:02:01 AM UTC+8, Ho Yeung Lee wrote:
> https://gist.github.com/hoyeunglee/f371f66d55f90dda043f7e7fea38ffa2
> 
> I am near succeed in another way, please run above code
> 
> when so much black words, it will be very slow
> so I only open notepad and maximum it without any content
> then capture screen and save as roster.png
> 
> and run it, but I discover it can not circle all words with red rectangle
> and only part of words
> 
> 
> On Wednesday, August 2, 2017 at 3:06:40 PM UTC+8, Peter Otten wrote:
> > Glenn Linderman wrote:
> > 
> > > On 8/1/2017 2:10 PM, Piet van Oostrum wrote:
> > >> Ho Yeung Lee  writes:
> > >>
> > >>> def isneighborlocation(lo1, lo2):
> > >>>  if abs(lo1[0] - lo2[0]) < 7  and abs(lo1[1] - lo2[1]) < 7:
> > >>>  return 1
> > >>>  elif abs(lo1[0] - lo2[0]) == 1  and lo1[1] == lo2[1]:
> > >>>  return 1
> > >>>  elif abs(lo1[1] - lo2[1]) == 1  and lo1[0] == lo2[0]:
> > >>>  return 1
> > >>>  else:
> > >>>  return 0
> > >>>
> > >>>
> > >>> sorted(testing1, key=lambda x: (isneighborlocation.get(x[0]), x[1]))
> > >>>
> > >>> return something like
> > >>> [(1,2),(3,3),(2,5)]
> > 
> > >> I think you are trying to sort a list of two-dimensional points into a
> > >> one-dimensiqonal list in such a way thet points that are close together
> > >> in the two-dimensional sense will also be close together in the
> > >> one-dimensional list. But that is impossible.
> > 
> > > It's not impossible, it just requires an appropriate distance function
> > > used in the sort.
> > 
> > That's a grossly misleading addition. 
> > 
> > Once you have an appropriate clustering algorithm
> > 
> > clusters = split_into_clusters(items) # needs access to all items
> > 
> > you can devise a key function
> > 
> > def get_cluster(item, clusters=split_into_clusters(items)):
> > return next(
> > index for index, cluster in enumerate(clusters) if item in cluster
> > )
> > 
> > such that
> > 
> > grouped_items = sorted(items, key=get_cluster)
> > 
> > but that's a roundabout way to write
> > 
> > grouped_items = sum(split_into_clusters(items), [])
> > 
> > In other words: sorting is useless, what you really need is a suitable 
> > approach to split the data into groups. 
> > 
> > One well-known algorithm is k-means clustering:
> > 
> > https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.vq.kmeans.html
> > 
> > Here is an example with pictures:
> > 
> > https://dzone.com/articles/k-means-clustering-scipy

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to sort a list of tuples with custom function

2017-08-02 Thread Ho Yeung Lee
https://gist.github.com/hoyeunglee/f371f66d55f90dda043f7e7fea38ffa2

I am near succeed in another way, please run above code

when so much black words, it will be very slow
so I only open notepad and maximum it without any content
then capture screen and save as roster.png

and run it, but I discover it can not circle all words with red rectangle
and only part of words


On Wednesday, August 2, 2017 at 3:06:40 PM UTC+8, Peter Otten wrote:
> Glenn Linderman wrote:
> 
> > On 8/1/2017 2:10 PM, Piet van Oostrum wrote:
> >> Ho Yeung Lee  writes:
> >>
> >>> def isneighborlocation(lo1, lo2):
> >>>  if abs(lo1[0] - lo2[0]) < 7  and abs(lo1[1] - lo2[1]) < 7:
> >>>  return 1
> >>>  elif abs(lo1[0] - lo2[0]) == 1  and lo1[1] == lo2[1]:
> >>>  return 1
> >>>  elif abs(lo1[1] - lo2[1]) == 1  and lo1[0] == lo2[0]:
> >>>  return 1
> >>>  else:
> >>>  return 0
> >>>
> >>>
> >>> sorted(testing1, key=lambda x: (isneighborlocation.get(x[0]), x[1]))
> >>>
> >>> return something like
> >>> [(1,2),(3,3),(2,5)]
> 
> >> I think you are trying to sort a list of two-dimensional points into a
> >> one-dimensiqonal list in such a way thet points that are close together
> >> in the two-dimensional sense will also be close together in the
> >> one-dimensional list. But that is impossible.
> 
> > It's not impossible, it just requires an appropriate distance function
> > used in the sort.
> 
> That's a grossly misleading addition. 
> 
> Once you have an appropriate clustering algorithm
> 
> clusters = split_into_clusters(items) # needs access to all items
> 
> you can devise a key function
> 
> def get_cluster(item, clusters=split_into_clusters(items)):
> return next(
> index for index, cluster in enumerate(clusters) if item in cluster
> )
> 
> such that
> 
> grouped_items = sorted(items, key=get_cluster)
> 
> but that's a roundabout way to write
> 
> grouped_items = sum(split_into_clusters(items), [])
> 
> In other words: sorting is useless, what you really need is a suitable 
> approach to split the data into groups. 
> 
> One well-known algorithm is k-means clustering:
> 
> https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.vq.kmeans.html
> 
> Here is an example with pictures:
> 
> https://dzone.com/articles/k-means-clustering-scipy

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to sort a list of tuples with custom function

2017-08-02 Thread Peter Otten
Glenn Linderman wrote:

> On 8/1/2017 2:10 PM, Piet van Oostrum wrote:
>> Ho Yeung Lee  writes:
>>
>>> def isneighborlocation(lo1, lo2):
>>>  if abs(lo1[0] - lo2[0]) < 7  and abs(lo1[1] - lo2[1]) < 7:
>>>  return 1
>>>  elif abs(lo1[0] - lo2[0]) == 1  and lo1[1] == lo2[1]:
>>>  return 1
>>>  elif abs(lo1[1] - lo2[1]) == 1  and lo1[0] == lo2[0]:
>>>  return 1
>>>  else:
>>>  return 0
>>>
>>>
>>> sorted(testing1, key=lambda x: (isneighborlocation.get(x[0]), x[1]))
>>>
>>> return something like
>>> [(1,2),(3,3),(2,5)]

>> I think you are trying to sort a list of two-dimensional points into a
>> one-dimensiqonal list in such a way thet points that are close together
>> in the two-dimensional sense will also be close together in the
>> one-dimensional list. But that is impossible.

> It's not impossible, it just requires an appropriate distance function
> used in the sort.

That's a grossly misleading addition. 

Once you have an appropriate clustering algorithm

clusters = split_into_clusters(items) # needs access to all items

you can devise a key function

def get_cluster(item, clusters=split_into_clusters(items)):
return next(
index for index, cluster in enumerate(clusters) if item in cluster
)

such that

grouped_items = sorted(items, key=get_cluster)

but that's a roundabout way to write

grouped_items = sum(split_into_clusters(items), [])

In other words: sorting is useless, what you really need is a suitable 
approach to split the data into groups. 

One well-known algorithm is k-means clustering:

https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.vq.kmeans.html

Here is an example with pictures:

https://dzone.com/articles/k-means-clustering-scipy

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to sort a list of tuples with custom function

2017-08-01 Thread Ho Yeung Lee
how to write this distance function in sort
there are the syntax error 


On Wednesday, August 2, 2017 at 6:03:13 AM UTC+8, Glenn Linderman wrote:
> On 8/1/2017 2:10 PM, Piet van Oostrum wrote:
> > Ho Yeung Lee  writes:
> >
> >> def isneighborlocation(lo1, lo2):
> >>  if abs(lo1[0] - lo2[0]) < 7  and abs(lo1[1] - lo2[1]) < 7:
> >>  return 1
> >>  elif abs(lo1[0] - lo2[0]) == 1  and lo1[1] == lo2[1]:
> >>  return 1
> >>  elif abs(lo1[1] - lo2[1]) == 1  and lo1[0] == lo2[0]:
> >>  return 1
> >>  else:
> >>  return 0
> >>
> >>
> >> sorted(testing1, key=lambda x: (isneighborlocation.get(x[0]), x[1]))
> >>
> >> return something like
> >> [(1,2),(3,3),(2,5)]
> > I think you are trying to sort a list of two-dimensional points into a
> > one-dimensiqonal list in such a way thet points that are close together
> > in the two-dimensional sense will also be close together in the
> > one-dimensional list. But that is impossible.
> It's not impossible, it just requires an appropriate distance function 
> used in the sort.

-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to sort a list of tuples with custom function

2017-08-01 Thread Glenn Linderman

On 8/1/2017 2:10 PM, Piet van Oostrum wrote:

Ho Yeung Lee  writes:


def isneighborlocation(lo1, lo2):
 if abs(lo1[0] - lo2[0]) < 7  and abs(lo1[1] - lo2[1]) < 7:
 return 1
 elif abs(lo1[0] - lo2[0]) == 1  and lo1[1] == lo2[1]:
 return 1
 elif abs(lo1[1] - lo2[1]) == 1  and lo1[0] == lo2[0]:
 return 1
 else:
 return 0


sorted(testing1, key=lambda x: (isneighborlocation.get(x[0]), x[1]))

return something like
[(1,2),(3,3),(2,5)]

I think you are trying to sort a list of two-dimensional points into a
one-dimensiqonal list in such a way thet points that are close together
in the two-dimensional sense will also be close together in the
one-dimensional list. But that is impossible.
It's not impossible, it just requires an appropriate distance function 
used in the sort.

--
https://mail.python.org/mailman/listinfo/python-list


Re: how to sort a list of tuples with custom function

2017-08-01 Thread Piet van Oostrum
Ho Yeung Lee  writes:

> def isneighborlocation(lo1, lo2):
> if abs(lo1[0] - lo2[0]) < 7  and abs(lo1[1] - lo2[1]) < 7:
> return 1
> elif abs(lo1[0] - lo2[0]) == 1  and lo1[1] == lo2[1]:
> return 1
> elif abs(lo1[1] - lo2[1]) == 1  and lo1[0] == lo2[0]:
> return 1
> else:
> return 0
>
>
> sorted(testing1, key=lambda x: (isneighborlocation.get(x[0]), x[1]))
>
> return something like
> [(1,2),(3,3),(2,5)]

I think you are trying to sort a list of two-dimensional points into a
one-dimensiqonal list in such a way thet points that are close together
in the two-dimensional sense will also be close together in the
one-dimensional list. But that is impossible.
-- 
Piet van Oostrum 
WWW: http://piet.vanoostrum.org/
PGP key: [8DAE142BE17999C4]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to sort a list of tuples with custom function

2017-08-01 Thread Ho Yeung Lee
i tried with
testing1.sort(key=lambda x: x[0])
but only first element of tuple are grouped

then i expect to sort with custom function if difference between first element 
of tuple and another first element of tuple is less than some value
and do for second element too,

goal to segmentation of black words from photo

from PIL import Image
from functools import partial 
ma = Image.open("roster.png")
color1 = ma.load()
print ma.size
print color1[1,1] 
color1 = ma.load()
print ma.size
print color1[1,1] 
colortolocation = {}
def addtogroupkey(keyandmemory, key1, memorycontent):
k = key1
if k in keyandmemory: 
keyandmemory[k].append(memorycontent) 
else: 
keyandmemory[k] = [memorycontent]
return keyandmemory

for ii in range(0, ma.size[0]):
for jj in range(0, ma.size[1]):
colortolocation = addtogroupkey(colortolocation, color1[ii,jj], (ii,jj))

def isneighborlocation(lo1, lo2):
if abs(lo1[0] - lo2[0]) < 7  and abs(lo1[1] - lo2[1]) < 7:
return 1
elif abs(lo1[0] - lo2[0]) == 1  and lo1[1] == lo2[1]:
return 1
elif abs(lo1[1] - lo2[1]) == 1  and lo1[0] == lo2[0]:
return 1
else:
return 0

for eachcolor in colortolocation:
testing1 = list(colortolocation[eachcolor])
#testing1.sort(key=lambda x: x[1])
#custom_list_indices = {v: i for i, v in enumerate(custom_list)}
testing1.sort(key=lambda x: x[0]-x[1])
locations = testing1
locationsgroup = {}
continueconnect = 0
for ii in range(0,len(locations)-1):
if isneighborlocation(locations[ii], locations[ii+1]) == 1:
if continueconnect == 0:
keyone = len(locationsgroup)+1
if keyone in locationsgroup:
if locations[ii] not in locationsgroup[keyone]:
locationsgroup = addtogroupkey(locationsgroup, keyone, 
locations[ii])
if locations[ii+1] not in locationsgroup[keyone]:
locationsgroup = addtogroupkey(locationsgroup, keyone, 
locations[ii+1])
else:
locationsgroup = addtogroupkey(locationsgroup, keyone, 
locations[ii])
locationsgroup = addtogroupkey(locationsgroup, keyone, 
locations[ii+1])
continueconnect = 1
else:
if len(locationsgroup) > 0:
if locations[ii] not in locationsgroup[len(locationsgroup)]:
locationsgroup = addtogroupkey(locationsgroup, 
len(locationsgroup)+1, locations[ii])
else:
locationsgroup = addtogroupkey(locationsgroup, 
len(locationsgroup)+1, locations[ii])
continueconnect = 0
colortolocation[eachcolor] = locationsgroup

for kk in colortolocation[(0,0,0)]:
if len(colortolocation[(0,0,0)][kk]) > 7:
print kk
print colortolocation[(0,0,0)][kk]




On Wednesday, August 2, 2017 at 3:50:52 AM UTC+8, Ho Yeung Lee wrote:
> def isneighborlocation(lo1, lo2):
> if abs(lo1[0] - lo2[0]) < 7  and abs(lo1[1] - lo2[1]) < 7:
> return 1
> elif abs(lo1[0] - lo2[0]) == 1  and lo1[1] == lo2[1]:
> return 1
> elif abs(lo1[1] - lo2[1]) == 1  and lo1[0] == lo2[0]:
> return 1
> else:
> return 0
> 
> 
> sorted(testing1, key=lambda x: (isneighborlocation.get(x[0]), x[1]))
> 
> return something like
> [(1,2),(3,3),(2,5)]

-- 
https://mail.python.org/mailman/listinfo/python-list


how to sort a list of tuples with custom function

2017-08-01 Thread Ho Yeung Lee


def isneighborlocation(lo1, lo2):
if abs(lo1[0] - lo2[0]) < 7  and abs(lo1[1] - lo2[1]) < 7:
return 1
elif abs(lo1[0] - lo2[0]) == 1  and lo1[1] == lo2[1]:
return 1
elif abs(lo1[1] - lo2[1]) == 1  and lo1[0] == lo2[0]:
return 1
else:
return 0


sorted(testing1, key=lambda x: (isneighborlocation.get(x[0]), x[1]))

return something like
[(1,2),(3,3),(2,5)]
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Chris Angelico
On Sun, May 26, 2013 at 1:38 PM, Steven D'Aprano
 wrote:
> On Sun, 26 May 2013 03:23:44 +1000, Chris Angelico wrote:
>
>> Does adding 1 to a random
>> number make it less random? It adds determinism to the number; can a
>> number be more deterministic while still no less random?
>>
>> Ah! I know. The answer comes from common sense:
> [snip spurious answer]
>
> I know you're being funny, but in fact adding a constant to a random
> variable still leaves it equally random. Adding, multiplying, dividing or
> subtracting a constant from a random variable X just shifts the possible
> values X can take, it doesn't change the shape of the distribution.

In real numbers, that's correct. However, computers don't work with
real numbers, so there's the very, uhh, REAL possibility that some of
the entropy will be lost. For instance, multiplying and dividing when
working with integers results in truncation, and adding huge numbers
to small floats results in precision loss.

I was deliberately playing around, but unfortunately there have been
many people who've genuinely thought things similar to what I was
saying - and then implemented into code.

> However, adding two random variables X and Y does change the
> distribution. In fact, a very cheap way of simulating an almost normally
> distributed random variable is to add up a whole lot of uniformly
> distributed random variables. Adding up 12 calls to random.random(), and
> subtracting 6, gives you a close approximation to a Gaussian random
> variable with mean 0 and standard deviation 1.

Yep. The more dice you roll, the more normal the distribution. Which
means that d100 is extremely swingy, but 11d10-10 is much less so, and
99d2-98 quite stable. The more randomness you add, the more
predictable the result.

Does that seem right to you?

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Dan Sommers
On Sun, 26 May 2013 03:38:12 +, Steven D'Aprano wrote:

> ... adding a constant to a random variable still leaves it equally
> random. Adding, multiplying, dividing or subtracting a constant from a
> random variable X just shifts the possible values X can take ...

That's mathematically true, but this is the Python mailing list.

Adding, subtracting, or dividing by a sufficiently large constant loses
all the randomness.

Python 3.2.4 (default, May  8 2013, 20:55:18) 
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>> random.random() + 1e200
1e+200
>>> random.random() - 1e200
-1e+200
>>> random.random() / 1e309
0.0

But you knew that.  ;-)

Dan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Chris Angelico
On Sun, May 26, 2013 at 1:09 PM, Steven D'Aprano
 wrote:
> You're right, all my dice are eight-sided and complex:
>
> 1+0i
> 1+1i
> 1-1i
> -1+0i
> -1+1i
> -1-1i
>
>
> :-)

Now THAT is a dice of win!

>> Now, I have here with me
>> a set used for maths drill (to be entirely accurate, what I have here is
>> the company's stock of them, so there are multiples of each of these -
>> anyone need to buy dice?)
>
> Are you serious? What's the cost, posted to Melbourne?

$1 each, postage probably $5 for any number. Or there may even be
option to pick up / hand deliver, depending on where in Melb you are.

http://www.kepl.com.au/ - company's winding down, but we still have stock.

> Oh, you mean ÷ (division sign)! Why didn't you say so? :-P

I tend to stick to ASCII in these posts. :)

> And another thing, shame on you, you mean × not x. It's easy to find too:
>
> py> from unicodedata import lookup
> py> print(lookup("MULTIPLICATION SIGN"))
> ×

I'm aware of that, but see above, I stick to ASCII where possible. The
faces would be better represented with some of the other digits (the
bolded ones, perhaps), but I used the ASCII digits. :)

>> Plus, if you roll 2d6 (that is, two
>> regular six-sided dice and add them up), 7 is statistically the most
>> likely number to come up with. Therefore it IS random.
>
> Yes, but if you subtract them the most common is 0, if you multiply the
> most common are 6 or 12, and if you divide the most common is 1. If you
> decide on the operation randomly, using the +-×÷+ die above (ignoring
> wildcards), the most common result is 6. The probability of getting a 7
> is just 1/15.
>
> from collections import Counter
> from operator import add, sub, mul, truediv as div
> ops = (add, sub, mul, div, add)
> Counter(op(i, j) for op in ops for i in range(1, 7) for j in range(1, 7))

LOL! I never thought to go THAT far into the analysis. Nice one!

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Steven D'Aprano
On Sun, 26 May 2013 03:23:44 +1000, Chris Angelico wrote:

> Does adding 1 to a random
> number make it less random? It adds determinism to the number; can a
> number be more deterministic while still no less random?
> 
> Ah! I know. The answer comes from common sense:
[snip spurious answer]

I know you're being funny, but in fact adding a constant to a random 
variable still leaves it equally random. Adding, multiplying, dividing or 
subtracting a constant from a random variable X just shifts the possible 
values X can take, it doesn't change the shape of the distribution. 
However, adding two random variables X and Y does change the 
distribution. In fact, a very cheap way of simulating an almost normally 
distributed random variable is to add up a whole lot of uniformly 
distributed random variables. Adding up 12 calls to random.random(), and 
subtracting 6, gives you a close approximation to a Gaussian random 
variable with mean 0 and standard deviation 1.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Steven D'Aprano
On Sun, 26 May 2013 01:41:58 +1000, Chris Angelico wrote:

> On Sun, May 26, 2013 at 12:28 AM, Steven D'Aprano
>  wrote:
>> On Sat, 25 May 2013 19:14:57 +1000, Chris Angelico wrote:
>>
>>> def random_number():
>>> return 7
>>
>> I call shenanigans! That value isn't generated randomly, you just made
>> it up! I rolled a die *hundreds* of times and not once did it come up
>> seven!
> 
> You've obviously never used a REAL set of dice.

You're right, all my dice are eight-sided and complex:

1+0i
1+1i
1-1i
-1+0i
-1+1i
-1-1i


:-)


But seriously, I have various D&D style gaming dice, d4, d6, d8, d12, d20 
and d30. But I thought the opportunity for a joke was more important than 
pedantic correctness :-)


> Now, I have here with me
> a set used for maths drill (to be entirely accurate, what I have here is
> the company's stock of them, so there are multiples of each of these -
> anyone need to buy dice?) 

Are you serious? What's the cost, posted to Melbourne?


> with everything except the classic 1 through 6 that everyone knows:
> 
> * Six sides, faces marked 7 through 12 
> * Six sides, faces marked "+x-\xf7+" and a "wild" marker 
>   (yes, two of +)

Oh, you mean ÷ (division sign)! Why didn't you say so? :-P

And another thing, shame on you, you mean × not x. It's easy to find too:

py> from unicodedata import lookup
py> print(lookup("MULTIPLICATION SIGN"))
×


> * Ten sides, numbered 0 through 9
> * Eight sides, numbered 1 through 8
> * Twelve sides, as above
> * Twenty sides, as above
> 
> Now, tabletop roleplayers will recognize the latter four as the ones
> notated as d10, d8, d12, and d20, but these are NOT for gameplay, they
> are for serious educational purposes! Honest!
> 
> Anyway, all of those can roll a 7... well, one of them has to roll a
> \xf7, but close enough right? 

I don't think so...

> Plus, if you roll 2d6 (that is, two
> regular six-sided dice and add them up), 7 is statistically the most
> likely number to come up with. Therefore it IS random.

Yes, but if you subtract them the most common is 0, if you multiply the 
most common are 6 or 12, and if you divide the most common is 1. If you 
decide on the operation randomly, using the +-×÷+ die above (ignoring 
wildcards), the most common result is 6. The probability of getting a 7 
is just 1/15.

from collections import Counter
from operator import add, sub, mul, truediv as div
ops = (add, sub, mul, div, add)
Counter(op(i, j) for op in ops for i in range(1, 7) for j in range(1, 7))


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Carlos Nepomuceno

> Date: Fri, 24 May 2013 23:05:17 -0700
> Subject: Re: help how to sort a list in order of 'n' in python without using 
> inbuilt functions??
> From: lokeshkopp...@gmail.com
[...]

> ya steven i had done the similar logic but thats not satisfying my professor
> he had given the following constrains
> 1. No in-built functions should be used
> 2. we are expecting a O(n) solution
> 3. Don't use count method


PS: If you find something faster please let me know!
  
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Carlos Nepomuceno

> Date: Sun, 26 May 2013 03:23:44 +1000
> Subject: Re: help how to sort a list in order of 'n' in python without using 
> inbuilt functions??
> From: ros...@gmail.com
> To: python-list@python.org
>
> On Sun, May 26, 2013 at 3:17 AM, Carlos Nepomuceno
>  wrote:
>> def f(x):
>> return x+1
>>
>> or you can just go:
>>
>> f(roll_d6())
>
> Hmm. Interesting. So now we have a question: Does adding 1 to a random
> number make it less random? It adds determinism to the number; can a
> number be more deterministic while still no less random?
>
> Ah! I know. The answer comes from common sense:
>
> a = random() # a is definitely a random number
> a -= random() # a is no longer random, we subtracted all the randomness from 
> it
>
> Of course, since number-number => number, a is still a number. And so
> we can conclude that adding 1 to a random dice roll does indeed leave
> all the randomness still in it. But wait! That means we can do
> better!!
>
> a = random() # a is a random number
> a *= 5 # a is clearly five times as random now!
>
> ChrisA
> --
> http://mail.python.org/mailman/listinfo/python-list

It depends if the result (any operation) is in the required range.

For example: "int(random.random()+1)" it's not random at all!

But "int(random.random()*1000)" my look random if it fits your needs.

;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Chris Angelico
On Sun, May 26, 2013 at 3:17 AM, Carlos Nepomuceno
 wrote:
> def f(x):
> return x+1
>
> or you can just go:
>
> f(roll_d6())

Hmm. Interesting. So now we have a question: Does adding 1 to a random
number make it less random? It adds determinism to the number; can a
number be more deterministic while still no less random?

Ah! I know. The answer comes from common sense:

a = random()   # a is definitely a random number
a -= random()  # a is no longer random, we subtracted all the randomness from it

Of course, since number-number => number, a is still a number. And so
we can conclude that adding 1 to a random dice roll does indeed leave
all the randomness still in it. But wait! That means we can do
better!!

a = random()   # a is a random number
a *= 5   # a is clearly five times as random now!

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Carlos Nepomuceno

> Date: Sun, 26 May 2013 01:41:58 +1000
> Subject: Re: help how to sort a list in order of 'n' in python without using 
> inbuilt functions??
> From: ros...@gmail.com
> To: python-list@python.org
>
> On Sun, May 26, 2013 at 12:28 AM, Steven D'Aprano
>  wrote:
>> On Sat, 25 May 2013 19:14:57 +1000, Chris Angelico wrote:
>>
>>> def random_number():
>>> return 7
>>
>> I call shenanigans! That value isn't generated randomly, you just made it
>> up! I rolled a die *hundreds* of times and not once did it come up seven!
>
> You've obviously never used a REAL set of dice. Now, I have here with
> me a set used for maths drill (to be entirely accurate, what I have
> here is the company's stock of them, so there are multiples of each of
> these - anyone need to buy dice?) with everything except the classic 1
> through 6 that everyone knows:
>
> * Six sides, faces marked 7 through 12
> * Six sides, faces marked "+x-\xf7+" and a "wild" marker (yes, two of +)
> * Ten sides, numbered 0 through 9
> * Eight sides, numbered 1 through 8
> * Twelve sides, as above
> * Twenty sides, as above
>
> Now, tabletop roleplayers will recognize the latter four as the ones
> notated as d10, d8, d12, and d20, but these are NOT for gameplay, they
> are for serious educational purposes! Honest!
>
> Anyway, all of those can roll a 7... well, one of them has to roll a
> \xf7, but close enough right? Plus, if you roll 2d6 (that is, two
> regular six-sided dice and add them up), 7 is statistically the most
> likely number to come up with. Therefore it IS random.
>
> ChrisA
> --
> http://mail.python.org/mailman/listinfo/python-list


def f(x):
    return x+1

or you can just go:

f(roll_d6())

;)
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Carlos Nepomuceno

> From: steve+comp.lang.pyt...@pearwood.info
> Subject: Re: help how to sort a list in order of 'n' in python without using 
> inbuilt functions??
> Date: Sat, 25 May 2013 14:28:33 +
> To: python-list@python.org
>
> On Sat, 25 May 2013 19:14:57 +1000, Chris Angelico wrote:
>
>> def random_number():
>> return 7
>
> I call shenanigans! That value isn't generated randomly, you just made it
> up! I rolled a die *hundreds* of times and not once did it come up seven!


lol It worked fine on my d8! lol  
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Carlos Nepomuceno

> To: python-list@python.org
> From: breamore...@yahoo.co.uk
> Subject: Re: help how to sort a list in order of 'n' in python without using 
> inbuilt functions??
> Date: Sat, 25 May 2013 13:01:06 +0100
[...]
> In my book this is another fail as lists are inbuilt (yuck!) and so is
> the add function that'll be called for z+=1.

Indeed! It's a joke Mark! lol
;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Chris Angelico
On Sun, May 26, 2013 at 12:28 AM, Steven D'Aprano
 wrote:
> On Sat, 25 May 2013 19:14:57 +1000, Chris Angelico wrote:
>
>> def random_number():
>> return 7
>
> I call shenanigans! That value isn't generated randomly, you just made it
> up! I rolled a die *hundreds* of times and not once did it come up seven!

You've obviously never used a REAL set of dice. Now, I have here with
me a set used for maths drill (to be entirely accurate, what I have
here is the company's stock of them, so there are multiples of each of
these - anyone need to buy dice?) with everything except the classic 1
through 6 that everyone knows:

* Six sides, faces marked 7 through 12
* Six sides, faces marked "+x-\xf7+" and a "wild" marker (yes, two of +)
* Ten sides, numbered 0 through 9
* Eight sides, numbered 1 through 8
* Twelve sides, as above
* Twenty sides, as above

Now, tabletop roleplayers will recognize the latter four as the ones
notated as d10, d8, d12, and d20, but these are NOT for gameplay, they
are for serious educational purposes! Honest!

Anyway, all of those can roll a 7... well, one of them has to roll a
\xf7, but close enough right? Plus, if you roll 2d6 (that is, two
regular six-sided dice and add them up), 7 is statistically the most
likely number to come up with. Therefore it IS random.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Mark Lawrence

On 25/05/2013 15:28, Steven D'Aprano wrote:

On Sat, 25 May 2013 19:14:57 +1000, Chris Angelico wrote:


def random_number():
 return 7


I call shenanigans! That value isn't generated randomly, you just made it
up! I rolled a die *hundreds* of times and not once did it come up seven!





Lies, damn lies and statistics? :)

--
If you're using GoogleCrap™ please read this 
http://wiki.python.org/moin/GoogleGroupsPython.


Mark Lawrence

--
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Jussi Piitulainen
Roy Smith writes:

> In article <78192328-b31b-49d9-9cd6-ec742c092...@googlegroups.com>,
>  lokeshkopp...@gmail.com wrote:
> 
> > On Friday, May 24, 2013 1:34:51 PM UTC+5:30, lokesh...@gmail.com wrote:
> > > i need to write a code which can sort the list in order of 'n'
> > > without use builtin functions
> > > 
> > > can anyone help me how to do?
> > 
> >  Note:
> > the list only contains 0's,1's,2's
> > need to sort them in order of 'n'
> 
> What do you mean by "need to sort them in order of 'n'".  Are you
> saying that you need to sort them into numerical order?  Or that you
> need to running time of the algorithm to be O(n)?
> 
> I'm assuming the later, in which case this is starting to sound like
> a classic interview question.
> 
> Assuming you can accept an unstable sort, there's an easy solution.
> I'm not aware of any solution if you require a stable sort.  Perhaps
> that's enough of a hint?

Surely it's assumed that each element of the input list can be
classified as 0, 1, or 2 in O(1) time. If O(n) auxiliary space can be
allocated in O(n) time, just put the 0's in their own list in the
order they are encountered, 1's in their own list in the order they
are encountered, 2's in their own list in the order they are
encountered, then put the 0's back into the input list in the order
they are encountered in their auxiliary list, followed by the 1's,
followed by the 2's. Stable and O(n), no?

Even ( [ x for x in input if x.key == 0 ] +
   [ x for x in input if x.key == 1 ] +
   [ x for x in input if x.key == 2 ] ).
I suppose a list comprehension is not technically a function any more
than a loop is.

(Neither stability nor O(1) space has been required yet, I think.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Fábio Santos
On 25 May 2013 15:35, "Steven D'Aprano" <
steve+comp.lang.pyt...@pearwood.info> wrote:
>
> On Sat, 25 May 2013 19:14:57 +1000, Chris Angelico wrote:
>
> > def random_number():
> > return 7
>
> I call shenanigans! That value isn't generated randomly, you just made it
> up! I rolled a die *hundreds* of times and not once did it come up seven!
>
>
>
> --
> Steven
> --
> http://mail.python.org/mailman/listinfo/python-list

Try flipping a coin. I flipped one a couple of times and got the seventh
face once.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Steven D'Aprano
On Fri, 24 May 2013 23:05:17 -0700, lokeshkoppaka wrote:

> On Saturday, May 25, 2013 11:27:38 AM UTC+5:30, Steven D'Aprano wrote:

>> tally = 0
>> for item in list_of_items:
>> if item == 0:
>> tally = tally + 1
>> 
>> print "The number of zeroes equals", tally
> 
>
> ya steven i had done the similar logic but thats not satisfying my
> professor he had given the following constrains
>  1. No in-built functions should be used 

The above does not use any built-in functions.

> 2. we are expecting a O(n) solution

The above is O(n).

>  3. Don't use count method

The above does not use the count method.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Steven D'Aprano
On Sat, 25 May 2013 19:14:57 +1000, Chris Angelico wrote:

> def random_number():
> return 7

I call shenanigans! That value isn't generated randomly, you just made it 
up! I rolled a die *hundreds* of times and not once did it come up seven!



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Dave Angel

On 05/25/2013 10:03 AM, Roy Smith wrote:

In article <74e33270-a79a-4878-a400-8a6cda663...@googlegroups.com>,
  lokeshkopp...@gmail.com wrote:


ya steven i had done the similar logic but thats not satisfying my professor
he had given the following constrains
  1. No in-built functions should be used
  2. we are expecting a O(n) solution
  3. Don't use count method


A couple of points here:

1) In general, people on mailing lists are not into doing homework
problems for other people.

2) If you're going to bring us a homework problem, at least describe the
whole problem up front.  It really doesn't help to dribble out new
requirements one at a time.

3) rustompm...@gmail.com already posted a pointer to the wikipedia
article describing the required algorithm in detail.

4) I don't know what "no built-in functions should be used" means.  I
assume it means, "don't call sort()"?  If you can't even call
int.__lt__(), it's going to be really hard to do this.



The OP has already admitted that he didn't want a sort at all.  He wants 
to COUNT the items, not sort them.  So nothing in his orginal post 
relates to the real homework assignment.


--
DaveA
--
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Roy Smith
In article <74e33270-a79a-4878-a400-8a6cda663...@googlegroups.com>,
 lokeshkopp...@gmail.com wrote:

> ya steven i had done the similar logic but thats not satisfying my professor 
> he had given the following constrains
>  1. No in-built functions should be used
>  2. we are expecting a O(n) solution
>  3. Don't use count method

A couple of points here:

1) In general, people on mailing lists are not into doing homework 
problems for other people.

2) If you're going to bring us a homework problem, at least describe the 
whole problem up front.  It really doesn't help to dribble out new 
requirements one at a time.

3) rustompm...@gmail.com already posted a pointer to the wikipedia 
article describing the required algorithm in detail.

4) I don't know what "no built-in functions should be used" means.  I 
assume it means, "don't call sort()"?  If you can't even call 
int.__lt__(), it's going to be really hard to do this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Roy Smith
In article <78192328-b31b-49d9-9cd6-ec742c092...@googlegroups.com>,
 lokeshkopp...@gmail.com wrote:

> On Friday, May 24, 2013 1:34:51 PM UTC+5:30, lokesh...@gmail.com wrote:
> > i need to write a code which can sort the list in order of 'n' without use 
> > builtin functions 
> > 
> > can anyone help me how to do?
> 
>  Note:
> the list only contains 0's,1's,2's
> need to sort them in order of 'n'

What do you mean by "need to sort them in order of 'n'".  Are you saying 
that you need to sort them into numerical order?  Or that you need to 
running time of the algorithm to be O(n)?

I'm assuming the later, in which case this is starting to sound like a 
classic interview question.

Assuming you can accept an unstable sort, there's an easy solution.  I'm 
not aware of any solution if you require a stable sort.  Perhaps that's 
enough of a hint?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Mark Lawrence

On 25/05/2013 09:54, Carlos Nepomuceno wrote:

lol

def absolute(x):
 return x if x>0 else -x

def reach(x):
 y=[]
 z=0
 while z

In my book this is another fail as lists are inbuilt (yuck!) and so is 
the add function that'll be called for z+=1.


--
If you're using GoogleCrap™ please read this 
http://wiki.python.org/moin/GoogleGroupsPython.


Mark Lawrence

--
http://mail.python.org/mailman/listinfo/python-list


RE: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Carlos Nepomuceno
lol http://search.dilbert.com/comic/Random%20Nine


> Date: Sat, 25 May 2013 19:14:57 +1000
> Subject: Re: help how to sort a list in order of 'n' in python without using 
> inbuilt functions??
> From: ros...@gmail.com
> To: python-list@python.org
>
> On Sat, May 25, 2013 at 7:10 PM, Carlos Nepomuceno
>  wrote:
>> 
>>> Date: Sat, 25 May 2013 19:01:09 +1000
>>> Subject: Re: help how to sort a list in order of 'n' in python without 
>>> using inbuilt functions??
>>> From: ros...@gmail.com
>>> To: python-list@python.org
>> [...]
>>> Very good. You are now in a position to get past the limitations of a
>>> restricted-environment eval/exec. Avoiding builtins is actually a fun
>>> skill to hone.
>>>
>>> ChrisA
>>
>>
>> I'm glad he didn't ask for a Pseudo-RNG without built-ins! ;)
>
> def random_number():
> return 7
>
> ChrisA
> --
> http://mail.python.org/mailman/listinfo/python-list   
>   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Chris Angelico
On Sat, May 25, 2013 at 7:10 PM, Carlos Nepomuceno
 wrote:
> 
>> Date: Sat, 25 May 2013 19:01:09 +1000
>> Subject: Re: help how to sort a list in order of 'n' in python without using 
>> inbuilt functions??
>> From: ros...@gmail.com
>> To: python-list@python.org
> [...]
>> Very good. You are now in a position to get past the limitations of a
>> restricted-environment eval/exec. Avoiding builtins is actually a fun
>> skill to hone.
>>
>> ChrisA
>
>
> I'm glad he didn't ask for a Pseudo-RNG without built-ins! ;)

def random_number():
return 7

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Carlos Nepomuceno

> Date: Sat, 25 May 2013 19:01:09 +1000
> Subject: Re: help how to sort a list in order of 'n' in python without using 
> inbuilt functions??
> From: ros...@gmail.com
> To: python-list@python.org
[...]
> Very good. You are now in a position to get past the limitations of a
> restricted-environment eval/exec. Avoiding builtins is actually a fun
> skill to hone.
>
> ChrisA


I'm glad he didn't ask for a Pseudo-RNG without built-ins! ;)   
  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Chris Angelico
On Sat, May 25, 2013 at 6:54 PM, Carlos Nepomuceno
 wrote:
> lol
>
> def absolute(x):
> return x if x>0 else -x
>
> def reach(x):
> y=[]
> z=0
> while z y.append(z)
> z+=1
> return y

Very good. You are now in a position to get past the limitations of a
restricted-environment eval/exec. Avoiding builtins is actually a fun
skill to hone.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Carlos Nepomuceno
lol

def absolute(x):
    return x if x>0 else -x

def reach(x):
    y=[]
    z=0
    while z Date: Sat, 25 May 2013 18:47:24 +1000
> Subject: Re: help how to sort a list in order of 'n' in python without using 
> inbuilt functions??
> From: ros...@gmail.com
> To: python-list@python.org
>
> On Sat, May 25, 2013 at 6:43 PM, Carlos Nepomuceno
>  wrote:
>> 
>> lol I forgot to include this monkey patch! ;)
>>
>> def length(l):
>> x=0
>> y=l[:]
>> while y:
>> x+=1
>> y.pop()
>> return x
>
> Nice. Now eliminate abs (easy) and range. :)
>
> ChrisA
> --
> http://mail.python.org/mailman/listinfo/python-list   
>   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Chris Angelico
On Sat, May 25, 2013 at 6:43 PM, Carlos Nepomuceno
 wrote:
> 
> lol I forgot to include this monkey patch! ;)
>
> def length(l):
> x=0
> y=l[:]
> while y:
> x+=1
> y.pop()
> return x

Nice. Now eliminate abs (easy) and range. :)

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Carlos Nepomuceno

> Date: Sat, 25 May 2013 18:28:32 +1000
> Subject: Re: help how to sort a list in order of 'n' in python without using 
> inbuilt functions??
> From: ros...@gmail.com
> To: python-list@python.org
>
> On Sat, May 25, 2013 at 5:53 PM, Carlos Nepomuceno
>  wrote:
>> 
>>> Date: Fri, 24 May 2013 23:05:17 -0700
>>> 1. No in-built functions should be used
>> count[2] = len(l)
>
> Fail! :)
>
> ChrisA
> --
> http://mail.python.org/mailman/listinfo/python-list

lol I forgot to include this monkey patch! ;)

def length(l):
    x=0
    y=l[:]
    while y:
    x+=1
    y.pop()
    return x  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Chris Angelico
On Sat, May 25, 2013 at 5:53 PM, Carlos Nepomuceno
 wrote:
> 
>> Date: Fri, 24 May 2013 23:05:17 -0700
>> 1. No in-built functions should be used
> count[2] = len(l)

Fail! :)

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-25 Thread Carlos Nepomuceno

> Date: Fri, 24 May 2013 23:05:17 -0700
> Subject: Re: help how to sort a list in order of 'n' in python without using 
> inbuilt functions??
> From: lokeshkopp...@gmail.com
> To: python-list@python.org
[...]
> ya steven i had done the similar logic but thats not satisfying my professor
> he had given the following constrains
> 1. No in-built functions should be used
> 2. we are expecting a O(n) solution
> 3. Don't use count method

That's trivial!

# l is a list of numbers: 0,1,2
def order_n(l):
    r = []
    count = [0]*3
    count[2] = len(l)
    for i in range(len(l)):
    count[1] += abs((l[i]>0)-1)
    r.insert(count[l[i]], l[i])
    return r

'count' is a list I've defined to count the quantity of the elements in the 
argument, not the method.

I don't think it needs any explanations, but if you have any doubts just ask. ;)

Good luck!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-24 Thread Chris Angelico
On Sat, May 25, 2013 at 4:05 PM,   wrote:
> ya steven i had done the similar logic but thats not satisfying my professor
> he had given the following constrains
>  1. No in-built functions should be used
>  2. we are expecting a O(n) solution
>  3. Don't use count method

And now you finally admit that it's homework.

Solve it yourself, or go to your prof and say that you need help.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-24 Thread lokeshkoppaka
On Saturday, May 25, 2013 11:27:38 AM UTC+5:30, Steven D'Aprano wrote:
> On Fri, 24 May 2013 22:39:06 -0700, lokeshkoppaka wrote:
> 
> 
> 
> > On Saturday, May 25, 2013 10:54:01 AM UTC+5:30, Chris Angelico wrote:
> 
> 
> 
> >> In that case, you're not really ordering them, you're counting them.
> 
> >> Look at the collections module; you can very easily figure out how
> 
> >> many of each there are, and then reconstruct the list afterward.
> 
> > 
> 
> > but i need to do it with out using builtin functions
> 
> 
> 
> 
> 
> How would you, an intelligent human being count them?
> 
> 
> 
> Describe how you would count them in English, or whatever your native 
> 
> language is.
> 
> 
> 
> "First I would start a tally for the number of zeroes, tally = 0. Then I 
> 
> look at each item in turn, and if it is 0, I add one to the tally. When I 
> 
> get to the end, I the number of zeroes is equal to the tally.
> 
> 
> 
> Then I do the same for the number of ones, and the number of twos."
> 
> 
> 
> Now turn that into Python code. 
> 
> 
> 
> tally = 0
> 
> for item in list_of_items:
> 
> if item == 0:
> 
> tally = tally + 1
> 
> 
> 
> print "The number of zeroes equals", tally
> 
> 
> 
> 
> 
> 
> 
> -- 
> 
> Steven

ya steven i had done the similar logic but thats not satisfying my professor 
he had given the following constrains
 1. No in-built functions should be used
 2. we are expecting a O(n) solution
 3. Don't use count method
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-24 Thread Steven D'Aprano
On Fri, 24 May 2013 22:39:06 -0700, lokeshkoppaka wrote:

> On Saturday, May 25, 2013 10:54:01 AM UTC+5:30, Chris Angelico wrote:

>> In that case, you're not really ordering them, you're counting them.
>> Look at the collections module; you can very easily figure out how
>> many of each there are, and then reconstruct the list afterward.
> 
> but i need to do it with out using builtin functions


How would you, an intelligent human being count them?

Describe how you would count them in English, or whatever your native 
language is.

"First I would start a tally for the number of zeroes, tally = 0. Then I 
look at each item in turn, and if it is 0, I add one to the tally. When I 
get to the end, I the number of zeroes is equal to the tally.

Then I do the same for the number of ones, and the number of twos."

Now turn that into Python code. 

tally = 0
for item in list_of_items:
if item == 0:
tally = tally + 1

print "The number of zeroes equals", tally



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-24 Thread rusi
On May 25, 10:15 am, lokeshkopp...@gmail.com wrote:
> On Friday, May 24, 2013 1:34:51 PM UTC+5:30, lokesh...@gmail.com wrote:
> > i need to write a code which can sort the list in order of 'n' without use 
> > builtin functions
>
> > can anyone help me how to do?
>
>  Note:
> the list only contains 0's,1's,2's
> need to sort them in order of 'n'

Its a classic problem
http://en.wikipedia.org/wiki/Dutch_national_flag_problem
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-24 Thread Chris Angelico
On Sat, May 25, 2013 at 3:39 PM,   wrote:
> On Saturday, May 25, 2013 10:54:01 AM UTC+5:30, Chris Angelico wrote:
>> On Sat, May 25, 2013 at 3:15 PM,   wrote:
>>
>> > On Friday, May 24, 2013 1:34:51 PM UTC+5:30, lokesh...@gmail.com wrote:
>>
>> >> i need to write a code which can sort the list in order of 'n' without 
>> >> use builtin functions
>>
>> >>
>>
>> >> can anyone help me how to do?
>>
>> >
>>
>> >  Note:
>>
>> > the list only contains 0's,1's,2's
>>
>> > need to sort them in order of 'n'
>>
>>
>>
>> In that case, you're not really ordering them, you're counting them.
>>
>> Look at the collections module; you can very easily figure out how
>>
>> many of each there are, and then reconstruct the list afterward.
>>
>>
>>
>> ChrisA
>
> but i need to do it with out using builtin functions

Depending on your definitions, that's either trivially easy (the
'collections' module is not builtin functions) or completely
impossible. Have fun.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-24 Thread lokeshkoppaka
On Saturday, May 25, 2013 10:54:01 AM UTC+5:30, Chris Angelico wrote:
> On Sat, May 25, 2013 at 3:15 PM,   wrote:
> 
> > On Friday, May 24, 2013 1:34:51 PM UTC+5:30, lokesh...@gmail.com wrote:
> 
> >> i need to write a code which can sort the list in order of 'n' without use 
> >> builtin functions
> 
> >>
> 
> >> can anyone help me how to do?
> 
> >
> 
> >  Note:
> 
> > the list only contains 0's,1's,2's
> 
> > need to sort them in order of 'n'
> 
> 
> 
> In that case, you're not really ordering them, you're counting them.
> 
> Look at the collections module; you can very easily figure out how
> 
> many of each there are, and then reconstruct the list afterward.
> 
> 
> 
> ChrisA

but i need to do it with out using builtin functions
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-24 Thread Chris Angelico
On Sat, May 25, 2013 at 3:15 PM,   wrote:
> On Friday, May 24, 2013 1:34:51 PM UTC+5:30, lokesh...@gmail.com wrote:
>> i need to write a code which can sort the list in order of 'n' without use 
>> builtin functions
>>
>> can anyone help me how to do?
>
>  Note:
> the list only contains 0's,1's,2's
> need to sort them in order of 'n'

In that case, you're not really ordering them, you're counting them.
Look at the collections module; you can very easily figure out how
many of each there are, and then reconstruct the list afterward.

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-24 Thread lokeshkoppaka
On Friday, May 24, 2013 1:34:51 PM UTC+5:30, lokesh...@gmail.com wrote:
> i need to write a code which can sort the list in order of 'n' without use 
> builtin functions 
> 
> can anyone help me how to do?

 Note:
the list only contains 0's,1's,2's
need to sort them in order of 'n'
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-24 Thread Carlos Nepomuceno
lol wtf?

If 'n' is the quantity of elements to be sorted there's 
no way you can write an algorithm with complexity O(n) for the worst 
case not knowing something special about the data.

For example, Quicksort will give you O(n*(log(n)) on average case (O(n^2) in 
the worst case).

You gotta be much more specific than that if you really need an O(n) code.

There's probably assumptions you didn't mention about the data if O(n) it's 
really what you're looking for.

PS: Looks like a joke as stated..


> Date: Fri, 24 May 2013 01:04:51 -0700
> Subject: help how to sort a list in order of 'n' in python without using 
> inbuilt functions??
> From: lokeshkopp...@gmail.com
> To: python-list@python.org
>
> i need to write a code which can sort the list in order of 'n' without use 
> builtin functions
> can anyone help me how to do?
> --
> http://mail.python.org/mailman/listinfo/python-list   
>   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-24 Thread Dave Angel

On 05/24/2013 04:04 AM, lokeshkopp...@gmail.com wrote:

i need to write a code which can sort the list in order of 'n' without use 
builtin functions
can anyone help me how to do?



You could sort, but you couldn't print out the results, so what's the 
point?  In Python 3.3 at least, print() is a built-in function.


Is the homework assignment more clearly worded than your summary?  And 
if so, how far have you gotten on it?


--
DaveA
--
http://mail.python.org/mailman/listinfo/python-list


Re: help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-24 Thread Chris Angelico
On Fri, May 24, 2013 at 6:04 PM,   wrote:
> i need to write a code which can sort the list in order of 'n' without use 
> builtin functions
> can anyone help me how to do?
> --
> http://mail.python.org/mailman/listinfo/python-list

http://lmgtfy.com/?q=sorting+algorithm
http://www.catb.org/esr/faqs/smart-questions.html

ChrisA
-- 
http://mail.python.org/mailman/listinfo/python-list


help how to sort a list in order of 'n' in python without using inbuilt functions??

2013-05-24 Thread lokeshkoppaka
i need to write a code which can sort the list in order of 'n' without use 
builtin functions 
can anyone help me how to do?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to sort a list of strings on a substring

2009-10-06 Thread n00m
Here you are:

LogList = [\
"inbound tcp office 192.168.0.125 inside 10.1.0.91 88",
"inbound tcp office 192.168.0.220 inside 10.1.0.31 2967",
"inbound udp lab 172.24.0.110 inside 10.1.0.6 161",
"inbound udp office 192.168.0.220 inside 10.1.0.13 53"]


LogList.sort(key=lambda x: x[x.index('1'):])

for item in LogList:
print item

===

inbound udp lab 172.24.0.110 inside 10.1.0.6 161
inbound tcp office 192.168.0.125 inside 10.1.0.91 88
inbound udp office 192.168.0.220 inside 10.1.0.13 53
inbound tcp office 192.168.0.220 inside 10.1.0.31 2967
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to sort a list of strings on a substring

2009-10-05 Thread n00m
In my early teen, school years "Let It Be" by The Beatles sounded for
my
ears (incredibly clearly and obviously!) as "Lia Ri Pip".
In school I studied French, English only many years later.

My inner translation of "Here you are!" is smth like
"Catch it!", "Take it!", "Look at this!" etc
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to sort a list of strings on a substring

2009-10-05 Thread Steven D'Aprano
On Mon, 05 Oct 2009 21:16:38 -0700, n00m wrote:

> English language is not my mother toung, so I can't grasp many subtle
> nuances of it. Maybe "here you are" means to me quite a different thing
> than to you.

It means "here is the thing you were looking for". Anyway, nothing I 
wrote was meant as an attack on you.


-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to sort a list of strings on a substring

2009-10-05 Thread alex23
Steven D'Aprano  wrote:
> Oh please. That's a ridiculous excuse. Your post started with "Here you
> are" -- the implication is that you thought it *was* a solution, not a
> hint. A hint would be something like "Write a key function, perhaps using
> lambda, and pass it to the sort() method using the key parameter."

In n00m's defense, the OP's question was "I'm just not getting how to
use an element of a string as a "key" within a list of strings", which
n00m's post did answer, and which did work with the data set given. If
Scott had asked "could someone show me how to do this", then yes, the
"here you are" would have been wrong.

Ah, semantics and the lack of expression in text :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to sort a list of strings on a substring

2009-10-05 Thread Scott
On Oct 5, 6:05 pm, MRAB  wrote:
> Scott wrote:
> > I create a list of logs called LogList. Here is a sample:
>
> > LogList =
> > ["inbound tcp office 192.168.0.125 inside 10.1.0.91 88",
> > "inbound tcp office 192.168.0.220 inside 10.1.0.31 2967",
> > "inbound udp lab 172.24.0.110 inside 10.1.0.6 161",
> > "inbound udp office 192.168.0.220 inside 10.1.0.13 53"]
>
> > I want to sort the list on index 3 of each string - the first IP
> > Address.
>
> > I only need strings with similar, first IP's to be together. I don't
> > need all of the IP's to be in order. For example:
> > either:
> > SortedList =
> > ["inbound udp lab 172.24.0.110 inside 10.1.0.6 161",
> > "inbound tcp office 192.168.0.220 inside 10.1.0.31 2967",
> > "inbound udp office 192.168.0.220 inside 10.1.0.13 53",
> > "inbound tcp office 192.168.0.125 inside 10.1.0.91 88"]
> > -or-
> > SortedList =
> > ["inbound tcp office 192.168.0.220 inside 10.1.0.31 2967",
> > "inbound udp office 192.168.0.220 inside 10.1.0.13 53",
> > "inbound udp lab 172.24.0.110 inside 10.1.0.6 161",
> > "inbound tcp office 192.168.0.125 inside 10.1.0.91 88"]
> > -or-
> > etc.
>
> > would be fine.
>
> > I'm reading a lot on sort, sorted, cmp, etc. but I'm just not getting
> > how to use an element of a string as a "key" within a list of strings.
> > I'm using Python 2.6.2.
>
> Forget about cmp, just use the 'key' argument of the list's 'sort'
> method or the 'sorted' function (the latter is better if you want to
> keep the original list). The 'key' argument expects a function (anything
> callable, actually) that accepts a single argument (the item) and
> returns a value to be used as the key, and the items will be sorted
> according to that key. In this case you want the items sorted by the
> fourth 'word', so split the item into words and return the one at index
> 3:
>
> def key_word(item):
>      return item.split()[3]
>
> SortedList = sorted(LogList, key=key_word)
>
> If the function is short and simple enough, lambda is often used instead
> of a named function:
>
> SortedList = sorted(LogList, key=lambda item: item.split()[3])

Ok, the lambda worked as advertised. THANK YOU!!

Thanks for giving both a def and lambda example. I'll be saving them.
-Scott
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to sort a list of strings on a substring

2009-10-05 Thread n00m
English language is not my mother toung,
so I can't grasp many subtle nuances of it.
Maybe "here you are" means to me quite a
different thing than to you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to sort a list of strings on a substring

2009-10-05 Thread Steven D'Aprano
On Mon, 05 Oct 2009 20:33:51 -0700, n00m wrote:

>> No, that's incorrect. Try it with this data and you will see it fails:
> 
> Of course, you are right, but I think the topic-starter is smart enough
> to understand that I suggested only a hint, a sketch, a sample of how to
> use "key=" with "lambda", not a ready-to-apply solution.

Oh please. That's a ridiculous excuse. Your post started with "Here you 
are" -- the implication is that you thought it *was* a solution, not a 
hint. A hint would be something like "Write a key function, perhaps using 
lambda, and pass it to the sort() method using the key parameter."

There's no shame at writing buggy code. There's not a person here who has 
never made a silly mistake, and most of us have done so in public too. 
Some real clangers too. What matters is how folks respond to having the 
their mistakes pointed out, and whether they learn from it.




-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to sort a list of strings on a substring

2009-10-05 Thread n00m
> No, that's incorrect. Try it with this data and you will see it fails:

Of course, you are right, but I think the topic-starter is smart
enough
to understand that I suggested only a hint, a sketch, a sample of how
to use "key=" with "lambda", not a ready-to-apply solution.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to sort a list of strings on a substring

2009-10-05 Thread Steven D'Aprano
On Mon, 05 Oct 2009 15:45:58 -0700, n00m wrote:

> Here you are:
> 
> LogList = [\
> "inbound tcp office 192.168.0.125 inside 10.1.0.91 88", "inbound tcp
> office 192.168.0.220 inside 10.1.0.31 2967", "inbound udp lab
> 172.24.0.110 inside 10.1.0.6 161", "inbound udp office 192.168.0.220
> inside 10.1.0.13 53"]
> 
> 
> LogList.sort(key=lambda x: x[x.index('1'):])


No, that's incorrect. Try it with this data and you will see it fails:


LogList = [
"inbound tcp office1 192.168.0.125 inside 10.1.0.91 88",
"inbound tcp office2 192.168.0.220 inside 10.1.0.31 2967",
"inbound udp lab1 172.24.0.110 inside 10.1.0.6 161",
"inbound udp office2 192.168.0.220 inside 10.1.0.13 53",
"inbound udp lab2 172.24.0.121 inside 10.1.0.6 161",
"inbound udp webby 220.96.0.2 inside 20.2.0.9 54",
]


Worse, if you delete the last item ("webby"), the code silently does the 
wrong thing. Code that crashes is bad, but code that silently does the 
wrong thing is a nightmare. Your test succeeded by accident -- it was a 
fluke of the data that you failed to see both failure modes.

The question asked was how to sort the list according to item 3 of the 
strings, *not* how to sort the list according to the first character '1'. 
The way to solve this correctly is by extracting item 3 and sorting on 
that, not by searching for the first character '1'. That is a hack[1] 
that just happened to work for the specific test data you tried it on.




[1] Hack in the bad sense, not in the good sense.



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to sort a list of strings on a substring

2009-10-05 Thread MRAB

Scott wrote:

I create a list of logs called LogList. Here is a sample:

LogList =
["inbound tcp office 192.168.0.125 inside 10.1.0.91 88",
"inbound tcp office 192.168.0.220 inside 10.1.0.31 2967",
"inbound udp lab 172.24.0.110 inside 10.1.0.6 161",
"inbound udp office 192.168.0.220 inside 10.1.0.13 53"]

I want to sort the list on index 3 of each string - the first IP
Address.

I only need strings with similar, first IP's to be together. I don't
need all of the IP's to be in order. For example:
either:
SortedList =
["inbound udp lab 172.24.0.110 inside 10.1.0.6 161",
"inbound tcp office 192.168.0.220 inside 10.1.0.31 2967",
"inbound udp office 192.168.0.220 inside 10.1.0.13 53",
"inbound tcp office 192.168.0.125 inside 10.1.0.91 88"]
-or-
SortedList =
["inbound tcp office 192.168.0.220 inside 10.1.0.31 2967",
"inbound udp office 192.168.0.220 inside 10.1.0.13 53",
"inbound udp lab 172.24.0.110 inside 10.1.0.6 161",
"inbound tcp office 192.168.0.125 inside 10.1.0.91 88"]
-or-
etc.

would be fine.

I'm reading a lot on sort, sorted, cmp, etc. but I'm just not getting
how to use an element of a string as a "key" within a list of strings.
I'm using Python 2.6.2.


Forget about cmp, just use the 'key' argument of the list's 'sort'
method or the 'sorted' function (the latter is better if you want to
keep the original list). The 'key' argument expects a function (anything
callable, actually) that accepts a single argument (the item) and
returns a value to be used as the key, and the items will be sorted
according to that key. In this case you want the items sorted by the
fourth 'word', so split the item into words and return the one at index
3:

def key_word(item):
return item.split()[3]

SortedList = sorted(LogList, key=key_word)

If the function is short and simple enough, lambda is often used instead
of a named function:

SortedList = sorted(LogList, key=lambda item: item.split()[3])

--
http://mail.python.org/mailman/listinfo/python-list


How to sort a list of strings on a substring

2009-10-05 Thread Scott
I create a list of logs called LogList. Here is a sample:

LogList =
["inbound tcp office 192.168.0.125 inside 10.1.0.91 88",
"inbound tcp office 192.168.0.220 inside 10.1.0.31 2967",
"inbound udp lab 172.24.0.110 inside 10.1.0.6 161",
"inbound udp office 192.168.0.220 inside 10.1.0.13 53"]

I want to sort the list on index 3 of each string - the first IP
Address.

I only need strings with similar, first IP's to be together. I don't
need all of the IP's to be in order. For example:
either:
SortedList =
["inbound udp lab 172.24.0.110 inside 10.1.0.6 161",
"inbound tcp office 192.168.0.220 inside 10.1.0.31 2967",
"inbound udp office 192.168.0.220 inside 10.1.0.13 53",
"inbound tcp office 192.168.0.125 inside 10.1.0.91 88"]
-or-
SortedList =
["inbound tcp office 192.168.0.220 inside 10.1.0.31 2967",
"inbound udp office 192.168.0.220 inside 10.1.0.13 53",
"inbound udp lab 172.24.0.110 inside 10.1.0.6 161",
"inbound tcp office 192.168.0.125 inside 10.1.0.91 88"]
-or-
etc.

would be fine.

I'm reading a lot on sort, sorted, cmp, etc. but I'm just not getting
how to use an element of a string as a "key" within a list of strings.
I'm using Python 2.6.2.

Thanks

-- 
http://mail.python.org/mailman/listinfo/python-list


RE: How to sort a list of file paths

2008-12-02 Thread Eriksson, John
Hi again,

I've updated the example using the ideas and python tricks used on pages found 
via the link you gave me, Chris.

So... for future references here's the best (?) way of sorting a list of file 
names in the correct way (correct for some applications at least).

Note: For some odd reason I seemed to get the best performance using a lambda 
defined function instead of an ordinary function.

# --- EXAMPLE ---

import re
RE_DIGIT = re.compile(r'(\d+)')
ALPHANUM_KEY = lambda s: [int(g) if g.isdigit() else g for g in 
RE_DIGIT.split(s)]

file_list = ["File2.txt","File1.txt","File10.txt"]
file_list.sort(key=ALPHANUM_KEY)

# ---

Best Regards
/John


-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Chris Rebert
Sent: den 2 december 2008 10:26
To: Eriksson, John
Cc: python-list@python.org
Subject: Re: How to sort a list of file paths

On Tue, Dec 2, 2008 at 12:36 AM, Eriksson, John
<[EMAIL PROTECTED]> wrote:
> Hi,
>
>
>
> This weekend I had some problems to get a list containing file paths to be
> sorted in a way that I could use.
>
>
>
> I also found a thread in this mailing list (
> http://mail.python.org/pipermail/python-list/2007-April/433590.html ) and
> realized that others might be interested in a solution.
>
>
>
> So... here is my five cents regarding file path sorting:
>
>
>
> Problem description:
>
>
>
> You have a list containing some file names:
>
>
>
>>>> file_list = ["File2.txt","File1.txt","File10.txt"]
>
>
>
> If you sort this list in the conventional way you end up with a result like:
>
>
>
>>>> file_list.sort()
>
>>>> print file_list
>
> ['File1.txt','File10.txt','File2.txt']
>
>
>
> Solution:
>
>
>
> Sort the list by splitting alphas and digits in to groups and compare them
> separately.
>
>
>
> import re
>
> def true_alphanum_cmp(a,b):
>
> aa = re.findall(r'\d |\D ', a)
>
> bb = re.findall(r'\d |\D ', b)
>
> for i in range(min(len(aa),len(bb))):
>
> if aa[i].isdigit() and bb[i].isdigit():
>
> c = cmp(int(aa[i]),int(bb[i]))
>
> else:
>
> c = cmp(aa[i],bb[i])
>
> if c!=0:
>
> return c
>
> return cmp(len(aa),len(bb))
>
>
>
> file_list = ["File2.txt","File1.txt","File10.txt"]
>
> file_list.sort(true_alphanum_cmp)
>
>
>
> If the formatting in this mail is messed up you can find the example at
> http://arainyday.se/notebook/true_alphanum_cmp.php
>
>
>
> All comments and improvements are welcome!

Sounds like the issue discussed in the post on Coding Horror:
http://www.codinghorror.com/blog/archives/001018.html
It even links to another Python version of the algorithm.

Cheers,
Chris
--
Follow the path of the Iguana...
http://rebertia.com

>
>
>
> Best regards
>
> John Eriksson
>
> _
>
>
>
> Logica - Releasing your potential
>
> Tegsplan 2b
>
> 904 20 UMEÅ
>
> Sweden
>
>
>
> T: +46 (0) 90 15 91 38
>
> M: +46 (0) 70 366 16 77
>
> E: [EMAIL PROTECTED]
>
> www.logica.se
>
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to sort a list of file paths

2008-12-02 Thread Chris Rebert
On Tue, Dec 2, 2008 at 12:36 AM, Eriksson, John
<[EMAIL PROTECTED]> wrote:
> Hi,
>
>
>
> This weekend I had some problems to get a list containing file paths to be
> sorted in a way that I could use.
>
>
>
> I also found a thread in this mailing list (
> http://mail.python.org/pipermail/python-list/2007-April/433590.html ) and
> realized that others might be interested in a solution.
>
>
>
> So... here is my five cents regarding file path sorting:
>
>
>
> Problem description:
>
>
>
> You have a list containing some file names:
>
>
>
 file_list = ["File2.txt","File1.txt","File10.txt"]
>
>
>
> If you sort this list in the conventional way you end up with a result like:
>
>
>
 file_list.sort()
>
 print file_list
>
> ['File1.txt','File10.txt','File2.txt']
>
>
>
> Solution:
>
>
>
> Sort the list by splitting alphas and digits in to groups and compare them
> separately.
>
>
>
> import re
>
> def true_alphanum_cmp(a,b):
>
> aa = re.findall(r'\d |\D ', a)
>
> bb = re.findall(r'\d |\D ', b)
>
> for i in range(min(len(aa),len(bb))):
>
> if aa[i].isdigit() and bb[i].isdigit():
>
> c = cmp(int(aa[i]),int(bb[i]))
>
> else:
>
> c = cmp(aa[i],bb[i])
>
> if c!=0:
>
> return c
>
> return cmp(len(aa),len(bb))
>
>
>
> file_list = ["File2.txt","File1.txt","File10.txt"]
>
> file_list.sort(true_alphanum_cmp)
>
>
>
> If the formatting in this mail is messed up you can find the example at
> http://arainyday.se/notebook/true_alphanum_cmp.php
>
>
>
> All comments and improvements are welcome!

Sounds like the issue discussed in the post on Coding Horror:
http://www.codinghorror.com/blog/archives/001018.html
It even links to another Python version of the algorithm.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

>
>
>
> Best regards
>
> John Eriksson
>
> _
>
>
>
> Logica - Releasing your potential
>
> Tegsplan 2b
>
> 904 20 UMEÅ
>
> Sweden
>
>
>
> T: +46 (0) 90 15 91 38
>
> M: +46 (0) 70 366 16 77
>
> E: [EMAIL PROTECTED]
>
> www.logica.se
>
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to sort a list of file paths

2008-12-02 Thread James Mills
Hi Eriksson,

It's nice to see people actually contribute what they've learned back
to the community.
Great problem, well thought out solution and congrats on the learning :)

I can't say per say that I've actually run into a situation where I
need to sort file paths
in this way ... But if I do I'll be sure to use your function :)

--JamesMills

On Tue, Dec 2, 2008 at 6:36 PM, Eriksson, John <[EMAIL PROTECTED]> wrote:
> Hi,
>
>
>
> This weekend I had some problems to get a list containing file paths to be
> sorted in a way that I could use.
>
>
>
> I also found a thread in this mailing list (
> http://mail.python.org/pipermail/python-list/2007-April/433590.html ) and
> realized that others might be interested in a solution.
>
>
>
> So... here is my five cents regarding file path sorting:
>
>
>
> Problem description:
>
>
>
> You have a list containing some file names:
>
>
>
 file_list = ["File2.txt","File1.txt","File10.txt"]
>
>
>
> If you sort this list in the conventional way you end up with a result like:
>
>
>
 file_list.sort()
>
 print file_list
>
> ['File1.txt','File10.txt','File2.txt']
>
>
>
> Solution:
>
>
>
> Sort the list by splitting alphas and digits in to groups and compare them
> separately.
>
>
>
> import re
>
> def true_alphanum_cmp(a,b):
>
> aa = re.findall(r'\d |\D ', a)
>
> bb = re.findall(r'\d |\D ', b)
>
> for i in range(min(len(aa),len(bb))):
>
> if aa[i].isdigit() and bb[i].isdigit():
>
> c = cmp(int(aa[i]),int(bb[i]))
>
> else:
>
> c = cmp(aa[i],bb[i])
>
> if c!=0:
>
> return c
>
> return cmp(len(aa),len(bb))
>
>
>
> file_list = ["File2.txt","File1.txt","File10.txt"]
>
> file_list.sort(true_alphanum_cmp)
>
>
>
> If the formatting in this mail is messed up you can find the example at
> http://arainyday.se/notebook/true_alphanum_cmp.php
>
>
>
> All comments and improvements are welcome!
>
>
>
> Best regards
>
> John Eriksson
>
> _
>
>
>
> Logica - Releasing your potential
>
> Tegsplan 2b
>
> 904 20 UMEÅ
>
> Sweden
>
>
>
> T: +46 (0) 90 15 91 38
>
> M: +46 (0) 70 366 16 77
>
> E: [EMAIL PROTECTED]
>
> www.logica.se
>
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>



-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


How to sort a list of file paths

2008-12-02 Thread Eriksson, John
Hi,

This weekend I had some problems to get a list containing file paths to be 
sorted in a way that I could use.

I also found a thread in this mailing list ( 
http://mail.python.org/pipermail/python-list/2007-April/433590.html ) and 
realized that others might be interested in a solution.

So... here is my five cents regarding file path sorting:

Problem description:

You have a list containing some file names:

>>> file_list = ["File2.txt","File1.txt","File10.txt"]

If you sort this list in the conventional way you end up with a result like:

>>> file_list.sort()
>>> print file_list
['File1.txt','File10.txt','File2.txt']

Solution:

Sort the list by splitting alphas and digits in to groups and compare them 
separately.

import re
def true_alphanum_cmp(a,b):
aa = re.findall(r'\d |\D ', a)
bb = re.findall(r'\d |\D ', b)
for i in range(min(len(aa),len(bb))):
if aa[i].isdigit() and bb[i].isdigit():
c = cmp(int(aa[i]),int(bb[i]))
else:
c = cmp(aa[i],bb[i])
if c!=0:
return c
return cmp(len(aa),len(bb))

file_list = ["File2.txt","File1.txt","File10.txt"]
file_list.sort(true_alphanum_cmp)

If the formatting in this mail is messed up you can find the example at 
http://arainyday.se/notebook/true_alphanum_cmp.php

All comments and improvements are welcome!

Best regards
John Eriksson
_

Logica - Releasing your potential
Tegsplan 2b
904 20 UMEÅ
Sweden

T: +46 (0) 90 15 91 38
M: +46 (0) 70 366 16 77
E: [EMAIL PROTECTED]
www.logica.se


--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there an easy way to sort a list by two criteria?

2008-02-11 Thread thebjorn
On Feb 11, 10:47 am, [EMAIL PROTECTED] wrote:
[...]
> A little known thing from Python 2.5:
[...]
> >>> sorted(lst, key=itemgetter(2, 1))

Cute, thanks :-)

--bjorn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there an easy way to sort a list by two criteria?

2008-02-11 Thread bearophileHUGS
[repost]

Duncan Booth:
> >>> from operator import itemgetter
> >>> lst = [(1,2,4),(3,2,1),(2,2,2),(2,1,4),(2,4,1)]
> >>> lst.sort(key=itemgetter(1))
> >>> lst.sort(key=itemgetter(2))
> >>> lst
> [(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)]

A little known thing from Python 2.5:

>>> from operator import itemgetter
>>> lst = [(1,2,4),(3,2,1),(2,2,2),(2,1,4),(2,4,1)]
>>> sorted(lst, key=itemgetter(2, 1))
[(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)]

Bye,
bearophile
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there an easy way to sort a list by two criteria?

2008-02-10 Thread neocortex
Hello!
Thank you all, so much! Now I can do double-criteria sort in at least
three ways. More than I have expected.

Best,
PM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there an easy way to sort a list by two criteria?

2008-02-09 Thread Duncan Booth
thebjorn <[EMAIL PROTECTED]> wrote:

> I'm not sure which Python is default for Ubuntu 6.06, but assuming you
> can access a recent one (2.4), the list.sort() function takes a key
> argument (that seems to be rather sparsely documented in the tutorial
> and the docstring...). E.g.:
> 
 lst = [(1,2,4),(3,2,1),(2,2,2),(2,1,4),(2,4,1)]
 lst.sort(key=lambda (a,b,c):(c,b))
 lst
> [(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)]


It may be simpler just to use the key argument multiple times (not 
forgetting to specify the keys in reverse order, i.e. the most significant 
comes last). So with this example, sorting by column 2 then column 1 and 
ignoring column 0 can be done by:

>>> from operator import itemgetter
>>> lst = [(1,2,4),(3,2,1),(2,2,2),(2,1,4),(2,4,1)]
>>> lst.sort(key=itemgetter(1))
>>> lst.sort(key=itemgetter(2))
>>> lst
[(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)]


or even:

>>> from operator import itemgetter
>>> lst = [(1,2,4),(3,2,1),(2,2,2),(2,1,4),(2,4,1)]
>>> for keycolumn in reversed([2,1]):
lst.sort(key=itemgetter(keycolumn))


>>> lst
[(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)]

The important point here is to remember that the sort is stable (so you can 
do multiple sorts without disrupting earlier results).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there an easy way to sort a list by two criteria?

2008-02-09 Thread thebjorn
On Feb 10, 3:05 am, neocortex <[EMAIL PROTECTED]> wrote:
> Hello!
> I am a newbie in Python. Recently, I get stuck with the problem of
> sorting by two criteria. In brief, I have a two-dimensional list (for
> a table or a matrix). Now, I need to sort by two columns, but I cannot
> figure out how to do that. I read somewhere that it is possible to do:>>> 
> table.sort().sort()
>
> but it does not work.
> Can anyone help me with this?
> PS: I am using Python under Ubuntu 6.06.
>
> Best,
> PM

I'm not sure which Python is default for Ubuntu 6.06, but assuming you
can access a recent one (2.4), the list.sort() function takes a key
argument (that seems to be rather sparsely documented in the tutorial
and the docstring...). E.g.:

>>> lst = [(1,2,4),(3,2,1),(2,2,2),(2,1,4),(2,4,1)]
>>> lst.sort(key=lambda (a,b,c):(c,b))
>>> lst
[(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)]
>>>

The "fancy" lambda simply takes a source-tuple and returns a tuple of
the keys to be sorted on, in this case sort on the last element, then
on the middle element.

You can use the cmp argument to get similar results (with the same
list as above):

>>> lst.sort(cmp=lambda (a1,a2,a3),(b1,b2,b3):cmp((a3,a2),(b3,b2)))
>>> lst
[(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)]

The lambda in this case is starting to get complicated though, so
probably better to write a separate function. Using the cmp argument
is slower than using the key argument since key is only called once
for each element in the list while cmp is called for each comparison
of elements (it's not the number of times the function is called
that's the big deal, but rather that the highly optimized sort needs
to continually call back to Python in the cmp case).

The old-school way of doing this is using a Schwartzian transform
(a.k.a. decorate-sort-undecorate) which creates an auxilliary list
with the keys in correct sorting order so that sort() can work
directly:

>>> lst
[(1, 2, 4), (3, 2, 1), (2, 2, 2), (2, 1, 4), (2, 4, 1)]
>>> decorate = [(x[2],x[1],x) for x in lst]
>>> decorate.sort()
>>> decorate
[(1, 2, (3, 2, 1)), (1, 4, (2, 4, 1)), (2, 2, (2, 2, 2)), (4, 1, (2,
1, 4)), (4, 2, (1, 2, 4))]
>>> lst = [x[2] for x in decorate]  # undecorate
>>> lst
[(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)]
>>>

hth,
-- bjorn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there an easy way to sort a list by two criteria?

2008-02-09 Thread Steven D'Aprano
On Sat, 09 Feb 2008 18:05:14 -0800, neocortex wrote:

> Hello!
> I am a newbie in Python. Recently, I get stuck with the problem of
> sorting by two criteria. In brief, I have a two-dimensional list (for a
> table or a matrix). Now, I need to sort by two columns, but I cannot
> figure out how to do that.


Can you give a (small, simple) example of your data, and what you expect 
if you sort it successfully?


> I read somewhere that it is possible to do:
> >>> table.sort().sort()
> but it does not work.

No it doesn't, because the sort() method returns None, and None doesn't 
have a sort() method of its own.

table.sort() will sort table in place, so you need something like this:

>>> table.sort()
>>> table.sort()

except naturally that just does the exact same sort twice in a row, which 
is silly. So what you actually need is something like this:

>>> table.sort(magic goes here)
>>> table.sort(different magic goes here)

where the first piece of magic tells Python to sort by the first column, 
and the second by the second column. But to do that, we need to know more 
about how you're setting up the table.

I'm *guessing* that you probably have something like this:


table = [ ['fred', 35, 8],  # name, age, score
['bill', 29, 8], 
['betty', 30, 9],
['morris', 17, 4], 
['catherine', 23, 6], 
['anna', 45, 8], 
['george', 19, 5],
['tanya', 27, 7],
]


Now let's sort it:


>>> from operator import itemgetter
>>> import pprint
>>> table.sort(key=itemgetter(0))  # sort by name
>>> table.sort(key=itemgetter(2))  # sort by score
>>> pprint.pprint(table)
[['morris', 17, 4],
 ['george', 19, 5],
 ['catherine', 23, 6],
 ['tanya', 27, 7],
 ['anna', 45, 8],
 ['bill', 29, 8],
 ['fred', 35, 8],
 ['betty', 30, 9]]



Does this help?



-- 
Steven
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there an easy way to sort a list by two criteria?

2008-02-09 Thread Steve Holden
neocortex wrote:
> Hello!
> I am a newbie in Python. Recently, I get stuck with the problem of
> sorting by two criteria. In brief, I have a two-dimensional list (for
> a table or a matrix). Now, I need to sort by two columns, but I cannot
> figure out how to do that. I read somewhere that it is possible to do:
 table.sort().sort()
> but it does not work.
> Can anyone help me with this?
> PS: I am using Python under Ubuntu 6.06.
> 
I think your best bet would be to google for "decorate sort undecorate" 
  or "Schwartzian transform" unless the columns happen to be in the 
right order in the rows you want to sort.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there an easy way to sort a list by two criteria?

2008-02-09 Thread Jeff Schwab
neocortex wrote:
> Hello!
> I am a newbie in Python. Recently, I get stuck with the problem of
> sorting by two criteria. In brief, I have a two-dimensional list (for
> a table or a matrix). Now, I need to sort by two columns, but I cannot
> figure out how to do that. I read somewhere that it is possible to do:
 table.sort().sort()
> but it does not work.
> Can anyone help me with this?
> PS: I am using Python under Ubuntu 6.06.

You can specify an arbitrary comparison function with the cmp key to 
sort.  IOW, use table.sort(cmp=f), where f is defined to compare table 
entries (rows?) by whichever criteria are required.
-- 
http://mail.python.org/mailman/listinfo/python-list


Is there an easy way to sort a list by two criteria?

2008-02-09 Thread neocortex
Hello!
I am a newbie in Python. Recently, I get stuck with the problem of
sorting by two criteria. In brief, I have a two-dimensional list (for
a table or a matrix). Now, I need to sort by two columns, but I cannot
figure out how to do that. I read somewhere that it is possible to do:
>>> table.sort().sort()
but it does not work.
Can anyone help me with this?
PS: I am using Python under Ubuntu 6.06.

Best,
PM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: about sort a list with integer key

2008-01-13 Thread lotrpy
On 1月13日, 下午8时32分, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
> Use lambda when it works better for you, the speed difference is
> marginal in practice anyway.  itemgetter is not (and was never
> intended to be) a general substitute for functions, as you've
> discovered.
>
> The marginal speed difference between itemgetter and an explicit
> lambda that does the subscripts is a consequence of itemgetter being
> written in C, meaning it avoids the creation of a Python stack frame,
> etc.  Combining int(...) with this operation requires coding the key
> function in Python, which removes itemgetter's advantage.  In other
> words, you cannot retain itemgetter's speed advantage with more
> complex keys.  If the sorting performance is a problem for you, please
> give more details about what you're doing -- there might be better
> ways to speed up the code.

Fredrik and Hrvoje, thanks for the reply, here the sorting performance
is not a big problem for me. the text file is just several hundred
line, each line include several item separated by space. I'll run the
script each week or month, just 1 second to get the result,so maybe
stick to lambda here is just fine.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: about sort a list with integer key

2008-01-13 Thread Hrvoje Niksic
lotrpy <[EMAIL PROTECTED]> writes:

> if i want sort each line by the first part,(it's a integer, in fact).
> don't know how to do it with itemgetter.
> key = int(itemgetter(0)) is wrong,  key = lambda x:int(x[0]) works.
> but s.b. told me itemgetter execute more quickly .

Use lambda when it works better for you, the speed difference is
marginal in practice anyway.  itemgetter is not (and was never
intended to be) a general substitute for functions, as you've
discovered.

The marginal speed difference between itemgetter and an explicit
lambda that does the subscripts is a consequence of itemgetter being
written in C, meaning it avoids the creation of a Python stack frame,
etc.  Combining int(...) with this operation requires coding the key
function in Python, which removes itemgetter's advantage.  In other
words, you cannot retain itemgetter's speed advantage with more
complex keys.  If the sorting performance is a problem for you, please
give more details about what you're doing -- there might be better
ways to speed up the code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: about sort a list with integer key

2008-01-13 Thread Fredrik Lundh
lotrpy wrote:

> key = int(itemgetter(0)) is wrong,  key = lambda x:int(x[0]) works.
> but s.b. told me itemgetter execute more quickly .

so you're more interested in speed than in correctness? ;-)

operator.itemgetter is a function factory that creates a *function* that 
fetches the given item from a sequence.  or in other words, typing

 func = itemgetter(0)

is pretty much the same thing as typing

 def func(seq):
 return seq[0]

given this, it should be fairly obvious what int(itemgetter(0)) does: it 
attemts to convert the *function* to an integer, which obviously doesn't 
work.

I'd stick to the lambda form if I were you.  It isn't only easier to 
understand for the Python layman, it also does the right thing.



-- 
http://mail.python.org/mailman/listinfo/python-list


about sort a list with integer key

2008-01-13 Thread lotrpy
hi, if I want sort each line ,by the last part,of a file, below is the
source.
from operator import itemgetter
content = (line.split() for line in file('foo.txt', 'rb'))
for cursor, line in enumerate(sorted(content, key = itemgetter(-1),
reverse = True)):
print cursor, ' '.join(line)
the content of foo.txt is
   21 job
   3 joke
the result is
0 3 joke
1 21 job

if i want sort each line by the first part,(it's a integer, in fact).
don't know how to do it with itemgetter.
key = int(itemgetter(0)) is wrong,  key = lambda x:int(x[0]) works.
but s.b. told me itemgetter execute more quickly .
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sort a list

2007-10-27 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> hello,
> 
> I'm new to python and this list.I hope this question don't repeat an old 
> story on the list.
> 
> I have a number list,say it's [3,2,1,4,5],I want to sort it as 
> [1,2,3,4,5],how to do?

your_list.sort()

Please read the documentation, all of this is properly documented.

And even google would have brought that up really fast:

google:python list sort

1) http://xahlee.org/perl-python/sort_list.html (Oh my, it's Xah)

2) http://docs.python.org/lib/typesseq-mutable.html (official python docs)


So the first two links give you all the information you needed.

Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


sort a list

2007-10-27 Thread _nospamnet_
hello,

I'm new to python and this list.I hope this question don't repeat an old story 
on the list.

I have a number list,say it's [3,2,1,4,5],I want to sort it as [1,2,3,4,5],how 
to do?

Thanks.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute

2007-09-10 Thread Stefan Arentz
[EMAIL PROTECTED] (Alex Martelli) writes:

> Stefan Arentz <[EMAIL PROTECTED]> wrote:
> 
> > Miki <[EMAIL PROTECTED]> writes:
> > 
> > > >   steps.sort(key = lambda s: s.time)
> > > This is why attrgetter in the operator module was invented.
> > > from operator import attrgetter
> > > ...
> > > steps.sort(key=attrgettr("time"))
> > 
> > Personally I prefer the anonymous function over attrgettr :)
> 
> However, Python disagrees with you...:
> 
> brain:~ alex$ python -mtimeit -s'from operator import attrgetter;
> L=map(complex,xrange(999))' 'sorted(L, key=lambda x:x.real)'
> 1000 loops, best of 3: 567 usec per loop
> 
> brain:~ alex$ python -mtimeit -s'from operator import attrgetter;
> L=map(complex,xrange(999))' 'sorted(L, key=attrgetter("real"))'
> 1000 loops, best of 3: 367 usec per loop
> 
> A speed-up of 35% is a pretty clear indicator of what _Python_ "prefers"
> in this situation:-).

I could not care less :-)

 S.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute

2007-09-09 Thread Alex Martelli
Stefan Arentz <[EMAIL PROTECTED]> wrote:

> Miki <[EMAIL PROTECTED]> writes:
> 
> > >   steps.sort(key = lambda s: s.time)
> > This is why attrgetter in the operator module was invented.
> > from operator import attrgetter
> > ...
> > steps.sort(key=attrgettr("time"))
> 
> Personally I prefer the anonymous function over attrgettr :)

However, Python disagrees with you...:

brain:~ alex$ python -mtimeit -s'from operator import attrgetter;
L=map(complex,xrange(999))' 'sorted(L, key=lambda x:x.real)'
1000 loops, best of 3: 567 usec per loop

brain:~ alex$ python -mtimeit -s'from operator import attrgetter;
L=map(complex,xrange(999))' 'sorted(L, key=attrgetter("real"))'
1000 loops, best of 3: 367 usec per loop

A speed-up of 35% is a pretty clear indicator of what _Python_ "prefers"
in this situation:-).


Alex
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute

2007-09-09 Thread Stefan Arentz
Miki <[EMAIL PROTECTED]> writes:

> >   steps.sort(key = lambda s: s.time)
> This is why attrgetter in the operator module was invented.
> from operator import attrgetter
> ...
> steps.sort(key=attrgettr("time"))

Personally I prefer the anonymous function over attrgettr :)

 S.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute

2007-09-08 Thread Miki
>   steps.sort(key = lambda s: s.time)
This is why attrgetter in the operator module was invented.
from operator import attrgetter
...
steps.sort(key=attrgettr("time"))

HTH,
--
Miki <[EMAIL PROTECTED]>
http://pythonwise.blogspot.com

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute

2007-09-07 Thread Marc 'BlackJack' Rintsch
On Fri, 07 Sep 2007 06:57:35 -0700, cjt22 wrote:

> I have a step class and store in a list step instances
> A step instance contains variables: name, startTime etc and startTime
> is stored as a string %H:%M:%S
> 
> What I would like to do is to be able to sort this list of objects
> based on the startTime object so that the first item in the list is
> the object with the earliest Start time and last item is the object
> with the last Start time.
> 
> I belive my key has to be = strpTime(step.sTime, "%H:%M:%S")
> But don't know how to create the comparison funciton.
> 
> Any help on how I can perform this whole operation would be much
> appreciated.

This should be enough::

  steps.sort(key=lambda s: s.startTime)

If you sort strings of the form 'hh:mm:ss' the represented times are
sorted chronological.  No need to convert them to a number first.

If the "natural" sort criterion for `Step` objects is the start time you
might override `__cmp__()` of `Step`\s instead::

def __cmp__(self, other):
return cmp(self.startTime, other.startTime)

Now you can just sort the list with ``steps.sort()``.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute

2007-09-07 Thread Stefan Arentz
[EMAIL PROTECTED] writes:

> Hi there
> 
> I am fairly new to Python and have not really used regular expressions
> before (I think this might be needed for my query) and wondered if you
> could help
> 
> I have a step class and store in a list step instances
> A step instance contains variables: name, startTime etc and startTime
> is stored as a string %H:%M:%S
> 
> What I would like to do is to be able to sort this list of objects
> based on the startTime object so that the first item in the list is
> the object with the earliest Start time and last item is the object
> with the last Start time.
> 
> I belive my key has to be = strpTime(step.sTime, "%H:%M:%S")
> But don't know how to create the comparison funciton.
> 
> Any help on how I can perform this whole operation would be much
> appreciated.

Code:

  class Step(object):
  def __init__(self, time):
  self.time = time
  def __repr__(self):
  return "" % self.time

  steps = [Step("03:23:23"), Step("12:59:12"), Step("02:32:17")]
  print steps

  steps.sort(key = lambda s: s.time)
  print steps

Output:

  [, , ]
  [, , ]

If the default sort order of a Step is always it's time then you can
also define a __cmp__ method like this:

  class Step(object):
 def __cmp__(self, other):
return cmp(self.time, other.time)

And simply do a steps.sort()

 S.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute

2007-09-07 Thread Tim Golden
[EMAIL PROTECTED] wrote:
> Hi there
> 
> I am fairly new to Python and have not really used regular expressions
> before (I think this might be needed for my query) and wondered if you
> could help
> 
> I have a step class and store in a list step instances
> A step instance contains variables: name, startTime etc and startTime
> is stored as a string %H:%M:%S
> 
> What I would like to do is to be able to sort this list of objects
> based on the startTime object so that the first item in the list is
> the object with the earliest Start time and last item is the object
> with the last Start time.
> 
> I belive my key has to be = strpTime(step.sTime, "%H:%M:%S")
> But don't know how to create the comparison funciton.

You're going to get a *lot* of answers on this one!

To start the ball rolling...


import random

class Step:

   def __init__ (self, name, startTime):
 self.name = name
 self.startTime = startTime

   def __cmp__ (self, other):
 return cmp (self.startTime, other.startTime)

   def __str__ (self):
 return str (self.startTime)
   __repr__ = __str__

steps = [Step (h, "%02d:00:00" % h) for h in range (10)]
random.shuffle (steps)
print "Shuffled:", steps

steps.sort ()
print "Sorted:", steps


In this case, I've given the class a ordering-semantic based
on its startTime attribute. Obviously, this only makes sense
if you *always* want your class to sort this way, rather than
in this one instance.

To do it on a per-sort basis, you *could* create simple per-sort
equivalent:



def compare_by_startTime (one, other):
   return cmp (one.startTime, other.startTime)

steps.sort (cmp=compare_by_startTime)



or, in the case you're asking about, you could use the
operator module's attrgetter function to do what you want:


import operator

steps.sort (key=operator.attrgetter ("startTime"))



TJG
-- 
http://mail.python.org/mailman/listinfo/python-list


Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute

2007-09-07 Thread cjt22
Hi there

I am fairly new to Python and have not really used regular expressions
before (I think this might be needed for my query) and wondered if you
could help

I have a step class and store in a list step instances
A step instance contains variables: name, startTime etc and startTime
is stored as a string %H:%M:%S

What I would like to do is to be able to sort this list of objects
based on the startTime object so that the first item in the list is
the object with the earliest Start time and last item is the object
with the last Start time.

I belive my key has to be = strpTime(step.sTime, "%H:%M:%S")
But don't know how to create the comparison funciton.

Any help on how I can perform this whole operation would be much
appreciated.

Thanks
Chris

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sort a list of files

2006-05-06 Thread Scott David Daniels
Ryan Forsythe wrote:
> Gary Wessle wrote:
>> Hi
>>
>> I am trying to print out the contents of a directory, sorted.
> ...
>> if I remove ".sort()" at the end of line 6 I get an unsorted list of
>> files, if I leave it I get None. who do I fix this?
> 
> `blah.sort()` sorts in-place and returns None. You probably want 
> sorted(blah):
> 
>  >>> a = [3, 1, 4, 1, 5, 9]
>  >>> sorted(a)
> [1, 1, 3, 4, 5, 9]
>  >>> a
> [3, 1, 4, 1, 5, 9]
>  >>> a.sort()
>  >>> a
> [1, 1, 3, 4, 5, 9]

If you are using an old version of Python (2.3.X or before),
the you just need to break your statement up:
Instead of:
 6  print os.listdir(sys.argv[1]).sort()
use:
 6  files = os.listdir(sys.argv[1])
 7  files.sort()
 8  print files

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sort a list of files

2006-05-06 Thread Ryan Forsythe
Gary Wessle wrote:
> Hi
> 
> I am trying to print out the contents of a directory, sorted.
...
> if I remove ".sort()" at the end of line 6 I get an unsorted list of
> files, if I leave it I get None. who do I fix this?

`blah.sort()` sorts in-place and returns None. You probably want 
sorted(blah):

 >>> a = [3, 1, 4, 1, 5, 9]
 >>> sorted(a)
[1, 1, 3, 4, 5, 9]
 >>> a
[3, 1, 4, 1, 5, 9]
 >>> a.sort()
 >>> a
[1, 1, 3, 4, 5, 9]

--
Ryan Forsythe
-- 
http://mail.python.org/mailman/listinfo/python-list


sort a list of files

2006-05-06 Thread Gary Wessle
Hi

I am trying to print out the contents of a directory, sorted.

 the code 
 1  import os, sys
 2  
 3  if len(sys.argv) < 2:
 4  sys.exit("please enter a suitable directory.")
 5  
 6  print os.listdir(sys.argv[1]).sort()


if I remove ".sort()" at the end of line 6 I get an unsorted list of
files, if I leave it I get None. who do I fix this?

thank you
-- 
http://mail.python.org/mailman/listinfo/python-list