Ask Your Question
0

While loop with recording intermediate steps

asked 2021-01-14 18:44:22 +0200

Cyrille gravatar image

updated 2021-01-14 22:06:03 +0200

Sorry for a certainly too long code but the problem is in the while the loop

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

cand=["A","B","C","D"]    
Ap=All_pref(cand,2)
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]
alf=[list(build_alphabet(x)) for x in Ap]
show(alf)
resultats={}
alfc={}
iteration=0
while len(alf[0])>0:
    show(alf)
    resultats[iteration]={}
    premier_par_pref =[[ne[i] if alf[i].index(x)==0 else 0 for i in range(len(alf))] for x in cand]
    nb_fois_premier_par_pref = [add(x) for x in premier_par_pref]
    show(nb_fois_premier_par_pref)
    min_nb_fois_premier_par_pref = min(nb_fois_premier_par_pref)
    index_min_nb_fois_premier_par_pref = nb_fois_premier_par_pref.index(min_nb_fois_premier_par_pref)
    cand_el=cand[index_min_nb_fois_premier_par_pref]
    show(cand_el)
    resultats[iteration]["elimine"]=cand_el
    alfc[iteration]=alf.copy()
    show(alfc[iteration])        
    resultats[iteration]["liste"]=alfc[iteration]
    [x.remove(cand_el) for x in alf]
    cand.remove(cand_el)
    iteration+=1
show(resultats)

if you look at the final result it is empty. Where do I fail ?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-01-14 23:42:08 +0200

Replace

alfc[iteration]=alf.copy()

with

alfc[iteration] = deepcopy(alf)

(This should work if you're using it in an interactive Sage session, but deepcopy may not be defined in a non interactive session, so you might need to also include from copy import deepcopy.)

See https://stackoverflow.com/questions/2..., for example.

edit flag offensive delete link more

Comments

Thanks John. I have done a lot of research on copy() but never deepcopy() never comes. Is there a place where one can find key words for Sagemath ?

Cyrille gravatar imageCyrille ( 2021-01-15 07:26:35 +0200 )edit

This is a Python issue, not a Sage one in particular. If you had replaced show(alfc[iteration]) with show(alfc), you would have seen alfc changing whenever alf did, and that would have perhaps led you to questions about how to copy nested lists, which is the issue here. (And it is a common source of confusion with Python.)

John Palmieri gravatar imageJohn Palmieri ( 2021-01-15 18:43:09 +0200 )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: 2021-01-14 18:44:22 +0200

Seen: 119 times

Last updated: Jan 14 '21