Background
I made the image of Irasutoya into a pixel art. (part1) When dividing a color into four
I manually set the threshold as range_color = [0, 85, 170, 255]
(or [i * int (255/3) for i in range (3)]
). (Actually, it was divided into 3 parts and approximated to 4 values.)
This time it was just divisible, so there was no problem, but I thought how to design the algorithm if the range and the number of divisions were arbitrary and different values, so I summarized it.
In the above example, the range is 255 and the number of divisions is 3.
Method
It is not divisible cleanly and a remainder is generated. In that case, add +1 evenly to the first element.
So, how to do it
It is the flow of.
Development
import sys
def main():
if len(sys.argv) != 3:
print("[USAGE] you give parameters this command.")
print("[EXAMPLE] python main.py [range number] [n-division number]")
print("[EXAMPLE] python main.py 255 4")
sys.exit()
r = int(sys.argv[1]) #range
d = int(sys.argv[2]) #n Number of divisions
q, mod = divmod(r, d) #Merchandise, calculation of remainder
#Addition list
plus = [q + 1 if i < mod else q for i, d in enumerate(range(d - 1))]
print(plus)
#output
dst = []
dst.append(plus[0])
for i in range(len(plus)):
dst.append(plus[0] + sum(plus[:1 + i]))
print(dst)
if __name__ == '__main__':
main()
Comment
\W $ python main2.py 255 6
[43, 43, 43, 42, 42]
[43, 86, 129, 172, 214, 256]
\W $ python main2.py 255 10
[26, 26, 26, 26, 26, 25, 25, 25, 25]
[26, 52, 78, 104, 130, 156, 181, 206, 231, 256]
The "addition list" is a list of the values of the intervals of each element.
Based on this list, calculate each element with sum (plus [: 1 + i])
.
Example) When you want to calculate the range 255, the number of divisions 10, and the 7th element Initial value 26 + [26, 26, 26, 26, 26, 25] total value = 181
It's the staff sequence that I learned in the high school sequence. : smirk_cat: Terra Natsu
a_n = a_1 + \sum_{k=1}^{n-1}b_k \quad (n \geqq 2 )
PostScript When creating some content, you may think a little about the algorithm even on a small scale. As a developer, there is no shortage of writing because the items of qiita will increase. : robot:
Reference
-Split integers as evenly as possible
--You can do it with [(x + i) // n for i in range (n)]
. This one is simpler.
Recommended Posts