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
Duncan Booth showed how to solve a problem posed by Mathijs. This is
very similar to Duncan's solution, except I (ab)use setdefault on a
regular basis... def occurrences(t):
.... res = {}
.... for item in t:
.... res.setdefault( item,[0])[0] += 1
.... return res
.... ref = [2,2,4,1,1] lst = [2,2,5,2,4] oref = occurrences(ref ) sum(min(v[0],oref.get(k,[0])[0]) for (k,v) in occurrences(lst ).iteritems())
3
Actually, this brings up an interesting point:
{}.setdefault(' foo',0) += 1
SyntaxError: can't assign to function call
I understand why this doesn't work, but it would sure be nice if it
did. I think somebody was mentioning "mutable ints" at one point,
which is basically what I abuse [0] to provide. If I were doing a lot
of this in one place, I would code a mutable integer class, and then
the rest of the code would get simpler.
Regards,
Pat
Bryan Olson wrote: 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
Arg! In illustrating a trivial point, I dropped something essential.
This version has almost three minutes of testing behind it:
def occurrences(it) :
res = {}
for item in it:
res[item] = res.get(item, 0) + 1
return res
--
--Bryan
On 23/01/2006 18:41, Mathijs uttered: 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.
May I suggest another one-liner:
len(set(ref).in tersection(lis) )
I have no idea how this scales/performs compared to the other
suggestions you've received, but I find it immediately comprehensible.
-- Morten
[Mathijs] 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)
[Morten Vold]
May I suggest another one-liner:
len(set(ref).in tersection(lis) )
I have no idea how this scales/performs compared to the other suggestions you've received, but I find it immediately comprehensible. len(set([2, 2, 4, 1, 1]).intersection([2, 2, 5, 2, 4]))
2
Close, but no cigar.
Peter
On 24/01/2006 09:46, Peter Otten uttered: len(set([2, 2, 4, 1, 1]).intersection([2, 2, 5, 2, 4]))
2 Close, but no cigar.
I need more coffee! (note to self: Always read entire problem set first)
-- Morten
Patrick Maupin wrote: def occurrences(t): ... res = {} ... for item in t: ... res.setdefault( item,[0])[0] += 1 ... return res
.... I think somebody was mentioning "mutable ints" at one point, which is basically what I abuse [0] to provide. If I were doing a lot of this in one place, I would code a mutable integer class, and then the rest of the code would get simpler.
Or you could use the facilities built in to Python: use the get method as
Bryan did, and the code gets simpler without using mutable integers.
I prefer writing an 'if' statement here, Bryan prefers 'get', that's just a
choice of style. But 'setdefault' here, that has no style.
Duncan Booth wrote: I prefer writing an 'if' statement here, Bryan prefers 'get', that's just a choice of style. But 'setdefault' here, that has no style.
Well, I'm often told I have no style, and I _did_ admit that it's an
abuse of setdefault. However, I often use setdefault to populate
nested dictionaries, or dictionaries of sets or lists, e.g.:
for x, y in somebiglist:
bigdict.setdefa ult(x,set()).ad d(y) # Strips duplicates
for x, y in somebiglist:
bigdict.setdefa ult(x,[]).append(y) # Preserves duplicates
To my mind, this latter is so much cleaner and clearer than any of the
alternatives that it just isn't funny:
for x, y in somebiglist:
if x in bigdict:
bigdict[x].append(y)
else:
bigdict[x] = [y]
for x, y in somebiglist:
if x not in bigdict:
bigdict[x] = []
bigdict[x].append(y)
for x, y in somebiglist:
try:
bigdict[x].append(y)
except KeyError:
bigdict[x] = [y]
etc.
Since I use setdefault in this manner quite often, I am very
comfortable with it. On a single line I know what I am creating (list,
dict, set, etc.), what the default value is, and how it is being
modified.
Because I am NOT a believer in the Perl idiom of TMTOWTDI, and because,
TO ME, setdefault screams "This line is creating and subsequently
modifying a dictionary entry", setdefault is absolutely my first choice
for this particular task.
Having said that, my enthusiasm for setdefault (for the given problem!)
IS tempered somewhat by having to abuse a list as a mutable integer.
That is the only reason that I concede that my solution is an abuse of
setdefault, but the setdefault idiom is (to me) so clear and compelling
that I view it as a toss-up whether to use a single line setdefault or
an if/else in this case.
And, as I mentioned earlier, if I had to do this same thing LOTS of
times in a program, I most likely would code a class (perhaps not as
fancy as a true mutable int, but certainly something with an increment
method), because, IMO, it would be a lot cleaner (hmmm, maybe there's
no style points in that) than tons and tons of if/else statements.
Regards,
Pat
Patrick Maupin wrote: Duncan Booth wrote:
I prefer writing an 'if' statement here, Bryan prefers 'get', that's just a choice of style. But 'setdefault' here, that has no style.
Well, I'm often told I have no style, and I _did_ admit that it's an abuse of setdefault. However, I often use setdefault to populate nested dictionaries, or dictionaries of sets or lists, e.g.:
for x, y in somebiglist: bigdict.setdefa ult(x,set()).ad d(y) # Strips duplicates
for x, y in somebiglist: bigdict.setdefa ult(x,[]).append(y) # Preserves duplicates
To my mind, this latter is so much cleaner and clearer than any of the alternatives that it just isn't funny:
Yes, but storing a mutable is a not unreasonable use of setdefault. What I
objected to was storing an immutable just to overwrite it immediately.
Also, while I agree it is shorter, I'm not convinced that it is much
cleaner, and it is likely to be slower if there are a lot of duplicates,
possibly a lot slower if the mutable object has much overhead on its
construction.
Umm,
My answer is not correct, but for a different reason; it seems you need
the length of my
previous answer, thus:
PythonWin 2.4 (#60, Feb 9 2005, 19:03:27) [MSC v.1310 32 bit (Intel)]
on win32.
Portions Copyright 1994-2004 Mark Hammond (mh******@skipp inet.com.au) -
see 'Help/About PythonWin' for further copyright information. ref = [3, 3, 1, 1, 3] lst=[5, 1, 4, 5, 3] answer = len([ val for val in set(ref) for x in range(min(lst.c ount(val), ref.count(val)) )]) answer
2
- Paddy.
23 jan 2006 ta (Steven D'Aprano) shuo le: 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?
For practical use: no! But I'm just learning python and to understand
sets/lists/dicts and it's functions, this seemed like good practise:) and
besides that: it's fun! A solution with local vaiables, if-statemenst and a
for loop wouldn't be much different from what I know with my current
programming skills.
*wink*
Yeah, yeah, I know, but I felt a response was on its place. :) This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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;
|
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
|
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
|
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;
|
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)
{
| |
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...
|
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 {
|
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...
|
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...
|
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...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
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...
|
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...
|
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...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
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...
|
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
| |
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...
| |