Waiter

  • + 0 comments

    Python

    def is_prime(n):
        if n < 2:
            return False
        for i in range(2, int(n**.5) + 1):
            if n % i == 0:
                return False
        return True
    
    def generate_primes(n):
        num, count = 2, 0
        while count < n:
            if is_prime(num):
                yield num
                count += 1
            num += 1
    
    def waiter(number, q):    
        answers = []
        stack = number
        for prime in generate_primes(q):
            a = []
            b = []
            while stack:
                num = stack.pop()
                if num % prime == 0:
                    b.append(num)
                else:
                    a.append(num)
            while b:
                answers.append(b.pop())
            stack = a
        
        while stack:
            answers.append(stack.pop())
        
        return answers