简体   繁体   中英

Problem in iterating over an integer list

I have this code

class Solution:
    def fizzBuzz(self, n: int) -> List[str]:
        l = []
        starting_pos = n-n+1
        ending_pos = n+1
        for i in range(starting_pos, ending_pos):
            l = [i]
            for j in l:
                if j % 5 == 0 and j % 3 == 0:
                    l.insert(j, "FizzBuzz")
                if j % 3 == 0:
                    l.insert(j, "Fizz")
                if j % 5 == 0:
                    l.insert(j, "Buzz")
                else:
                    continue

and when I run this, I get this error

TypeError: not all arguments converted during string formatting
    if j % 5 == 0 and j % 3 == 0:
Line 9 in fizzBuzz (Solution.py)
    ret = Solution().fizzBuzz(param_1)
Line 37 in _driver (Solution.py)
    _driver()
Line 48 in <module> (Solution.py)

I can't seem to fix this. Would appreciate some help.

You are inserting strings ( "FizzBuzz" , etc.) into the list l , over which you iterate.

j is an int at first but later it becomes a string. The meaning of % is completely different for ints and strings. So the expression j % 5 means the remainder ( j mod 5 ) when j is an int , but later it is interpreted as string formatting , which fails with the error you see.

What you probably should be doing instead is work with the value of i and drop the inner loop altogether.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM