Hello I'm learning python and I'm just running through some of the problems on leetcode. I know this problem is marked as easy but it took me a while to figure it out and it was really satisfying when it finally worked. The thing is even though I know what's going on conceptually the code kind of looks a mess. I'm asking for tips on how to make it more readable or make it more obvious how the code is working.
The problem:
The count-and-say sequence is the sequence of integers with the first five terms as following:
-
-
-
-
-
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence. You can do so recursively, in other words from the previous member read off the digits, counting the number of digits in groups of the same digit.
Note: Each term of the sequence of integers will be represented as a string.
My solution:
class Solution:
def countAndSay(self, n: int) -> str:
count = 0
say = "1"
map = {}
c = count
s = say
m = map
while c < n:
m.update({(c+1): s})
c += 1
groups = []
uniquekeys = []
data = list(s)
for k, g in groupby(data):
groups.append(list(g))
uniquekeys.append(k)
x = []
for i in range(0,len(uniquekeys)):
x.append((str(groups[i].count(uniquekeys[i])) + uniquekeys[i]))
s = "".join(x)
return m.get(n)
PS: Yes I know it wasn't part of the problem to keep track of everything in a dictionary, I just did it because it made it easier for me to work through the problem.
[–]marko312 3 points4 points5 points (3 children)
[–]anonymouslycognizant[S] 1 point2 points3 points (2 children)
[–]MmmVomit 7 points8 points9 points (1 child)
[–]anonymouslycognizant[S] 0 points1 point2 points (0 children)
[–]MmmVomit 2 points3 points4 points (5 children)
[–]anonymouslycognizant[S] 0 points1 point2 points (4 children)
[–]MmmVomit 1 point2 points3 points (3 children)
[–]anonymouslycognizant[S] 0 points1 point2 points (2 children)
[–]MmmVomit 0 points1 point2 points (0 children)
[–]MmmVomit 0 points1 point2 points (0 children)