Lien
Lien

Reputation: 99

Python : iterating over a list

With my code I would except that after looping one time he will jump to the next number in the list, but he doesn't. Anyone knows what is wrong with my code?

    for j in range(len(k)):
        s = [int(i) for i in str(k[j])]

This two lines of code are part of a bigger question I am solving.

def kaprekarseries(n):
    """
    >>> kaprekar_series(677)
    [677, 99, 0]
    >>> kaprekar_series(9876)
    [9876, 3087, 8352, 6174]
    >>> kaprekar_series(55500)
    [55500, 54945, 50985, 92961, 86922, 75933, 63954, 61974, 82962] 
    """

    k = list()
    k.append(n)
    count = 0

    while count < 10:
        for j in range(len(k)):
            s = [int(i) for i in str(k[j])]
            m = sorted(s, key=int, reverse=True) 
            m2 = int(''.join(str(i) for i in m))
            l = sorted(s, key=int)
            l2 = int(''.join(str(i) for i in l))
            g = m2 - l2
            k.append(g)
            if [item for item in k if k.count(item) <= 1]:
                count += 1
            else:
                return k 

Upvotes: 1

Views: 72

Answers (1)

Peter Majko
Peter Majko

Reputation: 1321

Your list k has just one element being appended prior to starting the loop. Therefore it is list of length of one, therefore it runs just once.

Rethink your algorythm.

Upvotes: 1

Related Questions