It's sometimes desirable to see whether a set of numbers can be reduced down proportionally - so that their value is reduced without changing the ratio between them. In order to do this, you need to find the largest number that all numbers in the set can be divided by - known as the greatest common multiple (the gcm) or highest common factor (HCF).
Once you've identified the HCF, it's simply a case of reducing each of the input numbers by dividing by that value.
from functools import reduce def scale_list_proportionally(nums): ''' Accept a list of numbers, and return them scaled proportionally - if possible @return: - nums: Scaled list - hcf: Highest Common Factor ''' hcf = greatest_common_denom_multiple(nums) if hcf > 1: # A HCF was found nums = [int(x/2) for x in nums] return nums,hcf def greatest_common_denom_multiple(nums): ''' Find the greatest common denominator amongst n numbers ''' return reduce(greatest_common_denom,nums) def greatest_common_denom(n1, n2): ''' Iterate over candidates running a modulo until we find something that fits ''' while (n2 != 0): t = n2; n2 = n1 % n2; n1 = t; return n1
nums=[2,4,6,8] print(scale_list_proportionally(nums)) #([1, 2, 3, 4], 2) nums=[250,5000,120,420] print(scale_list_proportionally(nums)) #([125, 2500, 60, 210], 10) nums=[14,49,21,28] print(scale_list_proportionally(nums)) # ([7, 24, 10, 14], 7) nums=[3,5,7,6] print(scale_list_proportionally(nums)) #([3, 5, 7, 6], 1)