Select to view content in your preferred language

# Getting the closest set of multiples depending on length of list items?

637
1
12-27-2022 01:42 PM
by
Frequent Contributor

Hi,

I came across this issue when trying to figure out the closest set of multiples for a given length of items in a list. The code below works but I wanted to see if anyone else had a better solution than the one below.

``````n = 12
ranges = [chr(i) for i in range(65, 65+n)]
print (ranges)
v = [i+1 for i in range(len(ranges))]
print (v)
testlist = [[x,y] for x in v for y in v if all([len(v) in [x*y, y*x], x%y > y%x])][-1]
print (testlist)``````

1 Reply
Occasional Contributor

Here is another way to write the code:

`import string# Number of items in the listnum_items = 12# Create a list of alphabet ranges (A-L)alphabet_ranges = list(string.ascii_uppercase)[:num_items]# Create a list of values (1-12)values = list(range(1, num_items+1))# Create the result list by iterating over the values# and only adding the pair if the length of the values list# is equal to either x*y or y*x, and x is divisible by y# but y is not divisible by xresult_list = [[x, y] for x in values for y in values               if len(values) in [x*y, y*x] and x % y > y % x][-1]print(alphabet_ranges)print(values)print(result_list)`