本文整理匯總了Python中past.builtins.range方法的典型用法代碼示例。如果您正苦於以下問題:Python builtins.range方法的具體用法?Python builtins.range怎麽用?Python builtins.range使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類past.builtins
的用法示例。
在下文中一共展示了builtins.range方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_check_type_and_size_of_param_list
# 需要導入模塊: from past import builtins [as 別名]
# 或者: from past.builtins import range [as 別名]
def test_check_type_and_size_of_param_list(self):
"""
Ensure that a ValueError is raised if param_list is not a list with the
expected number of elements
"""
expected_length = 4
bad_param_list_1 = set(range(4))
bad_param_list_2 = range(5)
# Note that for the purposes of the function being tested, good is
# defined as a list with four elements. Other functions check the
# content of those elements
good_param_list = range(4)
for param_list in [bad_param_list_1, bad_param_list_2]:
self.assertRaises(ValueError,
base_cm.check_type_and_size_of_param_list,
param_list,
expected_length)
args = [good_param_list, expected_length]
func_results = base_cm.check_type_and_size_of_param_list(*args)
self.assertIsNone(func_results)
return None
示例2: fcmp
# 需要導入模塊: from past import builtins [as 別名]
# 或者: from past.builtins import range [as 別名]
def fcmp(x, y): # fuzzy comparison function
"""
From Python 2.7 test.test_support
"""
if isinstance(x, float) or isinstance(y, float):
try:
fuzz = (abs(x) + abs(y)) * FUZZ
if abs(x-y) <= fuzz:
return 0
except:
pass
elif type(x) == type(y) and isinstance(x, (tuple, list)):
for i in range(min(len(x), len(y))):
outcome = fcmp(x[i], y[i])
if outcome != 0:
return outcome
return (len(x) > len(y)) - (len(x) < len(y))
return (x > y) - (x < y)
示例3: test_basic
# 需要導入模塊: from past import builtins [as 別名]
# 或者: from past.builtins import range [as 別名]
def test_basic(self):
data = range(100)
copy = data[:]
random.shuffle(copy)
self.assertEqual(data, sorted(copy))
self.assertNotEqual(data, copy)
data.reverse()
random.shuffle(copy)
self.assertEqual(data, sorted(copy, cmp=lambda x, y: cmp(y,x)))
self.assertNotEqual(data, copy)
random.shuffle(copy)
self.assertEqual(data, sorted(copy, key=lambda x: -x))
self.assertNotEqual(data, copy)
random.shuffle(copy)
self.assertEqual(data, sorted(copy, reverse=1))
self.assertNotEqual(data, copy)
示例4: get_bonds
# 需要導入模塊: from past import builtins [as 別名]
# 或者: from past.builtins import range [as 別名]
def get_bonds(self, typ=None, mode=None):
'''
Gives a generator to iterate throught bonds in
this interface. If no type given, bonds of all types
returned.
'''
if typ is None:
typ = self.types
if type(typ) is str:
typ = [typ]
for t in typ:
if t in self.__dict__:
for i in range(0, len(self.__dict__[t])):
if mode == 'dict':
yield {
self.id_a: self.__dict__[t][self.id_a][i],
self.id_b: self.id_b,
'res_b': self.__dict__[t][self.id_b][i],
'type': t
}
else:
yield (self.id_a,) + self.__dict__[t][self.id_a][i] + \
(self.id_b,) + self.__dict__[t][self.id_b][i] + \
(t,)
示例5: decode_chunk
# 需要導入模塊: from past import builtins [as 別名]
# 或者: from past.builtins import range [as 別名]
def decode_chunk(raw_logits, use_random, decode_times):
tree_decoder = create_tree_decoder()
chunk_result = [[] for _ in range(raw_logits.shape[1])]
for i in tqdm(range(raw_logits.shape[1])):
pred_logits = raw_logits[:, i, :]
walker = ConditionalDecoder(np.squeeze(pred_logits), use_random)
for _decode in range(decode_times):
new_t = Node('smiles')
try:
tree_decoder.decode(new_t, walker)
sampled = get_smiles_from_tree(new_t)
except Exception as ex:
if not type(ex).__name__ == 'DecodingLimitExceeded':
print('Warning, decoder failed with', ex)
# failed. output a random junk.
import random, string
sampled = 'JUNK' + ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(256))
chunk_result[i].append(sampled)
return chunk_result
示例6: run_job
# 需要導入模塊: from past import builtins [as 別名]
# 或者: from past.builtins import range [as 別名]
def run_job(L):
chunk_size = 5000
list_binary = Parallel(n_jobs=cmd_args.data_gen_threads, verbose=50)(
delayed(process_chunk)(L[start: start + chunk_size])
for start in range(0, len(L), chunk_size)
)
all_onehot = np.zeros((len(L), cmd_args.max_decode_steps, DECISION_DIM), dtype=np.byte)
all_masks = np.zeros((len(L), cmd_args.max_decode_steps, DECISION_DIM), dtype=np.byte)
for start, b_pair in zip( range(0, len(L), chunk_size), list_binary ):
all_onehot[start: start + chunk_size, :, :] = b_pair[0]
all_masks[start: start + chunk_size, :, :] = b_pair[1]
return all_onehot, all_masks
示例7: decode_chunk
# 需要導入模塊: from past import builtins [as 別名]
# 或者: from past.builtins import range [as 別名]
def decode_chunk(raw_logits, use_random, decode_times):
tree_decoder = ProgTreeDecoder()
chunk_result = [[] for _ in range(raw_logits.shape[1])]
for i in tqdm(range(raw_logits.shape[1])):
pred_logits = raw_logits[:, i, :]
walker = ConditionalProgramDecoder(np.squeeze(pred_logits), use_random)
for _decode in range(decode_times):
new_t = Node('program')
try:
tree_decoder.decode(new_t, walker)
sampled = get_program_from_tree(new_t)
except Exception as ex:
print('Warning, decoder failed with', ex)
# failed. output a random junk.
import random, string
sampled = 'JUNK' + ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(256))
chunk_result[i].append(sampled)
return chunk_result
示例8: crc16
# 需要導入模塊: from past import builtins [as 別名]
# 或者: from past.builtins import range [as 別名]
def crc16(string, value=0):
"""CRC-16 poly: p(x) = x**16 + x**15 + x**2 + 1
@param string: Data over which to calculate crc.
@param value: Initial CRC value.
"""
crc16_table = []
for byte in range(256):
crc = 0
for _ in range(8):
if (byte ^ crc) & 1:
crc = (crc >> 1) ^ 0xA001 # polly
else:
crc >>= 1
byte >>= 1
crc16_table.append(crc)
for ch in string:
value = crc16_table[ord(ch) ^ (value & 0xFF)] ^ (value >> 8)
return value
示例9: test_check_param_list_validity
# 需要導入模塊: from past import builtins [as 別名]
# 或者: from past.builtins import range [as 別名]
def test_check_param_list_validity(self):
"""
Go thorough all possible types of 'bad' param_list arguments and
ensure that the appropriate ValueErrors are raised. Ensure that 'good'
param_list arguments make it through the function successfully
"""
# Create a series of good parameter lists that should make it through
# check_param_list_validity()
good_list_1 = None
good_list_2 = [np.zeros(1), np.ones(2), np.ones(2), np.ones(2)]
good_list_3 = [np.zeros((1, 3)),
np.ones((2, 3)),
np.ones((2, 3)),
np.ones((2, 3))]
good_lists = [good_list_1, good_list_2, good_list_3]
# Create a series of bad parameter lists that should all result in
# ValueErrors being raised.
bad_list_1 = set(range(4))
bad_list_2 = range(5)
bad_list_3 = ['foo', np.zeros(2)]
bad_list_4 = [np.zeros(2), 'foo']
bad_list_5 = [np.zeros((2, 3)), np.zeros((2, 4))]
bad_list_6 = [np.zeros((2, 3)), np.ones(2)]
bad_list_7 = [np.zeros(3), np.ones((2, 3))]
bad_lists = [bad_list_1, bad_list_2, bad_list_3,
bad_list_4, bad_list_5, bad_list_6,
bad_list_7]
# Alias the function of interest to ensure it fits on one line
func = self.model_obj.check_param_list_validity
for param_list in good_lists:
self.assertIsNone(func(param_list))
for param_list in bad_lists:
self.assertRaises(ValueError, func, param_list)
return None
示例10: test_max
# 需要導入模塊: from past import builtins [as 別名]
# 或者: from past.builtins import range [as 別名]
def test_max(self):
self.assertEqual(max('123123'), '3')
self.assertEqual(max(1, 2, 3), 3)
self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3)
self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3)
self.assertEqual(max(1, 2, 3.0), 3.0)
self.assertEqual(max(1, 2.0, 3), 3)
self.assertEqual(max(1.0, 2, 3), 3)
for stmt in (
"max(key=int)", # no args
"max(1, key=int)", # single arg not iterable
"max(1, 2, keystone=int)", # wrong keyword
"max(1, 2, key=int, abc=int)", # two many keywords
"max(1, 2, key=1)", # keyfunc is not callable
):
try:
exec(stmt) in globals()
except TypeError:
pass
else:
self.fail(stmt)
self.assertEqual(max((1,), key=neg), 1) # one elem iterable
self.assertEqual(max((1,2), key=neg), 1) # two elem iterable
self.assertEqual(max(1, 2, key=neg), 1) # two elems
data = [random.randrange(200) for i in range(100)]
keys = dict((elem, random.randrange(50)) for elem in data)
f = keys.__getitem__
self.assertEqual(max(data, key=f),
sorted(reversed(data), key=f)[-1])
示例11: test_next
# 需要導入模塊: from past import builtins [as 別名]
# 或者: from past.builtins import range [as 別名]
def test_next(self):
it = iter(range(2))
self.assertEqual(next(it), 0)
self.assertEqual(next(it), 1)
self.assertRaises(StopIteration, next, it)
self.assertRaises(StopIteration, next, it)
self.assertEqual(next(it, 42), 42)
class Iter(object):
def __iter__(self):
return self
def next(self):
raise StopIteration
it = iter(Iter())
self.assertEqual(next(it, 42), 42)
self.assertRaises(StopIteration, next, it)
def gen():
yield 1
return
it = gen()
self.assertEqual(next(it), 1)
self.assertRaises(StopIteration, next, it)
self.assertEqual(next(it, 42), 42)
示例12: test_reduce
# 需要導入模塊: from past import builtins [as 別名]
# 或者: from past.builtins import range [as 別名]
def test_reduce(self):
add = lambda x, y: x+y
self.assertEqual(reduce(add, ['a', 'b', 'c'], ''), 'abc')
self.assertEqual(
reduce(add, [['a', 'c'], [], ['d', 'w']], []),
['a','c','d','w']
)
self.assertEqual(reduce(lambda x, y: x*y, range(2,8), 1), 5040)
self.assertEqual(
reduce(lambda x, y: x*y, range(2,21), 1),
2432902008176640000
)
self.assertEqual(reduce(add, Squares(10)), 285)
self.assertEqual(reduce(add, Squares(10), 0), 285)
self.assertEqual(reduce(add, Squares(0), 0), 0)
self.assertRaises(TypeError, reduce)
self.assertRaises(TypeError, reduce, 42)
self.assertRaises(TypeError, reduce, 42, 42)
self.assertRaises(TypeError, reduce, 42, 42, 42)
self.assertRaises(TypeError, reduce, None, range(5))
self.assertRaises(TypeError, reduce, add, 42)
self.assertEqual(reduce(42, "1"), "1") # func is never called with one item
self.assertEqual(reduce(42, "", "1"), "1") # func is never called with one item
self.assertRaises(TypeError, reduce, 42, (42, 42))
self.assertRaises(TypeError, reduce, add, []) # arg 2 must not be empty sequence with no initial value
self.assertRaises(TypeError, reduce, add, "")
self.assertRaises(TypeError, reduce, add, ())
self.assertEqual(reduce(add, [], None), None)
self.assertEqual(reduce(add, [], 42), 42)
class BadSeq:
def __getitem__(self, index):
raise ValueError
self.assertRaises(ValueError, reduce, 42, BadSeq())
示例13: test_noniterators_produce_lists
# 需要導入模塊: from past import builtins [as 別名]
# 或者: from past.builtins import range [as 別名]
def test_noniterators_produce_lists(self):
l = range(10)
self.assertTrue(isinstance(l, list))
l2 = zip(l, list('ABCDE')*2)
self.assertTrue(isinstance(l2, list))
double = lambda x: x*2
l3 = map(double, l)
self.assertTrue(isinstance(l3, list))
is_odd = lambda x: x % 2 == 1
l4 = filter(is_odd, range(10))
self.assertEqual(l4, [1, 3, 5, 7, 9])
self.assertTrue(isinstance(l4, list))
示例14: hex2rgb
# 需要導入模塊: from past import builtins [as 別名]
# 或者: from past.builtins import range [as 別名]
def hex2rgb(self, rgbhex):
rgbhex = rgbhex.lstrip('#')
lv = len(rgbhex)
return tuple(int(rgbhex[i:i + 2], 16) for i in range(0, lv, 2))
示例15: colnames
# 需要導入模塊: from past import builtins [as 別名]
# 或者: from past.builtins import range [as 別名]
def colnames(self):
# font size for labels:
self.xlabpt = self.max_text(self.xlabs, self.cellw)
y = self.margin[2] + self.ycoo[0] + self.ycoo[1] / 2.0
for xi in range(2, len(self.xcoo)):
x = self.margin[0] + sum(self.xcoo[:xi]) + self.cellw / 2.0
lab = self.xlabs[xi - 2]
self.label(lab, x, y, self.xlabpt, self.colors['embl_gray875'])