Time limit exceeded for my python code for count and say problem


  • 0
    L
    class Solution:
    # @return a string
    def countAndSay(self, n):
        
        if n<1:
            return ''
        i, res=1, '1'
        while i<n:
            keyList=[]
            keyList.append([res[0],1])
            k=0
            for j in range(1,len(res)):
                if res[j]==res[k]:
                    keyList[k][1]+=keyList[k][1]
                else:
                    keyList.append([res[j],1])
                    k+=1
            res=''
            for list in keyList:
                res=res+str(list[1])+list[0]
        return res
    

    this code count from 1 to n. Basically the k-th element is determined by the (k-1)-th element. Thus iteratively, this code calculate the count from 1 to n. Any suggestions on speeding it up?

    Thank you for your attention.


  • 1
    K

    At a first glance, you have an infinite loop. "i<n" is forever true.

    IMHO, nested list is not the best choice of data structure either.


  • 0
    L

    Thanks for the comments. Can you elaborate more on your choice of the data structure?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.