I was hoping someone could shed some light on a problem I have. I have a single array of variables:
[3,4,7,8,12,18,20,25,30,31,38,43,46,51,58,59]
And I would like to figure out how to split them up by a common multiple/denominator/whatever you would call it...say the common variable is 13 for this array, and I want the results to be n
number of variables, for example:
[4,30,43,56]
[7,20,46,59]
[12,25,38,51]
Is there an algorithm that can do something like that?
The closest to how i understand your question is that the numbers should be grouped by the remainder of division by n. (i%n).
input=[3,4,7,8,12,18,20,25,30,31,38,43,46,51,58,59]
n=13
result_dict = dict(zip(range(n),[[]]*n))
for i in input:
result_dict[i%n] = result_dict[i%n] + [i]
{0: [],
1: [],
2: [],
3: [3],
4: [4, 30, 43],
5: [18, 31],
6: [58],
7: [7, 20, 46, 59],
8: [8],
9: [],
10: [],
11: [],
12: [12, 25, 38, 51]}
This should solve your query. Replace array and number as per your requirement.
def run():
given_array = [3,4,7,8,12,18,20,25,30,31,38,43,46,51,58,59]
number = 13
final_result = []
for e in given_array:
d = e
intermediate_array = []
for f in given_array:
if e not in intermediate_array:
intermediate_array.append(e)
d = d+number
if d in given_array:
intermediate_array.append(d)
given_array.remove(d)
if intermediate_array and len(intermediate_array) > 1:
final_result.append(intermediate_array)
print final_result
if __name__ == '__main__':
run()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.