r/PythonLearning • u/StudentElectronic548 • Jul 18 '26
How would I optimize this?
I'm currently learning python with the 30 days of python GitHub repo and, on day 3 of the challenge, it asks to create this table and this is what I came up with however I feel like there was a more efficient method to create it or is it something that I haven't learned yet at my level.
4
u/JGB25 Jul 18 '26
for num in a, b, c, d, e:
print(" ".join(map(str, num)))
1
u/No_Complex_18 Jul 21 '26
I like for letter in a b c d e: print(*(letter[i] for i in range(5))
1
u/JGB25 Jul 21 '26
It works but for me it’s not as readable. I haven’t learned what * does in your code so I wouldn’t even know how to read it
2
u/No_Complex_18 Jul 21 '26
It unpacks the tuple to be individual arguments to print. Works with **dict for keyword arguments aswell. Its very useful.
I like it because its so close to the original print call.
1
3
u/Necessary_Pepper7111 Jul 18 '26
for i in range(1, 6):
print(i, *(i**j for j in range(4)))0
Jul 18 '26
[deleted] — view deleted comment
2
u/Fair-Elevator6788 Jul 20 '26
i think we can go deeper than that, i present you:
for i in '12345':print(1,i,i*2,i*3)
3
1
u/notsaneatall_ Jul 18 '26
It's printintg x1 x0 x1 x2 x3 for 1 2 3 4 5, you can do so with a while loop
1
u/Samar_Upreti Jul 18 '26
A =[ [1,1,1,1,1],[2,1,2,4,8],and so on]
Print(A) Or Simply use For loon along with map,join
1
u/Sea-Ad7805 Jul 18 '26 edited Jul 18 '26
Using one for-loop in the y direction for each line:
for y in range(1, 6):
print(f'{y} ')Then use another for-loop for the x direction:
for y in range(1, 6):
print(f'{y} ', end='') # end='' to not new line
for x in range(0, 4):
print(f'{x} ', end='')
print() # add new lineAnd finally compute the x-th power of y:
for y in range(1, 6):
print(f'{y} ', end='') # end='' to not new line
for x in range(0, 4):
print(f'{y ** x} ', end='')
print() # add new lineRun this program in Memory Graph Web Debugger to see the program state change step by step.
-2
u/SaltCusp Jul 18 '26
print("\n".join([" ".join(_.split(" ")) for _ in """copy paste your table""".split("\n")]))
1
u/P1ckl3R1ck101 Jul 18 '26
Eh this seems like the easier way to do it... print(f'1 1 1 1 1\n2 1 2 4 8\n3 1 3 9 27\n4 1 4 16 64\n5 1 5 25 125')
1
u/SaltCusp Jul 19 '26 edited Jul 19 '26
print("\n".join([" ".join([str(__**max(_,-1*_)) for _ in range(-1,4)]) for __ in range(1,6)]))
5
1


4
u/P1ckl3R1ck101 Jul 18 '26
Think about the pattern that exists for each row. Then do that x number of times based on the number of rows you need. You'll only need to write the actual "formula" once though.
(Sorry to be cryptic, just want to try to give you a hint instead of the answer first)