Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

I think you can greatly simplify your code:

  • use f-strings instead of the format method;
  • use HTML instead of LaTeX to format headers, since elements in headers are not math expressions;
  • place conditionals at proper places, not at the end.

This works for me in a Jupyter notebook:

def All_pref(cand=["A","B","C","D"], code=1) :
    ncand = len(cand)
    Scand = sorted(Set(cand))
    all_pref = Arrangements(Scand,ncand).list()
    all_pref1 = [str(Word(x)) for x in all_pref]
    if code==1 :
        return ncand
    if code==2 :
        return all_pref1

def Borda(cand, ne, cond=0) :
    Ap=All_pref(cand,2) 
    cond1 = [w for w in Ap]
    cond3 = [f"<em>{w}</em>" for w in cand]
    cond2 = [""] + cond3
    if cond==0 :
        return table([ne], header_row=cond1)
    rank = [[x.find(l) for x in Ap] for l in cand] 
    score_de_Borda = [[abs(x.find(l)-len(cand)) for x in Ap] for l in cand]
    if cond==1 :
        return table(rank, header_row=cond1, header_column=cond2)
    total_score_de_Borda = [add([score_de_Borda[j][i]*ne[i] 
                                 for i in range(24)]) for j in range(len(cand))]
    if cond==3 :
        return total_score_de_Borda
    if cond==2 :
        return table(score_de_Borda, header_column=cond3)
    max_total_score_de_Borda = max(total_score_de_Borda)
    ind_max_total_score_de_Borda = total_score_de_Borda.index(max_total_score_de_Borda)
    if cond==4 : # vainqueur_de_Borda
        return cand[ind_max_total_score_de_Borda]

cand = ["A","B","C","D"]
ne = [18,16,14,12,11,20,19,14,16,12,2,1,0,0,20,16,13,15,11,10,9,8,7,5]
show(html("Le tableau des rangs est :"))
show(Borda(cand,ne,1))
show(html("Le tableau des scores est :"))
show(Borda(cand,ne,2))
show(html(f"Les scores totaux de chaque candidat sont : {Borda(cand,ne,3)}"))
show(html(f"Le vainqueur d'un décompte à la Borda est : {Borda(cand,ne,4)}."))