Reputation: 37
I am having an issue continuing my workflow. I am using vanilla python to try and sort a list of strings into a certain evenly distributed order.
The input is a given length, which is then divided to gather the number of required unique instances in a list. This list then needs to be sorted as evenly as possible around the list center index.
Input list: C,C,C,C,C,B,B,AB
Expected output list: C,B,C,AB,C,B,C,C
I am so stuck, please help!
Code so far:
import math
def AddItem(list,item,index):
result = []
for idx, ele in enumerate(list):
# if index multiple of N
if idx % index == 0:
# extend to append all elements
result.extend(item)
result.append(ele)
return result
lengths = [14421.46,691.99,6992.992,6946.004]
spacings = [8025,3210,1605]
result = []
spacings1 = []
for s in spacings:
if s == None:
pass
else:
spacings1.append(s)
divisions = []
nums = []
for l in lengths:
pack = []
for s in spacings1:
n = math.ceil(l/s)
if n < 1:
r = 1
else:
r = n
pack.append(r)
nums.append(pack)
for p in nums:
types = []
l_num = p[0]
for x in xrange(l_num):
types.append("AB")
t_num = p[1]-p[0]
for x in xrange(t_num):
types.append("B")
try:
g_num = p[2]
for x in xrange(g_num):
types.append("C")
except:
pass
result.append(types)
OUT = result
Upvotes: 0
Views: 299
Reputation: 106881
You can evenly divide 1 by the number of each unique item plus one to get a fraction for that item and slot the items into multiples of the fraction so the resulting multiples can be used as keys for sorting:
from collections import Counter
from operator import itemgetter
lst = ['C', 'C', 'C', 'C', 'C', 'B', 'B', 'AB']
print(
list(
map(
itemgetter(1),
sorted(
((i + 1) / (count + 1), item)
for item, count in Counter(lst).items()
for i in range(count)
)
)
)
)
This outputs:
['C', 'B', 'C', 'AB', 'C', 'B', 'C', 'C']
Upvotes: 2