shaurya jain
shaurya jain

Reputation: 25

Split a list and create partitions(list) depending upon the unique set of values

deck = [1,2,3,4,4,3,2,1]

Output: True

Explanation: Possible partition [1,1],[2,2],[3,3],[4,4].

Input: deck = [1,1,1,2,2,2,3,3]

Output: False

Explanation: No possible partition.

The solution i tried was very , very basic but i couldn't solve further than this. P.S:I am starting my coding experience.

v=[1,2,3,4,4,3,2,1]
t=list()
flag=0
for i in v:
    t.append(v.count(i))
for i in range(len(t)):
    for j in range(len(t)):
        if(t[i]==t[j]):
            flag=0
        else:
            flag=1
if(flag==1):
    print("NO")
else:
    q=len(list(set(v)))
    n = q
    lists = [[] for _ in range(n)]

Upvotes: 2

Views: 64

Answers (2)

Ch3steR
Ch3steR

Reputation: 20689

You can use Counter here.

from collections import Counter
def partition(lst):
    count=Counter(lst)
    if len(set(count.values()))>1:
        return 'No partition'
    else:
        return [[i]*n for i,n in count.items()]

deck = [1,2,3,4,4,3,2,1]
partition(deck)
#[[1, 1], [2, 2], [3, 3], [4, 4]]
deck=[1,1,1,2,2,2,3,3]
partition(deck)
#'No partition found'

If you just want the output to be True or False try this.

def partition(lst):
    return len(set(Counter(lst).values()))==1

Upvotes: 1

lynxx
lynxx

Reputation: 612

Try this:

How it works - It goes through all the list and stores the occurrence of each value. Then It makes of a set of it. Returns true if length of set is 1 i.e every number appears exactly the same number of times.

EDIT - set has a property that its element dont repeat. So say if the value of dikt is {1: 3, 2:3, 3:3} then the value of dikt.values is [3,3,3]. Making a set out of it will be (3). IF the value of dikt was {1:3, 2:3, 3:2} then the set would be (3, 2)

def foo(x):

    dikt = {}

    for i in x:

        if i in dikt.keys():
            dikt[i]+=1
        else:
            dikt[i] = 1

    return len(set(dikt.values())) == 1

Upvotes: 1

Related Questions