def extract_val(self) -> Any: val = None if self.raw.HasField("any_val"): val = self.raw.any_val elif self.raw.HasField("ascii_val"): val = self.raw.ascii_val elif self.raw.HasField("bool_val"): val = self.raw.bool_val elif self.raw.HasField("bytes_val"): val = base64.b64encode(self.raw.bytes_val) elif self.raw.HasField("decimal_val"): val = self.raw.decimal_val val = Decimal(str(val.digits / 10**val.precision)) elif self.raw.HasField("float_val"): val = self.raw.float_val elif self.raw.HasField("int_val"): val = self.raw.int_val elif self.raw.HasField("json_ietf_val"): val = json.loads(self.raw.json_ietf_val) elif self.raw.HasField("json_val"): val = json.loads(self.raw.json_val) elif self.raw.HasField("leaflist_val"): val = [] for elem in self.raw.leaflist_val.element: val.append(TypedValue_(elem).extract_val()) elif self.raw.HasField("proto_bytes"): val = self.raw.proto_bytes elif self.raw.HasField("string_val"): val = self.raw.string_val elif self.raw.HasField("uint_val"): val = self.raw.uint_val else: raise ValueError("Unhandled typed value %s" % self.raw) return val
def name_value_extractor(token_generator): """ Generator to extract a name and value from input. Yields tuples of the form (name, value). Input format should be of form: name value1 [value2 value3 ...]; terminating with semicolon. If multiple values are present, they are summed. For the special case where "name" begins with "CapGains" (case- insensitive), the values extracted are 2-tuples containing a numeric value representing the gain, and a length of time (in days). In the future, a 3-tuple may contain the gain, the length of time, and a comment. """ field_name = re.compile(r'^[' + string.ascii_letters + r']') capgain_name = re.compile(r'cap-?gain', re.IGNORECASE) semicolon = re.compile(r'^;'); name = None value = Decimal(0.0) cap_gains_capture = False for token in token_generator: if re.match(capgain_name, token): log.debug("Interpreted token {0} as special cap gain field name.".format(token)) cap_gains_capture = True name = token value = list() elif re.match(field_name, token): name = token elif re.match(semicolon, token): yield (name, value) if (cap_gains_capture): cap_gains_capture = False name = None value = Decimal(0.0) else: if (not cap_gains_capture): # TODO: make sure to convert string to clean number value += Decimal(token) else: ## Read tokens in following order: purchase price, purchase date, ## sale price, sale date ## by advancing through token_generator's values buy_price = Decimal(token) buy_date = date(token_generator.__next__()) sell_price = Decimal(token_generator.__next__()) sell_date = date(token_generator.__next__()) if (buy_price < 0): # Purchase prices should be negative(cost). buy_price *= -1 if (buy_date > sell_date): raise InputError( "Sell date {0} occurs after buy date {1}" .format(sell_date, buy_date)) ## Push back a tuple of form ( gain, days ) into the list value.append( (sell_price + buy_price, (sell_date - buy_date).days) )
def _calculate(self, rolls, environment): T = self._initializeViterbi() for roll in rolls: U = {} for next_state in DiceTypes: total = Decimal(0) argmax = [] valmax = Decimal(0) # prob = None # vpath = [] # vprobability = None for state in DiceTypes: objs = T[state] prob = Decimal(objs[0]) vpath = objs[1] vprobability = Decimal(objs[2]) trans_value = environment.get_transition_probability( state, next_state) env_value = environment.get_emission_probability( state, roll.roll_value) prop_value = env_value * trans_value prob = prob * prop_value vprobability = vprobability * prop_value total = total + prob if vprobability > valmax: argmax.clear() argmax.extend(vpath) argmax.append(next_state) valmax = vprobability U[next_state] = [total, argmax, valmax] T = U total = Decimal(0) argmax = [] valmax = Decimal(0) for state in DiceTypes: objs = T[state] prob = Decimal(objs[0]) vpath = objs[1] vprob = objs[2] total = total.append(prob) if vprob > valmax: argmax.clear() argmax.extend(vpath) valmax = vprob for k, v in T.items(): logger.info("{} {}".format(k, v)) return argmax
def _calculate(self, rolls, environment): T = self._initializeViterbi() for roll in rolls: U = {} for next_state in DiceTypes: total = Decimal(0) argmax = [] valmax = Decimal(0) # prob = None # vpath = [] # vprobability = None for state in DiceTypes: objs = T[state] prob = Decimal(objs[0]) vpath = objs[1] vprobability = Decimal(objs[2]) trans_value = environment.get_transition_probability(state, next_state) env_value = environment.get_emission_probability(state, roll.roll_value) prop_value = env_value * trans_value prob = prob * prop_value vprobability = vprobability * prop_value total = total + prob if vprobability > valmax: argmax.clear() argmax.extend(vpath) argmax.append(next_state) valmax = vprobability U[next_state] = [total, argmax, valmax] T = U total = Decimal(0) argmax = [] valmax = Decimal(0) for state in DiceTypes: objs = T[state] prob = Decimal(objs[0]) vpath = objs[1] vprob = objs [2] total = total.append(prob) if vprob > valmax: argmax.clear() argmax.extend(vpath) valmax = vprob for k, v in T.items(): logger.info("{} {}".format(k, v)) return argmax
def deserialize_decimals(value): """Counterpart to serialize_decimals(). Recursively turns dict representations of decimals back into decimal.Decimal objects. """ if isinstance(value, dict) and '__ftw_publisher_serialized_obj__' in value: if value.get('__type__') == 'Decimal': retval = Decimal(value.get('value_str')) elif isinstance(value, dict) or isinstance(value, PersistentMapping): retval = value.__class__() for key in value: retval[key] = deserialize_decimals(value[key]) elif isinstance(value, list) or isinstance(value, PersistentList): retval = value.__class__() for item in value: retval.append(deserialize_decimals(item)) else: retval = value return retval
def _read_item(buf, offset=0, unpack_from=unpack_from): ftype = buf[offset] offset += 1 # 'S': long string if ftype == 'S': slen, = unpack_from('>I', buf, offset) offset += 4 val = buf[offset:offset + slen] offset += slen # 's': short string elif ftype == 's': slen, = unpack_from('>B', buf, offset) offset += 1 val = buf[offset:offset + slen] offset += slen # 'b': short-short int elif ftype == 'b': val, = unpack_from('>B', buf, offset) offset += 1 # 'B': short-short unsigned int elif ftype == 'B': val, = unpack_from('>b', buf, offset) offset += 1 # 'U': short int elif ftype == 'U': val, = unpack_from('>h', buf, offset) offset += 2 # 'u': short unsigned int elif ftype == 'u': val, = unpack_from('>H', buf, offset) offset += 2 # 'I': long int elif ftype == 'I': val, = unpack_from('>i', buf, offset) offset += 4 # 'i': long unsigned int elif ftype == 'i': val, = unpack_from('>I', buf, offset) offset += 4 # 'L': long long int elif ftype == 'L': val, = unpack_from('>q', buf, offset) offset += 8 # 'l': long long unsigned int elif ftype == 'l': val, = unpack_from('>Q', buf, offset) offset += 8 # 'f': float elif ftype == 'f': val, = unpack_from('>f', buf, offset) offset += 4 # 'd': double elif ftype == 'd': val, = unpack_from('>d', buf, offset) offset += 8 # 'D': decimal elif ftype == 'D': d, = unpack_from('>B', buf, offset) offset += 1 n, = unpack_from('>i', buf, offset) offset += 4 val = Decimal(n) / Decimal(10 ** d) # 'F': table elif ftype == 'F': tlen, = unpack_from('>I', buf, offset) offset += 4 limit = offset + tlen val = {} while offset < limit: keylen, = unpack_from('>B', buf, offset) offset += 1 key = buf[offset:offset + keylen] offset += keylen val[key], offset = _read_item(buf, offset) # 'A': array elif ftype == 'A': alen, = unpack_from('>I', buf, offset) offset += 4 limit = offset + alen val = [] while offset < limit: v, offset = _read_item(buf, offset) val.append(v) # 't' (bool) elif ftype == 't': val, = unpack_from('>B', buf, offset) val = bool(val) offset += 1 # 'T': timestamp elif ftype == 'T': val, = unpack_from('>Q', buf, offset) offset += 8 val = datetime.utcfromtimestamp(val) # 'V': void elif ftype == 'V': val = None else: raise FrameSyntaxError( 'Unknown value in table: {0!r} ({1!r})'.format( ftype, type(ftype))) return val, offset
def _read_item(buf, offset=0, unpack_from=unpack_from, ftype_t=ftype_t): ftype = ftype_t(buf[offset]) if ftype_t else buf[offset] offset += 1 # 'S': long string if ftype == 'S': slen, = unpack_from('>I', buf, offset) offset += 4 val = _bytes_to_str(buf[offset:offset + slen]) offset += slen # rabbitmq implement 's' not as short string # see https://github.com/rabbitmq/rabbitmq-common/issues/261 # 's': short string # elif ftype == 's': # slen, = unpack_from('>B', buf, offset) # offset += 1 # val = _bytes_to_str(buf[offset:offset + slen]) # offset += slen # 'b': short-short int elif ftype == 'b': val, = unpack_from('>B', buf, offset) offset += 1 # 'B': short-short unsigned int elif ftype == 'B': val, = unpack_from('>b', buf, offset) offset += 1 # RabbitMQ implement 's' as short int # 'U': short int elif ftype in ['U', 's']: val, = unpack_from('>h', buf, offset) offset += 2 # 'u': short unsigned int elif ftype == 'u': val, = unpack_from('>H', buf, offset) offset += 2 # 'I': long int elif ftype == 'I': val, = unpack_from('>i', buf, offset) offset += 4 # 'i': long unsigned int elif ftype == 'i': val, = unpack_from('>I', buf, offset) offset += 4 # 'L': long long int elif ftype == 'L': val, = unpack_from('>q', buf, offset) offset += 8 # 'l': long long unsigned int elif ftype == 'l': val, = unpack_from('>Q', buf, offset) offset += 8 # 'f': float elif ftype == 'f': val, = unpack_from('>f', buf, offset) offset += 4 # 'd': double elif ftype == 'd': val, = unpack_from('>d', buf, offset) offset += 8 # 'D': decimal elif ftype == 'D': d, = unpack_from('>B', buf, offset) offset += 1 n, = unpack_from('>i', buf, offset) offset += 4 val = Decimal(n) / Decimal(10**d) # 'F': table elif ftype == 'F': tlen, = unpack_from('>I', buf, offset) offset += 4 limit = offset + tlen val = {} while offset < limit: keylen, = unpack_from('>B', buf, offset) offset += 1 key = _bytes_to_str(buf[offset:offset + keylen]) offset += keylen val[key], offset = _read_item(buf, offset) # 'A': array elif ftype == 'A': alen, = unpack_from('>I', buf, offset) offset += 4 limit = offset + alen val = [] while offset < limit: v, offset = _read_item(buf, offset) val.append(v) # 't' (bool) elif ftype == 't': val, = unpack_from('>B', buf, offset) val = bool(val) offset += 1 # 'T': timestamp elif ftype == 'T': val, = unpack_from('>Q', buf, offset) offset += 8 val = datetime.utcfromtimestamp(val) # 'V': void elif ftype == 'V': val = None else: raise FrameSyntaxError('Unknown value in table: {0!r} ({1!r})'.format( ftype, type(ftype))) return val, offset
import sys a = list(map(int, sys.stdin.readlines())) print(sum(a[1:])) Напишите программу, которая находит сумму чётных чисел в числового ряда. Формат входных данных Числовой ряд, заканчивающийся нулём. Формат выходных данных Сумма чётных чисел. import sys a = list(map(int, sys.stdin.readlines())) b = [] for i in a: if i%2 == 0: b.append(i) print(sum(b)) def count_char(text, char): count = 0 for c in text: if c == char: count += 1 return count a = int(input()) b = int(input()) print(int((a*(a//b) + b*(b//a))/(b//a+a//b)))
def _read_item(buf, offset): ftype = ftype_t(buf[offset]) if ftype_t else buf[offset] offset += 1 # 'S': long string if ftype == "S": (slen, ) = unpack_from(">I", buf, offset) offset += 4 try: val = pstr_t(buf[offset:offset + slen]) except UnicodeDecodeError: val = buf[offset:offset + slen] offset += slen # 's': short string elif ftype == "s": (slen, ) = unpack_from(">B", buf, offset) offset += 1 val = pstr_t(buf[offset:offset + slen]) offset += slen # 'x': Bytes Array elif ftype == "x": (blen, ) = unpack_from(">I", buf, offset) offset += 4 val = buf[offset:offset + blen] offset += blen # 'b': short-short int elif ftype == "b": (val, ) = unpack_from(">B", buf, offset) offset += 1 # 'B': short-short unsigned int elif ftype == "B": (val, ) = unpack_from(">b", buf, offset) offset += 1 # 'U': short int elif ftype == "U": (val, ) = unpack_from(">h", buf, offset) offset += 2 # 'u': short unsigned int elif ftype == "u": (val, ) = unpack_from(">H", buf, offset) offset += 2 # 'I': long int elif ftype == "I": (val, ) = unpack_from(">i", buf, offset) offset += 4 # 'i': long unsigned int elif ftype == "i": (val, ) = unpack_from(">I", buf, offset) offset += 4 # 'L': long long int elif ftype == "L": (val, ) = unpack_from(">q", buf, offset) offset += 8 # 'l': long long unsigned int elif ftype == "l": (val, ) = unpack_from(">Q", buf, offset) offset += 8 # 'f': float elif ftype == "f": (val, ) = unpack_from(">f", buf, offset) offset += 4 # 'd': double elif ftype == "d": (val, ) = unpack_from(">d", buf, offset) offset += 8 # 'D': decimal elif ftype == "D": (d, ) = unpack_from(">B", buf, offset) offset += 1 (n, ) = unpack_from(">i", buf, offset) offset += 4 val = Decimal(n) / Decimal(10**d) # 'F': table elif ftype == "F": (tlen, ) = unpack_from(">I", buf, offset) offset += 4 limit = offset + tlen val = {} while offset < limit: (keylen, ) = unpack_from(">B", buf, offset) offset += 1 key = pstr_t(buf[offset:offset + keylen]) offset += keylen val[key], offset = _read_item(buf, offset) # 'A': array elif ftype == "A": (alen, ) = unpack_from(">I", buf, offset) offset += 4 limit = offset + alen val = [] while offset < limit: v, offset = _read_item(buf, offset) val.append(v) # 't' (bool) elif ftype == "t": (val, ) = unpack_from(">B", buf, offset) val = bool(val) offset += 1 # 'T': timestamp elif ftype == "T": (val, ) = unpack_from(">Q", buf, offset) offset += 8 val = datetime.utcfromtimestamp(val) # 'V': void elif ftype == "V": val = None else: raise FrameSyntaxError("Unknown value in table: {0!r} ({1!r})".format( ftype, type(ftype))) return val, offset
a = 3 print(sq(5)) # expected 125 but 25 returned ### this happens because partial take the reference to the object ### assign another value to a create another object in memory def my_func_8(a, b): print(a, b) a = [1, 2] f5 = partial(my_func_8, a) f5(100) # [1, 2] 100 a.append(3) f5(100) # [1, 2, 3] 100 ### it is only mutate the internal state of the same object, reference to list ### is the same ## applications examples ### distance between two points origin = (0, 0) l = [(1, 1), (0, 2), (-3, 2), (0, 0), (10, 10)] dist2 = lambda a, b: (a[0] - b[0])**2 + (a[1] - b[1])**2 print(dist2((1, 1), origin)) # 2 print(sorted(l)) # doesn't work well
class GenericDataContainer: """A data container for storing some common Python types with some basic validation capabilities """ def __init__(self, result_set_name: str = 'anonymous', data_type: object = str, data_validator: DataValidator = None, logger=L): self.data = None self.data_type = data_type if data_type.__name__ == 'str': self.data = '' elif data_type.__name__ == 'list' or data_type.__name__ == 'tuple': self.data = list() elif data_type.__name__ == 'int': self.data = 0 elif data_type.__name__ == 'float': self.data = 0.0 elif data_type.__name__ == 'Decimal': self.data = Decimal('0.0') elif data_type.__name__ == 'dict': self.data = dict() else: raise Exception( 'Data type "{}" was not found in the current supported types: {}' .format(data_type.__name__, ('str', 'list', 'tuple', 'int', 'float', 'Decimal', 'dict'))) self.data_validator = None if data_validator is not None: if isinstance(data_validator, DataValidator): self.data_validator = data_validator logger.info( 'Using DataValidator implementation of "{}"'.format( self.data_validator.__class__.__name__)) else: raise Exception( 'Invalid data validator type. Expected an implementation of DataValidator' ) else: logger.warning('No data validator set') logger.info('GenericDataContainer "{}" ready'.format(result_set_name)) self.logger = logger self.result_set_name = result_set_name def _store_dict(self, data: object, key: object, **kwarg) -> int: if key is None: raise Exception( 'Expected a key value but found None (data_type was set to dict)' ) if key in self.data: self.logger.warning( 'Key "{}" already exists in dict - old value was replaced with new value' .format(key)) if self.data_validator is not None: if isinstance(self.data_validator, DataValidator): if not self.data_validator.validate(data=data, **kwarg): raise Exception('Dictionary validation failed') self.logger.info( 'Validation for value passed. key="{}"'.format(key)) else: # FIXME: The code below should be unreachable. Further scenarios in testing should be explored. self.logger.warning( 'No DataValidator set - Dictionary value for key "{}" stored without validation! [2]' .format(key)) # pragma: no cover else: self.logger.warning( 'No DataValidator set - Dictionary value for key "{}" stored without validation! [1]' .format(key)) self.data[key] = data return len(self.data) def _store_str(self, data: object, key: object = None, **kwarg) -> int: validated = False if self.data_validator is not None: if isinstance(self.data_validator, StringDataValidator): validated = True if not self.data_validator.validate(data=data, **kwarg): raise Exception('String validation failed') self.data = data if not validated: if data is None: self.data = None return 0 else: self.data = '{}'.format(data) return len(self.data) def _store_list(self, data: object, key: object = None, **kwarg) -> int: if self.data_validator is not None: if isinstance(self.data_validator, DataValidator): if not self.data_validator.validate(data=data, **kwarg): raise Exception('List item validation failed') self.logger.debug( 'Validation for value passed. New list size: {}'.format( len(self.data) + 1)) else: self.logger.warning( 'No DataValidator set - List value stored without validation! [2]. New list size: {}' .format(len(self.data) + 1)) self.data.append(data) return len(self.data) def _store_tuple(self, data: object, key: object = None, **kwarg) -> int: if data is None: raise Exception( 'Input data cannot be None - expecting a list or tuple') if type(data).__name__ not in ('list', 'tuple'): raise Exception('Expecting a list or tuple but got "{}"'.format( type(data))) if self.data_validator is not None: item_index = 0 for item in data: if not self.data_validator.validate(data=item, **kwarg): raise Exception( 'List item validation failed on item number {}'.format( item_index)) item_index = item_index + 1 self.logger.info( 'Validation for value passed. New list size: {}'.format( len(self.data) + 1)) if len(self.data) == 0 and type(self.data).__name__ == 'list': if type(data).__name__ == 'list': self.data = data self.data = tuple(self.data) elif type(data).__name__ == 'tuple': self.data = data else: raise Exception( 'Tuple already set. You have to create another GenericDataContainer instance to store another tuple' ) return len(self.data) def _store_int(self, data: object, key: object = None, **kwarg) -> int: if type(data).__name__ not in ('int', 'float', 'str'): raise Exception( 'Expecting a int, float or str but got "{}"'.format( type(data).__name__)) tmp_value = None if isinstance(data, str): tmp_value = int(float(data)) elif isinstance(data, float): tmp_value = int(data) elif isinstance(data, int): tmp_value = data self.data = tmp_value if self.data_validator is not None: if isinstance(self.data_validator, NumberDataValidator): if self.data_validator.validate(data=self.data, ** kwarg) is False: raise Exception('Input validation failed') else: raise Exception('Expected a NumberDataValidator') return 1 def _store_float(self, data: object, key: object = None, **kwarg) -> int: if isinstance(data, str): self.data = float(data) elif isinstance(data, int): self.data = float(data) elif isinstance(data, float): self.data = data else: raise Exception('Could not convert input data to float') if self.data_validator is not None: if isinstance(self.data_validator, NumberDataValidator): if self.data_validator.validate(data=self.data, ** kwarg) is False: raise Exception('Input validation failed') else: raise Exception('Expected a NumberDataValidator') return 1 def _store_decimal(self, data: object, key: object = None, **kwarg) -> int: if isinstance(data, str) or isinstance(data, int) or isinstance( data, float): self.data = Decimal(data) elif isinstance(data, Decimal): self.data = data else: raise Exception('Could not convert input data to Decimal') if self.data_validator is not None: if isinstance(self.data_validator, NumberDataValidator): if self.data_validator.validate(data=self.data, ** kwarg) is False: raise Exception('Input validation failed') else: raise Exception('Expected a NumberDataValidator') return 1 def store(self, data: object, key: object = None, **kwarg) -> int: if self.data_type.__name__ == 'dict': return self._store_dict(data=data, key=key, **kwarg) elif self.data_type.__name__ == 'str': return self._store_str(data=data, key=key, **kwarg) elif self.data_type.__name__ == 'list': return self._store_list(data=data, key=key, **kwarg) elif self.data_type.__name__ == 'tuple': return self._store_tuple(data=data, key=key, **kwarg) elif self.data_type.__name__ == 'int': return self._store_int(data=data, key=key, **kwarg) elif self.data_type.__name__ == 'float': return self._store_float(data=data, key=key, **kwarg) elif self.data_type.__name__ == 'Decimal': return self._store_decimal(data=data, key=key, **kwarg)