1
$\begingroup$

I have some lists with peculiar nestings:

{
-1,
{-1},
{-1, -1},
{-1, -1, {-1}},
{-1, {-1}},
{-1, -1, {-1}, {-1, -1}, {-1, -1}, {-1, -1}},
{-1, {-1}, {-1, -1}},
{-1, {-1}, {-1, -1}, {-1}}
}

which I would like to total at each level and add 1,

so {-1, -1, {-1}} should become {-1}

where the stages of calculation are {1-2 - {1-1}} -> {-1 - {0}} -> {-1}

and {-1, {-1}, {-1, -1}, {-1}} should become {1}

where the stages are {1-1 - {1-1} - {1-2} - {1-1}} -> {0 - {0} - {-1} - {0}} -> {1}

and

{-1, -1, {-1}, {-1, -1}, {-1, -1}, {-1, -1}} -> {-1 - {0} - {-1} - {-1} - {-1}} -> {2}

but, if there are no curly brackets around an element, 1 is not added. Therefore, -1 remains -1.

The list above should therefore become

{-1,{0},{-1},{-1},{0},{2},{-1},{-1}}

I have tried various Map combinations, none of which have worked, leaving me rather stumped on this one.

$\endgroup$
  • 2
    $\begingroup$ You say total but there appears to be negation as well. Otherwise shouldn't {-1, {-1}, {-1, -1}, {-1}} become {1 - 1 + {1 - 1} + {1 - 1 - 1} + {1 - 1}} == {{-1}}? $\endgroup$ – Mr.Wizard Jan 28 '15 at 0:17
2
$\begingroup$

Close to what you want but I wait for clarification:

expr=
   {
    -1,
    {-1},
    {-1, -1},
    {-1, -1, {-1}},
    {-1, {-1}},
    {-1, -1, {-1}, {-1, -1}, {-1, -1}, {-1, -1}},
    {-1, {-1}, {-1, -1}},
    {-1, {-1}, {-1, -1}, {-1}}
   };

Replace[
 -expr,
 {x__} :> 1 - +x,
 -1
]
{1, 0, -1, -1, 0, 2, 1, 1}
| improve this answer | |
$\endgroup$
  • $\begingroup$ Absolutely fantastic -you make it look so easy! You are right about my non-parenthesised elements of course. This is enormously helpful - thank you so much :) $\endgroup$ – martin Jan 28 '15 at 0:36
  • $\begingroup$ @martin I'm glad to be of help but I'd still like to have the problem clarified if possible. My output is not the same as what you show. (Look at the signs.) If it happens that this is what you want that's great, but if not I'll be happy to attempt to refine it after clarification. $\endgroup$ – Mr.Wizard Jan 28 '15 at 0:54
  • $\begingroup$ the error was mine - the output is perfect :) $\endgroup$ – martin Jan 28 '15 at 1:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.