Select to view content in your preferred language

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

564
1
12-27-2022 01:42 PM
RPGIS
by
Regular 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)

 

 

0 Kudos
1 Reply
ChrisJRoss13
New Contributor III

Here is another way to write the code:

import string

# Number of items in the list
num_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 x
result_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)
0 Kudos