MathGroup Archive 2006

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: help with lists operations

  • To: mathgroup at smc.vnet.net
  • Subject: [mg67840] Re: [mg67822] help with lists operations
  • From: "Carl K. Woll" <carlw at wolfram.com>
  • Date: Mon, 10 Jul 2006 06:37:47 -0400 (EDT)
  • References: <200607090850.EAA24679@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

omk wrote:
> Hi ALL,
> I am a novice in Mathematica, know that there are no easy ways for learning, so spent 2 weeks trying to solve an easy problem, but so far have only ugly solutions.
> Yes, I read and reread the Book as well as searched for similar problems on the Forum.
> I have 2 lists:
> f1={{2, 1}, {3, 1}, {7, 2}, {9, 1}, {10, 1}, {12, 1}, {14, 3}, {19,
> 3}, {23, 1}, {24, 1}, {25, 1}}
> f2={{2, 2}, {5, 1}, {
> 6, 2}, {10, 1}, {14, 3}, {16, 1}, {18, 1}, {21, 3}, {22, 1}, {26, 1}}
> I need to compare sublists (pairs) from the first list f1 with pairs from f2.
> If pairs with 2 first equal numbers exist, I have to multiply the second, after having products for all such pairs, I need to receive their sum.
> Say from f1 and f2 I have {2,1} and {2,2}, the product is 1 2=2, similar {10,1} and {10,1},{14,3} and {14,3},
> so it should be 2+1+9=12
> Any ideas are very welcome
> TIA,
> omk

This seems like a good problem for sparse arrays. First, find the 
maximum number you might try to compare (the maximum of the first 
columns of f1 and f2):

In[6]:=
len=Max[f1[[All,1]], f2[[All,1]]]

Out[6]=
26

Now, create sparse arrays from f1 and f2. We need to convert the pairs 
{int, int} to int -> int, which I do using Rule@@@f1. One could also use 
something like f1 /. {a_Integer,b_Integer}->(a->b).

In[7]:=
sa1=SparseArray[Rule @@@ f1,len]
sa2=SparseArray[Rule @@@ f2,len]

Out[7]=
SparseArray[<11>, {26}]

Out[8]=
SparseArray[<10>, {26}]

Now, we just multiply and add:

In[9]:=
Total[sa1 sa2]

Out[9]=
12

Here is a function which puts the pieces together:

omk[f1_List, f2_List]:=Module[{len},
    len = Max[ f1[[All,1]], f2[[All,1]] ];
    Total[ SparseArray[Rule@@@f1, len] SparseArray[Rule@@@f2, len] ]
]

Test:

In[11]:=
omk[f1,f2]

Out[11]=
12

Carl Woll
Wolfram Research


  • Prev by Date: Re: help with lists operations
  • Next by Date: Re: help with lists operations
  • Previous by thread: help with lists operations
  • Next by thread: Re: help with lists operations