+ 1

Anyone have any ideas for cleaning up this code?(Python)

Put simply, I'm attempting to make a program that creates a grid - from scratch, so no imports or modules are included. I've finally gotten somewhere significant in this process, and it works. Question is, how can I make it better? Specifically, how can I shorten the GRAPH[g][#] part? (For reference, GRAPH is a dictionary, with integers as keys, and a list of strings as values) GRAPH = { 9:['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], 8:['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], 7:['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], 6:['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ... 0:[...] } for g in GRAPH: for key, val in GRAPH.items(): GRAPH[g][0] = grid GRAPH[g][1] = grid GRAPH[g][2] = grid GRAPH[g][3] = grid GRAPH[g][4] = grid GRAPH[g][5] = grid GRAPH[g][6] = grid GRAPH[g][7] = grid GRAPH[g][8] = grid GRAPH[g][9] = grid print(g, *GRAPH[g], sep="")

1st Jul 2023, 9:13 PM
Aza
Aza - avatar
12 Respostas
+ 6
When you loop through a dict, like so: for g in GRAPH then you are looping through the keys. It seems your inner loop is redundant and does not seem to do anything useful, you are not even using key and val anywhere. You did not specify what is in your grid variable. So it is not clear what is your intent, how your data should look like. You can use a comprehension to create the dict. And printing could also be simplified (depending on what is your goal). GRAPH = {i: list('0123456689') for i in range(10)} print(*GRAPH.items(), sep='\n')
2nd Jul 2023, 3:47 AM
Tibor Santa
Tibor Santa - avatar
+ 3
2nd Jul 2023, 3:40 AM
Bob_Li
Bob_Li - avatar
+ 3
These are all great! Thank you! Tibor Santa, my bad, grid = '+ ' I also didn't like the inner loop and at that point I wasn't completely sure if I didn't need it. I'm not great with dictionaries, so I came up with this exercise to learn about them. I really like this feedback
2nd Jul 2023, 4:00 AM
Aza
Aza - avatar
+ 3
Aza this is a really good point. Describing what problem you are trying to solve, brings us closer to offering an ideal solution. And I really like how you are trying to explore the possible options offered by different data structures. There can be many good approaches to the same problem. And some are more 'pythonic' or more straightforward than the others. Now the question is how you represent coordinates. Using a list of lists (you don't really need 3 levels) there is still a question of what value you put inside a grid. You may represent it with boolean (True, False) value, or 1 and 0, or if you need more choices then any value or object. This should not be confused with "how you print it". Data structure should focus on what you want to do with the data. For example, if you have an unfinished game of Tic Tac Toe, _ O X O X _ _ X O you could formulate the data structure like: board = [[None, False, True], [False, True, None], [None, True, False]] And you refer to the X in the middle as board[1][1]
5th Jul 2023, 5:21 AM
Tibor Santa
Tibor Santa - avatar
+ 2
For the numbers 0 to 9 you could use another loop so that the structure is like: for g in GRAPH... for key, val in GRAPH.items().... for n in range(10)....
1st Jul 2023, 9:46 PM
Lisa
Lisa - avatar
+ 2
# Hi, Aza ! # Maybe this code can give you a hint in the right direction: # Build dictionary. gph_0, grid, size = {}, '*', 10 base_vals = [str(i) for i in range(size)] for i in range(len(base_vals)): gph_0[i] = base_vals[:] gph_0[i][i] = grid # Print grid/dictionary. for key in sorted(gph_0): print(f"{key}: ", end='') print(*gph_0[key], sep='_', end=2*'\n') # Here’s another example: https://code.sololearn.com/cWLXwkIlPGxc/?ref=app
2nd Jul 2023, 9:16 AM
Per Bratthammar
Per Bratthammar - avatar
+ 2
I didn't explain this, and I probably should have for context, but the main reason I implemented a dictionary was so that the user could enter coordinate pairs, (x, y or in this case, x:y), instead of indices. I have tried this before with lists but it was getting very messy with trying to make this possible, and also having the grid pattern print automatically with a few for loops. Now that I think about it again, it must possible to do this, I suppose with a list, within a list, within another list. list_ = [ [[x,y],[x,y],[x,y],[x,y],[x,y],...], [[x,y],[x,y],[x,y],[x,y],[x,y],...], ... ]
5th Jul 2023, 1:37 AM
Aza
Aza - avatar
+ 2
Another possible implementation is that you store the coordinate pairs which are marked. Opposed to your list idea, I would put the two numbers in a tuple. The benefit is that it is now immutable and hashable, and you can put the tuples in a set. Which makes it very efficient to check, if a particular coordinate pair is in the set or not (so: marked or not). You can check this code and see an implementation of both approaches that I suggested, including how to print it nicely. https://code.sololearn.com/cesN6ejqECk2/?ref=app
5th Jul 2023, 7:04 AM
Tibor Santa
Tibor Santa - avatar
+ 1
Aza do GRAPH have to be a dict? for a 2d matrix, a list of lists is sufficient.
2nd Jul 2023, 4:17 AM
Bob_Li
Bob_Li - avatar
+ 1
As best as I understand, GRAPH works best as a dict. This way, the final output can be iterated over and printed out like a list, and, you can plot specific points on the output in a much more concise way. Remember how I was saying the grid variable = '+ '? That's because, the output looks something like this: 1 + + + + + + + + + + 2 + + + + + + + + + + 3 + + + + + + + + + + 4 + + + + + + + + + + 5 + + + + + + + + + + 6 + + + + + + + + + + ...(up to 10 lines) Because of it being a dict, it will be easier to manage than list indexing and appending newlines
3rd Jul 2023, 2:59 AM
Aza
Aza - avatar
+ 1
Aza In the typical dict implementation, the keys are not necessarily ordered. You could also remove keys from the sequence, thus creating a gap in the matrix, or add a completely unrelated key. But if you can keep that under control, and you iterate on the sorted keys, then yes this can work. A list is conceptually a mapping from the index to the values. So in this situation there is almost no difference, even in the syntax how you would use it. Typically in Python we would use numpy arrays, or list of lists to represent a 2d matrix. Also we usually store distinct data values on the final level. Maybe 0 or None value, when it does not exist or is not relevant. Putting strings and whitespaces is not a great idea. Printing the matrix is a completely different concern, and it should be easy with the join() method of str.
3rd Jul 2023, 4:42 AM
Tibor Santa
Tibor Santa - avatar
0
list2d = [] for i in range(10, -1, -1): child_list = [] for j in range(1, 11): child_list.append(j) list2d.append(child_list) This creates a 2d list or a grid of numbers
3rd Jul 2023, 1:00 AM
Ireneo language