chamathabeysinghe
chamathabeysinghe

Reputation: 868

What is the reason for difference in results?

I wrote a python program to print odd permutations of digits 1...9.

list1=[1,2,3,4,5,6,7,8,9] #this is used to generate permutations in lexicographic order
l3=[] #list to store odd permutations
k=7 # initial value of k
l3.append(list1)

while k!=-1:
    l=0
    #find value of l
    for x in range(len(list1)-1,k,-1):
         if list1[x]>list1[k]:
            l=x 
            break

    #swap values
    p=list1[k]
    list1[k]=list1[l]
    list1[l]=p

    #reverse the list 
    c1=list1[0:k+1]
    c2=list1[k+1:]
    c2.reverse()
    list1=c1+c2

    #finiding odd ones and printing them and storing them in l3 list
    if list1[8]%2!=0:       
        l3.append(list1)
        print list1 #in next program I replace this line with a for loop to print items in l3 list

    k=-1
    #find next value of k
    for x in range(len(list1)-2,-1,-1):
        if list1[x]<list1[x+1]:
            k=x 
            break

This program print the expected results. But when i add this code to end of it instead print line the results changed completely .

for x in l3:
     print x

I think I had made some silly mistakes but I can't find any error. plz help me to debug it.(I used permutation generating algorithm in Wikipedia(use k,l variables as mentioned in it).)

Upvotes: 0

Views: 44

Answers (1)

Irshad Bhat
Irshad Bhat

Reputation: 8709

This is a copy by reference problem. Just replace the two occurrences of:

l3.append(list1)  # cpoy by reference

with:

l3.append(list1[:])  # copy by value

Upvotes: 1

Related Questions