Home > database >  Python: How can I divide a number completely by 2 and 3 and return -1 if not possible
Python: How can I divide a number completely by 2 and 3 and return -1 if not possible

Time:10-29

I want to make a function where given a number like 7 I want to factorise the number by as many 3s and 2s. If left with a remainder then return -1.

For example given the number 11 I want the function to return 3:3 and 2:1 as 3 fits into 11 3 times and 2 once ie. 3 2 2=7, 3 3 3 2=11, 3 3 3 2 2=13. The preference should be being able to fit as many 3s first.

This is part of a wider problem:

from collections import Counter
#Choose two packages of the same weight
#Choose three packages of the same weight 
#Minimum number of trips to complete all the deliveries else return -1

def getMinimumTrips(weights):
    weights_counted = Counter(weights)
    minimum_trips = 0
    print(weights_counted)
    for i in weights_counted:
        if weights_counted[i]==1:
            return -1
        elif weights_counted[i]%3==0:
            minimum_trips  = (weights_counted[i]//3)
        elif weights_counted[i]%2==0:
            minimum_trips  = (weights_counted[i]//2)
    return minimum_trips

print(getMinimumTrips([2, 4, 6, 6, 4, 2, 4]))

CodePudding user response:

This will return 0 if you can completely factorise the number, or -1 if 1 is remaining:

return -(i % 3 % 2)

If this helps?

CodePudding user response:

Try this method using math.floor()

import math


def get_components(n: int) -> str:
    q3 = math.floor(n / 3)
    q2 = math.floor(q3 / 2)
    if not (q3 and q2):
        return '-1'  # returning '-1' as a string here for consistency
    return f'3:{q3}, 2:{q2}'
  • Related