Ejemplo n.º 1
0
  def Prune(self, curans, whites, blacks):
    """User input is number of whites, number of blacks."""
    validnums = '123456'
    print 'Current answer: %s' % curans
    print 'Num whites: %d' % whites
    print 'Num blacks: %d' % blacks
    num_blank = NUM_SPACES - whites - blacks
    num_keep = NUM_SPACES - num_blank

    itertools.product()
    
    itertools.permutation(validnums, num_keep)
Ejemplo n.º 2
0
def allpermutations(orgset, k):
    """
    returns all permutations of orgset with up to k items

    :param orgset: the list to be iterated
    :param k: the maxcardinality of the subsets

    :return: an iterator of the subsets

    example:

    >>> c = allpermutations([1,2,3,4],2)
    >>> for s in c:
    ...     print(s)
    (1,)
    (2,)
    (3,)
    (4,)
    (1, 2)
    (1, 3)
    (1, 4)
    (2, 1)
    (2, 3)
    (2, 4)
    (3, 1)
    (3, 2)
    (3, 4)
    (4, 1)
    (4, 2)
    (4, 3)
    """
    return itertools.chain(*[permutation(orgset, i) for i in range(1, k + 1)])
Ejemplo n.º 3
0
	def Permutation(self,ss):
		result = []
		if not ss:
			result []
		else:
			#itertools.permutation()  返回对象全排列的iterators(迭代器)
			#						  使用时用list()转换即可
			res = itertools.permutation(ss)
			for i in res:
				if ''.join(i) not in result:
					result.append(''.join(i))
		return  result
Ejemplo n.º 4
0
    def check_orientation(self):
        '''
			make sure that the orientation of single crystal is decided.
			if decided, unknown direction will be calculated and True will be returned. if not, return False
		'''

        vecs = self.vecs
        number_of_None = 0
        for vec in vecs:
            if vec is None:
                number_of_None += 1

        logging.debug("number of None is %d" % (number_of_None))

        if number_of_None in (2, 3):
            self.orientation_decided = False
            return False

        if number_of_None == 0:
            for pair in itertools.permutation(vecs, 2):
                if not pair[0].isperpendicular(pair[1]):
                    self.orientation_decided = False
                    logging.error(
                        'indexx, indexy, indexz is not perpendicular!')
                    return False

            v3 = vecs[0].cross(vecs[1])
            if vecs[2].isparallel(v3) != 1:
                logging.warning('three Vector may not be right-handed!')
                return False

            return True

        if number_of_None == 1:
            i_None, i1, i2 = -1, -1, -1
            for i, vec in enumerate(vecs):
                if vec is None:
                    i_None = i
                elif i1 == -1:
                    i1 = i
                else:
                    i2 = i

            vec_unknown = vecs[i1].cross(vecs[i2]).norm

            if i_None == 0:
                self.vecx = vec_unknown
            elif i_None == 1:
                self.vecy = -vec_unknown
            else:
                self.vecz = vec_unknown

            if not vecs[i1].isperpendicular(vecs[i2]):
                logging.warning(
                    'Vector %s and %s are not perpendicular, one Vector is adjusted!'
                    % (str(vecs[i1]), str(vecs[i2])))
                vec_new = vecs[i2].cross(vec_unknown)
                if i1 == 0:
                    self.vecx = vec_new
                elif i1 == 1:
                    self.vecy = vec_new
                else:
                    self.vecz = vec_new
                self.orientation_decided = True
            else:
                self.orientation_decided = True

            return True
Ejemplo n.º 5
0
def stableSolution(N, R, O, Y, G, B, V):
    if (G == R and N == G + R) or (O == B and N == O + B) or (V == Y
                                                              and N == V + Y):
        return ''.join(['GR' for _ in xrange(G)] + ['OB' for _ in xrange(O)] +
                       ['VY' for _ in xrange(V)])

    if (G > 0 and G + 1 > R) or (O > 0 and O + 1 > B) or (V > 0 and V + 1 > Y):
        return 'IMPOSSIBLE'

    remainingCounts = {}
    remainingCounts['R'] = R - ((G + 1) if G > 0 else 0)
    remainingCounts['B'] = B - ((O + 1) if O > 0 else 0)
    remainingCounts['Y'] = Y - ((V + 1) if V > 0 else 0)

    Gresult = ('R' + ''.join(['GR' for _ in xrange(G)]) if G > 0 else '')
    Oresult = ('B' + ''.join(['OB' for _ in xrange(O)]) if O > 0 else '')
    Vresult = ('Y' + ''.join(['VY' for _ in xrange(V)]) if V > 0 else '')

    if remainingCounts['R'] + remainingCounts['Y'] + remainingCounts['B'] == 0:
        result = Gresult + Oresult + Vresult
        if result[0] == result[-1]:
            return 'IMPOSSIBLE'
        return result

    complementaryCounts = {}
    complementaryCounts['R'] = G
    complementaryCounts['B'] = O
    complementaryCounts['Y'] = V

    result = ''
    sortedPrimaries = sorted(
        map(
            lambda color:
            (remainingCounts[color], -complementaryCounts[color], color),
            'RBY'))[::-1]
    [(n1, _, c1), (n2, _, c2), (n3, _, c3)] = sortedPrimaries
    if n1 > n2 + n3 + 2:
        return 'IMPOSSIBLE'
    print n1, n2, n3
    extraColor = c1
    extraAmount = max(n1 - (n2 + n3), 0)
    if extraAmount > 0:
        n1 -= extraAmount
    # n2 pairs of 12, followed by (n1 - n2) pairs of the 13, with remaining (n3 + n2 - n1) inserted in 12 pairs
    print n1, n2, n3
    for _ in xrange(n3 + n2 - n1):
        result += ''.join([c1, c3, c2])
        for c in [c1, c2, c3]:
            remainingCounts[c] -= 1
    for _ in xrange(n1 - n3):
        result += ''.join([c1, c2])
        for c in [c1, c2]:
            remainingCounts[c] -= 1
    for _ in xrange(n1 - n2):
        result += ''.join([c1, c3])
        for c in [c1, c3]:
            remainingCounts[c] -= 1

    for permutation in itertools.permutations(
        [extraColor for _ in xrange(extraAmount)] +
            filter(lambda x: len(x) > 0, [Oresult, Vresult, Gresult])):
        possibleString = [result] + list(permutation)
        L = len(possibleString)
        works = True
        for i in xrange(L):
            if possibleString[i % L][-1] == possibleString[(i + 1) % L][0]:
                works = False
                break
        if works:
            return ''.join(possibleString)

    if len(result) >= 3 and len(set(result[:3])) == 3:
        a = result[0]
        b = result[1]
        result = b + a + result[2:]
        for permutation in itertools.permutation(
            [extraColor for _ in xrange(extraAmount)] +
                filter(lambda x: len(x) > 0, [Oresult, Vresult, Gresult])):
            possibleString = [result] + permutation
            L = len(possibleString)
            works = True
            for i in xrange(L):
                if possibleString[i % L][-1] == possibleString[(i + 1) % L][0]:
                    works = False
                    break
            if works:
                return ''.join(possibleString)

    return 'IMPOSSIBLE'
Ejemplo n.º 6
0
import itertools

data = ['a', 'b', 'c']

result = itertools.permutation(data)
for res in result:
    print(res)
Ejemplo n.º 7
0
 def permute(self, nums: List[int]) -> List[List[int]]:
     return list(itertools.permutation(nums))
Ejemplo n.º 8
0
2. If no function will be pass,addition take place by default.If iterable will be empty, output iterable will be also empty.
3. Chain(iter1,iter2,....) ==> used to print all values 
4. We need to import itertools
= itertools.accumulate(list1)
= itertools.chain(list4) #list1+list2+list = list4
= itertools.chain.from_iterable(list3) #list3=[list1,list2]
= itertools.dropwhile() ==> This iterator start printing the characters only after the function in argument.Return false for first time.
= itertools.filterfalse(func,seq) ==> As the name suggest, this iterator prints only values that return false for passed function.
= itertools.isslice(iterable,start,stop,step)
= itertools.starmap(function,tuplelist)
= itertools.starmap(max,list)
= itertools.starmap(min,list)
= itertools.takewhile(func,iterator)
= itertools.tee(func,iterable)
= itertools.product(iter1,iter2)
= itertools.permutation(iter1,group=size)
= itertools.combination(iter1,group=size)
= itertools.combination_with_replacement(iter1,group=size)
= itertools.count(start,stop)
= itertools.cycle(iterable)
= itertools.repeat(val,num)
=====================================
import itertools 
import operator 
li1 = [1, 4, 5, 7] 
li2 = [1, 6, 5, 9] 
li3 = [8, 10, 5, 4] 
print ("The sum after each iteration is : ",end="") 
print (list(itertools.accumulate(li1))) 
print ("The product after each iteration is : ",end="") 
print (list(itertools.accumulate(li1,operator.mul))) 
Ejemplo n.º 9
0
2. If no function will be pass,addition take place by default.If iterable will be empty, output iterable will be also empty.
3. Chain(iter1,iter2,....) --> used to print all values 
4. We need to import itertools
- itertools.accumulate(list1)
- itertools.chain(list4) #list1+list2+list = list4
- itertools.chain.from_iterable(list3) #list3=[list1,list2]
- itertools.dropwhile() --> This iterator start printing the characters only after the function in argument.Return false for first time.
- itertools.filterfalse(func,seq) --> As the name suggest, this iterator prints only values that return false for passed function.
- itertools.isslice(iterable,start,stop,step)
- itertools.starmap(function,tuplelist)
- itertools.starmap(max,list)
- itertools.starmap(min,list)
- itertools.takewhile(func,iterator)
- itertools.tee(func,iterable)
- itertools.product(iter1,iter2)
- itertools.permutation(iter1,group-size)
- itertools.combination(iter1,group-size)
- itertools.combination_with_replacement(iter1,group-size)
- itertools.count(start,stop)
- itertools.cycle(iterable)
- itertools.repeat(val,num)
=====================================
import itertools 
import operator 
li1 = [1, 4, 5, 7] 
li2 = [1, 6, 5, 9] 
li3 = [8, 10, 5, 4] 
print ("The sum after each iteration is : ",end="") 
print (list(itertools.accumulate(li1))) 
print ("The product after each iteration is : ",end="") 
print (list(itertools.accumulate(li1,operator.mul))) 
Ejemplo n.º 10
0
def allpermutation(str):
    perlist = permutation(str)
    for perm in list(perlist):
        print(''.join(perm))
Ejemplo n.º 11
0
def best_hand(hand):
    return max(itertools.permutation(hand,5), hand_rank)