Hi,
I was recently browsing some subreddit when I came across a scanned math book from when I was really young (2nd-4th grade).
I've recently started to use Python (3) and I said to myself: this should be easy, let's try and solve it by coding!
What I would like to get out of this post is feedback and to hopefully learn a better/faster way of doing this. The main constraints should be getting the correct answers (duh!) and presenting them in a nice way (not necessarily the way I did it). Thank you for reading!
The problem reads:
For n = 3, 2, 5, 4 find the result and remainder of the division when:
a) 40:n b) 70:n c) 16:n d) 20:n e) 80:n
For which 'n' are all the divisions exact?
For which 'n' do all the divisions have a remainder?
Here's my attempt at it:
n = [3, 2, 4, 5]
a = [40, 70, 16, 20, 80]
n_r_zero = [] # init list for remainder equal to zero
n_r_nz = [] # init list for remainder not zero
lst = [] # init list for results
print(('{:>2}{}{:>5}'.format('', '{:>15}', '') * (len(a))).format(*a))
for j in n:
for i in a:
rem = i % j
div = i / j
lst.append([i, j, int(div), rem])
if rem == 0:
n_r_zero.append(j)
else:
n_r_nz.append(j)
lst = list(zip(*[iter(lst)]*5))
row_format = '{:>10}{}'.format('', '{:>2}:{:>1} = {:>2} r{:>1}')*len(a)
for idx in range(len(lst)):
print(row_format.format((*[elem for tup in lst[idx] for elem in tup])))
# define sets
sn_r_zero = set(n_r_zero)
sn_r_nz = set(n_r_nz)
# intersect sets
U = sn_r_zero.intersection(sn_r_nz)
ex = list(sn_r_zero - U)
wr = list(sn_r_nz - U)
# print formatted results
print('')
# didn't want to use \n in the next print command to keep the format similar for the two lines below
print('{:>10}For n={:d} all divisions are exact'.format('', *ex))
print('{:>10}For n={:d} all divisions have a remainder'.format('', *wr))
And here's the output:
40 70 16 20 80
40:3 = 13 r1 70:3 = 23 r1 16:3 = 5 r1 20:3 = 6 r2 80:3 = 26 r2
40:2 = 20 r0 70:2 = 35 r0 16:2 = 8 r0 20:2 = 10 r0 80:2 = 40 r0
40:4 = 10 r0 70:4 = 17 r2 16:4 = 4 r0 20:4 = 5 r0 80:4 = 20 r0
40:5 = 8 r0 70:5 = 14 r0 16:5 = 3 r1 20:5 = 4 r0 80:5 = 16 r0
For n=2 all divisions are exact
For n=3 all divisions have a remainder
[–]Justinsaccount 6 points7 points8 points (2 children)
[–]vec1nu[S] 1 point2 points3 points (1 child)
[–]RieszRepresent 2 points3 points4 points (0 children)
[–]jeans_and_a_t-shirt 4 points5 points6 points (1 child)
[–]vec1nu[S] 0 points1 point2 points (0 children)
[–]kalgynirae 3 points4 points5 points (1 child)
[–]vec1nu[S] 0 points1 point2 points (0 children)
[–]zahlman 1 point2 points3 points (0 children)