Ask Your Question
0

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

asked 2020-12-22 11:28:43 +0100

Cyrille gravatar image

updated 2020-12-22 21:08:29 +0100

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

Comments

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 15:05:36 +0100 )edit

Juanjo it was intended

Cyrille gravatar imageCyrille ( 2020-12-22 21:51:08 +0100 )edit

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

Cyrille gravatar imageCyrille ( 2020-12-22 21:52:01 +0100 )edit

I have transformed my comment into an answer.

Juanjo gravatar imageJuanjo ( 2020-12-22 22:39:32 +0100 )edit

1 Answer

Sort by ยป oldest newest most voted
0

answered 2020-12-22 22:32:43 +0100

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

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

edit flag offensive delete link more

Comments

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

Cyrille gravatar imageCyrille ( 2020-12-23 14:12:25 +0100 )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

Stats

Asked: 2020-12-22 11:28:43 +0100

Seen: 238 times

Last updated: Dec 22 '20