View Single Post
Old 10-03-2008   #2 (permalink)
RickB


 
 

Re: Programming Collective Intelligence

On Oct 2, 7:21*pm, Doug <D...@xxxxxx> wrote:
Quote:

> I am trying to reproduce the approach in the book Programming Collective
> Intelligence,
> for building up a dataset. The author uses nested hash tables.
>
> The idea is to collect peoples responses, setting the nested table to the
> reponse and its value 1.
>
> The $allItems hashtable is all the respones collected.
>
> Then iterate over the $hash inserting the 'missing' values.
> That is adding the reponses the person did not make and setting it to 0.
>
> I try it in a nested ForEach but get a Collection modified error.
>
> Any ideas how to iterate over the keys of a hash table and insert new keys?
>
> PS > $r=.\test.ps1
>
> An error occurred while enumerating through a collection: Collection was
> modified; enumeration operation may not execute..
> At C:\PoSHScripts\Copy of NetMap\test.ps1:10 char:8
> + foreach <<<< ($key in $hash.keys) {
>
> PS > $r
>
> Name * * * * * * * * * * * * * Value
> ---- * * * * * * * * * * * * * -----
> a * * * * * * * * * * * * * * *{b, c}
> b * * * * * * * * * * * * * * *{c}
>
> PS > $r.a
>
> Name * * * * * * * * * * * * * Value
> ---- * * * * * * * * * * * * * -----
> b * * * * * * * * * * * * * * *1
> c * * * * * * * * * * * * * * *0
>
> <Begin PowerShell>
> $hash=@{}
>
> $hash.a+=@{b=1}
> $hash.b+=@{c=1}
>
> $allItems=@{}
> $allItems.b=1
> $allItems.c=1
>
> foreach($key in $hash.keys) {
> *foreach($item in $allItems.keys) {
> * if(-not ($hash.$key.keys -eq $item) ){
> * *$hash.$key+=@{$item=0}
> * }
> *}
>
> }
>
> $hash
> <End PowerShell>
>
> <Begin Python>
> *# Fill in missing items with 0
> * for ratings in user_dict.values():
> * * for item in all_items:
> * * * if item not in ratings:
> * * * * ratings[item]=0.0
> <End Python>
I think the easiest way is to put the hash keys in a temp variable
then iterate over the temp variable.
My System SpecsSystem Spec