def test_afw_union_empty_states_2(self):
""" Tests a afw union where the second afw is empty """
union = AFW.afw_union(self.afw_union_1_test_01,
self.afw_union_test_empty)
i = 0
last = 7
while i <= last:
base = list(itertools.repeat('a', i))
base += list(itertools.repeat('b', i))
# build all permutation of 'a' and 'b' till length i
word_set = set(itertools.permutations(base, i))
for word in word_set:
word = list(word)
original_acceptance_1 = AFW.afw_word_acceptance(
self.afw_union_1_test_01, word)
original_acceptance_2 = AFW.afw_word_acceptance(
self.afw_union_test_empty, word)
union_acceptance = AFW.afw_word_acceptance(union, word)
self.assertEqual(
original_acceptance_1 or original_acceptance_2,
union_acceptance)
i += 1
python类permutations()的实例源码
def test_afw_intersection_disjoint(self):
""" Tests a correct afw intersection with completely disjoint afws """
AFW.rename_afw_states(self.afw_intersection_2_test_01, 'a_')
intersection = AFW.afw_intersection(self.afw_intersection_1_test_01,
self.afw_intersection_2_test_01)
i = 0
last = 7
while i <= last:
base = list(itertools.repeat('a', i))
base += list(itertools.repeat('b', i))
# build all permutation of 'a' and 'b' till length i
word_set = set(itertools.permutations(base, i))
for word in word_set:
word = list(word)
original_acceptance_1 = AFW.afw_word_acceptance(
self.afw_intersection_1_test_01, word)
original_acceptance_2 = AFW.afw_word_acceptance(
self.afw_intersection_2_test_01, word)
intersection_acceptance = AFW.afw_word_acceptance(intersection,
word)
self.assertEqual(
original_acceptance_1 and original_acceptance_2,
intersection_acceptance)
i += 1
def test_afw_intersection_equals(self):
""" Tests a correct afw intersection with the same afw """
AFW.rename_afw_states(self.afw_intersection_1_test_01, 'a_')
intersection = AFW.afw_intersection(self.afw_intersection_1_test_01,
self.afw_intersection_1_test_01)
i = 0
last = 7
while i <= last:
base = list(itertools.repeat('a', i))
base += list(itertools.repeat('b', i))
# build all permutation of 'a' and 'b' till length i
word_set = set(itertools.permutations(base, i))
for word in word_set:
word = list(word)
original_acceptance_1 = AFW.afw_word_acceptance(
self.afw_intersection_1_test_01, word)
original_acceptance_2 = AFW.afw_word_acceptance(
self.afw_intersection_1_test_01, word)
intersection_acceptance = AFW.afw_word_acceptance(intersection,
word)
self.assertEqual(
original_acceptance_1 and original_acceptance_2,
intersection_acceptance)
i += 1
def test_afw_intersection_empty_states_1(self):
""" Tests a afw intersection where the first afw is empty """
intersection = AFW.afw_intersection(self.afw_intersection_test_empty,
self.afw_intersection_1_test_01)
i = 0
last = 7
while i <= last:
base = list(itertools.repeat('a', i))
base += list(itertools.repeat('b', i))
# build all permutation of 'a' and 'b' till length i
word_set = set(itertools.permutations(base, i))
for word in word_set:
word = list(word)
original_acceptance_1 = AFW.afw_word_acceptance(
self.afw_intersection_1_test_01, word)
original_acceptance_2 = AFW.afw_word_acceptance(
self.afw_intersection_test_empty, word)
intersection_acceptance = AFW.afw_word_acceptance(intersection,
word)
self.assertEqual(
original_acceptance_1 and original_acceptance_2,
intersection_acceptance)
i += 1
def test_afw_intersection_empty_states_2(self):
""" Tests a afw intersection where the second afw is empty """
intersection = AFW.afw_intersection(self.afw_intersection_1_test_01,
self.afw_intersection_test_empty)
i = 0
last = 7
while i <= last:
base = list(itertools.repeat('a', i))
base += list(itertools.repeat('b', i))
# build all permutation of 'a' and 'b' till length i
word_set = set(itertools.permutations(base, i))
for word in word_set:
word = list(word)
original_acceptance_1 = AFW.afw_word_acceptance(
self.afw_intersection_1_test_01, word)
original_acceptance_2 = AFW.afw_word_acceptance(
self.afw_intersection_test_empty, word)
intersection_acceptance = AFW.afw_word_acceptance(intersection,
word)
self.assertEqual(
original_acceptance_1 and original_acceptance_2,
intersection_acceptance)
i += 1
def find_anagrams(word, dictionary):
"""Find all anagrams for a word.
This function only runs as fast as the test for
membership in the 'dictionary' container. It will
be slow if the dictionary is a list and fast if
it's a set.
Args:
word: String of the target word.
dictionary: Container with all strings that
are known to be actual words.
Returns:
List of anagrams that were found. Empty if
none were found.
"""
permutations = itertools.permutations(word, len(word))
possible = (''.join(x) for x in permutations)
found = {word for word in possible if word in dictionary}
return list(found)
def countArrangement(self, N):
"""
:type N: int
:rtype: int
"""
def judge(num, pos):
if not (num % pos) or not (pos % num):
return True
return False
from itertools import permutations
seq = range(1, N + 1)
seq_len = len(seq)
count = 0
for arrangement in (permutations(seq, seq_len)):
for index, ele in enumerate(arrangement, 1):
res = judge(ele, index)
if not res:
break
else:
count += 1
return count
def step_2(self):
'''
STEP 2: Set-Up Puzzle
- Extract Variable Names
- Populate Event Space
'''
first = self._find_first()
i = first
# print ('first var is ', self.prompt_text[first])
# print ('PROMPT', self.prompt_pairs)
# print ()
self.vars = self._collect_vars(i)
#print ('generating permutations...')
perms = list(itertools.permutations(self.vars))
print ('Possible permutations of {} variables: {}'.format(len(self.vars), len(perms)))
self.permutations = perms # before any rules
self.viable = perms # viable candidates after rule(s)
#print ()
return self.vars
def _winnow_all(self):
'''
Apply all the rules to the pool of conceivable permutations.
Winnow out those that satisfy all the rules.
Return: the winnowed pool as a list
'''
pool = self.viable
print ("With {} variables, the pool starts with {} permutations...".format(len(self.vars), len(pool)))
for i, rule in enumerate(self.rules):
print (" ", " ".join(rule.text_list))
pool = self._winnow_one(rule.output, pool)
print ("After rule {} pool size shrunk down to {}".format(i, len(pool)))
print ()
if len(pool)<10: # if the remaining pool is small, go ahead and print it
print(pool)
return pool
test_internals.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def test_equals_block_order_different_dtypes(self):
# GH 9330
mgr_strings = [
"a:i8;b:f8", # basic case
"a:i8;b:f8;c:c8;d:b", # many types
"a:i8;e:dt;f:td;g:string", # more types
"a:i8;b:category;c:category2;d:category2", # categories
"c:sparse;d:sparse_na;b:f8", # sparse
]
for mgr_string in mgr_strings:
bm = create_mgr(mgr_string)
block_perms = itertools.permutations(bm.blocks)
for bm_perm in block_perms:
bm_this = BlockManager(bm_perm, bm.axes)
self.assertTrue(bm.equals(bm_this))
self.assertTrue(bm_this.equals(bm))
def test_hf_state_plane_wave_basis_lowest_single_determinant_state(self):
grid_length = 7
dimension = 1
spinless = True
n_particles = 4
length_scale = 2.0
grid = Grid(dimension, grid_length, length_scale)
hamiltonian = jellium_model(grid, spinless)
hamiltonian_sparse = get_sparse_operator(hamiltonian)
hf_state = hartree_fock_state_jellium(grid, n_particles,
spinless, plane_wave=True)
HF_energy = expectation(hamiltonian_sparse, hf_state)
for occupied_orbitals in permutations(
[1] * n_particles + [0] * (grid_length - n_particles)):
state_index = numpy.sum(2 ** numpy.array(occupied_orbitals))
HF_competitor = csr_matrix(([1.0], ([state_index], [0])),
shape=(2 ** grid_length, 1))
self.assertLessEqual(
HF_energy, expectation(hamiltonian_sparse, HF_competitor))
def permutations(iterable):
pool = list(iterable)
n = len(pool)
indices = list(range(n))
cycles = list(range(n, n-r, -1))
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return
def _validate_options(cls, options):
"""Validate the mutually exclusive options.
Return `True` iff only zero or one of `BASE_ERROR_SELECTION_OPTIONS`
was selected.
"""
for opt1, opt2 in \
itertools.permutations(cls.BASE_ERROR_SELECTION_OPTIONS, 2):
if getattr(options, opt1) and getattr(options, opt2):
log.error('Cannot pass both {0} and {1}. They are '
'mutually exclusive.'.format(opt1, opt2))
return False
if options.convention and options.convention not in conventions:
log.error("Illegal convention '{0}'. Possible conventions: {1}"
.format(options.convention,
', '.join(conventions.keys())))
return False
return True
def find_routes(primaries, currencies, pairs):
"""
Find all permutations of trade routes for pairs
"""
discovered = []
for c in currencies:
for p in permutations(c, 3):
# We want to end with the beginning currency
p = p + (p[0],)
if not p in discovered and \
has_two_primary(primaries, p) and \
valid_pairs(pairs, p):
discovered.append(p)
yield p
def main():
count = 0
start = time.time()
for i in itertools.permutations(range(1, 10), 9):
if cube3(i):
count += 1
flag = 1
print('result %d:' % (count))
for k in i:
print('%d ' % (k), end = '')
if not(flag % 3):
print()
flag += 1
end = time.time()
print('time:', end - start)
print('total:', count)
def csg_check(self, li, writer):
m = writer(self._m)
r = uncurry(writer(self._r))
old_value = None
mapped = map(m, li)
if self._flattened:
mapped = flatten(mapped)
for permuted in itertools.permutations(mapped):
if self._keyed:
reduced = []
for k, v in collect(permuted):
reduced.append( (k, reduce(r, v)) )
else:
reduced = reduce(r, permuted)
if isinstance(reduced, list):
return sorted(reduced)
if old_value and (reduced != old_value):
return False
else:
old_value = reduced
return True
def gen_passwords(wordset, minlen, maxlen, permute, skip):
combinations, skip = drop_combinations(skip, wordset, permute)
variations = []
for combination in combinations:
if (len(''.join(combination)) < minlen
or len(''.join(combination)) > maxlen):
continue
if permute:
permutations, skip = drop_permutations(skip, combination)
for permutation in permutations:
variations = chain(variations, leet_word(''.join(permutation)))
else:
variations = chain(variations, leet_word(''.join(combination)))
try:
drop(skip, variations)
except AttributeError:
return
yield from variations
def test_drop_permutations():
combination = ('ha', 'bc', 'de')
varnum = variations_number(''.join(combination))
permutations, iteration = drop_permutations(0, combination)
assert (list(permutations) ==
[('ha', 'bc', 'de'), ('ha', 'de', 'bc'), ('bc', 'ha', 'de'),
('bc', 'de', 'ha'), ('de', 'ha', 'bc'), ('de', 'bc', 'ha')])
assert iteration == 0
permutations, iteration = drop_permutations(varnum-1, combination)
assert (list(permutations) ==
[('ha', 'bc', 'de'), ('ha', 'de', 'bc'), ('bc', 'ha', 'de'),
('bc', 'de', 'ha'), ('de', 'ha', 'bc'), ('de', 'bc', 'ha')])
assert iteration == varnum-1
permutations, iteration = drop_permutations(varnum+1, combination)
assert (list(permutations) ==
[ ('ha', 'de', 'bc'), ('bc', 'ha', 'de'),
('bc', 'de', 'ha'), ('de', 'ha', 'bc'), ('de', 'bc', 'ha')])
assert iteration == 1
def multipath_computation(self):
edges = []
self.mp_config = {}
for dpid, switch in self.dpid_to_switch.iteritems():
# Updating the capacity_maxflow variable which will be
# modified by the algorithm with the realtime monitored capacity
for port_no, port in switch.ports.iteritems():
port.capacity_maxflow = port.capacity
# Adding the edge switches to a list
if switch.edge_port:
edges.append(switch)
# Calculate forwarding paths between all edges couples
logger.info('%s', self.dpid_to_switch)
for edge_couple in itertools.permutations(edges, 2):
self.calculate_multipath(edge_couple[0], edge_couple[1])
self.create_flow_rules(edge_couple[0], edge_couple[1])
logger.info('-' * 20)
def _all_string_prefixes():
# The valid string prefixes. Only contain the lower case versions,
# and don't contain any permuations (include 'fr', but not
# 'rf'). The various permutations will be generated.
_valid_string_prefixes = ['b', 'r', 'u', 'f', 'br', 'fr']
# if we add binary f-strings, add: ['fb', 'fbr']
result = set([''])
for prefix in _valid_string_prefixes:
for t in _itertools.permutations(prefix):
# create a list with upper and lower versions of each
# character
for u in _itertools.product(*[(c, c.upper()) for c in t]):
result.add(''.join(u))
return result