Maximum volume of cube for every person when edge of N cubes are given


Given an array of N integers which denotes the edges of N cubical structures respectively. Also given are M integers which denotes the number of peoples. The task is to find the maximum amount of volume of a cube that can be given to every person.

Note: Cubes can be cut of any shape from any of the N cubes.

Examples:

Input: a[] = {1, 1, 1, 2, 2}, m = 3
Output: 4
All three person get a slice of volume 4 each
Person 1 gets a slice of volume 4 from the last cube.
Person 2 gets a slice of volume 4 from the last cube.
Person 3 gets a slice of volume 4 from the second last cube.

Input: a[] = {2, 2, 2, 2, 2}, m = 4
Output: 8


Naive Approach: A naive approach is to first calculate the volume of all of the cubes and then linearly check for every volume that it can be distributed among all M people or not and find the maximum volume among all such volumes.

Time Complexity: O(N2)

Efficient Approach: An efficient approach is to use binary search to find the answer. Since the edge lengths are given in the array, convert them to the volume of the respective cubes.

Find the maximum volume among volumes of all of the cubes. Say, the maximum volume is maxVolume. Now, perform binary search on the range [0, maxVolume].

  • Calculate the middle value of the range, say mid.
  • Now, calculate the total number of cubes that can be cut of all of the cubes of volume mid.
  • If the total cubes that can be cut exceed the number of persons, then that amount of volume of cubes can be cut for every person, hence we check for a larger value in the range [mid+1, maxVolume].
  • If the total cubes do not exceed the number of persons, then we check for an answer in the range [low, mid-1].

Below is the implementation of the above approach:

  

#include <bits/stdc++.h>

using namespace std;

  

int getMaximumVloume(int a[], int n, int m)

{

    int maxVolume = 0;

  

    

    

    for (int i = 0; i < n; i++) {

        a[i] = a[i] * a[i] * a[i];

  

        maxVolume = max(a[i], maxVolume);

    }

  

    

    

    int low = 0, high = maxVolume;

  

    

    int maxVol = 0;

  

    

    while (low <= high) {

  

        

        int mid = (low + high) >> 1;

  

        

        int cnt = 0;

        for (int i = 0; i < n; i++) {

            cnt += a[i] / mid;

        }

  

        

        

        

        if (cnt >= m) {

  

            

            low = mid + 1;

  

            

            

            maxVol = max(maxVol, mid);

        }

  

        

        else

            high = mid - 1;

    }

  

    return maxVol;

}

  

int main()

{

    int a[] = { 1, 1, 1, 2, 2 };

    int n = sizeof(a) / sizeof(a[0]);

    int m = 3;

  

    cout << getMaximumVloume(a, n, m);

  

    return 0;

}

Time Complexity: O(N * log (maxVolume))



Striver(underscore)79 at Codechef and codeforces D


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the “Improve Article” button below.

Article Tags :



Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.








Source link

Python | Bigram formation from given list


When we are dealing with text classification, sometimes we need to do certain kind of natural language processing and hence sometimes require to form bigrams of words for processing. In case of absence of appropriate library, its difficult and having to do the same is always quite useful. Let’s discuss certain ways in which this can be achieved.

Method #1 : Using list comprehension + enumerate() + split()
The combination of above three functions can be used to achieve this particular task. The enumerate function performs the possible iteration, split function is used to make pairs and list comprehension is used to combine the logic.

   

test_list = ['geeksforgeeks is best', 'I love it']

  

print ("The original list is : " + str(test_list))

  

res = [(x, i.split()[j + 1]) for i in test_list 

       for j, x in enumerate(i.split()) if j < len(i.split()) - 1]

  

print ("The formed bigrams are : " + str(res))

Output :

The original list is : [‘geeksforgeeks is best’, ‘I love it’]
The formed bigrams are : [(‘geeksforgeeks’, ‘is’), (‘is’, ‘best’), (‘I’, ‘love’), (‘love’, ‘it’)]

 
Method #2 : Using zip() + split() + list comprehension
The task that enumerate performed in the above method can also be performed by the zip function by using the iterator and hence in a faster way. Let’s discuss certain ways in which this can be done.

   

test_list = ['geeksforgeeks is best', 'I love it']

  

print ("The original list is : " + str(test_list))

  

res = [i for j in test_list 

       for i in zip(j.split(" ")[:-1], j.split(" ")[1:])]

  

print ("The formed bigrams are : " + str(res))

Output :

The original list is : [‘geeksforgeeks is best’, ‘I love it’]
The formed bigrams are : [(‘geeksforgeeks’, ‘is’), (‘is’, ‘best’), (‘I’, ‘love’), (‘love’, ‘it’)]




If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the “Improve Article” button below.

Article Tags :



Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.








Source link

Python | Convert case of elements in a list of strings


Given a list of strings, write a Python program to convert all string from lowercase/uppercase to uppercase/lowercase.

Input : ['GeEk', 'FOR', 'gEEKS']
Output: ['geeks', 'for', 'geeks']

Input : ['fun', 'Foo', 'BaR']
Output: ['FUN', 'FOO', 'BAR']

 
Method #1 : Convert Uppercase to Lowercase using map function

  

out = map(lambda x:x.lower(), ['GeEk', 'FOR', 'gEEKS'])

  

output = list(out)

  

print(output)

Output:


['geek', 'for', 'geeks']

 
Method #2: Convert Lowercase to Uppercase using List comprehension

  

input = ['fun', 'Foo', 'BaR']

  

lst = [x.upper() for x in input]

  

print(lst)

Output:


['FUN', 'FOO', 'BAR']




If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the “Improve Article” button below.

Article Tags :



Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.











Source link

Method resolution order in Python Inheritance


Method Resolution Order :
Method Resolution Order(MRO) it denotes the way a programming language resolves a method or attribute. Python supports classes inheriting from other classes. The class being inherited is called the Parent or Superclass, while the class that inherits is called the Child or Subclass. In python, method resolution order defines the order in which the base classes are searched when executing a method. First, the method or attribute is searched within a class and then it follows the order we specified while inheriting. This order is also called Linearization of a class and set of rules are called MRO(Method Resolution Order). While inheriting from another class, the interpreter needs a way to resolve the methods that are being called via an instance. Thus we need the method resolution order. For Example

  

class A:

    def rk(self):

        print(" In class A")

class B(A):

    def rk(self):

        print(" In class B")

  

r = B()

r.rk()

Output:

In the above example the methods that are invoked is from class B but not from class A, and this is due to Method Resolution Order(MRO).
The order that follows in the above code is- class B - > class A
In multiple inheritances, the methods are executed based on the order specified while inheriting the classes. For the languages that support single inheritance, method resolution order is not interesting, but the languages that support multiple inheritance method resolution order plays a very crucial role. Let’s look over another example to deeply understand the method resolution order:

  

class A:

    def rk(self):

        print(" In class A")

class B(A):

    def rk(self):

        print(" In class B")

class C(A):

    def rk(self):

        print("In class C")

  

class D(B, C):

    pass

     

r = D()

r.rk()

Output:

In the above example we use multiple inheritances and it is also called Diamond inheritance or Deadly Diamond of Death and it looks as follows:

Python follows a depth-first lookup order and hence ends up calling the method from class A. By following the method resolution order, the lookup order as follows.
Class D -> Class B -> Class C -> Class A
Python follows depth-first order to resolve the methods and attributes. So in the above example, it executes the method in class B.
 
Old and New Style Order :
In the older version of Python(2.1) we are bound to use old-style classes but in Python(3.x & 2.2) we are bound to use only new classes. New style classes are the ones whose first parent inherits from Python root ‘object’ class.


class OldStyleClass: 

    pass

  

class NewStyleClass(object): 

    pass

Method resolution order(MRO) in both the declaration style is different. Old style classes use DLR or depth-first left to right algorithm whereas new style classes use C3 Linearization algorithm for method resolution while doing multiple inheritances.
 
DLR Algorithm
During implementing multiple inheritances, Python builds a list of classes to search as it needs to resolve which method has to be called when one is invoked by an instance. As the name suggests, the method resolution order will search the depth-first, then go left to right. For Example

class A: 

    pass

  

  

class B: 

    pass

  

  

class C(A, B): 

    pass

  

  

class D(B, A): 

    pass

  

  

class E(C,D): 

    pass

In the above Example algorithm first looks into the instance class for the invoked method. If not present, then it looks into the first parent, if that too is not present then-parent of the parent is looked into. This continues till the end of the depth of class and finally, till the end of inherited classes. So, the resolution order in our last example will be D, B, A, C, A. But, A cannot be twice present thus, the order will be D, B, A, C. But this algorithm varying in different ways and showing different behaviours at different times .So Samuele Pedroni first discovered an inconsistency and introduce C3 Linearization algorithm.
 
C3 Linearization Algorithm :
C3 Linearization algorithm is an algorithm that uses new-style classes. It is used to remove an inconsistency created by DLR Algorithm. It has certain limitation they are:

  • Children precede their parents
  • If a class inherits from multiple classes, they are kept in the order specified in the tuple of the base class.

C3 Linearization Algorithm works on three rules:

  • Inheritance graph determines the structure of method resolution order.
  • User have to visit the super class only after the method of the local classes are visited.
  • Monotonicity

 
Methods for Method Resolution Order(MRO) of a class:
To get the method resolution order of a class we can use either __mro__ attribute or mro() method. By using these methods we can display the order in which methods are resolved. For Example

  

class A:

    def rk(self):

        print(" In class A")

class B:

    def rk(self):

        print(" In class B")

  

class C(A, B):

    def __init__(self):

        print("Constructor C")

  

r = C()

  

print(C.__mro__)

print(C.mro())

Output:





If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the “Improve Article” button below.

Article Tags :



Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.








Source link