content
stringlengths
7
1.05M
def insertion_sort(lst): """ Sorts list using insertion sort :param lst: list of unsorted elements :return comp: number of comparisons """ comp = 0 for i in range(1, len(lst)): key = lst[i] j = i - 1 cur_comp = 0 while j >= 0 and key < lst[j]: lst[j + 1] = lst[j] j -= 1 cur_comp += 1 comp += cur_comp if cur_comp == 0: comp += 1 lst[j + 1] = key return comp
# Financial events the contract logs Transfer: __log__({_from: indexed(address), _to: indexed(address), _value: currency_value}) Buy: __log__({_buyer: indexed(address), _buy_order: currency_value}) Sell: __log__({_seller: indexed(address), _sell_order: currency_value}) Pay: __log__({_vendor: indexed(address), _amount: wei_value}) # Own shares of a company! company: public(address) total_shares: public(currency_value) price: public(int128 (wei / currency)) # Store ledger of stockholder holdings holdings: currency_value[address] # Setup company @public def __init__(_company: address, _total_shares: currency_value, initial_price: int128(wei / currency) ): assert _total_shares > 0 assert initial_price > 0 self.company = _company self.total_shares = _total_shares self.price = initial_price # Company holds all the shares at first, but can sell them all self.holdings[self.company] = _total_shares @public @constant def stock_available() -> currency_value: return self.holdings[self.company] # Give value to company and get stock in return @public @payable def buy_stock(): # Note: full amount is given to company (no fractional shares), # so be sure to send exact amount to buy shares buy_order: currency_value = floor(msg.value / self.price) # rounds down # There are enough shares to buy assert self.stock_available() >= buy_order # Take the shares off the market and give to stockholder self.holdings[self.company] -= buy_order self.holdings[msg.sender] += buy_order # Log the buy event log.Buy(msg.sender, buy_order) # So someone can find out how much they have @public @constant def get_holding(_stockholder: address) -> currency_value: return self.holdings[_stockholder] # The amount the company has on hand in cash @public @constant def cash() -> wei_value: return self.balance # Give stock back to company and get my money back! @public def sell_stock(sell_order: currency_value): assert sell_order > 0 # Otherwise, will fail at send() below # Can only sell as much stock as you own assert self.get_holding(msg.sender) >= sell_order # Company can pay you assert self.cash() >= (sell_order * self.price) # Sell the stock, send the proceeds to the user # and put the stock back on the market self.holdings[msg.sender] -= sell_order self.holdings[self.company] += sell_order send(msg.sender, sell_order * self.price) # Log sell event log.Sell(msg.sender, sell_order) # Transfer stock from one stockholder to another # (Assumes the receiver is given some compensation, but not enforced) @public def transfer_stock(receiver: address, transfer_order: currency_value): assert transfer_order > 0 # AUDIT revealed this! # Can only trade as much stock as you own assert self.get_holding(msg.sender) >= transfer_order # Debit sender's stock and add to receiver's address self.holdings[msg.sender] -= transfer_order self.holdings[receiver] += transfer_order # Log the transfer event log.Transfer(msg.sender, receiver, transfer_order) # Allows the company to pay someone for services rendered @public def pay_bill(vendor: address, amount: wei_value): # Only the company can pay people assert msg.sender == self.company # And only if there's enough to pay them with assert self.cash() >= amount # Pay the bill! send(vendor, amount) # Log payment event log.Pay(vendor, amount) # The amount a company has raised in the stock offering @public @constant def debt() -> wei_value: return (self.total_shares - self.holdings[self.company]) * self.price # The balance sheet of the company @public @constant def worth() -> wei_value: return self.cash() - self.debt()
n = int(input("Enter the number of of rows: ")) for i in range(1,n+1): for j in range(1,i+1): print(j,end="") print()
def verify_format(_, res): return res def format_index(body): # pragma: no cover """Format index data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = { 'id': body['id'].split('/', 1)[-1], 'fields': body['fields'] } if 'type' in body: result['type'] = body['type'] if 'name' in body: result['name'] = body['name'] if 'deduplicate' in body: result['deduplicate'] = body['deduplicate'] if 'sparse' in body: result['sparse'] = body['sparse'] if 'unique' in body: result['unique'] = body['unique'] if 'minLength' in body: result['min_length'] = body['minLength'] if 'geoJson' in body: result['geo_json'] = body['geoJson'] if 'ignoreNull' in body: result['ignore_none'] = body['ignoreNull'] if 'selectivityEstimate' in body: result['selectivity'] = body['selectivityEstimate'] if 'isNewlyCreated' in body: result['new'] = body['isNewlyCreated'] if 'expireAfter' in body: result['expiry_time'] = body['expireAfter'] if 'inBackground' in body: result['in_background'] = body['inBackground'] if 'bestIndexedLevel' in body: result['best_indexed_level'] = body['bestIndexedLevel'] if 'worstIndexedLevel' in body: result['worst_indexed_level'] = body['worstIndexedLevel'] if 'maxNumCoverCells' in body: result['max_num_cover_cells'] = body['maxNumCoverCells'] return verify_format(body, result) def format_key_options(body): # pragma: no cover """Format collection key options data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'type' in body: result['key_generator'] = body['type'] if 'increment' in body: result['key_increment'] = body['increment'] if 'offset' in body: result['key_offset'] = body['offset'] if 'allowUserKeys' in body: result['user_keys'] = body['allowUserKeys'] if 'lastValue' in body: result['key_last_value'] = body['lastValue'] return verify_format(body, result) def format_database(body): # pragma: no cover """Format databases info. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'id' in body: result['id'] = body['id'] if 'name' in body: result['name'] = body['name'] if 'path' in body: result['path'] = body['path'] if 'system' in body: result['system'] = body['system'] if 'isSystem' in body: result['system'] = body['isSystem'] # Cluster only if 'sharding' in body: result['sharding'] = body['sharding'] if 'replicationFactor' in body: result['replication_factor'] = body['replicationFactor'] if 'writeConcern' in body: result['write_concern'] = body['writeConcern'] return verify_format(body, result) def format_collection(body): # pragma: no cover """Format collection data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'id' in body: result['id'] = body['id'] if 'objectId' in body: result['object_id'] = body['objectId'] if 'name' in body: result['name'] = body['name'] if 'isSystem' in body: result['system'] = body['isSystem'] if 'isSmart' in body: result['smart'] = body['isSmart'] if 'type' in body: result['type'] = body['type'] result['edge'] = body['type'] == 3 if 'waitForSync' in body: result['sync'] = body['waitForSync'] if 'status' in body: result['status'] = body['status'] if 'statusString' in body: result['status_string'] = body['statusString'] if 'globallyUniqueId' in body: result['global_id'] = body['globallyUniqueId'] if 'cacheEnabled' in body: result['cache'] = body['cacheEnabled'] if 'replicationFactor' in body: result['replication_factor'] = body['replicationFactor'] if 'minReplicationFactor' in body: result['min_replication_factor'] = body['minReplicationFactor'] if 'writeConcern' in body: result['write_concern'] = body['writeConcern'] # MMFiles only if 'doCompact' in body: result['compact'] = body['doCompact'] if 'journalSize' in body: result['journal_size'] = body['journalSize'] if 'isVolatile' in body: result['volatile'] = body['isVolatile'] if 'indexBuckets' in body: result['index_bucket_count'] = body['indexBuckets'] # Cluster only if 'shards' in body: result['shards'] = body['shards'] if 'replicationFactor' in body: result['replication_factor'] = body['replicationFactor'] if 'numberOfShards' in body: result['shard_count'] = body['numberOfShards'] if 'shardKeys' in body: result['shard_fields'] = body['shardKeys'] if 'distributeShardsLike' in body: result['shard_like'] = body['distributeShardsLike'] if 'shardingStrategy' in body: result['sharding_strategy'] = body['shardingStrategy'] if 'smartJoinAttribute' in body: result['smart_join_attribute'] = body['smartJoinAttribute'] # Key Generator if 'keyOptions' in body: result['key_options'] = format_key_options(body['keyOptions']) # Replication only if 'cid' in body: result['cid'] = body['cid'] if 'version' in body: result['version'] = body['version'] if 'allowUserKeys' in body: result['user_keys'] = body['allowUserKeys'] if 'planId' in body: result['plan_id'] = body['planId'] if 'deleted' in body: result['deleted'] = body['deleted'] # New in 3.7 if 'syncByRevision' in body: result['sync_by_revision'] = body['syncByRevision'] if 'tempObjectId' in body: result['temp_object_id'] = body['tempObjectId'] if 'usesRevisionsAsDocumentIds' in body: result['rev_as_id'] = body['usesRevisionsAsDocumentIds'] if 'isDisjoint' in body: result['disjoint'] = body['isDisjoint'] if 'isSmartChild' in body: result['smart_child'] = body['isSmartChild'] if 'minRevision' in body: result['min_revision'] = body['minRevision'] if 'schema' in body: result['schema'] = body['schema'] return verify_format(body, result) def format_aql_cache(body): """Format AQL cache data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = { 'mode': body['mode'], 'max_results': body['maxResults'], 'max_results_size': body['maxResultsSize'], 'max_entry_size': body['maxEntrySize'], 'include_system': body['includeSystem'] } return verify_format(body, result) def format_wal_properties(body): # pragma: no cover """Format WAL properties. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'allowOversizeEntries' in body: result['oversized_ops'] = body['allowOversizeEntries'] if 'logfileSize' in body: result['log_size'] = body['logfileSize'] if 'historicLogfiles' in body: result['historic_logs'] = body['historicLogfiles'] if 'reserveLogfiles' in body: result['reserve_logs'] = body['reserveLogfiles'] if 'syncInterval' in body: result['sync_interval'] = body['syncInterval'] if 'throttleWait' in body: result['throttle_wait'] = body['throttleWait'] if 'throttleWhenPending' in body: result['throttle_limit'] = body['throttleWhenPending'] return verify_format(body, result) def format_wal_transactions(body): # pragma: no cover """Format WAL transactions. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'minLastCollected' in body: result['last_collected'] = body['minLastCollected'] if 'minLastSealed' in body: result['last_sealed'] = body['minLastSealed'] if 'runningTransactions' in body: result['count'] = body['runningTransactions'] return verify_format(body, result) def format_aql_query(body): # pragma: no cover """Format AQL query data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {'id': body['id'], 'query': body['query']} if 'started' in body: result['started'] = body['started'] if 'state' in body: result['state'] = body['state'] if 'stream' in body: result['stream'] = body['stream'] if 'bindVars' in body: result['bind_vars'] = body['bindVars'] if 'runTime' in body: result['runtime'] = body['runTime'] return verify_format(body, result) def format_aql_tracking(body): # pragma: no cover """Format AQL tracking data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'enabled' in body: result['enabled'] = body['enabled'] if 'maxQueryStringLength' in body: result['max_query_string_length'] = body['maxQueryStringLength'] if 'maxSlowQueries' in body: result['max_slow_queries'] = body['maxSlowQueries'] if 'slowQueryThreshold' in body: result['slow_query_threshold'] = body['slowQueryThreshold'] if 'slowStreamingQueryThreshold' in body: result['slow_streaming_query_threshold'] = \ body['slowStreamingQueryThreshold'] if 'trackBindVars' in body: result['track_bind_vars'] = body['trackBindVars'] if 'trackSlowQueries' in body: result['track_slow_queries'] = body['trackSlowQueries'] return verify_format(body, result) def format_tick_values(body): # pragma: no cover """Format tick data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'tickMin' in body: result['tick_min'] = body['tickMin'] if 'tickMax' in body: result['tick_max'] = body['tickMax'] if 'tick' in body: result['tick'] = body['tick'] if 'time' in body: result['time'] = body['time'] if 'server' in body: result['server'] = format_server_info(body['server']) return verify_format(body, result) def format_server_info(body): # pragma: no cover """Format server data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ return {'version': body['version'], 'server_id': body['serverId']} def format_replication_applier_config(body): # pragma: no cover """Format replication applier configuration data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'endpoint' in body: result['endpoint'] = body['endpoint'] if 'database' in body: result['database'] = body['database'] if 'username' in body: result['username'] = body['username'] if 'verbose' in body: result['verbose'] = body['verbose'] if 'incremental' in body: result['incremental'] = body['incremental'] if 'requestTimeout' in body: result['request_timeout'] = body['requestTimeout'] if 'connectTimeout' in body: result['connect_timeout'] = body['connectTimeout'] if 'ignoreErrors' in body: result['ignore_errors'] = body['ignoreErrors'] if 'maxConnectRetries' in body: result['max_connect_retries'] = body['maxConnectRetries'] if 'lockTimeoutRetries' in body: result['lock_timeout_retries'] = body['lockTimeoutRetries'] if 'sslProtocol' in body: result['ssl_protocol'] = body['sslProtocol'] if 'chunkSize' in body: result['chunk_size'] = body['chunkSize'] if 'skipCreateDrop' in body: result['skip_create_drop'] = body['skipCreateDrop'] if 'autoStart' in body: result['auto_start'] = body['autoStart'] if 'adaptivePolling' in body: result['adaptive_polling'] = body['adaptivePolling'] if 'autoResync' in body: result['auto_resync'] = body['autoResync'] if 'autoResyncRetries' in body: result['auto_resync_retries'] = body['autoResyncRetries'] if 'maxPacketSize' in body: result['max_packet_size'] = body['maxPacketSize'] if 'includeSystem' in body: result['include_system'] = body['includeSystem'] if 'includeFoxxQueues' in body: result['include_foxx_queues'] = body['includeFoxxQueues'] if 'requireFromPresent' in body: result['require_from_present'] = body['requireFromPresent'] if 'restrictType' in body: result['restrict_type'] = body['restrictType'] if 'restrictCollections' in body: result['restrict_collections'] = body['restrictCollections'] if 'connectionRetryWaitTime' in body: result['connection_retry_wait_time'] = body['connectionRetryWaitTime'] if 'initialSyncMaxWaitTime' in body: result['initial_sync_max_wait_time'] = body['initialSyncMaxWaitTime'] if 'idleMinWaitTime' in body: result['idle_min_wait_time'] = body['idleMinWaitTime'] if 'idleMaxWaitTime' in body: result['idle_max_wait_time'] = body['idleMaxWaitTime'] return verify_format(body, result) def format_applier_progress(body): # pragma: no cover """Format replication applier progress data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'time' in body: result['time'] = body['time'] if 'message' in body: result['message'] = body['message'] if 'failedConnects' in body: result['failed_connects'] = body['failedConnects'] return verify_format(body, result) def format_applier_error(body): # pragma: no cover """Format replication applier error data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'errorNum' in body: result['error_num'] = body['errorNum'] if 'errorMessage' in body: result['error_message'] = body['errorMessage'] if 'time' in body: result['time'] = body['time'] return verify_format(body, result) def format_applier_state_details(body): # pragma: no cover """Format replication applier state details. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'started' in body: result['started'] = body['started'] if 'running' in body: result['running'] = body['running'] if 'phase' in body: result['phase'] = body['phase'] if 'time' in body: result['time'] = body['time'] if 'safeResumeTick' in body: result['safe_resume_tick'] = body['safeResumeTick'] if 'ticksBehind' in body: result['ticks_behind'] = body['ticksBehind'] if 'lastAppliedContinuousTick' in body: result['last_applied_continuous_tick'] = \ body['lastAppliedContinuousTick'] if 'lastProcessedContinuousTick' in body: result['last_processed_continuous_tick'] = \ body['lastProcessedContinuousTick'] if 'lastAvailableContinuousTick' in body: result['last_available_continuous_tick'] = \ body['lastAvailableContinuousTick'] if 'progress' in body: result['progress'] = format_applier_progress(body['progress']) if 'totalRequests' in body: result['total_requests'] = body['totalRequests'] if 'totalFailedConnects' in body: result['total_failed_connects'] = body['totalFailedConnects'] if 'totalEvents' in body: result['total_events'] = body['totalEvents'] if 'totalDocuments' in body: result['total_documents'] = body['totalDocuments'] if 'totalRemovals' in body: result['total_removals'] = body['totalRemovals'] if 'totalResyncs' in body: result['total_resyncs'] = body['totalResyncs'] if 'totalOperationsExcluded' in body: result['total_operations_excluded'] = body['totalOperationsExcluded'] if 'totalApplyTime' in body: result['total_apply_time'] = body['totalApplyTime'] if 'averageApplyTime' in body: result['average_apply_time'] = body['averageApplyTime'] if 'totalFetchTime' in body: result['total_fetch_time'] = body['totalFetchTime'] if 'averageFetchTime' in body: result['average_fetch_time'] = body['averageFetchTime'] if 'lastError' in body: result['last_error'] = format_applier_error(body['lastError']) return verify_format(body, result) def format_replication_applier_state(body): # pragma: no cover """Format replication applier state. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'endpoint' in body: result['endpoint'] = body['endpoint'] if 'database' in body: result['database'] = body['database'] if 'username' in body: result['username'] = body['username'] if 'state' in body: result['state'] = format_applier_state_details(body['state']) if 'server' in body: result['server'] = format_server_info(body['server']) return verify_format(body, result) def format_replication_state(body): # pragma: no cover """Format replication state. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ if not isinstance(body, dict): return body result = {} if 'running' in body: result['running'] = body['running'] if 'time' in body: result['time'] = body['time'] if 'lastLogTick' in body: result['last_log_tick'] = body['lastLogTick'] if 'totalEvents' in body: result['total_events'] = body['totalEvents'] if 'lastUncommittedLogTick' in body: result['last_uncommitted_log_tick'] = body['lastUncommittedLogTick'] return verify_format(body, result) def format_replication_logger_state(body): # pragma: no cover """Format replication collection data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'state' in body: result['state'] = format_replication_state(body['state']) if 'server' in body: result['server'] = format_server_info(body['server']) if 'clients' in body: result['clients'] = body['clients'] return verify_format(body, result) def format_replication_collection(body): # pragma: no cover """Format replication collection data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'planVersion' in body: result['plan_version'] = body['planVersion'] if 'isReady' in body: result['is_ready'] = body['isReady'] if 'allInSync' in body: result['all_in_sync'] = body['allInSync'] if 'indexes' in body: result['indexes'] = [format_index(index) for index in body['indexes']] if 'parameters' in body: result['parameters'] = format_collection(body['parameters']) return verify_format(body, result) def format_replication_database(body): # pragma: no cover """Format replication database data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = { 'id': body['id'], 'name': body['name'], 'collections': [ format_replication_collection(col) for col in body['collections'] ], 'views': [format_view(view) for view in body['views']] } if 'properties' in body: result['properties'] = format_database(body['properties']) return verify_format(body, result) def format_replication_inventory(body): # pragma: no cover """Format replication inventory data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'tick' in body: result['tick'] = body['tick'] if 'state' in body: result['state'] = format_replication_state(body['state']) if 'databases' in body: result['databases'] = { k: format_replication_database(v) for k, v in body['databases'].items() } if 'collections' in body: result['collections'] = [ format_replication_collection(col) for col in body['collections'] ] if 'views' in body: result['views'] = [format_view(view) for view in body['views']] if 'properties' in body: result['properties'] = format_database(body['properties']) return verify_format(body, result) def format_replication_sync(body): # pragma: no cover """Format replication sync result. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'collections' in body: result['collections'] = body['collections'] if 'lastLogTick' in body: result['last_log_tick'] = body['lastLogTick'] return verify_format(body, result) def format_replication_header(headers): # pragma: no cover """Format replication headers. :param headers: Request headers. :type headers: dict :return: Formatted body. :rtype: dict """ headers = {k.lower(): v for k, v in headers.items()} result = {} if 'x-arango-replication-frompresent' in headers: result['from_present'] = \ headers['x-arango-replication-frompresent'] == 'true' if 'x-arango-replication-lastincluded' in headers: result['last_included'] = \ headers['x-arango-replication-lastincluded'] if 'x-arango-replication-lastscanned' in headers: result['last_scanned'] = \ headers['x-arango-replication-lastscanned'] if 'x-arango-replication-lasttick' in headers: result['last_tick'] = \ headers['x-arango-replication-lasttick'] if 'x-arango-replication-active' in headers: result['active'] = \ headers['x-arango-replication-active'] == 'true' if 'x-arango-replication-checkmore' in headers: result['check_more'] = \ headers['x-arango-replication-checkmore'] == 'true' return result def format_view_link(body): # pragma: no cover """Format view link data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'analyzers' in body: result['analyzers'] = body['analyzers'] if 'fields' in body: result['fields'] = body['fields'] if 'includeAllFields' in body: result['include_all_fields'] = body['includeAllFields'] if 'trackListPositions' in body: result['track_list_positions'] = body['trackListPositions'] if 'storeValues' in body: result['store_values'] = body['storeValues'] return verify_format(body, result) def format_view_consolidation_policy(body): # pragma: no cover """Format view consolidation policy data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'type' in body: result['type'] = body['type'] if 'threshold' in body: result['threshold'] = body['threshold'] if 'segmentsMin' in body: result['segments_min'] = body['segmentsMin'] if 'segmentsMax' in body: result['segments_max'] = body['segmentsMax'] if 'segmentsBytesMax' in body: result['segments_bytes_max'] = body['segmentsBytesMax'] if 'segmentsBytesFloor' in body: result['segments_bytes_floor'] = body['segmentsBytesFloor'] if 'minScore' in body: result['min_score'] = body['minScore'] return verify_format(body, result) def format_view(body): # pragma: no cover """Format view data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'globallyUniqueId' in body: result['global_id'] = body['globallyUniqueId'] if 'id' in body: result['id'] = body['id'] if 'name' in body: result['name'] = body['name'] if 'type' in body: result['type'] = body['type'] if 'cleanupIntervalStep' in body: result['cleanup_interval_step'] = body['cleanupIntervalStep'] if 'commitIntervalMsec' in body: result['commit_interval_msec'] = body['commitIntervalMsec'] if 'consolidationIntervalMsec' in body: result['consolidation_interval_msec'] = \ body['consolidationIntervalMsec'] if 'consolidationPolicy' in body: result['consolidation_policy'] = \ format_view_consolidation_policy(body['consolidationPolicy']) if 'primarySort' in body: result['primary_sort'] = body['primarySort'] if 'primarySortCompression' in body: result['primary_sort_compression'] = body['primarySortCompression'] if 'storedValues' in body: result['stored_values'] = body['storedValues'] if 'writebufferIdle' in body: result['writebuffer_idle'] = body['writebufferIdle'] if 'writebufferActive' in body: result['writebuffer_active'] = body['writebufferActive'] if 'writebufferSizeMax' in body: result['writebuffer_max_size'] = body['writebufferSizeMax'] if 'links' in body: result['links'] = {link_key: format_view_link(link_content) for link_key, link_content in body['links'].items()} return verify_format(body, result) def format_vertex(body): # pragma: no cover """Format vertex data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ vertex = body['vertex'] if '_oldRev' in vertex: vertex['_old_rev'] = vertex.pop('_oldRev') if 'new' in body or 'old' in body: result = {'vertex': vertex} if 'new' in body: result['new'] = body['new'] if 'old' in body: result['old'] = body['old'] return result else: return vertex def format_edge(body): # pragma: no cover """Format edge data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ edge = body['edge'] if '_oldRev' in edge: edge['_old_rev'] = edge.pop('_oldRev') if 'new' in body or 'old' in body: result = {'edge': edge} if 'new' in body: result['new'] = body['new'] if 'old' in body: result['old'] = body['old'] return result else: return edge def format_tls(body): # pragma: no cover """Format TLS data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = body return verify_format(body, result)
# exc. 9.1.2 def file_options(file_name, task): if task == 'sort': edit_file = open(file_name, 'r') file_list = edit_file.read().split(' ') print(sorted(file_list)) edit_file.close() elif task == 'rev': edit_file = open(file_name, 'r') for line in edit_file: print(line[::-1]) edit_file.close() elif task == 'last': n = int(input('Enter a number: ')) n = n * (-1) file_list = [] edit_file = open(file_name, 'r') for line in edit_file: file_list += [line] file_list = file_list[n:] for line in file_list: print(line) #print(file_list[n:], sep="\n") def main(): file_name = "C:\\Users\\user\\Desktop\\sampleFile.txt" task = input('Enter a task: ') file_options(file_name, task) if __name__ == '__main__': main()
# Singly Linked List class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self): self.head = None def __repr__(self): node = self.head nodes = [] while node is not None: nodes.append(node.value) node = node.next nodes.append("None") return " -> ".join(nodes) llist = LinkedList() first_node = Node("a") second_node = Node("b") third_node = Node("c") llist.head = first_node first_node.next = second_node second_node.next = third_node print(llist)
# -*- coding: utf-8 -*- """Top-level package for pyqmc.""" __author__ = """Maxime Godin""" __email__ = 'maximegodin@polytechnique.org' __version__ = '0.1.0'
# Fibonacci Sequence: 0 1 1 2 3 5 8 13 ... def fibonacci(num): if num == 1: return 0 if num == 2: return 1 return fibonacci(num-1) + fibonacci(num-2) print(fibonacci(1)) print(fibonacci(2)) print(fibonacci(3)) print(fibonacci(4)) print(fibonacci(5))
cities = [ 'Sao Paulo', 'Rio de Janeiro', 'Salvador', 'Fortaleza', 'Belo Horizonte', 'Brasilia', 'Curitiba', 'Manaus', 'Recife', 'Belem', 'Porto Alegre', 'Goiania', 'Guarulhos', 'Campinas', 'Nova Iguacu', 'Maceio', 'Sao Luis', 'Duque de Caxias', 'Natal', 'Teresina', 'Sao Bernardo do Campo', 'Campo Grande', 'Jaboatao', 'Osasco', 'Santo Andre', 'Joao Pessoa', 'Jaboatao dos Guararapes', 'Contagem', 'Ribeirao Preto', 'Sao Jose dos Campos', 'Uberlandia', 'Sorocaba', 'Cuiaba', 'Aparecida de Goiania', 'Aracaju', 'Feira de Santana', 'Londrina', 'Juiz de Fora', 'Belford Roxo', 'Joinville', 'Niteroi', 'Sao Joao de Meriti', 'Ananindeua', 'Florianopolis', 'Santos', 'Ribeirao das Neves', 'Vila Velha', 'Serra', 'Diadema', 'Campos dos Goytacazes', 'Maua', 'Betim', 'Caxias do Sul', 'Sao Jose do Rio Preto', 'Olinda', 'Carapicuiba', 'Campina Grande', 'Piracicaba', 'Macapa', 'Itaquaquecetuba', 'Bauru', 'Montes Claros', 'Canoas', 'Mogi das Cruzes', 'Sao Vicente', 'Jundiai', 'Pelotas', 'Anapolis', 'Vitoria', 'Maringa', 'Guaruja', 'Porto Velho', 'Franca', 'Blumenau', 'Foz do Iguacu', 'Ponta Grossa', 'Paulista', 'Limeira', 'Viamao', 'Suzano', 'Caucaia', 'Petropolis', 'Uberaba', 'Rio Branco', 'Cascavel', 'Novo Hamburgo', 'Vitoria da Conquista', 'Barueri', 'Taubate', 'Governador Valadares', 'Praia Grande', 'Varzea Grande', 'Volta Redonda', 'Santa Maria', 'Santa Luzia', 'Gravatai', 'Caruaru', 'Boa Vista', 'Ipatinga', 'Sumare', 'Juazeiro do Norte', 'Embu', 'Imperatriz', 'Colombo', 'Taboao da Serra', 'Jacarei', 'Marilia', 'Presidente Prudente', 'Sao Leopoldo', 'Itabuna', 'Sao Carlos', 'Hortolandia', 'Mossoro', 'Itapevi', 'Sete Lagoas', 'Sao Jose', 'Palmas', 'Americana', 'Petrolina', 'Divinopolis', 'Maracanau', 'Planaltina', 'Santarem', 'Camacari', "Santa Barbara d'Oeste", 'Rio Grande', 'Cachoeiro de Itapemirim', 'Itaborai', 'Rio Claro', 'Indaiatuba', 'Passo Fundo', 'Cotia', 'Francisco Morato', 'Aracatuba', 'Araraquara', 'Ferraz de Vasconcelos', 'Arapiraca', 'Lages', 'Barra Mansa', 'Nossa Senhora do Socorro', 'Dourados', 'Criciuma', 'Chapeco', 'Barreiras', 'Sobral', 'Itajai', 'Ilheus', 'Angra dos Reis', 'Nova Friburgo', 'Rondonopolis', 'Itapecerica da Serra', 'Guarapuava', 'Parnamirim', 'Caxias', 'Nilopolis', 'Pocos de Caldas', 'Maraba', 'Luziania', 'Cabo', 'Macae', 'Ibirite', 'Lauro de Freitas', 'Paranagua', 'Parnaiba', 'Itu', 'Castanhal', 'Sao Caetano do Sul', 'Queimados', 'Pindamonhangaba', 'Sapucaia', 'Jaragua do Sul', 'Mogi Guacu', 'Jequie', 'Itapetininga', 'Patos de Minas', 'Braganca Paulista', 'Timon', 'Sao Jose dos Pinhais', 'Teresopolis', 'Uruguaiana', 'Porto Seguro', 'Alagoinhas', 'Palhoca', 'Barbacena', 'Cachoeirinha', 'Santa Rita', 'Toledo', 'Jau', 'Cubatao', 'Pinhais', 'Simoes Filho', 'Varginha', 'Sinop', 'Pouso Alegre', 'Eunapolis', 'Botucatu', 'Jandira', 'Ribeirao Pires', 'Conselheiro Lafaiete', 'Resende', 'Araucaria', 'Atibaia', 'Varzea Paulista', 'Garanhuns', 'Araruama', 'Catanduva', 'Franco da Rocha', 'Cabo Frio', 'Ji Parana', 'Araras', 'Poa', 'Vitoria de Santo Antao', 'Umuarama', 'Apucarana', 'Santa Cruz do Sul', 'Guaratingueta', 'Linhares', 'Araguaina', 'Esmeraldas', 'Birigui', 'Assis', 'Barretos', 'Colatina', 'Teofilo Otoni', 'Guaiba', 'Guarapari', 'Coronel Fabriciano', 'Itaguai', 'Rio das Ostras', 'Itabira', 'Votorantim', 'Sertaozinho', 'Santana de Parnaiba', 'Bage', 'Passos', 'Salto', 'Uba', 'Ourinhos', 'Trindade', 'Arapongas', 'Araguari', 'Corumba', 'Erechim', 'Japeri', 'Vespasiano', 'Campo Largo', 'Tatui', 'Patos', 'Timoteo', 'Muriae', 'Cambe', 'Bayeux', 'Bento Goncalves', 'Caraguatatuba', 'Itanhaem', 'Santana do Livramento', 'Almirante Tamandare', 'Planaltina', 'Crato', 'Valinhos', 'Sao Lourenco da Mata', 'Nova Lima', 'Brusque', 'Barra do Pirai', 'Alegrete', 'Caieiras', 'Barra do Corda', 'Igarassu', 'Paulo Afonso', 'Ituiutaba', 'Esteio', 'Sarandi', 'Itaperuna', 'Santana', 'Jardim Paulista', 'Codo', 'Araxa', 'Abreu e Lima', 'Itajuba', 'Lavras', 'Avare', 'Formosa', 'Leme', 'Cruzeiro do Sul', 'Itumbiara', 'Marica', 'Ubatuba', 'Tres Lagoas', 'Sao Joao del Rei', 'Mogi Mirim', 'Abaetetuba', 'Sao Bento do Sul', 'Itauna', 'Sao Mateus', 'Jatai', 'Sao Joao da Boa Vista', 'Lorena', 'Santa Cruz do Capibaribe', 'Sao Sebastiao', 'Tucurui', 'Embu Guacu', 'Sapiranga', 'Para de Minas', 'Campo Mourao', 'Cachoeira do Sul', 'Santo Antonio de Jesus', 'Paranavai', 'Joao Monlevade', 'Matao', 'Bacabal', 'Cacapava', 'Aruja', 'Cruzeiro', 'Patrocinio', 'Tres Rios', 'Bebedouro', 'Sao Cristovao', 'Alfenas', 'Ijui', 'Altamira', 'Paracatu', 'Carpina', 'Iguatu', 'Votuporanga', 'Paragominas', 'Lins', 'Jaboticabal', 'Vicosa', 'Sao Sebastiao do Paraiso', 'Balsas', 'Itatiba', 'Santa Ines', 'Tubarao', 'Pato Branco', 'Paulinia', 'Lajeado', 'Cruz Alta', 'Aquiraz', 'Itacoatiara', 'Gurupi', 'Itaituba', 'Santo Angelo', 'Parintins', 'Curvelo', 'Itabaiana', 'Cacador', 'Ouro Preto', 'Caldas Novas', 'Irece', 'Catalao', 'Tres Coracoes', 'Rio Largo', 'Vilhena', 'Valenca', 'Peruibe', 'Itapeva', 'Cataguases', 'Saquarema', 'Tupa', 'Fernandopolis', 'Senador Canedo', 'Itapira', 'Gravata', 'Valenca', 'Pirassununga', 'Unai', 'Caratinga', 'Itapetinga', 'Mococa', 'Sao Borja', 'Carazinho', 'Santa Rosa', 'Telemaco Borba', 'Guanambi', 'Aracruz', 'Ariquemes', 'Farroupilha', 'Francisco Beltrao', 'Picos', 'Lencois Paulista', 'Arcoverde', 'Braganca', 'Vacaria', 'Cajamar', 'Janauba', 'Vinhedo', 'Formiga', 'Cianorte', 'Nova Vicosa', 'Itapipoca', 'Ponta Pora', 'Estancia', 'Cacoal', 'Sao Gabriel', 'Concordia', 'Pacatuba', 'Viana', 'Sao Pedro da Aldeia', 'Caico', 'Seropedica' ]
##############class##################### class Board: """ This class defines the board object used in the game""" ##############constructeur################## def __init__(self): #self.boardTab = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] self.boardDic = {"A1":[0,"A2"],"A2":[0,"A3"],"A3":[0,"A4"],"A4":[0,"C1"],"A5":[0,"A6","C8"],"A6":[0,"Safe","A5"],"B5":[0,"B6","C8"],"B6":[0,"Safe","B5"],"B1":[0,"B2"],"B2":[0,"B3"],"B3":[0,"B4"],"B4":[0,"C1"],"C1":[0,"C2"],"C2":[0,"C3"],"C3":[0,"C4"],"C4":[0,"C5"],"C5":[0,"C6"],"C6":[0,"C7","C5"],"C7":[0,"C8","C6"],"C8":[0,"B5","A5","C7"]} self.specialSquares = ["A4","B4","C4"] def show(self): # function purpose: Pretty print the board # input: none print("""P1 : [A4: %s][A3: %s][A2: %s][A1: %s] [A6: %s][A5: %s] \n [C1: %s][C2: %s][C3: %s][C4: %s][C5: %s][C6: %s][C7: %s][C8: %s] \nP2 : [B4: %s][B3: %s][B2: %s][B1: %s] [B6: %s][B5: %s] """ % (self.boardDic["A4"][0],self.boardDic["A3"][0],self.boardDic["A2"][0],self.boardDic["A1"][0],self.boardDic["A5"][0],self.boardDic["A6"][0],self.boardDic["C1"][0],self.boardDic["C2"][0],self.boardDic["C3"][0],self.boardDic["C4"][0],self.boardDic["C5"][0],self.boardDic["C6"][0],self.boardDic["C7"][0],self.boardDic["C8"][0],self.boardDic["B4"][0],self.boardDic["B3"][0],self.boardDic["B2"][0],self.boardDic["B1"][0],self.boardDic["B5"][0],self.boardDic["B6"][0])) def placePawn(self,player,position): # function purpose: Place the players pawn on the given position on the board, after checking if it's possible # input: - player: player number # - position: label of one of the board squares if( not self.checkIsValidPosition(position)): return "invalid position" if (self.boardDic[position][0] == player ): return "MoveKO" elif (self.boardDic[position][0] == 0 ): self.boardDic[position][0] = player return "MoveOK" else: self.boardDic[position][0] = player return "ReplaceOK" def checkIsValidPosition(self,position): # function purpose: Check if the given position is a valid square on the board # input: - position: Value of the position of which we want to check the existence return position in self.boardDic def removePawn(self,position): # function purpose: Remove pawn from the board for a given board position # input: - position: label of one of the board squares if( not self.checkIsValidPosition(position)): return "invalid position" self.boardDic[position][0] = 0 return "OK" def getSquareState(self,position): # function purpose: returns the state of the square at the given position (0:not used 1: Player1 pawn 2: Player2 pawn) # input: - position: label of one of the board squares if (not self.checkIsValidPosition(position)): return "invalid position" return self.boardDic[position][0] def getNextSquare(self,player,position): # function purpose: returns the square that is next to the given one on the board (going forward) depending on the player # input: - position: label of one of the board squares # - player: player number if (not self.checkIsValidPosition(position)): return "invalid position" if (not 0<player<3): return "invalid player number" if (position == "C8"): if (player == 1): return self.boardDic[position][2] else: return self.boardDic[position][1] else: return self.boardDic[position][1] def getPreviousSquare(self,player,position): # function purpose: returns the square previous to the given one on the board (going forward) depending on the player # input: - position: label of one of the board squares # - player: player number if (not self.checkIsValidPosition(position)): return "invalid position" if (not 0 < player < 3): return "invalid player number" return self.boardDic[position][2] def isSpecialSquare(self,position): # function purpose: Indicates if the given square on the board is a special square # input: - position: label of one of the board squares return position in self.specialSquares
''' Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. Example: Input: [ [1,3,1], [1,5,1], [4,2,1] ] Output: 7 Explanation: Because the path 1→3→1→1→1 minimizes the sum. ''' class Solution: def minPathSum(self, grid): ''' :param grid: List[List[int]] :return: int ''' # the minimum path sum of arriving at pos (i,j) m,n = len(grid),len(grid[0]) for i in range(1,m): grid[i][0] = grid[i-1][0] + grid[i][0] for j in range(1,n): grid[0][j] = grid[0][j-1] + grid[0][j] for i in range(1,m): for j in range(1,n): grid[i][j] = min(grid[i][j-1],grid[i-1][j])+grid[i][j] return grid[-1][-1] # test grid = [ [1,3,1], [1,5,1], [4,2,1] ] print(Solution().minPathSum(grid))
__all__ = ('BaseIDGenerationStrategy', ) class BaseIDGenerationStrategy: def get_next_id(self, instance): raise NotImplementedError
# coding=utf-8 n, m = map(int, input().split()) s = [ list(str(input())) for _ in range(n) ] add = [[1, 0],[-1, 0],[0, 1],[0, -1]] ans = 'Yes' for i in range(n): for j in range(m): if s[i][j] == '.': continue mid = False for k in range(4): ii = i + add[k][0] jj = j + add[k][1] if ii >= 0 and jj < m and ii < n and jj >= 0: if s[ii][jj] == '#': mid = True if not mid: ans = 'No';break print(ans)
orbits = dict() with open('input.txt') as f: for line in f: center, satellite = line.strip().split(")") orbits[satellite] = center def calc_distance_to_com(orbs, sat): dist = 1 cent = orbs[sat] while cent != "COM": cent = orbs[cent] dist += 1 return dist def find_route_to_com(orbs, sat): route = [orbs[sat]] while route[0] != "COM": route.insert(0, orbs[route[0]]) return route checksum = 0 for satellite in orbits.keys(): checksum += calc_distance_to_com(orbits, satellite) print("checksum = %d" % checksum) route_me = find_route_to_com(orbits, "YOU") route_santa = find_route_to_com(orbits, "SAN") while route_me[0] == route_santa[0]: route_me = route_me[1:] route_santa = route_santa[1:] # Now the tricky piece. We need to count the number of transfers between nodes, # which is N-1 for N nodes. So the total number of transfers to traverse both # branches is (len(route_me) -1) + (len(route_santa) -1). Our branches don't # include their common node, which adds two more transfers, that are required # to switch between branches, thus the total number of transfers is just # len(route_me) + len(route_santa) print("transfers = %d" % (len(route_me) + len(route_santa)))
# The diameter of a tree (sometimes called the width) # is the number of nodes on the longest path between # two end nodes. # The diameter of a tree T is the largest of the following quantities: # * the diameter of T’s left subtree # * the diameter of T’s right subtree # * the longest path between leaves that goes through the # root of T (this can be computed from the heights of the subtrees of T) class Node(object): def __init__(self, data): self.data = data self.left = None self.right = None def height(tree): if tree is None: return 0 else: return 1 + max(height(tree.left), height(tree.right)) def diameter(tree): if tree is None: return 0 else: lheight = height(tree.left) rheight = height(tree.right) ldiameter = diameter(tree.left) rdiameter = diameter(tree.right) return max(rheight + lheight + 1, max(ldiameter, rdiameter)) root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print("Diameter of given binary tree is ",diameter(root))
class ParseError(Exception) : """Super class for exception classes used in Parsers package. """ def __init__(self, file='', msg=''): self.file = str(file) self.msg = str(msg) def __str__(self): if self.msg : s = self.msg + ': ' else : s = '' return s+self.file
# Commonly used java test dependencies def java_test_repositories(): native.maven_jar( name = "junit", artifact = "junit:junit:4.12", sha1 = "2973d150c0dc1fefe998f834810d68f278ea58ec", ) native.maven_jar( name = "hamcrest_core", artifact = "org.hamcrest:hamcrest-core:1.3", sha1 = "42a25dc3219429f0e5d060061f71acb49bf010a0", ) native.maven_jar( name = "org_mockito_mockito", artifact = "org.mockito:mockito-all:1.10.19", sha1 = "539df70269cc254a58cccc5d8e43286b4a73bf30", )
# # PySNMP MIB module CISCO-VLAN-BRIDGING-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VLAN-BRIDGING-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:02:27 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") CiscoPortList, = mibBuilder.importSymbols("CISCO-TC", "CiscoPortList") vtpVlanIndex, = mibBuilder.importSymbols("CISCO-VTP-MIB", "vtpVlanIndex") ModuleCompliance, ObjectGroup, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup", "NotificationGroup") TimeTicks, Bits, ModuleIdentity, Counter64, Counter32, IpAddress, MibIdentifier, iso, Gauge32, Integer32, ObjectIdentity, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "Bits", "ModuleIdentity", "Counter64", "Counter32", "IpAddress", "MibIdentifier", "iso", "Gauge32", "Integer32", "ObjectIdentity", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") ciscoVlanBridgingMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 56)) ciscoVlanBridgingMIB.setRevisions(('2003-08-22 00:00', '1996-09-12 00:00',)) if mibBuilder.loadTexts: ciscoVlanBridgingMIB.setLastUpdated('200308220000Z') if mibBuilder.loadTexts: ciscoVlanBridgingMIB.setOrganization('Cisco Systems, Inc.') ciscoVlanBridgingMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 56, 1)) cvbStp = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 56, 1, 1)) cvbStpTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 56, 1, 1, 1), ) if mibBuilder.loadTexts: cvbStpTable.setStatus('current') cvbStpEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 56, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-VTP-MIB", "vtpVlanIndex")) if mibBuilder.loadTexts: cvbStpEntry.setStatus('current') cvbStpForwardingMap = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 56, 1, 1, 1, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly") if mibBuilder.loadTexts: cvbStpForwardingMap.setStatus('deprecated') cvbStpForwardingMap2k = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 56, 1, 1, 1, 1, 3), CiscoPortList()).setMaxAccess("readonly") if mibBuilder.loadTexts: cvbStpForwardingMap2k.setStatus('current') ciscoVlanBridgingMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 56, 3)) ciscoVlanBridgingMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 56, 3, 1)) ciscoVlanBridgingMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 56, 3, 2)) ciscoVlanBridgingMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 56, 3, 1, 1)).setObjects(("CISCO-VLAN-BRIDGING-MIB", "ciscoVlanBridgingMIBGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoVlanBridgingMIBCompliance = ciscoVlanBridgingMIBCompliance.setStatus('deprecated') ciscoVlanBridgingMIBCompliance2 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 56, 3, 1, 2)).setObjects(("CISCO-VLAN-BRIDGING-MIB", "ciscoVlanBridgingMIBGroup2")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoVlanBridgingMIBCompliance2 = ciscoVlanBridgingMIBCompliance2.setStatus('current') ciscoVlanBridgingMIBGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 56, 3, 2, 1)).setObjects(("CISCO-VLAN-BRIDGING-MIB", "cvbStpForwardingMap")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoVlanBridgingMIBGroup = ciscoVlanBridgingMIBGroup.setStatus('deprecated') ciscoVlanBridgingMIBGroup2 = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 56, 3, 2, 2)).setObjects(("CISCO-VLAN-BRIDGING-MIB", "cvbStpForwardingMap2k")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoVlanBridgingMIBGroup2 = ciscoVlanBridgingMIBGroup2.setStatus('current') mibBuilder.exportSymbols("CISCO-VLAN-BRIDGING-MIB", PYSNMP_MODULE_ID=ciscoVlanBridgingMIB, ciscoVlanBridgingMIB=ciscoVlanBridgingMIB, cvbStp=cvbStp, ciscoVlanBridgingMIBCompliance=ciscoVlanBridgingMIBCompliance, ciscoVlanBridgingMIBConformance=ciscoVlanBridgingMIBConformance, cvbStpForwardingMap2k=cvbStpForwardingMap2k, ciscoVlanBridgingMIBCompliance2=ciscoVlanBridgingMIBCompliance2, ciscoVlanBridgingMIBGroup2=ciscoVlanBridgingMIBGroup2, cvbStpEntry=cvbStpEntry, cvbStpForwardingMap=cvbStpForwardingMap, ciscoVlanBridgingMIBGroup=ciscoVlanBridgingMIBGroup, ciscoVlanBridgingMIBCompliances=ciscoVlanBridgingMIBCompliances, cvbStpTable=cvbStpTable, ciscoVlanBridgingMIBGroups=ciscoVlanBridgingMIBGroups, ciscoVlanBridgingMIBObjects=ciscoVlanBridgingMIBObjects)
def run(): # nombre = input('Escribe tu nombre: ') # for letra in nombre: # print(letra) frase = input('Escribe una frase: ') for c in frase: print(c.upper()) if __name__ == '__main__': run()
def choose6(n,k): #computes nCk, the number of combinations n choose k result = 1 for i in range(n): result*=(i+1) for i in range(k): result/=(i+1) for i in range(n-k): result/=(i+1) return result
class ResultSet(list): """A list like object that holds results from a Unsplash API query.""" class Model(object): def __init__(self, **kwargs): self._repr_values = ["id"] @classmethod def parse(cls, data): """Parse a JSON object into a model instance.""" raise NotImplementedError @classmethod def parse_list(cls, data): """Parse a list of JSON objects into a result set of model instances.""" results = ResultSet() data = data or [] for obj in data: if obj: results.append(cls.parse(obj)) return results def __repr__(self): items = filter(lambda x: x[0] in self._repr_values, vars(self).items()) state = ['%s=%s' % (k, repr(v)) for (k, v) in items] return '%s(%s)' % (self.__class__.__name__, ', '.join(state)) class Photo(Model): @classmethod def parse(cls, data): data = data or {} photo = cls() if data else None for key, value in data.items(): if not value: setattr(photo, key, value) continue if key == "user": user = User.parse(value) setattr(photo, key, user) elif key == "exif": exif = Exif.parse(value) setattr(photo, key, exif) elif key in ["urls", "links"]: link = Link.parse(value) setattr(photo, key, link) elif key == "location": location = Location.parse(value) setattr(photo, key, location) else: setattr(photo, key, value) return photo class Exif(Model): def __init__(self, **kwargs): super(Exif, self).__init__(**kwargs) self._repr_values = ["make", "model"] @classmethod def parse(cls, data): data = data or {} exif = cls() if data else None for key, value in data.items(): setattr(exif, key, value) return exif class Link(Model): def __init__(self, **kwargs): super(Link, self).__init__(**kwargs) self._repr_values = ["html", "raw", "url"] @classmethod def parse(cls, data): data = data or {} link = cls() if data else None for key, value in data.items(): setattr(link, key, value) return link class Location(Model): def __init__(self, **kwargs): super(Location, self).__init__(**kwargs) self._repr_values = ["title"] @classmethod def parse(cls, data): data = data or {} location = cls() if data else None for key, value in data.items(): setattr(location, key, value) return location class User(Model): def __init__(self, **kwargs): super(User, self).__init__(**kwargs) self._repr_values = ["id", "name", "username"] @classmethod def parse(cls, data): data = data or {} user = cls() if data else None for key, value in data.items(): if not value: setattr(user, key, value) continue if key in ["links", "profile_image"]: link = Link.parse(value) setattr(user, key, link) elif key == "photos": photo = Photo.parse_list(value) setattr(user, key, photo) else: setattr(user, key, value) return user class Stat(Model): def __init__(self, **kwargs): super(Stat, self).__init__(**kwargs) self._repr_values = ["total_photos", "photo_downloads"] @classmethod def parse(cls, data): data = data or {} stat = cls() if data else None for key, value in data.items(): if not value: setattr(stat, key, value) continue if key == "links": link = Link.parse(value) setattr(stat, key, link) else: setattr(stat, key, value) return stat class Collection(Model): def __init__(self, **kwargs): super(Collection, self).__init__(**kwargs) self._repr_values = ["id", "title"] @classmethod def parse(cls, data): data = data or {} collection = cls() if data else None for key, value in data.items(): if not value: setattr(collection, key, value) continue if key == "cover_photo": photo = Photo.parse(value) setattr(collection, key, photo) elif key == "user": user = User.parse(value) setattr(collection, key, user) elif key == "links": link = Link.parse(value) setattr(collection, key, link) else: setattr(collection, key, value) return collection
class Rect(object): def __init__(self, cx, cy, width, height, confidence): self.cx = cx self.cy = cy self.width = width self.height = height self.confidence = confidence self.true_confidence = confidence def overlaps(self, other): if abs(self.cx - other.cx) > (self.width + other.width) / 1.5: return False elif abs(self.cy - other.cy) > (self.height + other.height) / 2.0: return False else: return True def distance(self, other): return sum( map( abs, [ self.cx - other.cx, self.cy - other.cy, self.width - other.width, self.height - other.height ] ) ) def intersection(self, other): left = max(self.cx - self.width / 2., other.cx - other.width / 2.) right = min(self.cx + self.width / 2., other.cx + other.width / 2.) width = max(right - left, 0) top = max(self.cy - self.height / 2., other.cy - other.height / 2.) bottom = min(self.cy + self.height / 2., other.cy + other.height / 2.) height = max(bottom - top, 0) return width * height def area(self): return self.height * self.width def union(self, other): return self.area() + other.area() - self.intersection(other) def iou(self, other): return self.intersection(other) / self.union(other) def __eq__(self, other): return ( self.cx == other.cx and self.cy == other.cy and self.width == other.width and self.height == other.height and self.confidence == other.confidence )
class Transformer: def __init__(self, name, allegiance, strength, intelligence, speed, endurance, rank, courage, firepower, skill): """Initialization function for a Transformer.""" self.name = name self.allegiance = allegiance self.strength = strength self.intelligence = intelligence self.speed = speed self.endurance = endurance self.rank = rank self.courage = courage self.firepower = firepower self.skill = skill self.rating = strength + intelligence + speed + endurance + firepower self.alive = True def fight(self, opponent): """Determines, between two transformers, who is the winner based on the following conditions.""" winner = None if (self.name == 'Optimus Prime' or self.name == 'Predaking') and \ (opponent.name == 'Optimus Prime' or opponent.name == 'Predaking'): winner = 'Optoking' elif self.name == 'Optimus Prime' or self.name == 'Predaking': winner = self elif opponent.name == 'Optimus Prime' or opponent.name == 'Predaking': winner = opponent elif self.courage - opponent.courage >= 4 and self.strength - opponent.strength >= 3: winner = self elif opponent.courage - self.courage >= 4 and opponent.strength - self.strength >= 3: winner = opponent elif self.skill - opponent.skill >= 3: winner = self elif opponent.skill - self.skill >= 3: winner = opponent elif self.rating > opponent.rating: winner = self elif self.rating < opponent.rating: winner = opponent else: winner = 'Tie' self.alive = False opponent.alive = False if winner == self: opponent.alive = False elif winner == opponent: self.alive = False return winner
def main(request, response): headers = [("Content-Type", "text/plain")] command = request.GET.first("cmd").lower(); test_id = request.GET.first("id") header = request.GET.first("header") if command == "put": request.server.stash.put(test_id, request.headers.get(header, "")) elif command == "get": stashed_header = request.server.stash.take(test_id) if stashed_header is not None: headers.append(("x-request-" + header, stashed_header )) else: response.set_error(400, "Bad Command") return "ERROR: Bad Command!" return headers, ""
n, k = map(int, input().split()) A = list(map(int, input().split())) step = 0 cnt = 0 # robot 위치 robot = [] while True: step += 1 # 벨트 한 칸 이동 A = [A[-1]] + A[:-1] for i in range(len(robot)): robot[i] += 1 # 로봇 내리는 위치 확인 if (n - 1) in robot: robot.remove(n - 1) # 로봇 이동 for i in range(len(robot)): if A[robot[i] + 1] >= 1 and (robot[i] + 1) not in robot: A[robot[i] + 1] -= 1 robot[i] += 1 # 로봇 내리는 위치 확인 if (n - 1) in robot: robot.remove(n - 1) if A[0] != 0: robot.append(0) A[0] -= 1 cnt = A.count(0) if cnt >= k: break print(step)
no_steps = 359 pos = 0 lst = [0] for x in range(1, 50000001): pos += no_steps pos %= len(lst) lst.insert(pos+1, x) pos += 1 print(lst[lst.index(0)+1])
#!/usr/bin/env python # AUTHOR: jo # DATE: 2019-08-12 # DESCRIPTION: Tuse homework assignment #1. def partitionOnZeroSumAndMax(row): # Ex. Passing in [1,1,0,1] returns [2,0,1]. # max([2,0,1]) -> 2 localSums = [0] for val in row: if val != 0: localSums.append(localSums.pop() + val) else: localSums.append(0) return max(localSums) def getDistanceAndMax(matrix): # Initialize empty array with identical dimensions as input. matrix_distance = [ [None for row in range(len(matrix))] for column in range(len(matrix[0])) ] for row in range(len(matrix)): for column in range(len(matrix[row])): # Top row stays the same, and for any coordinate that's zero. if (row == 0) or (matrix[row][column] == 0): matrix_distance[row][column] = matrix[row][column] else: distance = 0 # Iterate in reverse, from bottom to top. for row_range in range(row, -1, -1): if matrix[row_range][column] == 1: distance += 1 # Being explicit here to handle zero. # elif can be replaced with "else: break" instead. elif matrix[row_range][column] == 0: break matrix_distance[row][column] = distance return {'distance' : matrix_distance, 'max_score': max(partitionOnZeroSumAndMax(row) for row in matrix_distance) } if __name__ == '__main__': snoots = [ [1, 0, 1], [0, 1, 1], [1, 1, 1] ] winkler = [ [1, 0, 0], [1, 1, 1], [0, 1, 0] ] tootSnoots = [1,1,0,1] toodles = [ [1,1,0,1], [1,1,0,1], [1,1,0,1], [1,1,0,1] ] print(getDistanceAndMax(snoots)) print(getDistanceAndMax(winkler)) print(partitionOnZeroSumAndMax(tootSnoots)) print(getDistanceAndMax(toodles))
# -*- coding: utf-8 -*- """ @contact: lishulong.never@gmail.com @time: 2018/5/8 上午10:17 """
#!/usr/bin/env python2 def main(): n = input('') for i in range(0, n): rows = input('') matrix = [] for j in range(0, rows): matrix.append([int(x) for x in raw_input('').split()]) print(weight(matrix, 0, 0)) def weight(matrix, i, j): #print('weight called with', i, j) if i < len(matrix)-1: return matrix[i][j] + max(weight(matrix, i+1, j), weight(matrix, i+1, j+1)) else: return matrix[i][j] if __name__ == "__main__": main()
"""This module consist of API Groups. All the REST APIs are divided into several groups 1) Access 2) General 3) Organization 4) Service 5) Service Action Each group has a set of APIs with their own models and schemas. """
codon_protein = { "AUG": "Methionine", "UUU": "Phenylalanine", "UUC": "Phenylalanine", "UUA": "Leucine", "UUG": "Leucine", "UCU": "Serine", "UCG": "Serine", "UCC": "Serine", "UCA": "Serine", "UAU": "Tyrosine", "UAC": "Tyrosine", "UGU": "Cysteine", "UGC": "Cysteine", "UGG": "Tryptophan", "UAA": None, "UAG": None, "UGA": None } def proteins(strand: str): codons = get_codons(strand) result = [] for codon in codons: protein = codon_protein[codon] if protein is None: break if protein not in result: result.append(protein) return result def get_codons(strand): chunk_size = 3 codons = [strand[i:i + chunk_size] for i in range(0, len(strand), chunk_size)] return codons
# Copyright 2017-2022 Lawrence Livermore National Security, LLC and other # Hatchet Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: MIT __version_info__ = ("2022", "1", "0") __version__ = ".".join(__version_info__)
def solution(s): res = '' if s == s.lower(): res += s return res for i in range(len(s)): if s[i] == ' ': continue elif s[i] == s[i].upper(): res += ' ' + s[i] else: res += s[i] return res def testing(): a = "camelCasing" b = "camel Casing" print("Верно!" if solution(a) == b else "Не работает") print(solution(a)) c = "identifier" d = "identifier" print("Верно!" if solution(c) == d else "Не работает") print(solution(c)) if __name__ == "__main__": testing() print(solution('break CamelCase'))
# Functions (Funções) # DRY - Don't repeat yourself # Parametro --> Argumento # Default = Aquele que você define o valor no parametro # Non-Default = Aquele que você não define o valor do parametro ''' No exemplo abaixo NOME é o Non-Default, pq o valor dele ainda será atribuido posteriormente podendo ser trocado a atribuição. Já em QUANTIDADE ele está Default (definido) ou seja seu Valor sera sempre o mesmo até que voce troque. Deve-se respeitar as ordens, o NON-DEFAULT deve ser atribuido antes def boas_vindas( nome, quantidade = 6): print(f'Olá{nome}.') print(f'Temos {str(quantidade)} laptops em estoque') boas_vindas('Marcos')# Não sera necessario chamar a quantidade ''' # Realizam uma tarefa # Calcula e retorna o valor def cliente1(nome): print(f'Olá {nome}') def cliente2(nome): return f'Olá {nome}' # Em return ele armazena informação e sé escreve se for chamado x = cliente1 ('Maria') y = cliente2 ('José') print(x) print(y) # Fixando Exercicio def restaurante(nome): print(f'Bem vindos ao {nome} o melhor restaurante da cidade ') def espera(itens): return f'Neste momento temos {itens} clientes em espera' z = restaurante ('Bon Appetit') h = espera (6) print(z) print(h) # Criar uma função que soma vários números.
# Time: O(n) # Space: O(1) class Solution(object): # @param {TreeNode} root # @param {TreeNode} p # @param {TreeNode} q # @return {TreeNode} def lowestCommonAncestor(self, root, p, q): s, b = sorted([p.val, q.val]) while not s <= root.val <= b: # Keep searching since root is outside of [s, b]. root = root.left if s <= root.val else root.right # s <= root.val <= b. return root
n = int(input()) nsum = 0 for i in range(1, n+1): nsum += i if nsum == 1: print('BOWWOW') elif nsum <= 3: print('WANWAN') else: for i in range(2, n+1): if n % i == 0: print('BOWWOW') break else: print('WANWAN')
#!/usr/bin/env python3 def find_array_intersection(A, B): ai = 0 bi = 0 ret = [] while ai < len(A) and bi < len(B): if A[ai] < B[bi]: ai += 1 elif A[ai] > B[bi]: bi += 1 else: ret.append(A[ai]) v = A[ai] while ai < len(A) and A[ai] == v: ai += 1 while bi < len(B) and B[bi] == v: bi += 1 return ret A = [1, 2, 3, 4, 4, 5, 7, 8, 10] B = [3, 4, 8, 9, 9, 10, 13] print(find_array_intersection(A, B))
""" --- Day 18: Duet --- You discover a tablet containing some strange assembly code labeled simply "Duet". Rather than bother the sound card with it, you decide to run the code yourself. Unfortunately, you don't see any documentation, so you're left to figure out what the instructions mean on your own. It seems like the assembly is meant to operate on a set of registers that are each named with a single letter and that can each hold a single integer. You suppose each register should start with a value of 0. There aren't that many instructions, so it shouldn't be hard to figure out what they do. Here's what you determine: snd X plays a sound with a frequency equal to the value of X. set X Y sets register X to the value of Y. add X Y increases register X by the value of Y. mul X Y sets register X to the result of multiplying the value contained in register X by the value of Y. mod X Y sets register X to the remainder of dividing the value contained in register X by the value of Y (that is, it sets X to the result of X modulo Y). rcv X recovers the frequency of the last sound played, but only when the value of X is not zero. (If it is zero, the command does nothing.) jgz X Y jumps with an offset of the value of Y, but only if the value of X is greater than zero. (An offset of 2 skips the next instruction, an offset of -1 jumps to the previous instruction, and so on.) Many of the instructions can take either a register (a single letter) or a number. The value of a register is the integer it contains; the value of a number is that number. After each jump instruction, the program continues with the instruction to which the jump jumped. After any other instruction, the program continues with the next instruction. Continuing (or jumping) off either end of the program terminates it. For example: set a 1 add a 2 mul a a mod a 5 snd a set a 0 rcv a jgz a -1 set a 1 jgz a -2 The first four instructions set a to 1, add 2 to it, square it, and then set it to itself modulo 5, resulting in a value of 4. Then, a sound with frequency 4 (the value of a) is played. After that, a is set to 0, causing the subsequent rcv and jgz instructions to both be skipped (rcv because a is 0, and jgz because a is not greater than 0). Finally, a is set to 1, causing the next jgz instruction to activate, jumping back two instructions to another jump, which jumps again to the rcv, which ultimately triggers the recover operation. At the time the recover operation is executed, the frequency of the last sound played is 4. What is the value of the recovered frequency (the value of the most recently played sound) the first time a rcv instruction is executed with a non-zero value? --- Part Two --- As you congratulate yourself for a job well done, you notice that the documentation has been on the back of the tablet this entire time. While you actually got most of the instructions correct, there are a few key differences. This assembly code isn't about sound at all - it's meant to be run twice at the same time. Each running copy of the program has its own set of registers and follows the code independently - in fact, the programs don't even necessarily run at the same speed. To coordinate, they use the send (snd) and receive (rcv) instructions: snd X sends the value of X to the other program. These values wait in a queue until that program is ready to receive them. Each program has its own message queue, so a program can never receive a message it sent. rcv X receives the next value and stores it in register X. If no values are in the queue, the program waits for a value to be sent to it. Programs do not continue to the next instruction until they have received a value. Values are received in the order they are sent. Each program also has its own program ID (one 0 and the other 1); the register p should begin with this value. For example: snd 1 snd 2 snd p rcv a rcv b rcv c rcv d Both programs begin by sending three values to the other. Program 0 sends 1, 2, 0; program 1 sends 1, 2, 1. Then, each program receives a value (both 1) and stores it in a, receives another value (both 2) and stores it in b, and then each receives the program ID of the other program (program 0 receives 1; program 1 receives 0) and stores it in c. Each program now sees a different value in its own copy of register c. Finally, both programs try to rcv a fourth time, but no data is waiting for either of them, and they reach a deadlock. When this happens, both programs terminate. It should be noted that it would be equally valid for the programs to run at different speeds; for example, program 0 might have sent all three values and then stopped at the first rcv before program 1 executed even its first instruction. Once both of your programs have terminated (regardless of what caused them to do so), how many times did program 1 send a value? """ def read(): with open('inputs/day18.txt') as fd: return fd.readlines() def parse(lines): l = [] for line in lines: inst, *params = line.strip().split() l.append((inst, params)) return l test_input = """set a 1 add a 2 mul a a mod a 5 snd a set a 0 rcv a jgz a -1 set a 1 jgz a -2""".splitlines() test_input2 = """snd 1 snd 2 snd p rcv a rcv b rcv c rcv d""".splitlines() class Reg(dict): def __missing__(self, key): try: v = int(key) except ValueError: v = 0 self[key] = 0 return v class Register: def __init__(self): self.reg = Reg() self.INSTRUCTIONS = {'snd': self.send, 'set': self.set, 'add': self.add, 'mul': self.mul, 'mod': self.mod, 'rcv': self.recover, 'jgz': self.jump} self.last_played = None self.recovered = None self.instructions = None self.pos = 0 def send(self, reg): self.last_played = self.reg[reg] def set(self, reg, val): self.reg[reg] = self.reg[val] def add(self, reg, val): self.reg[reg] += self.reg[val] def mul(self, reg1, reg2): self.reg[reg1] *= self.reg[reg2] def mod(self, reg, val): self.reg[reg] = self.reg[reg] % self.reg[val] def recover(self, reg): if self.reg[reg] != 0: return self.last_played def jump(self, reg, val): if self.reg[reg] > 0: self.pos += self.reg[val] -1 def operate(self, instructions): self.instructions = instructions self.pos = 0 while True: inst, params = self.instructions[self.pos] r = self.INSTRUCTIONS[inst](*params) if r is not None: return r self.pos += 1 if self.pos < 0 or self.pos >= len(self.instructions): break return self.last_played def test1(): r = Register() assert 4 == r.operate(parse(test_input)) def part1(): r = Register() print(r.operate(parse(read()))) class Register2(Register): def __init__(self, read, write, id, instructions): self.read_queue = read self.write_queue = write self.sends = 0 self.blocked = False super().__init__() self.reg['p'] = id self.instructions = instructions self.ended = False self.waiting = False self.pos = 0 def send(self, reg): self.write_queue.append(self.reg[reg]) self.sends += 1 def recover(self, reg): self.reg[reg] = self.read_queue.pop(0) def operate(self): """Return True if it is ended or blocked""" if self.ended: return True inst, params = self.instructions[self.pos] if inst == 'rcv' and len(self.read_queue) == 0: return True self.INSTRUCTIONS[inst](*params) self.pos += 1 if self.pos < 0 or self.pos >= len(self.instructions): self.ended = True return False def dual(input): d1 = [] d2 = [] r0 = Register2(d1, d2, 0, input) r1 = Register2(d2, d1, 1, input) while True: if r0.operate() and r1.operate(): return r1.sends def test2(): assert 3 == dual(parse(test_input2)) def part2(): print(dual(parse(read()))) if __name__ == '__main__': # test1() # part1() # test2() part2()
v = float(input('Valor da casa a ser comprada: R$')) s = float(input('Salário do comprador: R$')) qa = float(input('Quantos anos irá pagar: ')) print('Para pagar uma casa de R${:.2f} em {:.0f} anos'.format(v, qa), end='') print(' a prestação sera de R${:.2f}'.format(v / (qa * 12))) if v / (qa* 12) >= s * 0.3: print('Seu empréstimo foi negado, sinto muito') else: print('Seu empréstimo foi aprovado, parabéns!!')
def do_stuff(fn, lhs, rhs): return fn(lhs, rhs) def add(lhs, rhs): return lhs + rhs def multiply(lhs, rhs): return lhs * rhs def exponent(lhs, rhs): return lhs ** rhs print(do_stuff(add, 2, 3)) print(do_stuff(multiply, 2, 3)) print(do_stuff(exponent, 2, 3))
# A tuple operates like a list but it's initial values can't be modified # Tuples are declared using the () # Use case examples of using Tuple - Dates of the week, Months of the Year, Hours of the clock # we can create a tuple like this... monthsOfTheYear = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") # Prints all the items in the tuple print(monthsOfTheYear) # prints an item in the tuple print(monthsOfTheYear[0]) print(monthsOfTheYear[:3]) # If we try to run the code below it will error # This is because we are change a value in the tuple, which is not allowed! # monthsOfTheYear[0] = "January" # Other operations we can do with tuples # find an item in the tuple myTuple = ('Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun') print(len(myTuple)) print(sorted(myTuple)) names = ['John', 'Lamin', 'Vicky', 'Jasmine'] print(names * 3)
tot=0 n=int(input('\033[mDigite um numero: ')) for c in range(1, n+1): if n%c==0: print('\033[34m',end='') tot+=1 else: print('\033[31m',end='') print('{} '.format(c), end='') print(f'\033[m\nO numero {n} foi divisível {tot} vezes')
# class Solution: # def lengthOfLIS(self, nums): # """ # :type nums: List[int] # :rtype: int # """ # O(n^2) complexity # if not nums: # return 0 # n = len(nums) # aux = [1] * n # for i in range(n): # for j in range(i): # if (nums[j] < nums[i] and aux[i] < aux[j] + 1): # aux[i] = aux[j] + 1 # return max(aux) class Solution: def lengthOfLIS(self, nums): ''' O(nlogn) Binary Search+Greedy ''' def binarySearch(arr, target): ''' find the position of this num ''' low = 0 high = len(arr) while (low < high): mid = (low + high) // 2 if arr[mid] == target: return mid if arr[mid] < target: low = mid+1 else: high = mid if low == len(arr): return low-1 return low if not nums: return 0 sequence = [nums[0]] for num in nums: if num < sequence[0]: sequence[0] = num elif num > sequence[-1]: sequence.append(num) else: sequence[binarySearch(sequence, num)] = num return len(sequence)
class Solution: def updateMatrix(self, matrix: list) -> list: # m, n = len(matrix), len(matrix[0]) # SomeZerosInds, SomeOnesInds = [], [] #01边界的0的索引 和 被1包围的1的索引 # ans = [ [0] * len(matrix[0]) for _ in range(len(matrix)) ] # for p in range(len(matrix)): # for q in range(len(matrix[0])): # if matrix[p][q] == 0: #如果这个元素等于0 # #如果这个元素周围存在1 # if self.fun(p-1, q, matrix, m, n) or self.fun(p+1, q, matrix, m, n) or self.fun(p, q-1, matrix, m, n) or self.fun(p, q+1, matrix, m, n): # SomeZerosInds.append(self.rc2ind(p, q, n)) # else: #如果这个元素等于1 # #如果这个元素周围存在0 # if not (self.fun(p-1, q, matrix, m, n) and self.fun(p+1, q, matrix, m, n) and self.fun(p, q-1, matrix, m, n) and self.fun(p, q+1, matrix, m, n)): # ans[p][q] = 1 # else: #如果这个元素周围不存在0 # SomeOnesInds.append(self.rc2ind(p, q, n)) # # print(SomeZerosInds, SomeOnesInds) # table = [ [0] * len(SomeZerosInds) for _ in range(len(SomeOnesInds)) ] # for p in range(len(SomeOnesInds)): # for q in range(len(SomeZerosInds)): # r1, c1 = self.ind2rc(SomeOnesInds[p], n) # r0, c0 = self.ind2rc(SomeZerosInds[q], n) # table[p][q] = abs(r1-r0) + abs(c1-c0) # # print(table) # for k in range(len(table)): # r, c = self.ind2rc(SomeOnesInds[k], n) # # print(r, c) # ans[r][c] = min(table[k]) # return ans # def ind2rc(self, ind, n): # return ind // n, ind % n # def rc2ind(self, r, c, n): # return n * r + c # def fun(self, row, col, matrix, m, n): # if row < 0 or col < 0: # return 1 #True # if row > m-1 or col > n-1: # return 1 #True # return matrix[row][col] #bool(matrix[row][col]) # m, n = len(matrix), len(matrix[0]) # dp = [ [float('inf')] * n for _ in range(m) ] # for p in range(m): # for q in range(n): # if matrix[p][q] == 1: #如果这个元素等于1 # #如果这个元素周围存在0 # if not (self.fun(p-1, q, matrix, m, n) and self.fun(p+1, q, matrix, m, n) and self.fun(p, q-1, matrix, m, n) and self.fun(p, q+1, matrix, m, n)): # dp[p][q] = 1 # else: #如果这个元素周围不存在0 # if p-1 >= 0 and q-1 >= 0: # dp[p][q] = min(dp[p-1][q], dp[p][q-1]) + 1 # elif p-1 < 0 and q-1 >= 0: # dp[p][q] = dp[p][q-1] + 1 # elif p-1 >= 0 and q-1 < 0: # dp[p][q] = dp[p-1][q] + 1 # for p in range(m-1, -1, -1): # for q in range(n-1, -1, -1): # if matrix[p][q] == 1: #如果这个元素等于1 # #如果这个元素周围存在0 # if not (self.fun(p-1, q, matrix, m, n) and self.fun(p+1, q, matrix, m, n) and self.fun(p, q-1, matrix, m, n) and self.fun(p, q+1, matrix, m, n)): # dp[p][q] = 1 # else: #如果这个元素周围不存在0 # if p+1 < m and q+1 < n: # dp[p][q] = min(dp[p][q], min(dp[p+1][q], dp[p][q+1]) + 1) # elif p+1 >= m and q+1 < n: # dp[p][q] = min(dp[p][q], dp[p][q+1] + 1) # elif p+1 < m and q+1 >= n: # dp[p][q] = min(dp[p][q], dp[p+1][q] + 1) # return dp # def fun(self, row, col, matrix, m, n): # if row < 0 or col < 0: # return 1 #True # if row > m-1 or col > n-1: # return 1 #True # return matrix[row][col] #bool(matrix[row][col]) if not matrix or not matrix[0]: return matrix m, n = len(matrix), len(matrix[0]) dp = [ [float('inf')] * n for _ in range(m) ] for p in range(m): for q in range(n): if matrix[p][q] == 0: dp[p][q] = 0 else: if p > 0: dp[p][q] = min(dp[p][q], dp[p-1][q]+1) if q > 0: dp[p][q] = min(dp[p][q], dp[p][q-1]+1) for p in range(m-1, -1, -1): for q in range(n-1, -1, -1): if p < m-1: dp[p][q] = min(dp[p][q], dp[p+1][q]+1) if q < n-1: dp[p][q] = min(dp[p][q], dp[p][q+1]+1) return dp solu = Solution() matrix = [[0,0,0], [0,1,0], [0,0,0]] # matrix = [[0,0,0], [0,1,0], [1,1,1]] matrix = [[1,0,0,1,0,1,1,0,0,0,0,0,1,1,1,0,1,1,0,1,1,1,1,1,1,1,0,0,0,0,0,1,0,1,1,0,0,0,1,1,0,0,0,0,0,0,1,0,0,1,1,0,1,1,1,1,0,1,0,0,1,0,1,1,0,0,0,0,0,0,1,0,0,1,1,1,1,0,1,0,1,0,1,1,1,1,0,0,1,1,0,0,0,0,0,1,0,1,0,1],[0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,1,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,1,1,1,1,0,0,0,1,1,0,0,0,1,1,1,0,0,1,0,1,1,1,0,1,1,0,0,1,1,1,0,1,1,1,0,1,1,1,1,1,0,0,1,1,0,1,0,0,1,0,1,0,1,1,0,1,1,0,0,1,0,0,1,1,0,1,1],[1,0,0,0,1,0,0,1,1,0,0,1,0,1,0,1,0,0,0,1,0,0,1,0,1,0,0,1,0,1,1,1,0,1,0,0,0,1,1,0,1,0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0,0,1,0,1,0,0,1,1,1,0,1,0,0,1,1,1,0,0,1,0,1,0,1,1,1,0,0,1,1,0,0,0,1,1,0,1,1,1,0,0,0,1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,1,0,1,0,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,1]] print(solu.updateMatrix(matrix))
def solve(array): even = [] odd = [] for i in range(len(array)): if array[i] % 2 == 0: even.append(i) else: odd.append(i) if even: return f"1\n{even[-1] + 1}" if len(odd) > 1: return f"2\n{odd[-1] + 1} {odd[-2] + 1}" else: return "-1" def main(): t = int(input()) for _ in range(t): __ = int(input()) array = [int(x) for x in input().split(' ')] print(solve(array)) main()
array = [5, 3, 2, 1, 6, 8, 7, 4] def merge_sort(array): if len(array) <= 1: return array mid = len(array) //2 left_array = array[:mid] right_array = array[mid:] print(left_array) print(right_array) return merge(merge_sort(left_array), merge_sort(right_array)) def merge(array1, array2): #시간복잡도 array1,array2의 길이 0(N) result = [] array1_index = 0 array2_index = 0 while array1_index < len(array1) and array2_index < len(array2): if array1[array1_index] < array2[array2_index]: result.append(array1[array1_index]) array1_index += 1 else: result.append(array2[array2_index]) array2_index += 1 if array1_index == len(array1): while array2_index < len(array2): result.append(array2[array2_index]) array2_index += 1 if array2_index == len(array2): while array1_index < len(array1): result.append(array1[array1_index]) array1_index += 1 return result print(merge_sort(array)) # [1, 2, 3, 4, 5, 6, 7, 8] 가 되어야 합니다! print("정답 = [-7, -1, 5, 6, 9, 10, 11, 40] / 현재 풀이 값 = ", merge_sort([-7, -1, 9, 40, 5, 6, 10, 11]))
# These constants can be set by the external UI-layer process, don't change them manually is_ui_process = False execution_id = '' task_id = '' executable_name = 'insomniac' do_location_permission_dialog_checks = True # no need in these checks if location permission is denied beforehand def callback(profile_name): pass hardban_detected_callback = callback softban_detected_callback = callback def is_insomniac(): return execution_id == ''
defaults = ''' const vec4 light = vec4(4.0, 3.0, 10.0, 0.0); const vec4 eye = vec4(4.0, 3.0, 2.0, 0.0); const mat4 mvp = mat4( -0.8147971034049988, -0.7172931432723999, -0.7429299354553223, -0.7427813410758972, 1.0863960981369019, -0.5379698276519775, -0.5571974515914917, -0.5570859909057617, 0.0, 2.2415409088134766, -0.37146496772766113, -0.3713906705379486, 0.0, 0.0, 5.186222076416016, 5.385164737701416 ); '''
# UTF-8 # # For more details about fixed file info 'ffi' see: # http://msdn.microsoft.com/en-us/library/ms646997.aspx VSVersionInfo( ffi=FixedFileInfo( # filevers and prodvers should be always a tuple with four items: (1, 2, 3, 4) # Set not needed items to zero 0. filevers=(0, 5, 0, 0), prodvers=(0, 5, 0, 1), # Contains a bitmask that specifies the valid bits 'flags'r mask=0x3f, # Contains a bitmask that specifies the Boolean attributes of the file. flags=0x0, # The operating system for which this file was designed. # 0x4 - NT and there is no need to change it. OS=0x40004, # The general type of file. # 0x1 - the file is an application. fileType=0x1, # The function of the file. # 0x0 - the function is not defined for this fileType subtype=0x0, # Creation date and time stamp. date=(0, 0) ), kids=[ StringFileInfo( [ StringTable( u'040904B0', [StringStruct(u'CompanyName', u'Tristan Crispijn'), StringStruct(u'FileDescription', u'ComicStreamer'), StringStruct(u'FileVersion', u'0.9.5.0'), StringStruct(u'InternalName', u'comicstreamer'), StringStruct(u'LegalCopyright', u'© Tristan Crispijn. All rights reserved.'), StringStruct(u'OriginalFilename', u'comicstreamer'), StringStruct(u'ProductName', u'ComicStreamer: TimmyB Edition'), StringStruct(u'ProductVersion', u'0.9.5.1')]) ]), VarFileInfo([VarStruct(u'Translation', [1033, 1200])]) ] )
class OutOfService(Exception): def __init__(self,Note:str=""): pass class InternalError(Exception): def __init__(self,Note:str=""): pass class NothingFoundError(Exception): def __init__(self,Note:str=""): pass class DummyError(Exception): def __init__(self,Note:str=""): pass
"""Cayley 2020, Problem 20""" def is_divisible(n, d): return (n % d) == 0 def solutions(): a = range(1, 101) b = range(101, 206) return [(m, n) for m in a for n in b if is_divisible(3**m + 7**n, 10)] s = solutions() a = len(s) print(f'Answer = {a}')
a = [1, 4, 5, 7, 19, 24] b = [4, 6, 7, 18, 24, 134] i = 0 j = 0 ans = [] while i < len(a) and j < len(b): if a[i] == b[j]: ans.append(a[i]) i += 1 j += 1 elif a[i] < b[j]: i += 1 else: j += 1 print(*ans)
class Node: def __init__(self, value): self.value = value self.next = None class Queue(object): def __init__(self, size): self.queue = [] self.size = size def enqueue(self, value): '''This function adds an value to the rear end of the queue ''' if(self.isFull() != True): self.queue.insert(0, value) else: print('Queue is Full!') def dequeue(self): ''' This function removes an item from the front end of the queue ''' if(self.isEmpty() != True): return self.queue.pop() else: print('Queue is Empty!') def peek(self): ''' This function helps to see the first element at the fron end of the queue ''' if(self.isEmpty() != True): return self.queue[-1] else: print('Queue is Empty!') def isEmpty(self): ''' This function checks if the queue is empty ''' return self.queue == [] def isFull(self): ''' This function checks if the queue is full ''' return len(self.queue) == self.size def __str__(self): myString = ' '.join(str(i) for i in self.queue) return myString if __name__ == '__main__': myQueue = Queue(10) myQueue.enqueue(4) myQueue.enqueue(5) myQueue.enqueue(6) print(myQueue) myQueue.enqueue(1) myQueue.enqueue(2) myQueue.enqueue(3) print(myQueue) myQueue.dequeue() print(myQueue)
# -*- coding: utf-8 -*- """Order related definitions.""" definitions = { "OrderType": { "MARKET": "A Market Order", "LIMIT": "A Limit Order", "STOP": "A Stop Order", "MARKET_IF_TOUCHED": "A Market-if-touched Order", "TAKE_PROFIT": "A Take Profit Order", "STOP_LOSS": "A Stop Loss Order", "TRAILING_STOP_LOSS": "A Trailing Stop Loss Order" }, "OrderState": { "PENDING": "The Order is currently pending execution", "FILLED": "The Order has been filled", "TRIGGERED": "The Order has been triggered", "CANCELLED": "The Order has been cancelled", }, "TimeInForce": { "GTC": "The Order is “Good unTil Cancelled”", "GTD": "The Order is “Good unTil Date” and will be cancelled at " "the provided time", "GFD": "The Order is “Good for Day” and will be cancelled at " "5pm New York time", "FOK": "The Order must be immediately “Filled Or Killed”", "IOC": "The Order must be “Immediately partially filled Or Killed”", }, "OrderPositionFill": { "OPEN_ONLY": "When the Order is filled, only allow Positions to be " "opened or extended.", "REDUCE_FIRST": "When the Order is filled, always fully reduce an " "existing Position before opening a new Position.", "REDUCE_ONLY": "When the Order is filled, only reduce an existing " "Position.", "DEFAULT": "When the Order is filled, use REDUCE_FIRST behaviour " "for non-client hedging Accounts, and OPEN_ONLY behaviour " "for client hedging Accounts." }, }
bill_board = list(map(int, input().split())) tarp = list(map(int, input().split())) xOverlap = max(min(bill_board[2], tarp[2]) - max(bill_board[0], tarp[0]), 0) yOverlap = max(min(bill_board[3], tarp[3]) - max(bill_board[1], tarp[1]), 0) if xOverlap == 0 or yOverlap == 0: print((bill_board[2] - bill_board[0]) * (bill_board[3] - bill_board[1])) exit() if xOverlap >= bill_board[2] - bill_board[0] and yOverlap >= bill_board[3] - bill_board[1]: print(0) exit() if xOverlap < bill_board[2] - bill_board[0] and yOverlap < bill_board[3] - bill_board[1]: print((bill_board[2] - bill_board[0])*(bill_board[3]-bill_board[1])) elif xOverlap >= bill_board[2] - bill_board[0] and yOverlap < bill_board[3] - bill_board[1]: print(xOverlap*(bill_board[3]-bill_board[1] - yOverlap)) elif yOverlap >= bill_board[3] - bill_board[1] and xOverlap < bill_board[2] - bill_board[0]: print(yOverlap*(bill_board[2] - bill_board[0] - xOverlap)) else: print((bill_board[2] - bill_board[0]) * (bill_board[3] - bill_board[1]))
numero = int(input('Digite um numero')) fatorial = numero contador = 1 while (numero - contador) > 1: fatorial = fatorial * (numero-contador) contador +=1 print('O fatorial de ', numero,'é', fatorial)
""" --- Day 21: RPG Simulator 20XX --- Little Henry Case got a new video game for Christmas. It's an RPG, and he's stuck on a boss. He needs to know what equipment to buy at the shop. He hands you the controller. In this game, the player (you) and the enemy (the boss) take turns attacking. The player always goes first. Each attack reduces the opponent's hit points by at least 1. The first character at or below 0 hit points loses. Damage dealt by an attacker each turn is equal to the attacker's damage score minus the defender's armor score. An attacker always does at least 1 damage. So, if the attacker has a damage score of 8, and the defender has an armor score of 3, the defender loses 5 hit points. If the defender had an armor score of 300, the defender would still lose 1 hit point. Your damage score and armor score both start at zero. They can be increased by buying items in exchange for gold. You start with no items and have as much gold as you need. Your total damage or armor is equal to the sum of those stats from all of your items. You have 100 hit points. Here is what the item shop is selling: Weapons: Cost Damage Armor Dagger 8 4 0 Shortsword 10 5 0 Warhammer 25 6 0 Longsword 40 7 0 Greataxe 74 8 0 Armor: Cost Damage Armor Leather 13 0 1 Chainmail 31 0 2 Splintmail 53 0 3 Bandedmail 75 0 4 Platemail 102 0 5 Rings: Cost Damage Armor Damage +1 25 1 0 Damage +2 50 2 0 Damage +3 100 3 0 Defense +1 20 0 1 Defense +2 40 0 2 Defense +3 80 0 3 You must buy exactly one weapon; no dual-wielding. Armor is optional, but you can't use more than one. You can buy 0-2 rings (at most one for each hand). You must use any items you buy. The shop only has one of each item, so you can't buy, for example, two rings of Damage +3. For example, suppose you have 8 hit points, 5 damage, and 5 armor, and that the boss has 12 hit points, 7 damage, and 2 armor: The player deals 5-2 = 3 damage; the boss goes down to 9 hit points. The boss deals 7-5 = 2 damage; the player goes down to 6 hit points. The player deals 5-2 = 3 damage; the boss goes down to 6 hit points. The boss deals 7-5 = 2 damage; the player goes down to 4 hit points. The player deals 5-2 = 3 damage; the boss goes down to 3 hit points. The boss deals 7-5 = 2 damage; the player goes down to 2 hit points. The player deals 5-2 = 3 damage; the boss goes down to 0 hit points. In this scenario, the player wins! (Barely.) You have 100 hit points. The boss's actual stats are in your puzzle input. What is the least amount of gold you can spend and still win the fight? Your puzzle answer was 121. --- Part Two --- Turns out the shopkeeper is working with the boss, and can persuade you to buy whatever items he wants. The other rules still apply, and he still only has one of each item. What is the most amount of gold you can spend and still lose the fight? Your puzzle answer was 201. """ class Character: def __init__(self, hit_points, damage, armor, inventory_cost=0): self.hit_points = hit_points self.damage = damage self.armor = armor self.inventory_cost = inventory_cost def attack(self, other_character): damage = self.damage - other_character.armor other_character.hit_points -= damage if damage >= 1 else 1 return self.is_alive and other_character.is_alive @property def is_alive(self): return self.hit_points > 0 def encounter(character1, character2): both_live = character1.attack(character2) if both_live: both_live = character2.attack(character1) if not both_live: return character1 if character1.is_alive else character2 class Inventory: def __init__(self, cost, damage, armor): self.cost = cost self.damage = damage self.armor = armor weapons = [ Inventory(cost, damage, 0) for cost, damage in [ (8, 4), (10, 5), (25, 6), (40, 7), (74, 8) ] ] armors = [ Inventory(cost, 0, armor) for cost, armor in [ (0, 0), (13, 1), (31, 2), (53, 3), (75, 4), (102, 5) ] ] rings = [ Inventory(cost, damage, armor) for cost, damage, armor in [ (0, 0, 0), (0, 0, 0), (25, 1, 0), (50, 2, 0), (100, 3, 0), (20, 0, 1), (40, 0, 2), (80, 0, 3) ] ] def character_variant(hit_points): for weapon in weapons: for armor in armors: for left_hand_ring in rings: for right_hand_ring in [ring for ring in rings if ring != left_hand_ring]: equipment = [weapon, armor, left_hand_ring, right_hand_ring] yield Character( hit_points=hit_points, damage=sum(e.damage for e in equipment), armor=sum(e.armor for e in equipment), inventory_cost=sum(e.cost for e in equipment)) def simulate_battle(character1, character2): winner = None while winner is None: winner = encounter(character1, character2) return winner def find_winners(boss_stats, is_player_winner=True): for player in character_variant(100): boss = Character(**boss_stats) winner = simulate_battle(player, boss) expected_winner = player if is_player_winner else boss if winner == expected_winner: yield player def find_cheapest_winning_inventory(victors): return min(victor.inventory_cost for victor in victors) def find_most_expensive_losing_inventory(losers): return max(loser.inventory_cost for loser in losers) if __name__ == "__main__": boss_stats = { "hit_points": 103, "damage": 9, "armor": 2 } player_victors = find_winners(boss_stats, is_player_winner=True) player_losers = find_winners(boss_stats, is_player_winner=False) print("Cheapest inventory: {}".format(find_cheapest_winning_inventory(player_victors))) print("Most expensive losing inventory: {}".format(find_most_expensive_losing_inventory(player_losers)))
''' Edges in a block diagram computational graph. The edges themselves don't have direction, but the ports that they attach to may. ''' class WireConnection: pass class NamedConnection(WireConnection): def __init__(self, target_uid: int, target_port: str): self.target_uid = target_uid self.target_port = target_port def __str__(self): return f'NamedConnection(id={self.target_uid}, port={self.target_port})' class IdentConnection(WireConnection): def __init__(self, target_uid: int): self.target_uid = target_uid def __str__(self): return f'IdentConnection(id={self.target_uid})' class Wire: ''' Wires in TIA's S7 XML format can have more than two terminals, but we always decompose them into a series of two terminal blocks. ''' def __init__(self, a: WireConnection, b: WireConnection): self.a = a self.b = b
with open('model_translations_bpe_dropout.txt', 'r') as f: data = f.read().split("\n") with open('model_translations_bpe_dropout_decoded.txt', 'w') as f: for sentence in data: word_list = sentence.split(" ") detokenized = ''.join(word_list).replace('▁', ' ').strip() f.write(detokenized + "\n")
RADIO_ENABLED = ":white_check_mark: **Radio enabled**" RADIO_DISABLED = ":x: **Radio disabled**" SKIPPED = ":fast_forward: **Skipped** :thumbsup:" NO_MATCH = ":x: **No matches**" SEARCHING = ":trumpet: **Searching** :mag_right:" PAUSE = "**Paused** :pause_button:" STOP = "**Stopped** :stop_button:" LOOP_ENABLED = "**Loop enabled**" LOOP_DISABLED = "**Loop disabled**" RESUME = "**Resumed**" SHUFFLE = "**Playlist shuffled**" CONNECT_TO_CHANNEL = ":x: **Please connect to a voice channel**" WRONG_CHANNEL = ":x: **You need to be in the same voice channel as HalvaBot to use this command**" CURRENT = "**Now playing** :notes:" NO_CURRENT = "**No current songs**" START_PLAYING = "**Playing** :notes: `{song_name}` - Now!" ENQUEUE = "`{song_name}` - **added to queue!**"
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. # List of contributors: # Jordi Esteve <jesteve@zikzakmedia.com> # Ignacio Ibeas <ignacio@acysos.com> # Dpto. Consultoría Grupo Opentia <consultoria@opentia.es> # Pedro M. Baeza <pedro.baeza@tecnativa.com> # Carlos Liébana <carlos.liebana@factorlibre.com> # Hugo Santos <hugo.santos@factorlibre.com> # Albert Cabedo <albert@gafic.com> # Olivier Colson <oco@odoo.com> # Roberto Lizana <robertolizana@trey.es> { "name" : "Spain - Accounting (PGCE 2008)", "version" : "4.0", "author" : "Spanish Localization Team", 'category': 'Localization', "description": """ Spanish charts of accounts (PGCE 2008). ======================================== * Defines the following chart of account templates: * Spanish general chart of accounts 2008 * Spanish general chart of accounts 2008 for small and medium companies * Spanish general chart of accounts 2008 for associations * Defines templates for sale and purchase VAT * Defines tax templates * Defines fiscal positions for spanish fiscal legislation * Defines tax reports mod 111, 115 and 303 """, "depends" : [ "account", "base_iban", "base_vat", ], "data" : [ 'data/account_group.xml', 'data/account_chart_template_data.xml', 'data/account.account.template-common.csv', 'data/account.account.template-pymes.csv', 'data/account.account.template-assoc.csv', 'data/account.account.template-full.csv', 'data/account_chart_template_account_account_link.xml', 'data/account_data.xml', 'data/account_tax_data.xml', 'data/account_fiscal_position_template_data.xml', 'data/account_chart_template_configure_data.xml', ], }
def leiaInt(msg): while True: try: n = int(input(msg)) except (ValueError, TypeError): print('Erro: Por favor, digite um numero valido') continue except (KeyboardInterrupt): print('Entrada interromepida pelo usuario') return 0 else: return n def leiaFloat(msg): while True: try: n = float(input(msg)) except (ValueError, TypeError): print('Erro: Por favor, digite um numero valido') continue except (KeyboardInterrupt): print('Entrada interromepida pelo usuario') return 0 else: return n num1 = leiaInt('digite um numero inteiro: ') num2 = leiaFloat('digite um numero real: ') print(num1, num2 )
#leia um numero inteiro e #imprima a soma do sucessor de seu triplo com #o antecessor de seu dobro num=int(input("Informe um numero: ")) valor=((num*3)+1)+((num*2)-1) print(f"A soma do sucessor de seu triplo com o antecessor de seu dobro eh {valor}")
""" [Weekly #22] Machine Learning https://www.reddit.com/r/dailyprogrammer/comments/3206mk/weekly_22_machine_learning/ # [](#WeeklyIcon) Asimov would be proud! [Machine learning](http://en.wikipedia.org/wiki/Machine_learning) is a diverse field spanning from optimization and data classification, to computer vision and pattern recognition. Modern algorithms for detecting spam email use machine learning to react to developing types of spam and spot them quicker than people could! Techniques include evolutionary programming and genetic algorithms, and models such as [artificial neural networks](http://en.wikipedia.org/wiki/Artificial_neural_network). Do you work in any of these fields, or study them in academics? Do you know something about them that's interesting, or have any cool resources or videos to share? Show them to the world! Libraries like [OpenCV](http://en.wikipedia.org/wiki/OpenCV) (available [here](http://opencv.org/)) use machine learning to some extent, in order to adapt to new situations. The United Kingdom makes extensive use of [automatic number plate recognition](http://en.wikipedia.org/wiki/Police-enforced_ANPR_in_the_UK) on speed cameras, which is a subset of optical character recognition that needs to work in high speeds and poor visibility. Of course, there's also /r/MachineLearning if you want to check out even more. They have a [simple questions thread](http://www.reddit.com/r/MachineLearning/comments/2xopnm/mondays_simple_questions_thread_20150302/) if you want some reading material! *This post was inspired by [this challenge submission](http://www.reddit.com/r/dailyprogrammer_ideas/comments/31wpzp/intermediate_hello_world_genetic_or_evolutionary/). Check out /r/DailyProgrammer_Ideas to submit your own challenges to the subreddit!* ### IRC We have an [IRC channel on Freenode](http://www.reddit.com/r/dailyprogrammer/comments/2dtqr7/), at **#reddit-dailyprogrammer**. Join the channel and lurk with us! ### Previously... The previous weekly thread was [**Recap and Updates**](http://www.reddit.com/r/dailyprogrammer/comments/2sx7nn/). """ def main(): pass if __name__ == "__main__": main()
input = open('input.txt', 'r').read().split("\n") depths = list(map(lambda s: int(s), input)) increases = 0; for i in range(1, len(depths)): if depths[i-2] + depths[i-1] + depths[i] > depths[i-3] + depths[i-2] + depths[i-1]: increases += 1 print(increases)
#!/usr/bin/env python # # Copyright 2019 DFKI GmbH. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. class HeightMapInterface(object): def __init__(self, image, width, depth, scale, height_scale, pixel_is_tuple=False): self.height_map_image = image self.scale = scale self.height_scale = height_scale self.width = width self.depth = depth self.x_offset = 0 self.z_offset = 0 self.is_tuple = pixel_is_tuple def to_relative_coordinates(self, center_x, center_z, x, z): """ get position relative to upper left """ relative_x = x - center_x relative_z = z - center_z relative_x /= self.scale[0] relative_z /= self.scale[1] relative_x += self.width / 2 relative_z += self.depth / 2 # scale by width and depth to range of 1 relative_x /= self.width relative_z /= self.depth return relative_x, relative_z def get_height_from_relative_coordinates(self, relative_x, relative_z): if relative_x < 0 or relative_x > 1.0 or relative_z < 0 or relative_z > 1.0: print("Coordinates outside of the range") return 0 # scale by image width and height to image range ix = relative_x * self.height_map_image.size[0] iy = relative_z * self.height_map_image.size[1] p = self.height_map_image.getpixel((ix, iy)) if self.is_tuple: p = p[0] return (p / 255) * self.height_scale def get_height(self, x, z): rel_x, rel_z = self.to_relative_coordinates(self.x_offset, self.z_offset, x, z) y = self.get_height_from_relative_coordinates(rel_x, rel_z) #print("get height", x, z,":", y) return y
""" Support for forex pip calculations. Resources: https://forums.babypips.com/t/having-problem-finding-number-of-pips/111993/2 https://stackoverflow.com/questions/48038949/find-pips-value-3-to-5-digits-forex-pricing-calculation https://www.luckscout.com/how-to-measure-the-number-of-pips-of-a-price-move-on-mt4/ """ def multiplier(price): """ The "multiplier" is a number that indicates what to multiply price difference by to get pips. Examples: The pip distance between 1.25661 and 1.10896 on EUR/USD chart is 1476.5 pips: 1.25661 – 1.10896 = 0.14765 Then multiply 0.14765 by 10000 The pip distance between 114.234 and 114.212 = abs(price1 - price2) * 100 The multiplier for prices with 3 digits after decimal = 100 The multiplier for prices with 4 or 5 digits after decimal = 10000 :param price: a floating point number that will have 3, 4, or 5 digits after decimal. E.g. 112.321 :return: """ before, after = str(price).split('.') if len(after) == 3: return 100 if len(after) == 4: return 10000 if len(after) == 5: return 10000 raise Exception(f"unable to calculate multipler for price {price}.") def pips_between(price1, price2): """ Return the number of pips between price1 and price2. :param price1: float :param price2: float :return: float """ diff = abs(price1 - price2) * multiplier(price1) return round(diff, 1) def to_points(pips): return int(pips * 10) if __name__ == '__main__': prices=[ (114.234, 114.204), (1.12345, 1.12305), (1.12345, 1.12340) ] for p1, p2 in prices: print("The pip difference between {} and {} is {}".format( p1, p2, pips_between(p1,p2) ))
class NasmPackage (Package): def __init__ (self): Package.__init__ (self, 'nasm', '2.10.07', sources = [ 'http://www.nasm.us/pub/nasm/releasebuilds/2.10.07/nasm-%{version}.tar.xz' ]) NasmPackage ()
''' Description: Given the root of a binary search tree with distinct values, modify it so that every node has a new value equal to the sum of the values of the original tree that are greater than or equal to node.val. As a reminder, a binary search tree is a tree that satisfies these constraints: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: Input: [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8] Note: The number of nodes in the tree is between 1 and 100. Each node will have value between 0 and 100. The given tree is a binary search tree. ''' # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def reversed_inorder_traversal( self, node: TreeNode): if not node: # empty node or empty tree return else: # DFS to next level yield from self.reversed_inorder_traversal( node.right ) yield node yield from self.reversed_inorder_traversal( node.left ) def bstToGst(self, root: TreeNode) -> TreeNode: accumulation_sum = 0 for node in self.reversed_inorder_traversal(root): accumulation_sum += node.val node.val = accumulation_sum return root # n : number of nodes in binary tree ## Time Complexity: O( n ) # # The overhead in time is the cost of reversed in-order DFS traversal, which is of O( n ). ## Space Complexity: O( 1 ) # # The overhead in space is the looping index and iterator, which is of O( n ) def print_inorder( node: TreeNode): if node: print_inorder( node.left ) print(f'{node.val} ', end = '') print_inorder( node.right ) return def test_bench(): node_0 = TreeNode( 0 ) node_1 = TreeNode( 1 ) node_2 = TreeNode( 2 ) node_3 = TreeNode( 3 ) node_4 = TreeNode( 4 ) node_5 = TreeNode( 5 ) node_6 = TreeNode( 6 ) node_7 = TreeNode( 7 ) node_8 = TreeNode( 8 ) root = node_4 root.left = node_1 root.right = node_6 node_1.left = node_0 node_1.right = node_2 node_6.left = node_5 node_6.right = node_7 node_2.right = node_3 node_7.right = node_8 # before: # expected output: ''' 0 1 2 3 4 5 6 7 8 ''' print_inorder( root ) Solution().bstToGst( root ) print("\n") # after: # expected output: ''' 36 36 35 33 30 26 21 15 8 ''' print_inorder( root ) return if __name__ == '__main__': test_bench()
# 所有对话信息 level_chats = (((1, "Hello there new challenger!"), (1, "Welcome to Snake Quest, where you will face multiple challenges!"), (2, "What's the prize?"), (1, "The prize is endless food!"), (2, "yeye how do I start"), (1, "But first I need to go through the controls with ya"), (1, "The snake will follow your cursor"), (1, "Going outside of the boundary will kill you"), (1, "When your hp drops to 0, you are basically dead"), (1, "On the top left corner, is your current level. The higher the level the longer the snake"), (1, "In the first stage, you only need to reach level 3"), (2, "ezpz"), (1, "You will regret saying that :^)"), (1, "Finish this dialog whenever you are ready!")), ((1, "Congrats on finishing stage one!"), (1, "The real challenge begins now"), (2, "git gud too ez"), (1, "In stage two you will need to dodge cannonballs."), (1, "Similarly, walking outside of the boundary will kill you."), (2, "that's it?"), (1, "yep that's it"), (1, "But you will need to reach level 5 this time."), (1, "Finish this dialog whenever you are ready!")), ((1, "Looks like you are adapting to this."), (1, "Here comes level 3."), (2, "What's in level 3?"), (1, "Lasers, four of them"), (1, "It will be right in the middle, get ready to dodge"), (1, "You gotta dodge them!"), (2, "well that's all?"), (1, "Not only that! In this stage each food gives double the xp"), (1, "You will also need to reach level 10"), (1, "In other words, you will grow longer"), (2, "gotcha, I'm ready"), (1, "Finish this dialog whenever you are ready!")), ((1, "Stage 4, is the hardest of them all in my opinion"), (2, "yeyeye?"), (1, "Do you remember the lazers?"), (2, "Too ez with my dodging skills"), (1, "But in this stage the lazers move as well~"), (2, "?say what"), (1, "Finish this dialog whenever you are ready!")), ((1, "We are starting stage 5!"), (2, "Stage 4 was too ez, twas not hard at all"), (1, "In that case, stage 5 will be even easier!"), (1, "There's only one trick: run in circles"), (2, "What does that mean?"), (1, "You will see~"), (1, "Hint: try not to stay in the middle after the first 2 seconds"), (2, "I should stay at the edges?"), (1, "Exactly~Finish this dialog whenever you are ready!")), ((1, "Congrats on finishing level 5!"), (2, "<_< that first laser scared me a lil"), (1, "lol I will make stage 6 clearer"), (2, "you'd better be <_<"), (1, "you'll still get the laser, but an ultra large one!"), (1, "It's so big that it covers half of the field!"), (2, "but, how am I supposed to dodge that?"), (1, "It's also so large that it needs a long time to recharge"), (1, "Just dodge it while it's charging!"), (2, "gocha"), (1, "GL, end this dialog whenever you are ready!")), ((1, "Welcome to the last stage!"), (2, "Finally!"), (1, "It was a long way here! So I made this level easier."), (2, "yeyeye?"), (1, "You will need to reach level 15, and dodge a few things"), (2, "ye?"), (1, "GL, end this dialog whenever you are ready!")), ((1, "Congrats! You finished the whole game!"), (2, "Yea!!"), (1, "Now you have gained access to infinite amount of food!"), (2, "yayay :DDDD"), (1, "Thank you for playing!"), (2, "It's a small game made with pygame by Jeff Yan"), (2, "Thank you very much for playing!"), (1, "Thank you!!!")) )
number_of_drugs = 5 max_id = 1<<5 string_length = len("{0:#b}".format(max_id-1)) -2 EC50_for_0 = 0.75 EC50_for_1 = 1.3 f = lambda x: EC50_for_0 if x=='0' else EC50_for_1 print("[\n", end="") for x in range(0,max_id): gene_string = ("{0:0"+str(string_length)+"b}").format(x) ec50 = list(map(f, list(gene_string))) print(ec50, end="") if(x != max_id-1) : print(",") else: print("") print("]")
# 30.python代码实现删除一个list里面的重复元素 a = [1,2,3,4,5,6,5,4,3,2,0] b = list(set(a)) print(b) # 或者可以考虑创建一个新的 空列表,然后遍历原列表,不在新列表中的进行append
frutas = {"maça","Laranja","Abacaxi"} frutas.add("Pera") frutas.remove("maça") frutas.pop() print(frutas) set1 = {"maça","Laranja","Abacaxi"} set2 = {0,3,50,-74} set3 = {True,False,False,False} set4 = {"Roger",34,True} print(set4)
input1='389125467' input2='496138527' lowest=1 highest=1000000 class Node: def __init__(self, val, next_node=None): self.val=val self.next=next_node cups=list(input2) cups=list(map(int,cups)) lookup_table={} prev=None # form linked list from the end node to beginning node for i in range(len(cups)-1,-1,-1): new=Node(cups[i]) new.next=prev lookup_table[cups[i]]=new # direct reference to the node that has the cup value prev=new for i in range(highest,9,-1): new=Node(i) new.next=prev lookup_table[i]=new prev=new lookup_table[cups[-1]].next=lookup_table[10] current=lookup_table[cups[0]] for _ in range(10000000): a=current.next b=a.next c=b.next current.next=c.next removed={current.val,a.val,b.val,c.val} destination=current.val while destination in removed: destination-=1 if destination==0: destination=highest destination_reference=lookup_table[destination] destination_old_next=destination_reference.next destination_reference.next=a c.next=destination_old_next current=current.next maincup=lookup_table[1] a=maincup.next b=a.next print(a.val*b.val)
def counting_sort(arr): k = max(arr) count = [0] * k + [0] for x in arr: count[x] += 1 for i in range(1, len(count)): count[i] = count[i] + count[i-1] output = [0] * len(arr) for x in arr: output[count[x]-1] = x yield output, count[x]-1 count[x] -= 1 yield output, count[x] #print(counting_sort([1,4,2,3,4,5]))
number = int(input()) if 100 <= number <= 200 or number == 0: pass else: print('invalid')
def nth(test, items): if test > 0: test -= 1 else: test = 0 for i, v in enumerate(items): if i == test: return v
# Combinations class Solution: def combine(self, n, k): ans = [] def helper(choices, start, count, ans): if count == k: # cloning the list here ans.append(list(choices)) return for i in range(start, n + 1): choices[count] = i helper(choices, i + 1, count + 1, ans) helper([None] * k, 1, 0, ans) return ans if __name__ == "__main__": sol = Solution() n = 1 k = 1 print(sol.combine(n, k))
class PyTime: def printTime(self,input): time_in_string = str(input) length = len(time_in_string) if length == 3: hour,minute1,minute2 = time_in_string hours = "0" + hour minutes = minute1 + minute2 converted_time = self.calculateTime(hours,minutes) elif length == 4: hour1,hour2,minute1,minute2 = time_in_string hours = hour1 + hour2 minutes = minute1 + minute2 converted_time = self.calculateTime(hours,minutes) elif time_in_string=="000" or time_in_string=="0000": hour1,hour2,minute1,minute2 = time_in_string hours = hour1 + hour2 minutes = minute1 + minute2 converted_time = self.calculateTime(hours,minutes) else: return "Invalid Format" return converted_time def calculateTime(self,hours,minutes): hours_in_int = int(hours) minutes_in_int = int(minutes) if hours_in_int >= 1 and hours_in_int < 12: converted_time = hours + ":" + minutes + " AM" elif hours_in_int >= 12 and hours_in_int < 24: converted_time = hours + ":" + minutes + " PM" elif hours == "00": hours = "12" converted_time = hours + ":" + minutes + " AM" return converted_time
# create sets names = {'anonymous','tazri','farha'}; extra_name = {'tazri','farha','troy'}; name_list = {'solus','xenon','neon'}; name_tuple = ('helium','hydrogen'); print("names : ",names); # add focasa in names print("add 'focasa' than set : "); names.add("focasa"); print(names); # update method print("\n\nadd extra_name in set with update method : "); names.update(extra_name); print(names); # update set with list print("\nadd name_list in set with update method : "); names.update(name_list); print(names); # update set with tuple print("\nadd name_tuple in set with update method : "); names.update(name_tuple); print(names);
#! /usr/bin/python3.6 def create_spa_workbench(document): """ :param document: :return: workbench com object """ return document.GetWorkbench("SPAWorkbench")
user = int(input("ENTER NUMBER OF STUDENTS IN CLASS : ")) i = 1 marks = [] absent = [] # mark = marks.copy() print("FOR ABSENT STUDENTS TYPE -1 AS MARKS") for j in range(user): student = int(input("ENTER MARKS OF STUDENT {} : ".format(i))) if student == -1: absent.append(i) else: marks.append(student) i += 1 def avg(): mrk = 0 for mark in marks: mrk += mark avg = mrk/(user-len(absent)) print("AVERAGE SCORE OF THE CLASS IS {}".format(avg)) def hmax_hmin(): hmax = 0 hmin = 100 for high in marks: if high > hmax: hmax = high for min in marks: if min < hmin: hmin = min print("HIGHEST SCORE OF THE CLASS IS {}".format(hmax)) print("--------------------------") print("LOWEST SCORE OF THE CLASS IS {}".format(hmin)) print("--------------------------") # print("--------------------------") # print("--------------------------") def abs_nt(): if len(absent) > 1: print("{} STUDENTS WERE ABSENT FOR THE TEST".format(len(absent))) elif len(absent) >= 1: print("{} STUDENT WAS ABSENT FOR THE TEST".format(len(absent))) else: print("ALL STUDENTS WERE PRESENT FOR THE TEST") print("--------------------------") def freq(): frq = 0 frmax = 0 for ele in marks: if marks.count(ele) > frq: frq = marks.count(ele) frmax = ele print("{} IS THE SCORE WITH HIGHEST OCCURING FREQUENCY {}".format(frmax, frq)) ######################################## while(1): print("FOR AVG TYPE 1") print("FOR MAX_MARKS AND MIN_MARKS TYPE 2") print("FOR FREQUENCY TYPE 3") print("FOR NUMBER OF ABSENT STUDENT TYPE 4") choise=int(input()) if choise==1: print("--------------------------") avg() print("--------------------------") elif choise==2: print("--------------------------") hmax_hmin() print("--------------------------") elif choise==3: print("--------------------------") freq() print("--------------------------") elif choise==4: print("--------------------------") abs_nt() print("--------------------------") else: print("--------------------------") print("TYPE RIGHT CHOICE") print("--------------------------") break
def sum_func(num1,num2 =30,num3=40): return num1 + num2 + num3 print(sum_func(10)) print(sum_func(10,20)) print(sum_func(10,20,30))
#!/usr/bin/env python # -*- config : utf-8 -*- 'help' class Report(object): """ You can wirte the report has created into a html file. """ def __init__(self, headtitle, content): self.headtitle = 'Bat''s' + headtitle self.content = content def replace(self): self.content = self.content.replace('\n', '<br>') self.content = self.content.replace('###', '') self.content = self.content.replace('[', '<h3>') self.content = self.content.replace(']', '</h3>') def create(self): self.replace() self.content = '<h1>' + self.headtitle + ' Report</h1>' + self.content with open('./' + self.headtitle + '.html', 'w') as f: f.write(self.content) class ScanReport(Report): """ For scan """ def __init__(self, headtitle, content): pass
''' No automobilismo é bastante comum que o líder de uma prova, em determinado momento, ultrapasse o último colocado. O líder, neste momento, está uma volta à frente do último colocado, que se torna, assim, um retardatário. Neste problema, dados os tempos que o piloto mais rápido e o piloto mais lento levam para completar uma volta, você deve determinar em que volta o último colocado se tornará um retardatário, ou seja, será ultrapassado pelo líder. Você deve considerar que, inicialmente, eles estão lado a lado, na linha de partida do circuito, ambos no início da volta de número 1 (a primeira volta da corrida); e que uma nova volta se inicia sempre depois que o líder cruza a linha de partida. Entrada A única linha da entrada contém dois números inteiros X e Y (1 ≤ X < Y ≤ 10000), os tempos, em segundos, que o piloto mais rápido e o piloto mais lento levam para completar uma volta, respectivamente. Saída Seu programa deve produzir uma única linha, contendo um único inteiro: a volta em que o piloto mais lento se tornará um retardatário. ''' entrada = str(input()).split() X = int(entrada[0]) Y = int(entrada[1]) dif = abs(X - Y) count = i = 0 while i < max(X, Y): i += dif count += 1 print(count)
def variableName(name): str_name = [i for i in str(name)] non_acc_chars = [ " ", ">", "<", ":", "-", "|", ".", ",", "!", "[", "]", "'", "/", "@", "#", "&", "%", "?", "*", ] if str_name[0] in str([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]): return False for j in range(len(str_name)): if str_name[j] in non_acc_chars: return False return True
# 372.在O(1)时间复杂度删除链表节点 / delete-node-in-the-middle-of-singly-linked-lis # http://www.lintcode.com/problem/delete-node-in-the-middle-of-singly-linked-list # 给定一个单链表中的一个等待被删除的节点(非表头或表尾)。请在在O(1)时间复杂度删除该链表节点。 # Exa # 给定 1->2->3->4,和节点 3,删除 3 之后,链表应该变为 1->2->4。 """ Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: # @param node: the node in the list should be deleted # @return: nothing def deleteNode(self, node): # write your code here if node is None: return if node.next is not None: node.val = node.next.val node.next = node.next.next
class Vector2d( object, ISerializable, IEquatable[Vector2d], IComparable[Vector2d], IComparable, IEpsilonComparable[Vector2d], ): """ Represents the two components of a vector in two-dimensional space, using System.Double-precision floating point numbers. Vector2d(x: float,y: float) """ def CompareTo(self, other): """ CompareTo(self: Vector2d,other: Vector2d) -> int Compares this Rhino.Geometry.Vector2d with another Rhino.Geometry.Vector2d. Components evaluation priority is first X,then Y. other: The other Rhino.Geometry.Vector2d to use in comparison. Returns: 0: if this is identical to other-1: if this.X < other.X-1: if this.X == other.X and this.Y < other.Y+1: otherwise. """ pass def EpsilonEquals(self, other, epsilon): """ EpsilonEquals(self: Vector2d,other: Vector2d,epsilon: float) -> bool Check that all values in other are within epsilon of the values in this """ pass def Equals(self, *__args): """ Equals(self: Vector2d,vector: Vector2d) -> bool Determines whether the specified vector has the same value as the present vector. vector: The specified vector. Returns: true if vector has the same components as this; otherwise false. Equals(self: Vector2d,obj: object) -> bool Determines whether the specified System.Object is a Vector2d and has the same value as the present vector. obj: The specified object. Returns: true if obj is Vector2d and has the same components as this; otherwise false. """ pass def GetHashCode(self): """ GetHashCode(self: Vector2d) -> int Provides a hashing value for the present vector. Returns: A non-unique number based on vector components. """ pass def ToString(self): """ ToString(self: Vector2d) -> str Constructs a string representation of the current vector. Returns: A string in the form X,Y. """ pass def Unitize(self): """ Unitize(self: Vector2d) -> bool Unitizes the vector in place. A unit vector has length 1 unit. An invalid or zero length vector cannot be unitized. Returns: true on success or false on failure. """ pass def __eq__(self, *args): """ x.__eq__(y) <==> x==y """ pass def __ge__(self, *args): pass def __gt__(self, *args): pass def __init__(self, *args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __le__(self, *args): pass def __lt__(self, *args): pass @staticmethod def __new__(self, x, y): """ __new__[Vector2d]() -> Vector2d __new__(cls: type,x: float,y: float) """ pass def __ne__(self, *args): pass def __reduce_ex__(self, *args): pass def __repr__(self, *args): """ __repr__(self: object) -> str """ pass def __str__(self, *args): pass IsValid = property(lambda self: object(), lambda self, v: None, lambda self: None) """Gets a value indicating whether this vector is valid. A valid vector must be formed of valid component values for x,y and z. Get: IsValid(self: Vector2d) -> bool """ Length = property(lambda self: object(), lambda self, v: None, lambda self: None) """Computes the length (or magnitude,or size) of this vector. This is an application of Pythagoras' theorem. Get: Length(self: Vector2d) -> float """ X = property(lambda self: object(), lambda self, v: None, lambda self: None) """Gets or sets the X (first) component of this vector. Get: X(self: Vector2d) -> float Set: X(self: Vector2d)=value """ Y = property(lambda self: object(), lambda self, v: None, lambda self: None) """Gets or sets the Y (second) component of this vector. Get: Y(self: Vector2d) -> float Set: Y(self: Vector2d)=value """ Unset = None Zero = None
def palindrome(num): return str(num) == str(num)[::-1] # Bots are software programs that combine requests # top Returns a reference to the top most element of the stack def largest(bot, top): z = 0 for i in range(top, bot, -1): for j in range(top, bot, -1): if palindrome(i * j): if i*j > z: z = i*j return z print(largest(100, 999))
# # Copyright (c) 2020 Xilinx, Inc. All rights reserved. # SPDX-License-Identifier: MIT # plnx_package_boot = True # Generate Package Boot Images
# # PySNMP MIB module AGG-TRAP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AGG-TRAP-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:15:43 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # devName, mateHost, unknownDeviceTrapContents, pepName, oldFile, reason, result, matePort, file, sbProducerPort, port, snName, host, myHost, minutes, newFile, sbProducerHost, myPort = mibBuilder.importSymbols("AGGREGATED-EXT-MIB", "devName", "mateHost", "unknownDeviceTrapContents", "pepName", "oldFile", "reason", "result", "matePort", "file", "sbProducerPort", "port", "snName", "host", "myHost", "minutes", "newFile", "sbProducerHost", "myPort") ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") snmpModules, ObjectName, Counter32, IpAddress, Integer32, TimeTicks, ModuleIdentity, Unsigned32, Gauge32, NotificationType, enterprises, Counter64, Bits, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, iso = mibBuilder.importSymbols("SNMPv2-SMI", "snmpModules", "ObjectName", "Counter32", "IpAddress", "Integer32", "TimeTicks", "ModuleIdentity", "Unsigned32", "Gauge32", "NotificationType", "enterprises", "Counter64", "Bits", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "iso") RowStatus, TruthValue, TestAndIncr, DisplayString, TimeStamp, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "TruthValue", "TestAndIncr", "DisplayString", "TimeStamp", "TextualConvention") lucent = MibIdentifier((1, 3, 6, 1, 4, 1, 1751)) products = MibIdentifier((1, 3, 6, 1, 4, 1, 1751, 1)) mantraDevice = MibIdentifier((1, 3, 6, 1, 4, 1, 1751, 1, 1198)) mantraTraps = ModuleIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0)) if mibBuilder.loadTexts: mantraTraps.setLastUpdated('240701') if mibBuilder.loadTexts: mantraTraps.setOrganization('Lucent Technologies') if mibBuilder.loadTexts: mantraTraps.setContactInfo('') if mibBuilder.loadTexts: mantraTraps.setDescription('The MIB module for entities implementing the xxxx protocol.') unParsedEvent = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 5)).setObjects(("AGGREGATED-EXT-MIB", "unknownDeviceTrapContents")) if mibBuilder.loadTexts: unParsedEvent.setStatus('current') if mibBuilder.loadTexts: unParsedEvent.setDescription('An event is sent up as unParsedEvent, if there is an error in formatting, and event construction does not succeed. The variables are: 1) unknownDeviceTrapContents - a string representing the event text as the pep received it. Severity: MAJOR') styxProducerConnect = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 6)).setObjects(("AGGREGATED-EXT-MIB", "pepName"), ("AGGREGATED-EXT-MIB", "devName"), ("AGGREGATED-EXT-MIB", "host"), ("AGGREGATED-EXT-MIB", "port"), ("AGGREGATED-EXT-MIB", "file")) if mibBuilder.loadTexts: styxProducerConnect.setStatus('current') if mibBuilder.loadTexts: styxProducerConnect.setDescription('Indicates that the pep was sucessfully able to connect to the source of events specified in its config. The variables are: 1) pepName - this is the name of the PEP who is raising the event 2) devName - this is the logical name of the device this pep is connected to 3-4) host:port - these two identify the device that was mounted by the pep 5) file - this is the file name used internally start-up event, mainly. Severity: INFO') styxProducerUnReadable = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 7)).setObjects(("AGGREGATED-EXT-MIB", "pepName"), ("AGGREGATED-EXT-MIB", "devName"), ("AGGREGATED-EXT-MIB", "host"), ("AGGREGATED-EXT-MIB", "port"), ("AGGREGATED-EXT-MIB", "file")) if mibBuilder.loadTexts: styxProducerUnReadable.setStatus('current') if mibBuilder.loadTexts: styxProducerUnReadable.setDescription("Indicates that the pep's connection exists to the device, but the file named in the trap is not readable. The variables are: 1) pepName - this is the name of the PEP who is raising the event 2) devName - this is the logical name of the device this pep is connected to 3-4) host:port - these two identify the device that was mounted by the pep 5) file - this is the file name used internally Severity: MAJOR") styxProducerDisconnect = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 8)).setObjects(("AGGREGATED-EXT-MIB", "pepName"), ("AGGREGATED-EXT-MIB", "devName"), ("AGGREGATED-EXT-MIB", "host"), ("AGGREGATED-EXT-MIB", "port"), ("AGGREGATED-EXT-MIB", "file")) if mibBuilder.loadTexts: styxProducerDisconnect.setStatus('current') if mibBuilder.loadTexts: styxProducerDisconnect.setDescription("Indicates that the pep's connection to the source of events was severed. This could either be because device process died, or because there is a network outage. The variables are: 1) pepName - this is the name of the PEP who is raising the event 2) devName - this is the logical name of the device this pep is connected to 3-4) host:port - these two identify the device that was mounted by the pep 5) file - this is the file name used internally Severity: MAJOR") styxProducerUnReachable = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 9)).setObjects(("AGGREGATED-EXT-MIB", "pepName"), ("AGGREGATED-EXT-MIB", "devName"), ("AGGREGATED-EXT-MIB", "host"), ("AGGREGATED-EXT-MIB", "port"), ("AGGREGATED-EXT-MIB", "file"), ("AGGREGATED-EXT-MIB", "minutes")) if mibBuilder.loadTexts: styxProducerUnReachable.setStatus('current') if mibBuilder.loadTexts: styxProducerUnReachable.setDescription("Indicates that the pep's connection to the device has not been up for some time now, indicated in minutes. The variables are: 1) pepName - this is the name of the PEP who is raising the event 2) devName - this is the logical name of the device this pep is connected to 3-4) host, port - these two identify the device that was mounted by the pep 5) file - this is the file name used internally minutes - the time in minutes for which the connection to the device has not been up. Severity: MAJOR") logFileChanged = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 10)).setObjects(("AGGREGATED-EXT-MIB", "oldFile"), ("AGGREGATED-EXT-MIB", "newFile"), ("AGGREGATED-EXT-MIB", "result"), ("AGGREGATED-EXT-MIB", "reason")) if mibBuilder.loadTexts: logFileChanged.setStatus('current') if mibBuilder.loadTexts: logFileChanged.setDescription("Indicates that a log-file-change attempt is successful or failure. The variables are: 1) oldFile - this is the name of the old file which was to be changed. 2) newFile - this is the new log file name 3) result - this indicates 'success' or failure of logFileChange attempt. 4) reason - this describes the reason when log file change has failed. Severity: INFO") styxFTMateConnect = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 11)).setObjects(("AGGREGATED-EXT-MIB", "snName"), ("AGGREGATED-EXT-MIB", "myHost"), ("AGGREGATED-EXT-MIB", "myPort"), ("AGGREGATED-EXT-MIB", "mateHost"), ("AGGREGATED-EXT-MIB", "matePort")) if mibBuilder.loadTexts: styxFTMateConnect.setStatus('current') if mibBuilder.loadTexts: styxFTMateConnect.setDescription('Indicates that this ServiceNode was sucessfully able to connect to its redundant mate. This event is usually raised by the Backup mate who is responsible for monitoring its respective Primary. The variables are: 1) snName - this is the name of the ServiceNode who is raising the event. 2-3) myHost:myPort - these identify the host and port of the ServiceNode raising the event. 4-5) mateHost:matePort - these identify the host and port of the mate to which this ServiceNode connected. Severity: INFO') styxFTMateDisconnect = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 12)).setObjects(("AGGREGATED-EXT-MIB", "snName"), ("AGGREGATED-EXT-MIB", "myHost"), ("AGGREGATED-EXT-MIB", "myPort"), ("AGGREGATED-EXT-MIB", "mateHost"), ("AGGREGATED-EXT-MIB", "matePort")) if mibBuilder.loadTexts: styxFTMateDisconnect.setStatus('current') if mibBuilder.loadTexts: styxFTMateDisconnect.setDescription('Indicates that this ServiceNode has lost connection to its redundant mate due to either process or host failure. This event is usually raised by the Backup mate who is monitoring its respective Primary. Connection will be established upon recovery of the mate. The variables are: 1) snName - this is the name of the ServiceNode who is raising the event 2-3) myHost:myPort - these identify the host and port of the ServiceNode raising the event. 4-5) mateHost:matePort - these identify the host and port of the mate to which this ServiceNode lost connection. Severity: MAJOR') sBProducerUnreachable = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 13)).setObjects(("AGGREGATED-EXT-MIB", "pepName"), ("AGGREGATED-EXT-MIB", "devName"), ("AGGREGATED-EXT-MIB", "sbProducerHost"), ("AGGREGATED-EXT-MIB", "sbProducerPort")) if mibBuilder.loadTexts: sBProducerUnreachable.setStatus('current') if mibBuilder.loadTexts: sBProducerUnreachable.setDescription('Indicates that this Socket Based Producer is not reachable by the Policy Enforcement Point. The variables are: 1) pepName - this is the name of the Policy Enforcement Point (PEP) who is raising the event 2) devName: Device which is unreachable 3) sbProducerHost: Host where the Socket Based event producer is on. 4) sbProducerPort: Port where the Socket Based event producer is running on. Severity: MAJOR') sBProducerConnected = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 14)).setObjects(("AGGREGATED-EXT-MIB", "pepName"), ("AGGREGATED-EXT-MIB", "devName"), ("AGGREGATED-EXT-MIB", "sbProducerHost"), ("AGGREGATED-EXT-MIB", "sbProducerPort")) if mibBuilder.loadTexts: sBProducerConnected.setStatus('current') if mibBuilder.loadTexts: sBProducerConnected.setDescription('Indicates that this Socket Based Producer has connected to the Policy Enforcement Point (PEP). The variables are: 1) pepName - this is the name of the Policy Enforcement Point (PEP) who is raising the event 2) devName: Device which is unreachable 3) sbProducerHost: Host where the Socket Based event producer is on. 4) sbProducerPort: Port where the Socket Based event producer is running on. Severity: MAJOR') sBProducerRegistered = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 15)).setObjects(("AGGREGATED-EXT-MIB", "pepName"), ("AGGREGATED-EXT-MIB", "devName"), ("AGGREGATED-EXT-MIB", "sbProducerHost"), ("AGGREGATED-EXT-MIB", "sbProducerPort")) if mibBuilder.loadTexts: sBProducerRegistered.setStatus('current') if mibBuilder.loadTexts: sBProducerRegistered.setDescription('Indicates that this Socket Based Producer has registered with the Policy Enforcement Point (PEP). The variables are: 1) pepName - this is the name of the Policy Enforcement Point (PEP) who is raising the event 2) devName: Device which is unreachable 3) sbProducerHost: Host where the Socket Based event producer is on. 4) sbProducerPort: Port where the Socket Based event producer is running on. Severity: INFO') sBProducerDisconnected = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 16)).setObjects(("AGGREGATED-EXT-MIB", "pepName"), ("AGGREGATED-EXT-MIB", "devName"), ("AGGREGATED-EXT-MIB", "sbProducerHost"), ("AGGREGATED-EXT-MIB", "sbProducerPort")) if mibBuilder.loadTexts: sBProducerDisconnected.setStatus('current') if mibBuilder.loadTexts: sBProducerDisconnected.setDescription('Indicates that this Socket Based Producer has disconnected from the Policy Enforcement Point (PEP). The variables are: 1) pepName - this is the name of the Policy Enforcement Point (PEP) who is raising the event 2) devName: Device which is unreachable 3) sbProducerHost: Host where the Socket Based event producer is on. 4) sbProducerPort: Port where the Socket Based event producer is running on. Severity: INFO') sBProducerCannotRegister = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 17)).setObjects(("AGGREGATED-EXT-MIB", "pepName"), ("AGGREGATED-EXT-MIB", "devName"), ("AGGREGATED-EXT-MIB", "sbProducerHost"), ("AGGREGATED-EXT-MIB", "sbProducerPort")) if mibBuilder.loadTexts: sBProducerCannotRegister.setStatus('current') if mibBuilder.loadTexts: sBProducerCannotRegister.setDescription('Indicates that this Socket Based Producer cannot register to the Policy Enforcement Point (PEP). The variables are: 1) pepName - this is the name of the Policy Enforcement Point (PEP) who is raising the event 2) devName: Device which is unreachable 3) sbProducerHost: Host where the Socket Based event producer is on. 4) sbProducerPort: Port where the Socket Based event producer is running on. Severity: INFO') sBProducerCannotDisconnect = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 18)).setObjects(("AGGREGATED-EXT-MIB", "pepName"), ("AGGREGATED-EXT-MIB", "devName"), ("AGGREGATED-EXT-MIB", "sbProducerHost"), ("AGGREGATED-EXT-MIB", "sbProducerPort")) if mibBuilder.loadTexts: sBProducerCannotDisconnect.setStatus('current') if mibBuilder.loadTexts: sBProducerCannotDisconnect.setDescription('Indicates that this Socket Based Producer cannot disconenct from the Policy Enforcement Point (PEP). The variables are: 1) pepName - this is the name of the Policy Enforcement Point (PEP) who is raising the event 2) devName: Device which is unreachable 3) sbProducerHost: Host where the Socket Based event producer is on. 4) sbProducerPort: Port where the Socket Based event producer is running on. Severity: INFO') mibBuilder.exportSymbols("AGG-TRAP-MIB", sBProducerUnreachable=sBProducerUnreachable, sBProducerRegistered=sBProducerRegistered, PYSNMP_MODULE_ID=mantraTraps, sBProducerDisconnected=sBProducerDisconnected, products=products, styxProducerConnect=styxProducerConnect, mantraTraps=mantraTraps, styxFTMateDisconnect=styxFTMateDisconnect, sBProducerCannotDisconnect=sBProducerCannotDisconnect, styxProducerUnReachable=styxProducerUnReachable, sBProducerCannotRegister=sBProducerCannotRegister, unParsedEvent=unParsedEvent, styxFTMateConnect=styxFTMateConnect, sBProducerConnected=sBProducerConnected, logFileChanged=logFileChanged, lucent=lucent, styxProducerDisconnect=styxProducerDisconnect, mantraDevice=mantraDevice, styxProducerUnReadable=styxProducerUnReadable)
nums = [int(input()) for _ in range(int(input()))] nums_count = [nums.count(a) for a in nums] min_count, max_count - min(nums_count), max(nums_count) min_num, max_num = 0, 0 a, b = 0, 0 for i in range(len(nums)): if nums_count[i] > b: max_num = nums[i] elif nums_count[i] == b: if nums[i] > max_num: max_num = numx[i]
# File: phishtank_consts.py # # Copyright (c) 2016-2021 Splunk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under # the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # either express or implied. See the License for the specific language governing permissions # and limitations under the License. PHISHTANK_DOMAIN = 'http://www.phishtank.com' PHISHTANK_API_DOMAIN = 'https://checkurl.phishtank.com/checkurl/' PHISHTANK_APP_KEY = 'app_key' PHISHTANK_MSG_QUERY_URL = 'Querying URL: {query_url}' PHISHTANK_MSG_CONNECTING = 'Polling Phishtank site ...' PHISHTANK_SERVICE_SUCC_MSG = 'Phishtank Service successfully executed.' PHISHTANK_SUCC_CONNECTIVITY_TEST = 'Connectivity test passed' PHISHTANK_ERR_CONNECTIVITY_TEST = 'Connectivity test failed' PHISHTANK_MSG_GOT_RESP = 'Got response from Phishtank' PHISHTANK_NO_RESPONSE = 'Server did not return a response \ for the object queried' PHISHTANK_SERVER_CONNECTION_ERROR = 'Server connection error' PHISHTANK_MSG_CHECK_CONNECTIVITY = 'Please check your network connectivity' PHISHTANK_SERVER_RETURNED_ERROR_CODE = 'Server returned error code: {code}' PHISHTANK_ERR_MSG_OBJECT_QUERIED = "Phishtank response didn't \ send expected response" PHISHTANK_ERR_MSG_ACTION_PARAM = 'Mandatory action parameter missing' PHISHTANK_SERVER_ERROR_RATE_LIMIT = 'Query is being rate limited. \ Server returned 509'
# coding:utf-8 # File Name: bit_operator_test # Author : yifengyou # Date : 2021/07/18 print(5|9)
# -*- coding: utf-8 -*- { 'name': 'Events', 'category': 'Website/Website', 'sequence': 166, 'summary': 'Publish events, sell tickets', 'website': 'https://www.odoo.com/page/events', 'description': "", 'depends': ['website', 'website_partner', 'website_mail', 'event'], 'data': [ 'data/event_data.xml', 'views/res_config_settings_views.xml', 'views/event_snippets.xml', 'views/event_templates.xml', 'views/event_views.xml', 'security/ir.model.access.csv', 'security/event_security.xml', ], 'demo': [ 'data/event_demo.xml' ], 'application': True, 'license': 'LGPL-3', }
Ds = [1, 1.2, 1.5, 2, 4] file_name = "f.csv" f = open(file_name, 'r') for depth in Ds: print('\n\n DEALING WITH ALL D = ', depth-1) DATA['below_depth'] = (depth - 1) * HEIGHT for angle in range(2,90,1): if angle %5 ==0: continue if angle >= 50 and angle <=60: continue f.close() f = open(file_name, 'a') update_data(new_slope=angle, radius_step=0.1, steps_number=400) DATA['below_depth'] = (depth - 1) * HEIGHT mySlope = generate_failures(DATA['h'], DATA['slope_angle'], DATA['steps_number'], DATA['left_right'], DATA['radius_range'], below_level=DATA['below_depth'], density=DATA['density'], plot=False) iter_data = [depth, SLOPE, mySlope.stability_number, mySlope.radius, mySlope.circle_cg[0], mySlope.circle_cg[1], mySlope.type, mySlope.compound] f.write(write_list(iter_data)) f.close() for angle in range(10,90,5): plt.clf() update_data(new_slope=angle) mySlope = generate_failures(DATA['h'], DATA['slope_angle'], DATA['steps_number'], DATA['left_right'], DATA['radius_range'], below_level=DATA['below_depth'], density=DATA['density']) plt.gca().set_aspect('equal', adjustable='box') plt.xlim(-10,70) plt.ylim(-1*DATA['below_depth']-1,50) plt.savefig('plots/' + str(angle) + '.png')
class lista: def __init__(self,list): self.list=list def tamaño(self): for i in range(len(self.list)): print(f'{i+1}- {self.list[i]}') print(len(self.list)) lista1=[1,2,3,4,5] lista(lista1).tamaño()
class Db(): def __init__(self, section, host, wiki): self.section = section self.host = host self.wiki = wiki
"""Classes for handling geometry. Geometric objects (see :class:`GeometricObject`) are usually used in :class:`~ihm.restraint.GeometricRestraint` objects. """ class Center(object): """Define the center of a geometric object in Cartesian space. :param float x: x coordinate :param float y: y coordinate :param float z: z coordinate """ def __init__(self, x, y, z): self.x, self.y, self.z = x, y, z class Transformation(object): """Rotation and translation applied to an object. Transformation objects are typically used in subclasses of :class:`GeometricObject`, or by :class:`ihm.dataset.TransformedDataset`. :param rot_matrix: Rotation matrix (as a 3x3 array of floats) that places the object in its final position. :param tr_vector: Translation vector (as a 3-element float list) that places the object in its final position. """ def __init__(self, rot_matrix, tr_vector): self.rot_matrix, self.tr_vector = rot_matrix, tr_vector """Return the identity transformation. :return: A new identity Transformation. :rtype: :class:`Transformation` """ @classmethod def identity(cls): return cls([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]], [0.,0.,0.]) class GeometricObject(object): """A generic geometric object. See also :class:`Sphere`, :class:`Torus`, :class:`Axis`, :class:`Plane`. Geometric objects are typically assigned to one or more :class:`~ihm.restraint.GeometricRestraint` objects. :param str name: A short user-provided name. :param str description: A brief description of the object. """ type = 'other' def __init__(self, name=None, description=None): self.name, self.description = name, description class Sphere(GeometricObject): """A sphere in Cartesian space. :param center: Coordinates of the center of the sphere. :type center: :class:`Center` :param radius: Radius of the sphere. :param transformation: Rotation and translation that moves the sphere from the original center to its final location, if any. :type transformation: :class:`Transformation` :param str name: A short user-provided name. :param str description: A brief description of the object. """ type = 'sphere' def __init__(self, center, radius, transformation=None, name=None, description=None): super(Sphere, self).__init__(name, description) self.center, self.transformation = center, transformation self.radius = radius class Torus(GeometricObject): """A torus in Cartesian space. :param center: Coordinates of the center of the torus. :type center: :class:`Center` :param major_radius: The major radius - the distance from the center of the tube to the center of the torus. :param minor_radius: The minor radius - the radius of the tube. :param transformation: Rotation and translation that moves the torus (which by default lies in the xy plane) from the original center to its final location, if any. :type transformation: :class:`Transformation` :param str name: A short user-provided name. :param str description: A brief description of the object. """ type = 'torus' def __init__(self, center, major_radius, minor_radius, transformation=None, name=None, description=None): super(Torus, self).__init__(name, description) self.center, self.transformation = center, transformation self.major_radius, self.minor_radius = major_radius, minor_radius class HalfTorus(GeometricObject): """A section of a :class:`Torus`. This is defined as a surface over part of the torus with a given thickness, and is often used to represent a membrane. :param thickness: The thickness of the surface. :param inner: True if the surface is the 'inner' half of the torus (i.e. closer to the center), False for the outer surface, or None for some other section (described in `description`). See :class:`Torus` for a description of the other parameters. """ type = 'half-torus' def __init__(self, center, major_radius, minor_radius, thickness, transformation=None, inner=None, name=None, description=None): super(HalfTorus, self).__init__(name, description) self.center, self.transformation = center, transformation self.major_radius, self.minor_radius = major_radius, minor_radius self.thickness, self.inner = thickness, inner class Axis(GeometricObject): """One of the three Cartesian axes - see :class:`XAxis`, :class:`YAxis`, :class:`ZAxis`. :param transformation: Rotation and translation that moves the axis from the original Cartesian axis to its final location, if any. :type transformation: :class:`Transformation` :param str name: A short user-provided name. :param str description: A brief description of the object. """ type = 'axis' def __init__(self, transformation=None, name=None, description=None): super(Axis, self).__init__(name, description) self.transformation = transformation class XAxis(Axis): """The x Cartesian axis. See :class:`GeometricObject` for a description of the parameters. """ axis_type = 'x-axis' class YAxis(Axis): """The y Cartesian axis. See :class:`GeometricObject` for a description of the parameters. """ axis_type = 'y-axis' class ZAxis(Axis): """The z Cartesian axis. See :class:`GeometricObject` for a description of the parameters. """ axis_type = 'z-axis' class Plane(GeometricObject): """A plane in Cartesian space - see :class:`XYPlane`, :class:`YZPlane`, :class:`XZPlane`. :param transformation: Rotation and translation that moves the plane from the original position to its final location, if any. :type transformation: :class:`Transformation` :param str name: A short user-provided name. :param str description: A brief description of the object. """ type = 'plane' def __init__(self, transformation=None, name=None, description=None): super(Plane, self).__init__(name, description) self.transformation = transformation class XYPlane(Plane): """The xy plane in Cartesian space. See :class:`GeometricObject` for a description of the parameters. """ plane_type = 'xy-plane' class YZPlane(Plane): """The yz plane in Cartesian space. See :class:`GeometricObject` for a description of the parameters. """ plane_type = 'yz-plane' class XZPlane(Plane): """The xz plane in Cartesian space. See :class:`GeometricObject` for a description of the parameters. """ plane_type = 'xz-plane'
# a dp method class Solution: def longestPalindrome(self, s: str) -> str: size = len(s) if size < 2: return s dp = [[False for _ in range(size)] for _ in range(size)] maxLen = 1 start = 0 for i in range(size): dp[i][i] = True for j in range(1, size): for i in range(0, j): if s[i] == s[j]: if j - i <= 2: dp[i][j] = True else: dp[i][j] = dp[i + 1][j - 1] if dp[i][j]: curLen = j - i + 1 if curLen > maxLen: maxLen = curLen start = i return s[start : start + maxLen]