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

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 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)

( 2020-12-22 15:05:36 +0200 )edit

Juanjo it was intended

( 2020-12-22 21:51:08 +0200 )edit

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

( 2020-12-22 21:52:01 +0200 )edit

I have transformed my comment into an answer.

( 2020-12-22 22:39:32 +0200 )edit

Sort by ยป oldest newest most voted

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)
3
sage: score(3, ncand=7)
4
sage: score(3,7)
4


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

more

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

( 2020-12-23 14:12:25 +0200 )edit