[Date Index]
[Thread Index]
[Author Index]
Re: Pattern problem: How to count from a long list of numbers all
*To*: mathgroup at smc.vnet.net
*Subject*: [mg87421] Re: Pattern problem: How to count from a long list of numbers all
*From*: "jwmerrill at gmail.com" <jwmerrill at gmail.com>
*Date*: Thu, 10 Apr 2008 02:12:34 -0400 (EDT)
*References*: <fti404$ok1$1@smc.vnet.net>
On Apr 9, 5:58 am, "Nasser Abbasi" <n... at 12000.org> wrote:
> Hello;
>
> I think using Pattern is my weakest point in Mathematica.
>
> I have this list, say this: (it is all a list of integers, no real numbers).
>
> x = {1, 3, 3, 3, 2, 3, 3, 1, 3, 3}
>
> And I want to count how many say a 3 followed immediately by 3. So in the
> above list, there will be 4 such occurrences. And if I want to count how
> many 1 followed by a 3, there will be 2 such cases, etc...
>
> I tried Count[] but I do not know how to set the pattern for "3 followed by
> a comma followed by 3" or just "3 followed immediately by 3".
>
> I tried few things, such as the following
>
> In[68]:= Count[x, {3, 3}_]
> Out[68]= 0
>
> Also tried Cases, but again, I am not to good with Patterns, so not sure how
> to set this up at this moment.
>
> Any ideas will be appreciated.
>
> Nasser
> I really need to sit down and study Patterns in Mathematica really well one
> day :)
I don't think you can solve this problem using only Count with a
pattern. The pattern only gets to look at one element at a time. You
can set things up using Partition, though.
In[20]:= x = {1, 3, 3, 3, 2, 3, 3, 1, 3, 3}
Out[20]= {1, 3, 3, 3, 2, 3, 3, 1, 3, 3}
In[21]:= Partition[x, 2, 1]
Out[21]= {{1, 3}, {3, 3}, {3, 3}, {3, 2}, {2, 3}, {3, 3}, {3, 1}, {1,
3}, {3, 3}}
Now you can count how many times {3,3} occurs:
In[32]:= Count[Partition[x, 2, 1], {3, 3}]
Out[32]= 4
If you wanted to count how many times any element is repeated, you
could do
In[33]:= Count[Partition[x, 2, 1], {y_, y_}]
Out[33]= 4
Regards,
Jason
Prev by Date:
**Re: Pattern problem: How to count from a long list of numbers all**
Next by Date:
**Re: Pattern problem: How to count from a long list of numbers all occurrences of 2 numbers next to each others?**
Previous by thread:
**Re: Pattern problem: How to count from a long list of numbers all**
Next by thread:
**Re: Pattern problem: How to count from a long list of numbers all**
| |