473,785 Members | 2,298 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

list comprehention

Hi,

Python beginner here and very much enjoying it. I'm looking for a
pythonic way to find how many listmembers are also present in a reference
list. Don't count duplicates (eg. if you already found a matching member
in the ref list, you can't use the ref member anymore).

Example1:
ref=[2, 2, 4, 1, 1]
list=[2, 3, 4, 5, 3]
solution: 2

Example2:
ref=[2, 2, 4, 1, 1]
list=[2, 2, 5, 2, 4]
solution: 3 (note that only the first two 2's count, the third 2 in the
list should not be counted)

Any suggestions or comments?

Thanks.
M.
#my failing effort:
sum([min(r.count(n)-l[:i].count(n),l.cou nt(n)) for i,n in enumerate(l)])

#test lists
import random
#reference list
r=[random.randint( 1,5) for n in range(5)]
#list
l=[random.randint( 1,5) for n in range(5)]

Jan 19 '06
29 1529
Hi,
I liked the twist at the end when you state that only the first two 2's
count. It reminded me
of my maths O'level revision where you always had to read the question
thoroughly.

Here is what I came up with:
ref [2, 2, 4, 1, 1] lst [2, 2, 5, 2, 4] tmp = [ [val]*min(lst.count( val), ref.count(val)) for val in set(ref)]
tmp [[], [2, 2], [4]] answer = [x for y in tmp for x in y]
answer [2, 2, 4]
I took a lot from Peter Ottens reply to generate tmp then flattened the
inner lists.

After a bit more thought, the intermediate calculation of tmp can be
removed with a
little loss in clarity though, to give:
answer = [ val for val in set(ref) for x in range(min(lst.c ount(val), ref.count(val)) )]
answer

[2, 2, 4]

- Cheers, Paddy.

Jan 19 '06 #11
Mathijs wrote:
Python beginner here and very much enjoying it. I'm looking for a
pythonic way to find how many listmembers are also present in a
reference list. Don't count duplicates (eg. if you already found a
matching member in the ref list, you can't use the ref member
anymore).

Example1:
ref=[2, 2, 4, 1, 1]
list=[2, 3, 4, 5, 3]
solution: 2

Example2:
ref=[2, 2, 4, 1, 1]
list=[2, 2, 5, 2, 4]
solution: 3 (note that only the first two 2's count, the third 2 in
the list should not be counted)


Here's the way I would do it:
def occurrences(it) : res = {}
for item in it:
if item in res:
res[item] += 1
else:
res[item] = 1
return res
ref=[2, 2, 4, 1, 1]
lst=[2, 2, 5, 2, 4]
oref = occurrences(ref )
sum(min(v,oref. get(k,0)) for (k,v) in occurrences(lst ).iteritems()) 3 lst=[2, 3, 4, 5, 3]
sum(min(v,oref. get(k,0)) for (k,v) in occurrences(lst ).iteritems()) 2


Or in other words, define a function to return a dictionary containing
a count of the number of occurrences of each element in the list (this
assumes that the list elements are hashable). Then you just add up the
values in the test list making sure each count is limited to no higher than
the reference count.
Jan 20 '06 #12
Duncan Booth wrote:
Here's the way I would do it:
def occurrences(it) :

res = {}
for item in it:
if item in res:
res[item] += 1
else:
res[item] = 1
return res


I slightly prefer:

def occurrences(it) :
res = {}
res[item] = res.get(item, 0) + 1
return res
[...] Or in other words, define a function to return a dictionary containing
a count of the number of occurrences of each element in the list (this
assumes that the list elements are hashable). Then you just add up the
values in the test list making sure each count is limited to no higher than
the reference count.


Resulting in a linear-time average case, where the posted
list-comprehension-based solutions are quadratic. The title
of the thread is unfortunate.

The generalized problem is multiset (AKA "bag") intersection:

http://en.wikipedia.org/wiki/Bag_(mathematics)
--
--Bryan

Jan 20 '06 #13
Op 19 jan 2006 vond "ma*******@gmai l.com" :
another approach:

ref = [2,2,4,1,1]
lis = [2,2,5,2,4]

len([ref.pop(ref.ind ex(x)) for x in lis if x in ref])


This is the type of solution I was hoping to see: one-liners, with no use
of local variables. As Tim Chase already wrote, it has only one less
elegant side: it alters the original ref list.

Thanks for your suggestion.
Jan 23 '06 #14
Op 19 jan 2006 vond Peter Otten <__*******@web. de> :
sum(min(list.co unt(n), ref.count(n)) for n in set(ref))

Is that it?


Seems like this is it! Thanks.
Jan 23 '06 #15
Op 19 jan 2006 vond "Paddy" <pa*******@nets cape.net>:
answer = [ val for val in set(ref) for x in
range(min(lst.c ount(val), ref.count(val)) )] answer

[2, 2, 4]


I don't think it's correct. Your algoritm with the ref and lst below gives
3 as answer. The answer should have been 2 (1,3).

ref=[3, 3, 1, 1, 3]
lst=[5, 1, 4, 5, 3]

Jan 23 '06 #16
Op 20 jan 2006 vond Duncan Booth <du**********@i nvalid.invalid> :
Or in other words, define a function to return a dictionary containing
a count of the number of occurrences of each element in the list (this
assumes that the list elements are hashable). Then you just add up the
values in the test list making sure each count is limited to no higher
than the reference count.


Thanks. Though I don't know much about python (yet), this is more or less
the way I'de do it the language I'm more comfortable with (object pascal),
and I wouldn't label this as a pythonic solution. I could be wrong,
though:)
Jan 23 '06 #17
Mathijs wrote:
Op 20 jan 2006 vond Duncan Booth <du**********@i nvalid.invalid> :
Or in other words, define a function to return a dictionary
containing a count of the number of occurrences of each element in
the list (this assumes that the list elements are hashable). Then you
just add up the values in the test list making sure each count is
limited to no higher than the reference count.


Thanks. Though I don't know much about python (yet), this is more or
less the way I'de do it the language I'm more comfortable with (object
pascal), and I wouldn't label this as a pythonic solution. I could be
wrong, though:)

I'm curious what you think isn't pythonic about this solution?
Jan 23 '06 #18
Mathijs wrote:
Op 20 jan 2006 vond Duncan Booth <du**********@i nvalid.invalid> :
Or in other words, define a function to return a dictionary containing
a count of the number of occurrences of each element in the list (this
assumes that the list elements are hashable). Then you just add up the
values in the test list making sure each count is limited to no higher
than the reference count.


Thanks. Though I don't know much about python (yet), this is more or less
the way I'de do it the language I'm more comfortable with (object pascal),
and I wouldn't label this as a pythonic solution. I could be wrong,
though:)


You *are* wrong. Also, as the lists grow, Duncan's approach scales *much*
better than, e. g., mine.

If picking a better algorithm were unpythonic there would not be much value
in striving for pythonic solutions.

Peter
Jan 23 '06 #19
On Mon, 23 Jan 2006 17:41:55 +0000, Mathijs wrote:
Op 19 jan 2006 vond "ma*******@gmai l.com" :
another approach:

ref = [2,2,4,1,1]
lis = [2,2,5,2,4]

len([ref.pop(ref.ind ex(x)) for x in lis if x in ref])


This is the type of solution I was hoping to see: one-liners, with no use
of local variables.


Because you like unreadable, incomprehensibl e, unmaintainable code?

*wink*

--
Steven.

Jan 23 '06 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
3108
by: massimo | last post by:
Hey, I wrote this program which should take the numbers entered and sort them out. It doesnąt matter what order, if decreasing or increasing. I guess I'm confused in the sorting part. Anyone has any advices?? #include <iostream> using namespace std;
10
15134
by: Kent | last post by:
Hi! I want to store data (of enemys in a game) as a linked list, each node will look something like the following: struct node { double x,y; // x and y position coordinates struct enemy *enemydata; // Holds information about an enemy (in a game) // Its a double linked list node
24
5779
by: Robin Cole | last post by:
I'd like a code review if anyone has the time. The code implements a basic skip list library for generic use. I use the following header for debug macros: /* public.h - Public declarations and macros */ #ifndef PUBLIC #define PUBLIC
4
3604
by: JS | last post by:
I have a file called test.c. There I create a pointer to a pcb struct: struct pcb {   void *(*start_routine) (void *);   void *arg;   jmp_buf state;   int    stack; };   struct pcb *pcb_pointer;
3
2712
by: chellappa | last post by:
hi this simple sorting , but it not running...please correect error for sorting using pointer or linked list sorting , i did value sorting in linkedlist please correct error #include<stdio.h> #include<stdlib.h> int main(void) {
0
1824
by: drewy2k12 | last post by:
Heres the story, I have to create a doubly linked list for class, and i have no clue on how to do it, i can barely create a single linked list. It has to have both a head and a tail pointer, and each node in the list must contain two pointers, one pointing forward and one pointing backwards. Each node in the list will contain 3 data values: an item ID (string), a quantity (integer) and a price (float). The ID will contain only letters and...
10
6581
by: AZRebelCowgirl73 | last post by:
This is what I have so far: My program! import java.util.*; import java.lang.*; import java.io.*; import ch06.lists.*; public class UIandDB {
0
8633
by: Atos | last post by:
SINGLE-LINKED LIST Let's start with the simplest kind of linked list : the single-linked list which only has one link per node. That node except from the data it contains, which might be anything from a short integer value to a complex struct type, also has a pointer to the next node in the single-linked list. That pointer will be NULL if the end of the single-linked list is encountered. The single-linked list travels only one...
12
4055
by: kalyan | last post by:
Hi, I am using Linux + SysV Shared memory (sorry, but my question is all about offset + pointers and not about linux/IPC) and hence use offset's instead on pointers to store the linked list in the shared memory. I run fedora 9 and gcc 4.2. I am able to insert values in to the list, remove values from the list, but the problem is in traversing the list. Atlease one or 2 list nodes disappear when traversing from the base of the list or...
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10341
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10155
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8979
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5383
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5513
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4054
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3656
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2881
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.