Home > database >  I am getting None type error for my code. This is from Pattern of strings in Geek for geeks
I am getting None type error for my code. This is from Pattern of strings in Geek for geeks

Time:10-31

The code should print in the decreasing order

Example: input a = "Geek"

Output Geek Gee Ge G END

This is actually from geek for geeks I am trying to solve it using different variations

#User function Template for python3
class Solution:
    def pattern(self, S):
        n = len(S)
        for i in range (0, n):
            for j in range(0, n - i) :
                print(S[j], end = "")
            print("")



#{ 
 # Driver Code Starts
#Initial Template for Python 3

if __name__ == '__main__':
    T=int(input())
    for i in range(T):
        S = input()
# ob = Solution()
        answer = ob.pattern(S)
        for value in answer:
            print(value)
            

# } Driver Code Ends
Traceback (most recent call last):
  File "/home/ba2f900c4eca91e4a091a2c7bf208eb5.py", line 22, in <module>
    for value in answer:
TypeError: 'NoneType' object is not iterable

CodePudding user response:

Using two loops is usually not the most efficient I would recommend slicing.

Like this:

class Solution:
    def pattern(self,a):
        return [a[i:] for i in range(len(a))]


# {
# Driver Code Starts
# Initial Template for Python 3

if __name__ == '__main__':
    a = input()
    ob = Solution()
    answer = ob.pattern(a)
    print(answer)

# } Driver Code Ends

CodePudding user response:

You are printing the results once by calling answer = ob.Pattern(S) but then you loop through answer right after which at this point is None.

  • Related