Ask Your Question

Extending piecwise to 2 variables (or a variable and a parameter)

asked 2020-12-22 04:28:43 -0600

Cyrille gravatar image

updated 2020-12-22 14:08:29 -0600

This piecewise function work correctly

score =  piecewise([([i,i], ncand - i) for i in range(ncand)])

because ncand is defined earlier in my notebook. when I typeset say score(1) It returns what I expect. But I would like that ncand be a variable.

edit retag flag offensive close merge delete


score can only be evaluated in the integers $0, 1, 2,...,\mathtt{ncand}-1$ and, in fact, $\mathtt{score}(i)=\mathtt{ncand}-i$. Is it intended? Anyway, if you have something like

ncand = some value
score = piecewise(list of cases depending on ncand)

you can redefine score to depend on ncand as follows:

def score(x,ncand):
    s = piecewise(list of cases depending on ncand)
    return s(x)
Juanjo gravatar imageJuanjo ( 2020-12-22 08:05:36 -0600 )edit

Juanjo it was intended

Cyrille gravatar imageCyrille ( 2020-12-22 14:51:08 -0600 )edit

But you answer is not self evident. Even short it ananswer not a comment.

Cyrille gravatar imageCyrille ( 2020-12-22 14:52:01 -0600 )edit

I have transformed my comment into an answer.

Juanjo gravatar imageJuanjo ( 2020-12-22 15:39:32 -0600 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2020-12-22 15:32:43 -0600

Juanjo gravatar image

Define score as follows:

def score(x, ncand=10):
    s = piecewise([([i,i], ncand - i) for i in range(ncand)])
    return s(x)

Then you can use score as in the following examples:

sage: score(7)
sage: score(3, ncand=7)
sage: score(3,7)

Observe that, if omitted, the value of ncand is 10.

edit flag offensive delete link more


I was aware of the default mechanism. But in all cases thanks for uour answer.

Cyrille gravatar imageCyrille ( 2020-12-23 07:12:25 -0600 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2020-12-22 04:28:43 -0600

Seen: 53 times

Last updated: Dec 22 '20