content
stringlengths
7
1.05M
# -*- coding: utf-8 -*- """ This module recieves an ForecastIO object and holds the currently weather conditions. It has one class for this purpose. """ class FIOCurrently(object): """ This class recieves an ForecastIO object and holds the currently weather conditions. """ currently = None def __init__(self, forecast_io): """ Construct a new 'FIOCurrently' object. Recieves an ForecastIO object and gets the currently weather conditions if they are available in the object. Args: forecast_io (ForecastIO): The ForecastIO object """ if forecast_io.has_currently(): self.currently = forecast_io.get_currently() for item in self.currently.keys(): setattr(self, item, self.currently[item]) def get(self): """ Returns a dictionary with current weather conditions. Returns None is none are available. Returns: Dictionary with current weather conditions. None is none are available. """ return self.currently
"""Module providing logic for retrieving bibitems via xml2rfc-style paths, and serializing them to xml2rfc-style RFC 7991 XML. """
# # PySNMP MIB module AILUXCONNECT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AILUXCONNECT-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:00:39 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) # AIIConnType, = mibBuilder.importSymbols("AISYSTEM-MIB", "AIIConnType") ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint") InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Counter32, Bits, Gauge32, enterprises, ObjectIdentity, NotificationType, Counter64, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, TimeTicks, Unsigned32, IpAddress, iso, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "Bits", "Gauge32", "enterprises", "ObjectIdentity", "NotificationType", "Counter64", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "TimeTicks", "Unsigned32", "IpAddress", "iso", "MibIdentifier") DisplayString, TextualConvention, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "TruthValue") aii = MibIdentifier((1, 3, 6, 1, 4, 1, 539)) aiLuxConnect = ModuleIdentity((1, 3, 6, 1, 4, 1, 539, 33)) aiLuxConnect.setRevisions(('2001-04-30 17:00',)) if mibBuilder.loadTexts: aiLuxConnect.setLastUpdated('200104301700Z') if mibBuilder.loadTexts: aiLuxConnect.setOrganization('Applied Innovation Inc.') aiLCTrapInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 539, 33, 0)) aiLCTrapGtranSwitch = NotificationType((1, 3, 6, 1, 4, 1, 539, 33, 0, 1)).setObjects(("AILUXCONNECT-MIB", "aiLCGtranActiveIndex"), ("AILUXCONNECT-MIB", "aiLCGtranActiveSpan")) if mibBuilder.loadTexts: aiLCTrapGtranSwitch.setStatus('current') aiLCTrapGbicInserted = NotificationType((1, 3, 6, 1, 4, 1, 539, 33, 0, 2)).setObjects(("AILUXCONNECT-MIB", "aiLCGbicIndex"), ("AILUXCONNECT-MIB", "aiLCGbicConnectorType")) if mibBuilder.loadTexts: aiLCTrapGbicInserted.setStatus('current') aiLCTrapGbicRemoved = NotificationType((1, 3, 6, 1, 4, 1, 539, 33, 0, 3)).setObjects(("AILUXCONNECT-MIB", "aiLCGbicIndex"), ("AILUXCONNECT-MIB", "aiLCGbicConnectorType")) if mibBuilder.loadTexts: aiLCTrapGbicRemoved.setStatus('current') aiLCGtranActiveTable = MibTable((1, 3, 6, 1, 4, 1, 539, 33, 1), ) if mibBuilder.loadTexts: aiLCGtranActiveTable.setStatus('current') aiLCGtranActiveEntry = MibTableRow((1, 3, 6, 1, 4, 1, 539, 33, 1, 1), ).setIndexNames((0, "AILUXCONNECT-MIB", "aiLCGtranActiveIndex")) if mibBuilder.loadTexts: aiLCGtranActiveEntry.setStatus('current') aiLCGtranActiveIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 1), InterfaceIndex()).setMaxAccess("readonly") if mibBuilder.loadTexts: aiLCGtranActiveIndex.setStatus('current') aiLCGtranActiveBackupIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 2), InterfaceIndex()).setMaxAccess("readonly") if mibBuilder.loadTexts: aiLCGtranActiveBackupIndex.setStatus('current') aiLCGtranActiveSpan = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("work", 1), ("protect", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: aiLCGtranActiveSpan.setStatus('current') aiLCGtranActiveRxUtilization = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("readonly") if mibBuilder.loadTexts: aiLCGtranActiveRxUtilization.setStatus('current') aiLCGtranActiveTxUtilization = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("readonly") if mibBuilder.loadTexts: aiLCGtranActiveTxUtilization.setStatus('current') aiLCGtranActiveClockSlave = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 6), TruthValue()).setMaxAccess("readwrite") if mibBuilder.loadTexts: aiLCGtranActiveClockSlave.setStatus('current') aiLCGtranActiveCoolerStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("up", 1), ("down", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: aiLCGtranActiveCoolerStatus.setStatus('current') aiLCGtranActiveTemperature = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("okay", 1), ("trouble", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: aiLCGtranActiveTemperature.setStatus('current') aiLCGtranActiveRxPower = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("okay", 1), ("under", 2), ("over", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: aiLCGtranActiveRxPower.setStatus('current') aiLCGtranActiveTxPower = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("okay", 1), ("under", 2), ("over", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: aiLCGtranActiveTxPower.setStatus('current') aiLCGtranBackupTable = MibTable((1, 3, 6, 1, 4, 1, 539, 33, 2), ) if mibBuilder.loadTexts: aiLCGtranBackupTable.setStatus('current') aiLCGtranBackupEntry = MibTableRow((1, 3, 6, 1, 4, 1, 539, 33, 2, 1), ).setIndexNames((0, "AILUXCONNECT-MIB", "aiLCGtranBackupIndex")) if mibBuilder.loadTexts: aiLCGtranBackupEntry.setStatus('current') aiLCGtranBackupIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 2, 1, 1), InterfaceIndex()).setMaxAccess("readonly") if mibBuilder.loadTexts: aiLCGtranBackupIndex.setStatus('current') aiLCGtranBackupActiveIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 2, 1, 2), InterfaceIndex()).setMaxAccess("readonly") if mibBuilder.loadTexts: aiLCGtranBackupActiveIndex.setStatus('current') aiLcGbicTable = MibTable((1, 3, 6, 1, 4, 1, 539, 33, 3), ) if mibBuilder.loadTexts: aiLcGbicTable.setStatus('current') aiLCGbicEntry = MibTableRow((1, 3, 6, 1, 4, 1, 539, 33, 3, 1), ).setIndexNames((0, "AILUXCONNECT-MIB", "aiLCGbicIndex")) if mibBuilder.loadTexts: aiLCGbicEntry.setStatus('current') aiLCGbicIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 3, 1, 1), InterfaceIndex()).setMaxAccess("readonly") if mibBuilder.loadTexts: aiLCGbicIndex.setStatus('current') aiLCGbicConnectorType = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 3, 1, 2), AIIConnType()).setMaxAccess("readonly") if mibBuilder.loadTexts: aiLCGbicConnectorType.setStatus('current') aiLCGbicTxMode = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("down", 1), ("up", 2), ("gtran", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: aiLCGbicTxMode.setStatus('current') aiLCGbicRxUtilization = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 3, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("readonly") if mibBuilder.loadTexts: aiLCGbicRxUtilization.setStatus('current') aiLCGbicTxUtilization = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 33, 3, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("readonly") if mibBuilder.loadTexts: aiLCGbicTxUtilization.setStatus('current') mibBuilder.exportSymbols("AILUXCONNECT-MIB", aiLCGtranActiveBackupIndex=aiLCGtranActiveBackupIndex, aiLCGbicConnectorType=aiLCGbicConnectorType, aiLCGtranActiveEntry=aiLCGtranActiveEntry, aiLCGtranActiveClockSlave=aiLCGtranActiveClockSlave, aiLCTrapGbicInserted=aiLCTrapGbicInserted, aiLCGbicEntry=aiLCGbicEntry, aiLCGtranBackupIndex=aiLCGtranBackupIndex, aiLCGtranActiveTxPower=aiLCGtranActiveTxPower, aiLCTrapGbicRemoved=aiLCTrapGbicRemoved, aiLCGtranBackupEntry=aiLCGtranBackupEntry, aiLCTrapGtranSwitch=aiLCTrapGtranSwitch, aiLuxConnect=aiLuxConnect, aii=aii, aiLCGtranActiveRxUtilization=aiLCGtranActiveRxUtilization, aiLCGtranBackupTable=aiLCGtranBackupTable, aiLCGtranActiveIndex=aiLCGtranActiveIndex, aiLCTrapInfo=aiLCTrapInfo, aiLCGtranActiveTable=aiLCGtranActiveTable, aiLCGtranActiveTxUtilization=aiLCGtranActiveTxUtilization, aiLCGtranBackupActiveIndex=aiLCGtranBackupActiveIndex, PYSNMP_MODULE_ID=aiLuxConnect, aiLCGbicTxUtilization=aiLCGbicTxUtilization, aiLCGtranActiveRxPower=aiLCGtranActiveRxPower, aiLcGbicTable=aiLcGbicTable, aiLCGbicIndex=aiLCGbicIndex, aiLCGtranActiveSpan=aiLCGtranActiveSpan, aiLCGtranActiveTemperature=aiLCGtranActiveTemperature, aiLCGbicRxUtilization=aiLCGbicRxUtilization, aiLCGbicTxMode=aiLCGbicTxMode, aiLCGtranActiveCoolerStatus=aiLCGtranActiveCoolerStatus)
''' 用户登录的三次机会 ‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬ 描述 给用户三次输入用户名和密码的机会,要求如下:‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬ 1)如输入第一行输入用户名为‘Kate’,第二行输入密码为‘666666’,输出‘登录成功!’,退出程序;‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬ 2)当一共有3次输入用户名或密码不正确输出“3次用户名或者密码均有误!退出程序。”。 ''' count = 0 while count < 3: name = input() password = input() if name == 'Kate'and password == '666666': print("登录成功!") break else: count += 1 if count == 3: print("3次用户名或者密码均有误!退出程序。")
def test_get_custom_properties(exporters, mocker): blender_data = mocker.MagicMock() vector = mocker.MagicMock() vector.to_list.return_value = [0.0, 0.0, 1.0] blender_data.items.return_value = [ ['str', 'spam'], ['float', 1.0], ['int', 42], ['bool', False], ['vector', vector], ] assert exporters.BaseExporter.get_custom_properties(blender_data) == { 'str': 'spam', 'float': 1.0, 'int': 42, 'bool': False, 'vector': [0.0, 0.0, 1.0] } def test_ignore_properties(exporters, mocker): blender_data = mocker.MagicMock() blender_data.items.return_value = [ ['_RNA_UI', None], ['cycles', None], ['cycles_visibility', None], ['str', 'remains'], ] assert exporters.BaseExporter.get_custom_properties(blender_data) == { 'str': 'remains', } def test_invalid_properties(exporters, mocker): blender_data = mocker.MagicMock() blender_data.items.return_value = [ ['unserializable', set()], ['str', 'remains'], ] assert exporters.BaseExporter.get_custom_properties(blender_data) == { 'str': 'remains', } def test_check(exporters): assert exporters.BaseExporter.check(None, None) def test_default(exporters, mocker): blender_data = mocker.MagicMock() blender_data.name = 'Name' assert exporters.BaseExporter.default(None, blender_data) == {'name': 'Name'} def test_export(exporters): assert exporters.BaseExporter.export(None, None) == {}
{ 'includes': [ '../common.gypi' ], 'targets': [ { 'target_name': 'shbench', 'product_name': 'shbench', 'type' : 'executable', 'conditions': [ ['OS=="linux"', { 'ldflags': [ '-pthread' ] }], ], 'defines': [ 'SYS_MULTI_THREAD' ], 'sources': [ 'src/sh6bench.c' ], 'include_dirs': [ 'src' ] } ] }
# coding=utf-8 font = { "black": "\033[30m{content}\033[0m", "red": "\033[31m{content}\033[0m", "green": "\033[32m{content}\033[0m", "yellow": "\033[33m{content}\033[0m", "blue": "\033[34m{content}\033[0m", "purple ": "\033[35m{content}\033[0m", "celeste": "\033[36m{content}\033[0m", "white": "\033[37m{content}\033[0m" } font_background = { "black": "\033[40;37m{content}\033[0m", "read": "\033[41;37m{content}\033[0m", "green": "\033[42;37m{content}\033[0m", "yellow": "\033[43;37m{content}\033[0m", "blue": "\033[44;37m{content}\033[0m", "purple": "\033[45;37m{content}\033[0m", "celeste": "\033[46;37m{content}\033[0m", "white": "\033[47;30m{content}\033[0m", } # % echo -e '\u2620' # \u takes four hexadecimal digits # ☠ # % echo -e '\U0001f602' # \U takes eight hexadecimal digits emoji = { "warn": u"\u26A0\uFE0F INFO", "earth": u"\U0001F310", "project": u"\U0001F4C1", "keystone": u"\U0001F510", "glance": u"\U0001F4BF", "nova": u"\U0001F31F", "edit": u"\U0001F4DD", "fire": u"\U0001F525", "exec": u"\U0001F5A5", "failed": u"\U0001F621", "succeed": u"\U0001F600", "clock": u"\U0001F552", "horizon": u"\U0001F579", } if __name__ == '__main__': for k, v in font.items(): print(v.format(content='test...')) for k, v in font_background.items(): print(v.format(content='test...')) for k, v in emoji.items(): print("%s: %s" % (k, v))
# # Copyright (c) 2019 Intel Corporation # # 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. # """ Definitions file: It's main functionality are: 1) housing project constants and enums. 2) housing configuration parameters. 3) housing resource paths. """ class Definitions: GROUP_NAME = "rl_coach" PROCESS_NAME = "coach" DASHBOARD_PROC = "firefox" class Flags: css = "checkpoint_save_secs" crd = "checkpoint_restore_dir" et = "environment_type" ept = "exploration_policy_type" cp = "custom_parameter" seed = "seed" dccp = "distributed_coach_config_path" """ Arguments that can be tested for python coach command ** None = Flag - no need for string or int ** {} = Add format for this parameter """ cmd_args = { # '-l': None, # '-e': '{}', # '-r': None, # '-n': '{' + enw + '}', # '-c': None, # '-ew': None, '--play': None, '--evaluate': None, # '-v': None, # '-tfv': None, '--nocolor': None, # '-s': '{' + css + '}', # '-crd': '{' + crd + '}', '-dg': None, '-dm': None, # '-et': '{' + et + '}', # '-ept': '{' + ept + '}', # '-lvl': '{level}', # '-cp': '{' + cp + '}', '--print_networks_summary': None, '-tb': None, '-ns': None, '-d': None, # '--seed': '{' + seed + '}', '-onnx': None, '-dc': None, # '-dcp': '{' + dccp + '}', '-asc': None, '--dump_worker_logs': None, } class Presets: # Preset list for testing the flags/ arguments of python coach command args_test = [ "CartPole_A3C", # "CartPole_NEC", ] class Path: experiments = "./experiments" tensorboard = "tensorboard" gifs = "gifs" videos = "videos" class Consts: ASSERT_MSG = "Expected: {}, Actual: {}." RESULTS_SORTED = "Results stored at:" TOTAL_RUNTIME = "Total runtime:" DISCARD_EXP = "Do you want to discard the experiment results" REACHED_REQ_ASC = "Reached required success rate. Exiting." INPUT_EMBEDDER = "Input Embedder:" MIDDLEWARE = "Middleware:" OUTPUT_HEAD = "Output Head:" ONNX_WARNING = "Exporting ONNX graphs requires setting the " \ "--checkpoint_save_secs flag. The --export_onnx_graph" \ " will have no effect." COLOR_PREFIX = "## agent: Starting evaluation phase" TRAINING = "Training - " PLAY_WARNING = "Both the --preset and the --play flags were set. " \ "These flags can not be used together. For human " \ "control, please use the --play flag together with " \ "the environment type flag (-et)" class TimeOuts: test_time_limit = 60 * 60 wait_for_files = 20
class AST: """ Base class for abstract syntax trees """ pass class BinOp(AST): """ Binary operation for abstract syntax trees """ def __init__(self, left, op, right): self.left = left self.op = op self.right = right class Num(AST): """ Node for numbers in abstract syntax trees """ def __init__(self, token): self.token = token self.value = token.value
data = [['accesstoken', 'title', 'tab', 'content'], ['6eb92a53-9392-4dc5-a10a-3a853cad6e2c', 'helloworld', 'share', 'hshahdhsahashhdhahda']] def parse_data(): json_data ={} for i in range(len(data)): for j in range(len(data[i])): json_data[data[0][j]] = data[1][j] print(json_data) # parse_data() jsondata = { "accesstoken": "6eb92a53-9392-4dc5-a10a-3a853cad6e2c", "title": "helloworld", "tab": "share", "content": "how to do api testing" } def queue_json_data(): # print(jsondata.keys(),jsondata.values()) for x in jsondata.keys(): temp = jsondata[x] jsondata[x] = "" print(jsondata) jsondata[x] = temp queue_json_data()
# Wrapper node Model # Holds the rules and associated key class Node: def __init__(self, rules, key) -> None: self.rules = rules self.key = key
# binary search tree # author: D1N3SHh # https://github.com/D1N3SHh/algorithms class Red_black_tree(): def __init__(self): self.nil = Node(0, 'black', None, None) self.root = self.nil def __repr__(self): return str(self.root) def left_rotate(self, x): y = x.right x.right = y.left if y.left != self.nil: y.left.parent = x y.parent = x.parent if x.parent == self.nil: self.root = y elif x == x.parent.left: x.parent.left = y else: x.parent.right = y x.left = x x.parent = y def right_rotate(self, x): y = x.left x.left = y.right if y.right != self.nil: y.right.parent = x y.parent = x.parent if x.parent == self.nil: self.root = y elif x == x.parent.right: x.parent.right = y else: x.parent.left = y x.right = x x.parent = y def insert(self, z): y = self.nil x = self.root while x != self.nil: y = x if z.key < x.key: x = x.left else: x = x.right z.parent = y if y == self.nil: self.root = z elif z.key < y.key or y.key == None: y.left = z else: y.right = z z.left = self.nil z.right = self.nil z.color = 'red' self.insert_fixup(z) def insert_fixup(self, z): while z != self.root and z.parent.color == 'red': if z.parent == z.parent.parent.left: y = z.parent.parent.right if y.color == 'red': z.parent.color = 'black' y.color = 'black' z.parent.parent.color = 'red' z = z.parent.parent else: if z == z.parent.right: z = z.parent self.left_rotate(z) z.parent.color = 'black' z.parent.parent.color = 'red' self.right_rotate(z.parent.parent) else: y = z.parent.parent.left if y.color == 'red': z.parent.color = 'black' y.color = 'black' z.parent.parent.color = 'red' z = z.parent.parent else: if z == z.parent.left: z = z.parent self.right_rotate(z) z.parent.color = 'black' z.parent.parent.color = 'red' self.left_rotate(z.parent.parent) self.root.color = 'black' def transplant(self, u, v): if u.parent == self.nil: self.root = v elif u == u.parent.left: u.parent.left = v else: u.parent.right = v v.parent = u.parent def delete(self, z): y = z y_original_color = y.color if z.left == self.nil: x = z.right self.transplant(z, z.right) elif z.right == self.nil: x = z.left self.transplant(z, z.left) else: y = self.minimum(z.right) y_original_color = y.color x = y.right if y.parent == z: x.parent = y else: self.transplant(y, y.right) y.right = z.right y.right.parent = y self.transplant(z, y) y.left = z.left y.left.parent = y y.color = z.color if y_original_color == 'black': self.delete_fixup(x) def delete_fixup(self, x): while x != self.root and x.color == 'black': if x == x.parent.left: w = x.parent.right if w.color == 'red': w.color = 'black' x.parent.color = 'red' self.left_rotate(x.parent) w = x.parent.right if w.left.color == 'black' and w.right.color == 'black': w.color = 'red' x = x.parent else: if w.right.color == 'black': w.left.color = 'black' w.color = 'red' self.right_rotate(w) w = x.parent.right w.color = x.parent.color x.parent.color = 'black' w.right.color = 'black' self.left_rotate(x.parent) x = self.root else: w = x.parent.left if w.color == 'red': w.color = 'black' x.parent.color = 'red' self.right_rotate(x.parent) w = x.parent.left if w.right.color == 'black' and w.left.color == 'black': w.color = 'red' x = x.parent else: if w.left.color == 'black': w.right.color = 'black' w.color = 'red' self.left_rotate(w) w = x.parent.left w.color = x.parent.color x.parent.color = 'black' w.left.color = 'black' self.right_rotate(x.parent) x = self.root x.color = 'black' def minimum(self, x): while x.left.left != None: x = x.left return x.key def maximum(self, x): while x.right.right != None: x = x.right return x.key def search(self, x, key): if x == None or key == x.key: return x if key < x.key: return self.search(x.left, key) else: return self.search(x.right, key) class Node(): def __init__(self, key, color = 'red', parent = None, left = None, right = None): self.key = key self.color = color self.parent = parent self.left = left self.right = right def __repr__(self) -> str: return '{|%s%s|:%s,%s}' % (self.color, self.key, self.left, self.right) def example_usage(): rb_tree = Red_black_tree() node_1 = Node(6) # 6 node_2 = Node(4) # / \ node_3 = Node(8) # 4 8 node_4 = Node(2) # / rb_tree.insert(node_1) # 2 rb_tree.insert(node_2) rb_tree.insert(node_3) rb_tree.insert(node_4) print('Tree text reprezentation:', rb_tree) print('Searching for key = 4:', rb_tree.search(rb_tree.root, 4)) print('Minimum:', rb_tree.minimum(rb_tree.root)) print('Maksimum:', rb_tree.maximum(rb_tree.root)) rb_tree.delete(node_2) print('Tree text reprezentation after removing node 2 (key=4):', rb_tree) if __name__ == "__main__": example_usage() # run an example on start
# -*- coding: utf-8 -*- """Top-level package for pyDarknetServer.""" __author__ = """Lionel Atty""" __email__ = 'yoyonel@hotmail.com' __version__ = '0.2.0'
# -*- coding: utf-8 -*- '''A completely generic, data-driven, configuration dialog''' class ConfigDialog(QtGui.QDialog): def __init__(self, parent): QtGui.QDialog.__init__(self, parent) # Set up the UI from designer self.ui=UI_ConfigDialog() self.ui.setupUi(self) pages=[] sections=[] self.values={} for sectionName, options in config.options: # Create a page widget/layout for this section: page=QtGui.QScrollArea() innerpage=QtGui.QFrame() layout=QtGui.QGridLayout() row=-2 for optionName, definition in options: row+=2 if definition[0]=='bool': cb=QtGui.QCheckBox(optionName) cb.setChecked(config.getValue(sectionName, optionName, definition[1])) layout.addWidget(cb, row, 0, 1, 2) self.values[sectionName+'/'+optionName]=[cb, lambda cb: cb.isChecked()] elif definition[0]=='int': label=QtGui.QLabel(optionName+":") label.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter) spin=QtGui.QSpinBox() if definition[3] is not None: spin.setMinimum(definition[3]) else: spin.setMinimum(-99999) if definition[4] is not None: spin.setMaximum(definition[4]) else: spin.setMaximum(99999) spin.setValue(config.getValue(sectionName, optionName, definition[1])) layout.addWidget(label, row, 0, 1, 1) layout.addWidget(spin, row, 1, 1, 1) self.values[sectionName+'/'+optionName]=[spin, lambda spin: spin.value()] elif definition[0]=='string': label=QtGui.QLabel(optionName+":") label.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter) text=QtGui.QLineEdit() text.setText(str(config.getValue(sectionName, optionName, definition[1]))) layout.addWidget(label, row, 0, 1, 1) layout.addWidget(text, row, 1, 1, 1) self.values[sectionName+'/'+optionName]=[text, lambda text: str(text.text())] elif definition[0]=='password': label=QtGui.QLabel(optionName+":") label.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter) text=QtGui.QLineEdit() text.setEchoMode(QtGui.QLineEdit.Password) text.setText(str(config.getValue(sectionName, optionName, definition[1]))) layout.addWidget(label, row, 0, 1, 1) layout.addWidget(text, row, 1, 1, 1) self.values[sectionName+'/'+optionName]=[text, lambda text: str(text.text())] help=QtGui.QLabel(definition[2]) help.setWordWrap(True) layout.addWidget(help, row, 2, 1, 1) separator=QtGui.QFrame() separator.setFrameStyle(QtGui.QFrame.HLine|QtGui.QFrame.Plain) layout.addWidget(separator, row+1, 0, 1, 3) innerpage.setLayout(layout) innerpage.adjustSize() page.resize(QtCore.QSize(innerpage.width()+5, page.height())) page.setWidget(innerpage) pages.append(page) sections.append(sectionName) for page, name in zip(pages,sections) : # Make a tab out of it self.ui.tabs.addTab(page, name) self.ui.tabs.setCurrentIndex(1) self.ui.tabs.removeTab(0) def accept(self): for k in self.values: sec, opt=k.split('/') widget, l = self.values[k] config.setValue(sec, opt, l(widget)) QtGui.QDialog.accept(self)
# The XPATH to determine if the main page has fully loaded HOME_PAGE_XPATH: str = '/html/body/center/table/tbody/tr[2]/td/center/table[1]/tbody/tr/td[3]' + \ '/table/tbody/tr/td/ul[1]/li[1]/a' # The XPATH on the main page to the table listing the kits KITS_XPATH: str = '/html/body/center/table/tbody/tr[2]/td/center/table[1]/tbody/tr/td[1]' + \ '/table/tbody/tr[4]/td/table/tbody/tr[4]/td/table'
""" 09: See my workflow as a graph ------------------------------- """
# -*- coding: utf-8 -*- """ Created on Mon Mar 14 14:43:55 2022 @author: D.Albert-Weiss """ spec_win1D = [ ('win', int32), ]
def test_parameter_exclusion_empty(api_client, api_prefix): response = api_client.get(f"{api_prefix}/parameters/1/exclusions/") assert response.status_code == 200 json_dict = response.json expected = { "message": "exclusions for parameter 1", "parameter": {"excluded": [], "excluded_by": [], "name": "Colour", "uid": 1}, "parameter_url": f"{api_prefix}/parameters/1", "parameter_exclusion_url": f"{api_prefix}/parameters/1/exclusions/", } assert json_dict == expected def test_parameter_exclusion_non_empty(api_client, api_prefix): request_data = { "excluded": [ 3, ], } response = api_client.post( f"{api_prefix}/parameters/1/exclusions/", json=request_data ) assert response.status_code == 201 response = api_client.get(f"{api_prefix}/parameters/1/exclusions/") assert response.status_code == 200 json_dict = response.json expected = { "message": "exclusions for parameter 1", "parameter": { "name": "Colour", "uid": 1, "excluded": [{"name": "Speed", "uid": 3}], "excluded_by": [], }, "parameter_url": f"{api_prefix}/parameters/1", "parameter_exclusion_url": f"{api_prefix}/parameters/1/exclusions/", } assert json_dict == expected def test_parameter_exclusion_post(api_client, api_prefix): request_data = { "excluded": [3, 4], } response = api_client.post( f"{api_prefix}/parameters/1/exclusions/", json=request_data ) assert response.status_code == 201 json_dict = response.json expected = { "message": "parameter exclusion created", "parameter": { "uid": 1, "name": "Colour", "excluded": [ {"name": "Speed", "uid": 3}, {"name": "Music", "uid": 4}, ], "excluded_by": [], }, "parameter_url": "/tconfig/api/v1/parameters/1", } assert json_dict == expected
g = int(input()) l = list(map(int,input().split())) mi = min(l) ma = max(l) y=0 for i in l: if i == ma: break y+=1 l.remove(ma) l.insert(0,ma) x = l[-1::-1] for j in x: if j==mi: break y+=1 print(y)
TITLE = 'Красивое место' STATEMENT = ''' Солнце над Зоной — редкое явление. Но в те дни, когда оно пробивается из-за туч, можно заметить интересную особенность: его свет не похож на то, к чему привыкли люди до катастрофы. Более того, порой оно высвечивает то, что сложно увидеть в обычном сумраке затянутого облаками неба. В один такой день, восхищённый внезапно открывшейся панорамой, я сделал [фотоснимок](/static/files/7bjf8qvcne/photo.jpg). ''' def generate(context): return TaskStatement(TITLE, STATEMENT)
def vsota_stevk(n): s = str(n) vsota = 0 for x in s: vsota += int(x) return vsota def euler56(): najvecja_vsota = 0 for a in range(1,100): for b in range(1,100): st = a ** b s = vsota_stevk(st) if s > najvecja_vsota: najvecja_vsota = s return najvecja_vsota euler56()
def newArr(arr): """ MapReduce: O(n^2) 1. Map: construct the Map with Key is each element and Value is the array 2. Reduce: product all element of Value except the key """ result = [] hashmap = {} for i in arr: hashmap[i] = arr for key, value in hashmap.items(): product = 1 for v in value: if (v != key): product *=v result.append(product) return result def optimizedNewArr(arr): """ Ref: https://www.geeksforgeeks.org/a-product-array-puzzle/ O(n) 1) Construct a temporary array left[] such that left[i] contains product of all elements on left of arr[i] excluding arr[i]. 2) Construct another temporary array right[] such that right[i] contains product of all elements on on right of arr[i] excluding arr[i]. 3) To get prod[], multiply left[] and right[]. """ result = [] temp = 1 for i in range(len(arr)): result.append(temp) temp *= arr[i] temp = 1 j = len(arr) - 1 while (j >= 0): result[j] *= temp temp *= arr[j] j -= 1 return result
""" Dados n e uma seqüência de n números inteiros, determinar a soma dos números pares. """
# this one needs to be a multiple of 8 bitsString = "1111111101111111001111110001111100001111000001110000001100000001" # store here the hex values bhex = list() # check the size of bitsString if len(bitsString) % 8 != 0 : print("Invalid string len provided") # split, convert to 8 and append to a string (make this more pythonable) for i in range(0, len(bitsString), 8): bhex.append(hex(int(bitsString[i:i+8], 2))) print(bhex) # move to bytes for i in range(len(bhex)): c = bytearray(bhex[i],encoding='utf8') print(c, end='\t') print(bin(int(bhex[i], 16))[2:].zfill(8))
#TRATANDO VÁRIOS VALORES total = soma = numb = 0 numb = int(input('digite o numero [999 para parar]: ')) while numb != 999: total += 1 soma = numb + soma numb = int(input('digite o numero [999 para parar]: ')) print(f'voce digitou {total} numeros e a soma entre eles é {soma}')
def gcd(a, b): while b: a, b = b, a % b return a def isPrimeMR(n): d = n - 1 d = d // (d & -d) L = [2] for a in L: t = d y = pow(a, t, n) if y == 1: continue while y != n - 1: y = (y * y) % n if y == 1 or t == n - 1: return 0 t <<= 1 return 1 def findFactorRho(n): m = 1 << n.bit_length() // 8 for c in range(1, 99): f = lambda x: (x * x + c) % n y, r, q, g = 2, 1, 1, 1 while g == 1: x = y for _ in range(r): y = f(y) k = 0 while k < r and g == 1: ys = y for _ in range(min(m, r - k)): y = f(y) q = q * abs(x - y) % n g = gcd(q, n) k += m r <<= 1 if g == n: g = 1 while g == 1: ys = f(ys) g = gcd(abs(x - ys), n) if g < n: if isPrimeMR(g): return g elif isPrimeMR(n // g): return n // g return findFactorRho(g) def primeFactor(n): i = 2 ret = {} rhoFlg = 0 while i*i <= n: k = 0 while n % i == 0: n //= i k += 1 if k: ret[i] = k i += 1 + i % 2 if i == 101 and n >= 2 ** 20: while n > 1: if isPrimeMR(n): ret[n], n = 1, 1 else: rhoFlg = 1 j = findFactorRho(n) k = 0 while n % j == 0: n //= j k += 1 ret[j] = k if n > 1: ret[n] = 1 if rhoFlg: ret = {x: ret[x] for x in sorted(ret)} return ret if __name__ == "__main__": print(primeFactor(1234567891012354))
x=int(input()) for i in range(0,x): a,b=map(int,input().split()) print(a+b)
suppressions = [ # This one cannot be covered by any Python language test because there is # no code pathway to it. But it is part of the C API, so must not be # excised from the code. [ r".*/multiarray/mapping\.", "PyArray_MapIterReset" ], # PyArray_Std trivially forwards to and appears to be superceded by # __New_PyArray_Std, which is exercised by the test framework. [ r".*/multiarray/calculation\.", "PyArray_Std" ], # PyCapsule_Check is declared in a header, and used in # multiarray/ctors.c. So it isn't really untested. [ r".*/multiarray/common\.", "PyCapsule_Check" ], ]
""" * Assignment: FuncProg Closure Define * Complexity: easy * Lines of code: 4 lines * Time: 5 min English: 1. Define function `check` with `func: Callable` as a parameter 2. Define closure function `wrapper` inside `check` 3. Function `wrapper` takes `*args` and `**kwargs` as arguments 4. Function `wrapper` returns `None` 5. Function `check` must return `wrapper: Callable` 6. Run doctests - all must succeed Polish: 1. Zdefiniuj funkcję `check`, z `func: Callable` jako parametr 2. Zdefiniuj funkcję closure `wrapper` wewnątrz `check` 3. Funkcja `wrapper` przyjmuje `*args` i `**kwargs` jako argumenty 4. Funkcja `wrapper` zwraca `None` 5. Funkcja `check` ma zwracać `wrapper: Callable` 6. Uruchom doctesty - wszystkie muszą się powieść Tests: >>> import sys; sys.tracebacklimit = 0 >>> assert callable(check) >>> assert callable(check(lambda:...)) >>> result = check(lambda:...).__call__() >>> result is None True """ # Callable: parameter: func; inside: wrapper with args, kwargs; return: wrapper def check(): ...
# _*_coding:utf-8_*_ class Solution: def get_maybe(self, index, pushV): maybe = [None] j = index - 1 while j >= 0: if None is not pushV[j]: maybe[0] = j break j -= 1 j = index + 1 while j < len(pushV): if None is not pushV[j]: maybe.append(j) j += 1 return maybe def IsPopOrder(self, pushV, popV): if None is pushV or None is popV: return False if len(pushV) != len(popV) or len(pushV) <= 0 or len(popV) <= 0: return False val = popV[0] index = -1 for i, value in enumerate(pushV): if val == value: index = i break if -1 == index: return False pushV[index] = None maybe = self.get_maybe(index, pushV) for i in range(1, len(popV)): val = popV[i] for maybeValue in maybe: if None is not maybeValue and maybeValue >= 0 and maybeValue < len(pushV) and val == pushV[maybeValue]: index = maybeValue pushV[index] = None maybe = self.get_maybe(index, pushV) break else: return False return True s = Solution() case_list = [ ([1], [2]), ([1,2,3,4,5], [4,3,5,1,2]), ([1,2,3,4,5],[3,5,4,2,1]), ([1,2,3,4,5], [4,5,3,2,1]), ([1,2,3,4,], [4,5,3,2,1]), (None, [4,5,3,2,1]) ] for case in case_list: print(s.IsPopOrder(case[0], case[1]))
# 2020.07.09 # Problem Statement: # https://leetcode.com/problems/longest-palindromic-substring/ class Solution: def longestPalindrome(self, s: str) -> str: # discuss corner cases if len(s) == 0: return "" elif len(s) == 1: return s elif len(s) == 2: if s[0] == s[1]: return s else: return s[0] # declare current best result and current palindromic substring current_longest = '' current_longest = s[0] current_explored = '' current_explored = s[0] center_index = 0 # if there exists substrings with repeat chars, eg: "abbbc" # need to know the number of repeat chars # if even, center should be 2 chars, palindromic substring shoule be even # otherwise center should be 1 char, palindtomic substring should be odd # initialize count for repeating substrings count_left = 0 count_right = 0 count_continuous = 1 # each element can be the center of the substring # first and last excluded, since current_longest is already initialized as a single-element string for index in range(1, len(s)-1): count_left, count_right, count_continuous = 0, 0, 1 center_index = index # if not continuously reapeating if s[center_index] != s[center_index-1] and s[center_index] != s[center_index+1]: for i in range(0, min(index+1, len(s)-index)) : if s[center_index-i] == s[center_index+i]: current_explored = s[center_index-i: center_index+i+1] else: # not a palindromic string break # continuously repeating else: for left_index in range(1, index+1) : if s[center_index] == s[center_index-left_index]: count_left = count_left + 1 else: break for right_index in range(1, len(s)-index): if s[center_index] == s[center_index+right_index]: count_right = count_right + 1 else: break count_continuous = count_continuous + count_left + count_right # even if count_continuous % 2 == 0: current_explored = count_continuous * s[center_index] for j in range(0, min(index, len(s)-index)): if s[center_index-1-j] == s[center_index+j]: current_explored = s[center_index-1-j: center_index+j+1] else: break # odd else: for k in range(0, min(index+1, len(s)-index)) : if s[center_index-k] == s[center_index+k]: current_explored = s[center_index-k: center_index+k+1] else: break # update if current result is better if len(current_explored) >= len(current_longest): current_longest = current_explored return current_longest
""" Data model module. In this module the data types used in CGnal framework are defined. """
###Titulo: Lista ###Função: Este programa forma uma terceira lista a partir das duas primeiras ###Autor: Valmor Mantelli Jr. ###Data: 31/12/2018 ###Versão: 0.0.2 ### Declaração de variáve list1 = [] list2 = [] list3 = [] n = 0 x = 0 ### Atribuição de valor while True: n = int(input("Digite os valores da lista 1 (ou 0 para sair): ")) if n == 0: break list1.append (n) while True: n = int(input("Digite os valores da lista 2 (ou 0 para sair): ")) if n == 0: break list2.append (n) ### Processamento list3 = list1 [:] list3.extend (list2) while x < len(list3): ### Saída print ("%d: %d" % (x, list3 [x])) x +=1
# -*- coding: utf-8 -*- """Top-level package for Tractography Meta-Pipeline Command Line Tool (TRAMPOLINO).""" __author__ = """Matteo Mancini""" __email__ = 'ingmatteomancini@gmail.com' __version__ = '0.1.9'
class Solution: @staticmethod def naive(nums,target): l,r = 0,len(nums)-1 while l<=r: m = (l+r)//2 if nums[m]==target: return m if nums[l]<=nums[m]: if target>=nums[l] and target<nums[m]: r=m-1 else: l=m+1 else: if target<=nums[r] and target>nums[m]: l=m+1 else: r=m-1 return -1
step( """ create unique index unq_image_tag_image_id_tag_id on image_tag (image_id, tag_id) """, """ drop index unq_image_tag_image_id_tag_id """ )
consumer_key = 'gdLsE3urZ6HqjE2RjiwaFBwag' consumer_secret = 'rubc1WvJoYOnsBoUMXXV660MUOhw685uTFjqnYmrRWdqoq6Y48' access_token = '846813944186650627-CpBzbP1i8ag3pREHkd6YcGQeMHbaLOx' access_secret = 'rX2ikxxtI4zplBp9kbEEpibWVKyCwKJmvuxTiKxFgeJKA'
# Programa que inverte a sequência de itens de uma lista através do loop while utilizando um contador reverso (len(lista) - 1) lista = [66, 78, 2, 45, 97, 17, 34, 105, 44, 52] x = len(lista) - 1 nova_lista = [] while x >= 0: nova_lista.append(lista[x]) x -= 1 print(nova_lista) # fim do programa
""" The Notebook module. """ class Notebook: """ This notebook does... """ def run(self): """ Your notebook code goes here. """ notebook = Notebook() notebook.run()
save_dir = './logs' # miniImageNet_path = '../../semifew_data/miniImagenetFullSize' miniImageNet_path = '/home/ojas/projects/unsupervised-meta-learning/data/untarred/miniImagenetFullSize' ISIC_path = "../../semifew_data/ISIC" ChestX_path = "../../semifew_data/chestX" CropDisease_path = "../../semifew_data/plant-disease" EuroSAT_path = "/home/ojas/projects/unsupervised-meta-learning/data/untarred/EuroSat"
class Result(object): ''' Simple wrapper object to contain result of single iteration MPI computation ''' def __init__(self, rank, idx): self.rank = rank self.idx = idx self.result = None def __repr__(self): return "rank: %d idx: %s result: %s" % (self.rank, self.idx, self.result) def __eq__(self, other): return self.result == other.result def __ne__(self, other): return self.result != other.result def __hash__(self): return hash(self.result)
# Copyright 2020 Google LLC # # 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 # # https://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. # ------------------------------------------------------------------ # GA Details GA_ACCOUNT_ID = "" # requierd for DI only GA_PROPERTY_ID = "" # required for both DI and MP GA_DATASET_ID = "" # required for DI only GA_IMPORT_METHOD = "di" # "di" - Data Import or "mp" - Measurement Protocol # GA measurement protocol hit details. Add any additional fields which are # the same for all hits here. GA_MP_STANDARD_HIT_DETAILS = { # mandatory fields below. Do not remove. "v": 1, # MP API version "tid": GA_PROPERTY_ID, # ga property id - same as above "t": "", # hit type # optional fields below: "ni": 1, # non interaction hit: 1 or 0, "ec": "", # event category "ea": "", # event action "el": "", # event label "ds": "", # data source "ua": "modem", # user agent override } # BigQuery Query Details - BQML query or normal BQ Query possible # Ensure that the BQ result headers resemble the data import schema in SELECT # E.g. If data import schema looks like - ga:dimension32, ga:dimension1, etc. # BQ result headers should like SELECT X AS ga_dimension32, Y AS ga_dimension1 BQML_PREDICT_QUERY = """ """ # ------------------------------------------------------------------- # Options for logging & error monitoring # LOGGING: Create BQ Table for logs with schema as follows - # time TIMESTAMP, status STRING, error ERROR ENABLE_BQ_LOGGING = False # ERROR MONITORING: Sign up for the free Sendgrid API. ENABLE_SENDGRID_EMAIL_REPORTING = False # (OPTIONAL) Workflow Logging - BQ details, if enabled GCP_PROJECT_ID = "" BQ_DATASET_NAME = "" BQ_TABLE_NAME = "" # (OPTIONAL) Email Reporting - Sendgrid details, if enabled SENDGRID_API_KEY = "" TO_EMAIL = "" # ------------------------------------------------------------------- # (OPTIONAL) Email Reporting - Additional Parameters FROM_EMAIL = "workflow@example.com" SUBJECT = "FAILED: Audience Upload to GA" HTML_CONTENT = """ <p> Hi WorkflowUser, <br> Your BQML Custom Audience Upload has failed- <br> Time: {0} UTC <br> Reason: {1} </p> """
option='y' while option=='y': print("Enter the number whose factorial to find") num=int(input()) fac=1 while(num!=1): fac=fac*num num=num-1 print("Factorial is "+str(fac)) print("Do you want to continue?(y/n)") option=input() print('Thank you for using this programme')
def poly(a, x): val = 0 for ai in reversed(a): val *= x val += ai return val def diff(a): return [a[i + 1] * (i + 1) for i in range(len(a) - 1)] def divroot(a, x0): b, a[-1] = a[-1], 0 for i in reversed(range(len(a) - 1)): a[i], b = a[i + 1] * x0 + b, a[i] a.pop() return a
tickers = [ 'aapl', 'tsla', ]
LAMBDA_232 = 4.934E-11#Amelin and Zaitsev, 2002. # LAMBDA_232 = 4.9475E-11 #old value, used in isoplot ERR_LAMBDA_232 = 0.015E-11#Amelin and Zaitsev, 2002. LAMBDA_235 = 9.8485E-10 #ERR_LAMBDA_235 = LAMBDA_238 = 1.55125E-10 #ERR_LAMBDA_238 = U238_U235 = 137.817 #https://doi.org/10.1016/j.gca.2018.06.014 # U238_U235 = 137.88 #old value, used in isoplot ERR_U238_U235 = 0.031 ##https://doi.org/10.1016/j.gca.2018.06.014 lambdas = [LAMBDA_238, LAMBDA_235, LAMBDA_232] isotope_ratios = ["U238_Pb206", "U235_Pb207", "Th232_Pb208", "Pb206_Pb207"] minerals = ["zircon", "baddeleyite", "perovskite", "monazite", "apatite"] EarthAge = 4600 sqrt2pi = 2.506628274631 listColumnNames = ['Th232/Pb208', 'err.Th232/Pb208', '206Pb/207Pb', 'err.206Pb/207Pb', '235U/207Pb', 'err.235U/207Pb', '238U/206Pb', 'err.238U/206Pb', 'corr.', 'Age_232Th/208Pb', 'err.Age_232Th/208Pb', 'Age_206Pb/207Pb', 'err.Age_206Pb/207Pb', 'Age_238U/206Pb', 'err.Age_238U/206Pb', 'Age_235U/207Pb', 'err.Age_235U/207Pb', '%disc.67-86', '%disc.86-57', 'is grain good?']
#! /usr/bin/python # -*- coding:utf-8 -*- """ Author: AsherYang Email: ouyangfan1991@gmail.com Date: 2018/5/30 Desc: 商品排序 sort: 排序字段,根据 "综合","销量","价格"排序 """ # 综合排序,处理为按照上新时间排列,最新的展示在最前面(_id 越大说明上新时间越近,_id 降序) SORT_COMMON = 0 # 价格降序排序 SORT_PRICE_DOWN = 1 # 价格升序排序 SORT_PRICE_UP = 2 # 按销量排序,从高到低 SORT_SALE_COUNT = 3
# Bar chart # a graph that represents the category of data with rectangular bars with lengths and heights that are proportional # to the values which they represent. # Can be vertical or horizontal. Can also be grouped. # matplotlib fig, ax = plt.subplots(1, figsize=(24,14)) plt.bar(wrestling_count.index, wrestling_count.ID, width=0.9, color='xkcd:plum', edgecolor='ivory', linewidth=0, hatch='-') plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode='anchor') plt.title('\nHUNGARIAN WRESTLERS\n', fontsize=55, loc='left') ax.tick_params(axis='x', size=8, labelsize=26) ax.tick_params(axis='y', size=8, labelsize=26) fig.show() # plotly of the above fig = px.bar( wrestling_count, x='Games', y='ID', labels={'index':'Games'}, title='HUNGARIAN WRESTLERS', text="ID", color="ID", template = "plotly_dark", ) fig.update_traces(textfont_size=12, textangle=0, textposition="outside", cliponaxis=False) fig.show() # horizontal bars y = np.array(winter_games_gold_fs['Games']) x = np.array(winter_games_gold_fs['Age']) fig, ax = plt.subplots(1, figsize=(24,15)) ax.barh(y, x, color='xkcd:darkblue', edgecolor='ivory', linewidth=0, hatch='-') ax.set_yticks(y, labels=winter_games_gold_fs['Games'], fontsize=20) ax.invert_yaxis() ax.set_xlabel('Age', fontsize=35) ax.set_title("\nFREESTYLE SKIER'S AGES -\nGOLD MEDALISTS\n", fontsize=44, loc='left') ax.tick_params(axis='x', labelsize=30) ax.tick_params(axis='y', labelsize=30) plt.show() # plotly of the above fig = px.bar( winter_games_gold_fs, x='Age', y='Games', title="FREESTYLE SKIER'S AGES - GOLD MEDALISTS", text="Age", color="Age", color_continuous_scale='Bluered_r', template = "plotly_dark", orientation="h" ) fig.update_traces(textfont_size=12, textangle=0, textposition="inside", cliponaxis=False) fig.show() # grouped bars fig, ax = plt.subplots(figsize = (30,20)) width = 0.4 labels = gymnists_fn.Year.unique() label_locations = np.arange(len(gymnists_fn.Games.unique())) y_m = np.array(gymnists_fn_m.ID) y_w = np.array(gymnists_fn_w.ID) semi_bar_m = ax.bar(label_locations-width/2, y_m, width, label="M", color='xkcd:brown') semi_bar_w = ax.bar(label_locations+width/2, y_w, width, label="F", color='purple') ax.set_ylabel('Athlete Count', fontsize=30) ax.set_title('\nFRENCH GYMNISTS FROM 1952 \n', fontsize=46, loc='left') ax.set_xticks(label_locations, labels, fontsize=30) ax.tick_params(axis='y', labelsize=26) ax.legend(prop={'size': 36}, shadow=True) ax.bar_label(semi_bar_m, padding=3, fontsize=24) ax.bar_label(semi_bar_w, padding=3, fontsize=24) plt.show() # plotly of the above # done with graph objects fig = go.Figure() fig.add_trace(go.Bar( x=labels, y= y_m, name='Male', marker_color='saddlebrown' )) fig.add_trace(go.Bar( x=labels, y=y_w, name='Female', marker_color='lightsalmon' )) # Here we modify the tickangle of the xaxis, resulting in rotated labels. fig.update_layout(barmode='group', xaxis_tickangle=-45, font=dict(size=18), title="FRENCH GYMNISTS FROM 1952") fig.show()
# “ab”是地址(Address)簿(Book)的缩写 ab = { 'Swaroop': 'swaroop@swaroopch.com', 'Larry': 'larry@wall.org', 'Matsumoto': 'matz@ruby-lang.org', 'Spammer': 'spammer@hotmail.com' } print("Swaroop's address is",ab['Swaroop']) del ab['Spammer'] print('\n There are {} contacts in the address-book\n'.format(len(ab))) for name,address in ab.items():#注意itmes是方法,不是字段 print('Contact {} at {}'.format(name,address)) #添加一对键值对 ab['Guido']='auido@python.org' if 'Guido' in ab: print("\n Guido's address is",ab['Guido']) #查看帮助信息 help(dict)
print('\033[34m-=\033[m'*12) print('Analisador de Trianulo') print('\033[34m-=\033[m'*12) a = float(input('Informe a primeira reta: ')) b = float(input('Informe a segunda reta: ')) c = float(input('Informe a terceira reta: ')) if a + b > c and a + c > b and b + c > a: print(f'Com essas retas {a} X {b} X {c} consegeuimos montar um triangulo.') if a == b == c: print(f'Esse é um triangulo Equilátero.') elif a == b and a != c or a == c and a != b: print(f'Esse é um triangulo Isósceles.') elif a != b and a != c and b != c: print(f'Esse é um triangulo Escaleno.') else: print(f'Com essas retas {a} X {b} X {c} NÃO consegeuimos montar um triangulo.')
{ "targets": [ { "target_name": "gles3", "sources": [ "src/node-gles3.cpp" ], 'include_dirs': [ 'src', 'src/include' ], 'cflags':[], 'conditions': [ ['OS=="mac"', { 'libraries': [ '-lGLEW', '-framework OpenGL' ], 'include_dirs': [ './node_modules/native-graphics-deps/include' ], 'library_dirs': [ '../node_modules/native-graphics-deps/lib/macos/glew' ], 'xcode_settings': { 'MACOSX_DEPLOYMENT_TARGET': '10.13', 'OTHER_CFLAGS': [ "-Wno-unused-but-set-variable","-Wno-unused-parameter","-Wno-unused-variable","-Wno-int-to-void-pointer-cast" ], } } ], ['OS=="linux"', { 'libraries': [ '-lGLEW','-lGL'] } ], ['OS=="win"', { 'include_dirs': [ './node_modules/native-graphics-deps/include', ], 'library_dirs': [ './node_modules/native-graphics-deps/lib/windows/glew', 'lib/<(target_arch)', ], 'libraries': [ 'glew32.lib', 'opengl32.lib' ], 'defines' : [ 'WIN32_LEAN_AND_MEAN', 'VC_EXTRALEAN' ], 'msvs_settings' : { 'VCCLCompilerTool' : { 'AdditionalOptions' : [] }, 'VCLinkerTool' : { 'AdditionalOptions' : ['/OPT:REF','/OPT:ICF','/LTCG'] }, }, 'copies': [ { 'destination': './build/<(CONFIGURATION_NAME)/', 'files': [ './node_modules/native-graphics-deps/lib/windows/glew/glew32.dll' ] } ], } ], ], }, { "target_name": "glfw3", "sources": [ "src/node-glfw3.cpp" ], 'include_dirs': [ 'src', 'src/include' ], 'cflags':[], 'conditions': [ ['OS=="mac"', { 'libraries': [ '-framework Cocoa', '../node_modules/native-graphics-deps/lib/macos/glfw/libglfw3.a' ], 'include_dirs': [ './node_modules/native-graphics-deps/include' ], 'library_dirs': [ ], 'xcode_settings': { 'MACOSX_DEPLOYMENT_TARGET': '10.13', 'OTHER_CFLAGS': [ "-Wno-unused-but-set-variable","-Wno-unused-parameter","-Wno-unused-variable" ], } } ], ['OS=="linux"', { 'libraries': [] } ], ['OS=="win"', { 'include_dirs': [ './node_modules/native-graphics-deps/include', ], 'library_dirs': [ './node_modules/native-graphics-deps/lib/windows/glfw' ], 'libraries': [ 'glfw3dll.lib' ], 'defines' : [ 'WIN32_LEAN_AND_MEAN', 'VC_EXTRALEAN' ], 'msvs_settings' : { 'VCCLCompilerTool' : { 'AdditionalOptions' : [] }, 'VCLinkerTool' : { 'AdditionalOptions' : ['/OPT:REF','/OPT:ICF','/LTCG'] }, }, 'copies': [ { 'destination': './build/<(CONFIGURATION_NAME)/', 'files': [ './node_modules/native-graphics-deps/lib/windows/glfw/glfw3.dll' ] } ], } ], ], }, { "target_name": "openvr", "sources": [ "src/node-openvr.cpp" ], 'include_dirs': [ './node_modules/native-graphics-deps/include', './node_modules/native-openvr-deps/headers', 'src', 'src/include' ], "cflags": ["-std=c++11", "-Wall", "-pedantic"], 'conditions': [ ['OS=="mac"', { 'libraries': [ ], 'library_dirs': [ ], 'xcode_settings': { 'MACOSX_DEPLOYMENT_TARGET': '10.13', 'OTHER_CFLAGS': [ "-Wno-unused-but-set-variable","-Wno-unused-parameter","-Wno-unused-variable","-Wno-int-to-void-pointer-cast" ], }, 'copies': [ { 'destination': './build/<(CONFIGURATION_NAME)/', 'files': [ './node_modules/native-openvr-deps/lib/osx32/libopenvr_api.dylib' ] } ], } ], ['OS=="linux"', { 'libraries': [ '-lGLEW','-lGL'] } ], ['OS=="win"', { 'library_dirs': [ './node_modules/native-openvr-deps/lib/win64', ], 'libraries': [ 'openvr_api.lib' ], 'defines' : [ 'WIN32_LEAN_AND_MEAN', 'VC_EXTRALEAN' ], 'msvs_settings' : { 'VCCLCompilerTool' : { 'AdditionalOptions' : [] }, 'VCLinkerTool' : { 'AdditionalOptions' : ['/OPT:REF','/OPT:ICF','/LTCG'] }, }, 'copies': [ { 'destination': './build/<(CONFIGURATION_NAME)/', 'files': [ './node_modules/native-openvr-deps/bin/win64/openvr_api.dll' ] } ], } ], ], }, { "target_name": "audio", "sources": [ "src/node-audio.cpp" ], "defines": [], "cflags": ["-std=c++11", "-Wall", "-pedantic"], 'cflags!': [ '-fno-exceptions' ], 'cflags_cc!': [ '-fno-exceptions' ], "include_dirs": [ "<!(node -p \"require('node-addon-api').include_dir\")", "src/miniaudio.h" ], "libraries": [], "dependencies": [], "conditions": [ ['OS=="win"', { 'msvs_settings': { 'VCCLCompilerTool': { 'ExceptionHandling': 1 }, } }], ['OS=="mac"', { 'cflags+': ['-fvisibility=hidden'], 'xcode_settings': { 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', 'CLANG_CXX_LIBRARY': 'libc++', 'MACOSX_DEPLOYMENT_TARGET': '10.7', 'GCC_SYMBOLS_PRIVATE_EXTERN': 'YES', # -fvisibility=hidden }, }], ['OS=="linux"', {}], ], }, { "target_name": "zed", "sources": [], "defines": [], "cflags": ["-std=c++11", "-Wall", "-pedantic"], "include_dirs": [ "<!(node -p \"require('node-addon-api').include_dir\")", ], "libraries": [], "dependencies": [], "conditions": [ ['OS=="win"', { "sources": [ "src/node-zed.cpp" ], 'include_dirs': [ "$(CUDA_PATH)/include", "$(ZED_SDK_ROOT_DIR)/include"], 'library_dirs': [ '$(ZED_SDK_ROOT_DIR)/lib', ], 'libraries': [ 'sl_zed64.lib' ], 'msvs_settings': { 'VCCLCompilerTool': { 'ExceptionHandling': 1 } } }], ['OS=="mac"', { 'cflags+': ['-fvisibility=hidden'], 'xcode_settings': {}, }], ['OS=="linux"', {}], ], }, { "target_name": "realsense", "sources": [ "src/node-realsense.cpp" ], "defines": [], "cflags": ["-std=c++11", "-Wall", "-pedantic"], "include_dirs": [ "<!(node -p \"require('node-addon-api').include_dir\")" ], "libraries": [], "dependencies": [], "conditions": [ ['OS=="win"', { 'include_dirs': [ "C:\\Program Files (x86)\\Intel RealSense SDK 2.0\\include" ], 'library_dirs': [ 'C:\\Program Files (x86)\\Intel RealSense SDK 2.0\\lib\\x64', ], 'libraries': [ '-lrealsense2.lib' ], 'msvs_settings': { 'VCCLCompilerTool': { 'ExceptionHandling': 1 } }, "copies": [{ 'destination': './build/<(CONFIGURATION_NAME)/', 'files': ['C:\\Program Files (x86)\\Intel RealSense SDK 2.0\\bin\\x64\\realsense2.dll'] }] }], ['OS=="mac"', { 'cflags+': ['-fvisibility=hidden'], 'xcode_settings': {}, }], ['OS=="linux"', {}], ], } ] }
''' Created on 7 jan. 2013 @author: sander ''' # The following Key ID values are defined by this specification as used # in any packet type that references a Key ID field: # # Name Number Defined in #----------------------------------------------- # None 0 n/a # HMAC-SHA-1-96 1 [RFC2404] # HMAC-SHA-256-128 2 [RFC6234] KEY_ID_NONE = 0 KEY_ID_HMAC_SHA_1_96 = 1 KEY_ID_HMAC_SHA_256_128 = 2
#!/usr/bin/env python # coding: utf-8 # In[1]: days_dict = {1:31, 2:29, 3:31, 4:30, 5:31, 6:30, 7:31,8:31, 9:30, 10:31, 11:30, 12:31} start_week = {1:3, 2:6, 3:0, 4:3, 5:5, 6:1, 7:3, 8:6, 9:2, 10:4, 11:0, 12:2} with open('Q3-output.txt', 'w') as f: for i in range(1,13): print('\n\n\t\t\t%d月'%i, file = f) print('日\t一\t二\t三\t四\t五\t六', file = f) for k in range(start_week[i]): print('\t', end = '', file = f) for j in range(1, days_dict[i]+1): print(j, '\t', end = '', file = f) if (start_week[i]+j) % 7 == 0: print('\n', file = f) # In[ ]:
#!/usr/bin/python3 # ref: https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange#Cryptographic_explanation # ref: https://en.wikipedia.org/wiki/RSA_(cryptosystem) shared_modulus = 23 shared_base = 5 print("shared modulus: %s" % shared_modulus) print("shared base: %s" % shared_base) print("-"*40) alice_secret = 4 bob_secret = 3 print("alice's secret key: %s" % alice_secret) print("bob's secret key: %s" % bob_secret) print("-"*40) A = (shared_base**alice_secret) % shared_modulus B = (shared_base**bob_secret) % shared_modulus print("alice's public key: %s" % A) print("bob's public key: %s" % B) print("-"*40) alice_s = (B**alice_secret) % shared_modulus bob_s = (A**bob_secret) % shared_modulus print("alice's shared secret key: %s" % alice_s) print("bob's shared secret key: %s" % bob_s)
#!/usr/bin/env python # @Time : 2019-06-03 # @Author : hongshu BUFF_SIZE = 32 * 1024
'''Faça um programa que mostre a tabuada de varios numeros, um de cada vez, para cada valor digitado pelo usuario. O programa sera interrompido quando u número solicitado for negativo''' while True: n = int(input('Quer ver a taboada de qual valor: ')) print('-' * 35) if n < 0: break for c in range(1,11): print(f'{n} x {c} = {n*c}') print('-' * 35) print('PROGRAMA DE TABOADA ENCERRADO')
########################### # 6.0002 Problem Set 1b: Space Change # Name: # Collaborators: # Time: # Author: charz, cdenise #================================ # Part B: Golden Eggs #================================ # Problem 1 def dp_make_weight(egg_weights, target_weight, memo = {}): """ Find number of eggs to bring back, using the smallest number of eggs. Assumes there is an infinite supply of eggs of each weight, and there is always a egg of value 1. Parameters: egg_weights - tuple of integers, available egg weights sorted from smallest to largest value (1 = d1 < d2 < ... < dk) target_weight - int, amount of weight we want to find eggs to fit memo - dictionary, OPTIONAL parameter for memoization (you may not need to use this parameter depending on your implementation) Returns: int, smallest number of eggs needed to make target weight """ # base case if target weight is zero! if target_weight == 0: return 0 # try to get solution for current target_weight from memo try: return memo[target_weight] # if unsuccesful apply recursion to get solution except KeyError: solutions = [] for e in egg_weights: # weight if we choose this egg? new_weight = target_weight - e # always true for at least one weight if there is always a egg of value 1 if new_weight >= 0: solutions.append(1 + dp_make_weight(egg_weights, new_weight, memo)) best_solution = min(solutions) memo[target_weight] = best_solution return best_solution # EXAMPLE TESTING CODE, feel free to add more if you'd like if __name__ == '__main__': egg_weights = (1, 5, 10, 25) n = 99 print("Egg weights = (1, 5, 10, 25)") print("n = 99") print("Expected ouput: 9 (3 * 25 + 2 * 10 + 4 * 1 = 99)") print("Actual output:", dp_make_weight(egg_weights, n)) print()
# from functools import wraps # def debugMethod(func, cls=None): # '''decorator for debugging passed function''' # @wraps(func) # def wrapper(*args, **kwargs): # print({ # 'class': cls, # class object, not string # 'method': func.__qualname__, # method name, string # 'args': args, # all args, including self # 'kwargs': kwargs # }) # return func(*args, **kwargs) # return wrapper class Meta(type): # def __new__(cls, clsname, bases, clsdict): # obj = super().__new__(cls, clsname, bases, clsdict) # def IS_DUNDER(x): return x.startswith("__") and x.endswith("__") # for item, val in vars(obj).items(): # if callable(val): # # setattr(obj, item, debugMethod(val, cls=cls)) # pass # return obj def __getattribute__(self, name): print({'action': "get", 'attr': name}) return object.__getattribute__(self, name) class A(object, metaclass=Meta): # def __init__(self): # pass # def __setattr__(self, name, value): # print("setting attribute", name, value) # return super().__setattr__(name, value) # def __getattribute__(self, name): # print("getting attribute", name) # return super().__getattribute__(name) def add(self, x, y): return x+y def mul(self, x, y): return x*y a = A() # a.mul(2, 3) # a.mul(0, 100) # a.mul(2, 100) # a.mul(2323, 3) # a.mul(2, 2) # a.mul(2, 3414) # another setter a.x = 200 # print(vars(a)) # # settter # a.x = 1000 # # setter # a.x = "23931903" # # finally a getter # my_getter_val = a.x
#!/usr/bin/env python3 """Solves problem xxx from the Project Euler website""" def solve(): """Solve the problem and return the result""" oneToNine = sum( [len('one'), len('two'), len('three'), len('four'), len('five'), len('six'), len('seven'), len('eight'), len('nine')]) oneToNintynine = 10 * sum( [len('twenty'), len('thirty'), len('forty'), len('fifty'), len('sixty'), len('seventy'), len('eighty'), len('ninety')]) + sum( [len('ten'), len('eleven'), len('twelve'), len('thirteen'), len('fourteen'), len('fifteen'), len('sixteen'), len('seventeen'), len('eighteen'), len('nineteen')]) + 9 * oneToNine result = len('one') + len('thousand') + 100 * (9 * len('hundred') + oneToNine) + 99 * 9 * len( 'and') + 10 * oneToNintynine return result if __name__ == '__main__': print(solve())
class NCBaseError(Exception): def __init__(self, message) -> None: super(NCBaseError, self).__init__(message) class DataTypeMismatchError(Exception): def __init__(self, provided_data, place:str=None, required_data_type:str=None) -> None: message = f"{provided_data} datatype isn't supported for {place}.\nRequired datatype is: {required_data_type}, got: {str(type(provided_data).__name__)}" super(DataTypeMismatchError, self).__init__(message) class InsufficientArgumentsError(Exception): def __init__(self, message): message = f"Insufficient arguments.\n{message}" super(InsufficientArgumentsError, self).__init__(message) class InvalidArgumentsError(Exception): def __init__(self, message:str) -> None: super(InvalidArgumentsError, self).__init__(message) class DirectoryAlreadyExistsError(Exception): def __init__(self,project_dir): message = f"{project_dir} already exists at the location." super(DirectoryAlreadyExistsError, self).__init__(message) class ImportNameNotFoundError(Exception): def __init__(self, location) -> None: message = f"import_name notm provided for the sister app at {location}" super(ImportNameNotFoundError, self).__init__(message) class ConfigurationError(Exception): def __init__(self, message) -> None: super(ConfigurationError, self).__init__(message)
class Node: def __init__(self, data): self.data= data self.previous= None self.next= None class DoublyLinkedList: def __init__(self): self.head= None def create_list(self, arr): start= self.head n= len(arr) temp= start i=0 while(i<n): new_node= Node(arr[i]) if (i==0): start= new_node temp= start else: temp.next= new_node new_node.prev= temp temp= temp.next i+=1 self.head= start return start def count_elements(self): temp= self.head count=0 while(temp): count+=1 temp=temp.next return count def insert_node(self, value, pos): temp= self.head count_of_elem= self.count_elements() #index is 6, count is 5, valid #index is 7, count is 5, if (count_of_elem+1<pos): return temp new_node= Node(value) if (pos==1): new_node.next= temp temp.previous= new_node self.head= new_node return self.head if (pos==count_of_elem+1): while(temp.next): temp= temp.next temp.next= new_node new_node.previous= temp return self.head counter = 1 while (counter < pos): temp = temp.next counter += 1 node_at_target = temp previous_node = node_at_target.previous previous_node.next = new_node new_node.previous = previous_node new_node.next = node_at_target node_at_target.previous = new_node return self.head def delete_node(self, pos): temp= self.head count_of_elem= self.count_elements() if (count_of_elem<pos): return 'delete position {} is greater than list size {}'.format(pos, count_of_elem) if (pos==1): temp= temp.next self.head=temp return self.head if(pos==count_of_elem): while(temp.next and temp.next.next): temp=temp.next temp.next= None return self.head i=1 while(i<pos-1): temp= temp.next i+=1 prev_node= temp target_node= temp.next next_node= target_node.next next_node.previous= prev_node prev_node.next= next_node return self.head def print_list(self): temp= self.head linked_list= "head=>" while(temp.next): linked_list+= str(temp.data)+"<=>" temp= temp.next linked_list+= str(temp.data) print(linked_list) arr= [1,2,3,4,5] dll= DoublyLinkedList() dll.create_list(arr) dll.print_list() dll.count_elements() dll.insert_node(6,3) dll.print_list() dll.count_elements() dll.insert_node(10000,3) dll.print_list() # dll.delete_node(2) # dll.print_list()
# The ranges below are as specified in the Yellow Paper. # Note: range(s, e) excludes e, hence the +1 valid_opcodes = [ *range(0x00, 0x0b + 1), *range(0x10, 0x1d + 1), 0x20, *range(0x30, 0x3f + 1), *range(0x40, 0x48 + 1), *range(0x50, 0x5b + 1), *range(0x60, 0x6f + 1), *range(0x70, 0x7f + 1), *range(0x80, 0x8f + 1), *range(0x90, 0x9f + 1), *range(0xa0, 0xa4 + 1), # Note: 0xfe is considered assigned. *range(0xf0, 0xf5 + 1), 0xfa, 0xfd, 0xfe, 0xff ] # STOP, RETURN, REVERT, INVALID, SELFDESTRUCT terminating_opcodes = [ 0x00, 0xf3, 0xfd, 0xfe, 0xff ] # Only for PUSH1..PUSH32 immediate_sizes = 256 * [0] for opcode in range(0x60, 0x7f + 1): # PUSH1..PUSH32 immediate_sizes[opcode] = opcode - 0x60 + 1 # Fails with assertion on invalid code def validate_code(code: bytes): # Note that EOF1 already asserts this with the code section requirements assert len(code) > 0 opcode = 0 pos = 0 while pos < len(code): # Ensure the opcode is valid opcode = code[pos] pos += 1 assert opcode in valid_opcodes # Skip immediates pos += immediate_sizes[opcode] # Ensure last opcode's immediate doesn't go over code end assert pos == len(code) # opcode is the *last opcode* assert opcode in terminating_opcodes def test_validate_code(code: bytes) -> bool: try: validate_code(code) return True except: return False # Some valid opcodes assert test_validate_code(b'\x30\x00') == True assert test_validate_code(b'\x50\x00') == True assert test_validate_code(b'\xfe\x00') == True assert test_validate_code(b'\xff\x00') == True # PUSHes with valid immediates assert test_validate_code(b'\x60\x00\x00') == True assert test_validate_code(b'\x61' + b'\x00' * 2 + b'\x00') == True assert test_validate_code(b'\x62' + b'\x00' * 3 + b'\x00') == True assert test_validate_code(b'\x63' + b'\x00' * 4 + b'\x00') == True assert test_validate_code(b'\x64' + b'\x00' * 5 + b'\x00') == True assert test_validate_code(b'\x65' + b'\x00' * 6 + b'\x00') == True assert test_validate_code(b'\x66' + b'\x00' * 7 + b'\x00') == True assert test_validate_code(b'\x67' + b'\x00' * 8 + b'\x00') == True assert test_validate_code(b'\x68' + b'\x00' * 9 + b'\x00') == True assert test_validate_code(b'\x69' + b'\x00' * 10 + b'\x00') == True assert test_validate_code(b'\x6a' + b'\x00' * 11 + b'\x00') == True assert test_validate_code(b'\x6b' + b'\x00' * 12 + b'\x00') == True assert test_validate_code(b'\x6c' + b'\x00' * 13 + b'\x00') == True assert test_validate_code(b'\x6d' + b'\x00' * 14 + b'\x00') == True assert test_validate_code(b'\x6e' + b'\x00' * 15 + b'\x00') == True assert test_validate_code(b'\x6f' + b'\x00' * 16 + b'\x00') == True assert test_validate_code(b'\x70' + b'\x00' * 17 + b'\x00') == True assert test_validate_code(b'\x71' + b'\x00' * 18 + b'\x00') == True assert test_validate_code(b'\x72' + b'\x00' * 19 + b'\x00') == True assert test_validate_code(b'\x73' + b'\x00' * 20 + b'\x00') == True assert test_validate_code(b'\x74' + b'\x00' * 21 + b'\x00') == True assert test_validate_code(b'\x75' + b'\x00' * 22 + b'\x00') == True assert test_validate_code(b'\x76' + b'\x00' * 23 + b'\x00') == True assert test_validate_code(b'\x77' + b'\x00' * 24 + b'\x00') == True assert test_validate_code(b'\x78' + b'\x00' * 25 + b'\x00') == True assert test_validate_code(b'\x79' + b'\x00' * 26 + b'\x00') == True assert test_validate_code(b'\x7a' + b'\x00' * 27 + b'\x00') == True assert test_validate_code(b'\x7b' + b'\x00' * 28 + b'\x00') == True assert test_validate_code(b'\x7c' + b'\x00' * 29 + b'\x00') == True assert test_validate_code(b'\x7d' + b'\x00' * 30 + b'\x00') == True assert test_validate_code(b'\x7e' + b'\x00' * 31 + b'\x00') == True assert test_validate_code(b'\x7f' + b'\x00' * 32 + b'\x00') == True # Valid code terminators assert test_validate_code(b'\x00') == True assert test_validate_code(b'\xf3') == True assert test_validate_code(b'\xfd') == True assert test_validate_code(b'\xfe') == True # Empty code assert test_validate_code(b'') == False # Valid opcode, but invalid as terminator assert test_validate_code(b'\x5b') == False # Invalid opcodes assert test_validate_code(b'\x0c\x00') == False assert test_validate_code(b'\x0d\x00') == False assert test_validate_code(b'\x0e\x00') == False assert test_validate_code(b'\x0f\x00') == False assert test_validate_code(b'\x1e\x00') == False assert test_validate_code(b'\x1f\x00') == False assert test_validate_code(b'\x21\x00') == False assert test_validate_code(b'\x22\x00') == False assert test_validate_code(b'\x23\x00') == False assert test_validate_code(b'\x24\x00') == False assert test_validate_code(b'\x25\x00') == False assert test_validate_code(b'\x26\x00') == False assert test_validate_code(b'\x27\x00') == False assert test_validate_code(b'\x28\x00') == False assert test_validate_code(b'\x29\x00') == False assert test_validate_code(b'\x2a\x00') == False assert test_validate_code(b'\x2b\x00') == False assert test_validate_code(b'\x2c\x00') == False assert test_validate_code(b'\x2d\x00') == False assert test_validate_code(b'\x2e\x00') == False assert test_validate_code(b'\x2f\x00') == False assert test_validate_code(b'\x49\x00') == False assert test_validate_code(b'\x4a\x00') == False assert test_validate_code(b'\x4b\x00') == False assert test_validate_code(b'\x4c\x00') == False assert test_validate_code(b'\x4d\x00') == False assert test_validate_code(b'\x4e\x00') == False assert test_validate_code(b'\x4f\x00') == False assert test_validate_code(b'\x5c\x00') == False assert test_validate_code(b'\x5d\x00') == False assert test_validate_code(b'\x5e\x00') == False assert test_validate_code(b'\x5f\x00') == False assert test_validate_code(b'\xa5\x00') == False assert test_validate_code(b'\xa6\x00') == False assert test_validate_code(b'\xa7\x00') == False assert test_validate_code(b'\xa8\x00') == False assert test_validate_code(b'\xa9\x00') == False assert test_validate_code(b'\xaa\x00') == False assert test_validate_code(b'\xab\x00') == False assert test_validate_code(b'\xac\x00') == False assert test_validate_code(b'\xad\x00') == False assert test_validate_code(b'\xae\x00') == False assert test_validate_code(b'\xaf\x00') == False assert test_validate_code(b'\xb0\x00') == False assert test_validate_code(b'\xb1\x00') == False assert test_validate_code(b'\xb2\x00') == False assert test_validate_code(b'\xb3\x00') == False assert test_validate_code(b'\xb4\x00') == False assert test_validate_code(b'\xb5\x00') == False assert test_validate_code(b'\xb6\x00') == False assert test_validate_code(b'\xb7\x00') == False assert test_validate_code(b'\xb8\x00') == False assert test_validate_code(b'\xb9\x00') == False assert test_validate_code(b'\xba\x00') == False assert test_validate_code(b'\xbb\x00') == False assert test_validate_code(b'\xbc\x00') == False assert test_validate_code(b'\xbd\x00') == False assert test_validate_code(b'\xbe\x00') == False assert test_validate_code(b'\xbf\x00') == False assert test_validate_code(b'\xc0\x00') == False assert test_validate_code(b'\xc1\x00') == False assert test_validate_code(b'\xc2\x00') == False assert test_validate_code(b'\xc3\x00') == False assert test_validate_code(b'\xc4\x00') == False assert test_validate_code(b'\xc5\x00') == False assert test_validate_code(b'\xc6\x00') == False assert test_validate_code(b'\xc7\x00') == False assert test_validate_code(b'\xc8\x00') == False assert test_validate_code(b'\xc9\x00') == False assert test_validate_code(b'\xca\x00') == False assert test_validate_code(b'\xcb\x00') == False assert test_validate_code(b'\xcc\x00') == False assert test_validate_code(b'\xcd\x00') == False assert test_validate_code(b'\xce\x00') == False assert test_validate_code(b'\xcf\x00') == False assert test_validate_code(b'\xd0\x00') == False assert test_validate_code(b'\xd1\x00') == False assert test_validate_code(b'\xd2\x00') == False assert test_validate_code(b'\xd3\x00') == False assert test_validate_code(b'\xd4\x00') == False assert test_validate_code(b'\xd5\x00') == False assert test_validate_code(b'\xd6\x00') == False assert test_validate_code(b'\xd7\x00') == False assert test_validate_code(b'\xd8\x00') == False assert test_validate_code(b'\xd9\x00') == False assert test_validate_code(b'\xda\x00') == False assert test_validate_code(b'\xdb\x00') == False assert test_validate_code(b'\xdc\x00') == False assert test_validate_code(b'\xdd\x00') == False assert test_validate_code(b'\xde\x00') == False assert test_validate_code(b'\xdf\x00') == False assert test_validate_code(b'\xe0\x00') == False assert test_validate_code(b'\xe1\x00') == False assert test_validate_code(b'\xe2\x00') == False assert test_validate_code(b'\xe3\x00') == False assert test_validate_code(b'\xe4\x00') == False assert test_validate_code(b'\xe5\x00') == False assert test_validate_code(b'\xe6\x00') == False assert test_validate_code(b'\xe7\x00') == False assert test_validate_code(b'\xe8\x00') == False assert test_validate_code(b'\xe9\x00') == False assert test_validate_code(b'\xea\x00') == False assert test_validate_code(b'\xeb\x00') == False assert test_validate_code(b'\xec\x00') == False assert test_validate_code(b'\xed\x00') == False assert test_validate_code(b'\xee\x00') == False assert test_validate_code(b'\xef\x00') == False assert test_validate_code(b'\xf6\x00') == False assert test_validate_code(b'\xf7\x00') == False assert test_validate_code(b'\xf8\x00') == False assert test_validate_code(b'\xf9\x00') == False assert test_validate_code(b'\xfb\x00') == False assert test_validate_code(b'\xfc\x00') == False # PUSHes with truncated immediates assert test_validate_code(b'\x60\x00') == False assert test_validate_code(b'\x61' + b'\x00' * 1 + b'\x00') == False assert test_validate_code(b'\x62' + b'\x00' * 2 + b'\x00') == False assert test_validate_code(b'\x63' + b'\x00' * 3 + b'\x00') == False assert test_validate_code(b'\x64' + b'\x00' * 4 + b'\x00') == False assert test_validate_code(b'\x65' + b'\x00' * 5 + b'\x00') == False assert test_validate_code(b'\x66' + b'\x00' * 6 + b'\x00') == False assert test_validate_code(b'\x67' + b'\x00' * 7 + b'\x00') == False assert test_validate_code(b'\x68' + b'\x00' * 8 + b'\x00') == False assert test_validate_code(b'\x69' + b'\x00' * 9 + b'\x00') == False assert test_validate_code(b'\x6a' + b'\x00' * 10 + b'\x00') == False assert test_validate_code(b'\x6b' + b'\x00' * 11 + b'\x00') == False assert test_validate_code(b'\x6c' + b'\x00' * 12 + b'\x00') == False assert test_validate_code(b'\x6d' + b'\x00' * 13 + b'\x00') == False assert test_validate_code(b'\x6e' + b'\x00' * 14 + b'\x00') == False assert test_validate_code(b'\x6f' + b'\x00' * 15 + b'\x00') == False assert test_validate_code(b'\x70' + b'\x00' * 16 + b'\x00') == False assert test_validate_code(b'\x71' + b'\x00' * 17 + b'\x00') == False assert test_validate_code(b'\x72' + b'\x00' * 18 + b'\x00') == False assert test_validate_code(b'\x73' + b'\x00' * 19 + b'\x00') == False assert test_validate_code(b'\x74' + b'\x00' * 20 + b'\x00') == False assert test_validate_code(b'\x75' + b'\x00' * 21 + b'\x00') == False assert test_validate_code(b'\x76' + b'\x00' * 22 + b'\x00') == False assert test_validate_code(b'\x77' + b'\x00' * 23 + b'\x00') == False assert test_validate_code(b'\x78' + b'\x00' * 24 + b'\x00') == False assert test_validate_code(b'\x79' + b'\x00' * 25 + b'\x00') == False assert test_validate_code(b'\x7a' + b'\x00' * 26 + b'\x00') == False assert test_validate_code(b'\x7b' + b'\x00' * 27 + b'\x00') == False assert test_validate_code(b'\x7c' + b'\x00' * 28 + b'\x00') == False assert test_validate_code(b'\x7d' + b'\x00' * 29 + b'\x00') == False assert test_validate_code(b'\x7e' + b'\x00' * 30 + b'\x00') == False assert test_validate_code(b'\x7f' + b'\x00' * 31 + b'\x00') == False
QUESTIONS = { 'a1': { 'Q': 'What is the chemical symbol for gold?', 'A': 'au' }, 'a2': { 'Q': '', 'A': '' }, 'a3': { 'Q': '', 'A': '' }, 'a4': { 'Q': '', 'A': '' }, 'b1': { 'Q': '', 'A': '' }, 'b2': { 'Q': '', 'A': '' }, 'b3': { 'Q': '', 'A': '' }, 'b4': { 'Q': '', 'A': '' }, 'c1': { 'Q': '', 'A': '' }, 'c2': { 'Q': '', 'A': '' }, 'c3': { 'Q': '', 'A': '' }, 'c4': { 'Q': '', 'A': '' }, 'd1': { 'Q': '', 'A': '' }, 'd2': { 'Q': '', 'A': '' }, 'd3': { 'Q': '', 'A': '' }, 'd4': { 'Q': '', 'A': '' }, }
#Multilevel Inner Classes #In multilevel inner classes, the inner class contains another class which inner classes to the previous one. class Outer: """Outer Class""" def __init__(self): ## instantiating the 'Inner' class self.inner = self.Inner() ## instantiating the multilevel 'InnerInner' class self.innerinner = self.inner.InnerInner() def show_classes(self): print("This is Outer class's function") self.inner.inner_display('message 1 ' ) self.innerinner.inner_display('message 3' ) ## inner class class Inner: """First Inner Class""" def inner_display(self, msg): print("This is Inner class's function") print(msg) def __init__(self): ## instantiating the 'InnerInner' class self.innerinner = self.InnerInner() def show_classes(self): print("This is Inner class's function ") self.innerinner.inner_display('message 2 ' ) ## multilevel inner class class InnerInner: def inner_display(self, msg): print("This is Inner's Inner class function") print(msg) c1 = Outer() c1.show_classes() c1.Inner().show_classes() #output ''' This is Outer class's function This is Inner class's function message 1 This is Inner's Inner class function message 3 This is Inner class's function This is Inner's Inner class function message 2 '''
# Дуэль + Выигрышные номера нескольких тиражей def test_duel_winning_numbers_for_several_draws(app): app.ResultAndPrizes.open_page_results_and_prizes() app.ResultAndPrizes.click_game_duel() app.ResultAndPrizes.click_the_winning_numbers_for_several_draws() app.ResultAndPrizes.click_ok_for_several_draws_modal_window() app.ResultAndPrizes.message_id_33_duel_winning_numbers_for_5_draws() app.ResultAndPrizes.parser_report_text_winners() assert "ВЫИГРЫШНЫЕ НОМЕРА" in app.ResultAndPrizes.parser_report_text_winners() app.ResultAndPrizes.comeback_main_page()
#!/usr/bin/python3 ''' Collects Weather Forecast by Indian Meterological Department, by parsing webpages :) ''' __version__ = '0.2.0' __author__ = 'Anjan Roy<anjanroy@yandex.com>'
# Contains all the basic info about awards class Award: count = 0 def __init__(self, url, number, name, type, application, restrictions, renewable, value, due, description, sequence): self.url = url self.number = number self.name = name self.type = type self.application = application self.restrictions = restrictions self.renewable = renewable self.value = value self.due = due self.description = description self.sequence = sequence Award.count += 1 def displayCount(self): return "There are a total of %d awards" % Award.count def displayAward(self): return "Award Number: ", self.number, ", Name: ", self.name, ", Type: ", self.type, ", Application: ", self.application, ", Restrictions: ", self.restrictions, ", Renewable: ", self.renewable, ", Value: ", self.value, ", Due Day: ", self.due, ", description: ", self.description, ", URL: ", self.url
""" """ load("@bazel_skylib//lib:paths.bzl", "paths") load("@fbcode_macros//build_defs/lib/thrift:thrift_interface.bzl", "thrift_interface") load("@fbcode_macros//build_defs/lib:common_paths.bzl", "common_paths") load("@fbcode_macros//build_defs/lib:src_and_dep_helpers.bzl", "src_and_dep_helpers") load("@fbcode_macros//build_defs/lib:thrift_common.bzl", "thrift_common") load("@fbsource//tools/build_defs:fb_native_wrapper.bzl", "fb_native") def _get_lang(): return "js" def _get_names(): return ("js",) def _get_generated_sources( base_path, name, thrift_src, services, options, **_kwargs): _ignore = base_path _ignore = name thrift_base = paths.split_extension(paths.basename(thrift_src))[0] genfiles = [] genfiles.append("%s_types.js" % thrift_base) for service in services: genfiles.append("%s.js" % service) out_dir = "gen-nodejs" if "node" in options else "gen-js" return { paths.join("node_modules", thrift_base, path): paths.join(out_dir, path) for path in genfiles } def _get_language_rule( base_path, name, thrift_srcs, options, sources_map, deps, visibility = None, **_kwargs): _ignore = base_path _ignore = thrift_srcs _ignore = options sources = thrift_common.merge_sources_map(sources_map) cmds = [] for dep in deps: cmds.append('rsync -a $(location {})/ "$OUT"'.format(dep)) for dst, raw_src in sources.items(): src = src_and_dep_helpers.get_source_name(raw_src) dst = paths.join('"$OUT"', dst) cmds.append("mkdir -p {}".format(paths.dirname(dst))) cmds.append("cp {} {}".format(paths.basename(src), dst)) fb_native.genrule( name = name, visibility = visibility, out = common_paths.CURRENT_DIRECTORY, labels = ["generated"], srcs = sources.values(), cmd = " && ".join(cmds), ) js_thrift_converter = thrift_interface.make( get_lang = _get_lang, get_names = _get_names, get_generated_sources = _get_generated_sources, get_language_rule = _get_language_rule, )
# Cracking the Coding Interview 6th Edition # Chapter 1 - Arrays and Strings. Page 88 # Question 1.2 # Solved by Yong Lin Wang """ Given two strings, write a method to decide if one is a permutation of the other. """ def check_permutation(str1, str2): """ If two strings are permutation to one another, they should have the same characters. This solution evaluates the sum of the orders of the strings if they are the same then they are permutation to one another, otherwise, they are not and I am a fucking retard that cant get any shit done properly i am such a failure in life that I cant do anything right. :( """ ord1 = 0 ord2 = 0 for char in str1: ord1 += ord(char) for char in str2: ord2 += ord(char) return ord1 == ord2
# 题意:给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。请你将两个数相加,并以相同形式返回一个表示和的链表。你可以假设除了数字 0 之外,这两个数都不会以 0 开头。 # 解法1: 用while来迭代。考虑两点:进位和不同长两个情况,分别采用:设置一个进位变量,和当某个输入为None(短的已遍历完)时输入的val为0. 对于链表移动,需要先初始化节点,再赋值给一个空指针,在循环内部用next迭代节点。 # 解法2: dfs思路递归。除了判断边界情况,与迭代的while循环不同的是,这里不用初始化,每次递归先给当前节点赋值,再令节点的next和下一个递归结果相等,即可完成一个链表。 # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next # 解法1: class Solution: def addTwoNumbers(self, l1, l2): # input: l1: ListNode, l2: ListNode # output: ListNode jw = 0 node = ListNode(0) # 初始化 p = node # 因为node要进行迭代,所以把node的初始值赋给另一个指针 while l1 or l2 or jw: temp = (l1.val if l1 else 0) + (l2.val if l2 else 0) + jw res = temp%10 jw = temp//10 # ListNode结构用这种方法遍历+构造链表 node.next = ListNode(res) node = node.next l1,l2 = l1.next if l1 else None, l2.next if l2 else None return p.next # 解法2: class Solution_2: def dfs(self, l1, l2, jw): if not l1 and not l2 and jw==0: return None res = (l1.val if l1 else 0) + (l2.val if l2 else 0) + jw jw = res//10 p = ListNode(res%10) l1,l2 = l1.next if l1 else None,l2.next if l2 else None p.next = self.dfs(l1,l2,jw) return p def addTwoNumbers(self, l1, l2): # input: l1: ListNode, l2: ListNode # output: ListNode if not l1 and not l2: return None elif not l1 and l2: return l2 elif l1 and not l2: return l1 else: return self.dfs(l1,l2,0)
class Solution: def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """ if (not nums): return None n = len(nums) result = [1] * n prod = 1 for i in range(n): result[i] = result[i] * prod prod = prod * nums[i] prod = 1 for i in range(n-1,-1,-1): result[i] = result[i] * prod prod = prod * nums[i] return result
class Solution: def dailyTemperatures(self, T: List[int]) -> List[int]: warmer_day = [0]*len(T) recent_day = [2**31-1]*101 MAXLEN = 30000 for i in range(len(T)-1, -1, -1): minday = 2**31-1 for warmer_temp in range(T[i]+1, 101): if recent_day[warmer_temp] <= MAXLEN: minday = min(minday, recent_day[warmer_temp]-i) if minday <= MAXLEN: warmer_day[i] = minday recent_day[T[i]] = i return warmer_day
""" 046 Ask the user to enter a number. Keep asking until they enter a value over 5 and then display the message “The last number you entered was a [number]” and stop the program """ number = 0 while number < 5 : number = float(input("Enter a number : ")) print("The last number you entered was ", number)
# encoding: utf-8 class Animals(object): def __init__(self, sound): self.sound = sound def speak(self): return self.sound
# Classes are a form of complex data that combines data and functions. # ML Libraries frequently provide classes as one of the main features, # where each model is a class that has an internal state as well as some # useful functions for fitting/training the model and using it to make # predictions. # Classes are used throughout the programming industry, not just by ML # folks. class SimpleLinearRegression: """ This simplistic implementation of linear regression assumes data is provided in a two dimensional space and creates a line of best fit using squared error. The resulting line is in the form y=mX+b where m is the slope of the regression line and b is the y-intercept of that line. We're using a classical formula for computing this line using covariance, but not explaining these concepts. For a more complete treatment of least squares regression see: https://www.khanacademy.org/math/statistics-probability/describing-relationships-quantitative-data/regression-library/v/introduction-to-residuals-and-least-squares-regression NOTE: This code is meant as a tool to teach the conept of classes NOT as a tool for performing statistical analysis. Use Numpy, SciKit-Learn, or some other well tested library for your analytical needs. """ # Note, all methods should take "self" as the first parameter. # This has to do with how Python implements classes. The first # passed parameter is always a reference to the current instance # of this class and the name is always "self" by convention. def __init__(self): """ This method is called the "constructor" and in python it always uses the special name __init__. Every time we create a new instance of this class this function will be called to initialize that new instance. We can pass parameters to this function if our class requires data at the time of its creation. Our example class does not need initialization data, so we don't pass any parameters to it. """ # Within methods of the class, the keyword 'self' refers to the # particular instance of the class — in this case it's the instance # that we are creating in the constructor. self.slope = None self.y_intercept = None def fit(self, x_points, y_points): """ This method accepts two lists representing the points in the dataset in the following format: x_points: [x1, x2, x3, ...] y_points: [y1, y2, y3, ...] Calling this method will result in the slope and y_intercept being set after computing the line of best fit using the squared error for the provided data points. """ # It's common to check that the input is valid, and raise an # exeption if the caller made a mistake. if len(x_points) != len(y_points): raise ValueError("There must be the same number of x and y data points.") x_mean = sum(x_points) / len(x_points) y_mean = sum(y_points) / len(y_points) x_variance = 0.0 covariance = 0.0 for x, y in zip(x_points, y_points): covariance += (x - x_mean) * (y - y_mean) x_variance += (x - x_mean)**2 # Note: now we are setting the properties on self # that we created in the constructor self.slope = covariance / x_variance self.y_intercept = y_mean - (self.slope * x_mean) def predict(self, x): """ Given an x value compute and return the corresponding y value from on the regression line. """ return (self.slope * x) + self.y_intercept # When we want to use a class, we envoke the constructor using the # name of the class. linear_model = SimpleLinearRegression() # We've created a unique data type! print(type(linear_model)) # <class '__main__.SimpleLinearRegression'> # We need some data to fit our linear model... # Here is some very simple toy data that has # perfect covariance to test our model... x_values = [1, 2, 3, 4, 5] y_values = [2, 4, 6, 8, 10] # Calling a method is done using dot notation. linear_model.fit(x_values, y_values) # We can access the properties of an object this way too print(linear_model.slope, linear_model.y_intercept) # 2, 0 # Using our predict method... prediction = linear_model.predict(3.45) print(prediction) # Micro-exercise: Create a second instance of the SimpleLinearModel class # then create two new lists of x and y data and fit the model on that data. # Then, print the slope and y_intercept of your model, and use it to make a # prediction for some made up x point.
"""Top-level package for Calorimeter.""" __author__ = """Jonathon Vandezande""" __email__ = 'jevandezande@gmail.com' __version__ = '0.2.1'
f = open('graph.dot') def find_between( s, first, last ): try: start = s.index( first ) + len( first ) end = s.index( last, start ) return s[start:end] except ValueError: return "" s1 = "digraph " s2 = """ { graph [ rankdir="RL" ] """ s3 = "}" for line in f: name = find_between(line, 'label="', '\\n') g = open(name+'.dot', 'w') res = s1 + name + s2 + line + s3 g.write(res) g.close() f.close()
# coding: utf-8 class Partitioner(object): @staticmethod def partition(array): """ Берем певый в качастве Pivot """ IDX_PIVOT = 0 # Возможно лучше выбрать последний # тогда будет проще работать с индексами pivot_value = array[IDX_PIVOT] i = 1 for j, value in enumerate(array): # j сканирет весь, но первый элемент пропускаем if j == 0: continue if pivot_value > array[j]: swap(array, j, i) i += 1 # Last swap swap(array, IDX_PIVOT, i-1) return i # Текущий номер pivot def swap(array, i, j): a, b = i, j array[b], array[a] = array[a], array[b]
lista = [] cont = cinco = 0 print('Digite 999 para encerrar') while True: n = [int(input('escolha um número: '))] if n == [999]: print(f'foram digitados {cont} vezes') lista.sort(reverse=True) print(lista) if [5] in lista: print(f'o valor 5 foi digitado e está na lista') else: print(f'o valor 5 não se encontra na lista') break cont += 1 lista.append(n) #lista.sort(reverse= True) -> para ficar em decrescente #print(sorted(lista)) => para [ # ficar em crescente #print(lista.sort()) => tambem para crescente
# Copyright 2021 Nokia # Licensed under the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause class ApiVersion(object): def __init__(self, group: str, version: str): self.group = group self.version = version class Kind(ApiVersion): def __init__(self, group: str, version: str, kind: str): super().__init__(group, version) self.kind = kind class Resource(ApiVersion): def __init__(self, group: str, version: str, kind: str): super().__init__(group, version) self.resource = kind def parse_api_version(api_version: str) -> ApiVersion: if '/' in api_version: return ApiVersion(*api_version.split('/', 1)) return ApiVersion('', api_version)
class Accessor(object): """""" pass class WriteThru(Accessor): """Implement write-thru access pattern.""" pass class WriteAround(Accessor): """Implement write-around access pattern.""" pass class WriteBack(Accessor): """Implement write-back access pattern.""" pass
_base_ = '../cascade_rcnn/cascade_mask_rcnn_r50_fpn_mstrain_3x_coco.py' model = dict( backbone=dict( type='ResNeXt', depth=101, groups=32, base_width=8, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=False), style='pytorch', init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://detectron2/resnext101_32x8d')), roi_head=dict( _delete_=True, type='KeypointCascadeRoIHead', output_heatmaps=False, keypoint_decoder=dict(type='HeatmapDecodeOneKeypoint', upscale=4), num_keypoints=5, num_stages=3, stage_loss_weights=[1, 0.5, 0.25], bbox_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32]), bbox_head=[ dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.1, 0.1, 0.2, 0.2]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.05, 0.05, 0.1, 0.1]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.033, 0.033, 0.067, 0.067]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)) ], mask_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32]), mask_head=dict( type='FCNMaskHead', num_convs=4, in_channels=256, conv_out_channels=256, num_classes=80, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0))) )
def find_missing(S): if len(S) > 0: m = max(S) vals = [ 0 for i in range(m)] for x in S: if x < 0: print("Warning {} is <0. Ignoring it.".format(x)) else: vals[x-1] += 1 return [x+1 for x in range(m) if vals[x] == 0] else: print("Warning: list is empty. Returning None") if __name__ == "__main__": S = [1,9,7, 7, 4, 3, 3, 3] S1 = list(range(10)) print(find_missing(S)) print(find_missing(S1)) print(find_missing([])) S2 = [1, -72, 4, -3, -3, 3,10] M = find_missing(S2) print(M)
def solution(inpnum): upnum = int(str(9)*inpnum) lownum = int(str(1)+(str(0)*(inpnum-1))) ansnum = None for i in range(upnum,lownum,-1): if len(str(i))==len(set(str(i))): if 2**(i-1)%i==1: ansnum = i break return ansnum
def visualize(**images): """PLot images in one row.""" n = len(images) plt.figure(figsize=(16, 5)) for i, (name, image) in enumerate(images.items()): plt.subplot(1, n, i + 1) plt.xticks([]) plt.yticks([]) plt.title(' '.join(name.split('_')).title()) plt.imshow(image) plt.show() def guided_filter(data, width=image_size, height=image_size, channel=num_channels): r = 15 eps = 1.0 batch_q = np.zeros((height, width, channel)) for j in range(channel): I = data[:, :, j] p = data[:, :, j] ones_array = np.ones([height, width]) N = cv2.boxFilter(ones_array, -1, (2 * r + 1, 2 * r + 1), normalize=False, borderType=0) mean_I = cv2.boxFilter(I, -1, (2 * r + 1, 2 * r + 1), normalize=False, borderType=0) / N mean_p = cv2.boxFilter(p, -1, (2 * r + 1, 2 * r + 1), normalize=False, borderType=0) / N mean_Ip = cv2.boxFilter(I * p, -1, (2 * r + 1, 2 * r + 1), normalize=False, borderType=0) / N cov_Ip = mean_Ip - mean_I * mean_p mean_II = cv2.boxFilter(I * I, -1, (2 * r + 1, 2 * r + 1), normalize=False, borderType=0) / N var_I = mean_II - mean_I * mean_I a = cov_Ip / (var_I + eps) b = mean_p - a * mean_I mean_a = cv2.boxFilter(a, -1, (2 * r + 1, 2 * r + 1), normalize=False, borderType=0) / N mean_b = cv2.boxFilter(b, -1, (2 * r + 1, 2 * r + 1), normalize=False, borderType=0) / N q = mean_a * I + mean_b batch_q[:, :, j] = q return batch_q
""" USO DO JOIN """ string = 'O brasil é penta.' lista = string.split(' ') strint_2 = ','.join(lista) print(string) print(lista) print(strint_2)
class Solution: def toHex(self, num: int) -> str: if num == 0: return '0' chars, result = '0123456789abcdef', [] if num < 0: num += (1 << 32) while num > 0: result.insert(0, chars[num % 16]) num //= 16 return ''.join(result)
#!/usr/bin/python3 """ Class check module Functions: is_kind_of_class: checks if obj is inherit from determined class """ def is_kind_of_class(obj, a_class): """ checks class inheritance Args: obj: object to evaluate a_class: suspect father """ return isinstance(obj, a_class)
# Space: O(1) # Time: O(n) # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def diameterOfBinaryTree(self, root): self.res = 0 self.dfs(root) return self.res def dfs(self, root): if root is None: return 0 left, right = 0, 0 if root.left: left = self.dfs(root.left) + 1 if root.right: right = self.dfs(root.right) + 1 self.res = max(self.res, left + right) return max(left, right)
''' this is the file holding the description texts to be inserted this file is imported to the src.py ''' bf_desc = [ "Brute-Force Algorithm:", " ", "Summary:", "The brute force algorithm is very aggressive.", "It checks every single line segment against every other line segment for an intersection.", "This is done through vector mathematics, direction vectors and scalars.", " ", "Order List:", "This algorithm produces an ordered list of intersection points, in order of intersections from left to right.", " ", "Efficiency:", "The efficiency of this algorithm is O(n*n). This is due to the fact that the presence of", "intersections has to be checked between all line segments. This is computationally expensive.", "There is no consideration of shortcuts, rather all possibilities are computed till it finds a solution." ] bo_desc = [ "Bentley-Ottmann Algorithm:", " ", "Summary:", "The Bentley-Ottmann algorithm incorporates the idea of an imaginary line.", "This line will sweep from left-to-right over the line segments to compute", "all the intersecting pairs of line segments. Once again, this is done through", "vector mathematics, direction vectors and scalars.", " ", "Event Queue:", "This algorithm keeps an event queue.", "Adding a line-segment to the list when its leftmost endpoint is discovered during", "the sweep and also deleting a line-segment from the list when its rightmost endpoint", "is discovered during the sweep. This way, when the sweep reaches the end of the plane,", "the event queue should be empty.", " ", "Order List:", "This algorithm produces an ordered list of intersection points, in order of", "when they are discovered by the sweep-line." " " "Efficiency:", "The efficiency of this algorithm is O((n + k)logn). This algorithm is output-sensitive", "as the running time is sensitive to the size of the output. This algorithm is also intersection-sensitive", "as the number of intersections contributes to the size of the output generated." ] sh_desc = [ "Shamos-Hoey Algorithm:", " ", "Summary:", "The Shamos-Hoey algorithm also incorporates the idea of an imaginary line.", "This line will sweep from left-to-right over the line segments. Once it discovers its first intersection,", "the algorithm will stop. Once again, this is done through vector mathematics, direction vectors and scalars.", " ", "Event Queue:", "This algorithm keeps an event queue. Adding a line-segment to the list when its leftmost endpoint is discovered", "during the sweep and also deleting a line-segment from the list when its rightmost endpoint is discovered during the sweep.", "As the algorithm stops at the first intersection that is discovered, the event queue will not be empty by the time the algorithm terminates.", " ", "Order List:", "This algorithm produces an ordered list of intersection points, in order of when they are discovered by the sweep-line.", " ", "Efficiency:", "The efficiency of this algorithm is O(nlogn) time to compute due to it terminating on the first intersection point that it discovers.", "As the algorithm terminates at the first intersection point, its efficiency is not sensitive to the number of intersections that it discovers.", ] effic_desc = [ "Efficiency:", " ", "Brute-Force Algorithm:", "O(n*n) is very computationally expensive. Out of all the algorithms, where we see a high number of line segments,the brute-force algorithm", "will always be the most inefficient.", " ", "Bentley-Ottmann Algorithm:", "O((n + k)logn) is very efficient in terms of taking into consideration the number of intersections. Where we see a high number of line", "segments but low number of intersections, the brute-force algorithm will play its part as an efficient algorithm.", " ", "Shamos-Hoey Algorithm:", "O(nlogn) is also very efficient which is all due to how the algorithm terminates at the first intersection", "point that it discovers. Because of this, the efficiency is not hindered by a large number of intersection points within the plane.", " ", "Summary:", "If we look at the map-overlay problem, we wish to discover every intersection point that exists within the plane. The likeliness that when two thematic", "map layers overlap, all of their line segments intersect is slim. Knowing this, the better suited algorithm would be the Bentley-Ottmann algorithm rather", "than the Brute-Force algorithm. We have a plane with many line segments whereby, all intersections in existence need to be identified and we know that", "not every pair of line segments intersect. Here, the Shamos-Hoey algorithm would not be suitable as we are interested in finding more than one intersection.", "However, where we concern ourself with robotic movement, a given motion trajectory between two ligaments such as the humanoids arms, we only need to look at", "whether this motion trajectory has any intersection. We are not interested in searching for every single intersection within the plane. For this, the Shamos-Hoey algorithm", "would be better suited. Furthermore, the efficiency O(nlogn) of the Shamos-Hoey algorithm compared to O((n+k)logn) is also another key reason the Shamos-Hoey would be a better suit.", "We would expect the movement of a humanoid to be flawless and not at any stage have to pause for a long-period of time to calculate its next movements. The Shamos-Hoey algorithm yielding", "a higher efficiency would mean that intersections can be calculated faster, which will in turn, contribute towards the flawless movement of the humanoid robot." ]
try: n = int(input("Enter number")) print(n*n) except: print("Non integer entered")
height = int(input()) for i in range(0,height+1): for j in range(0,i+1): if(j == i): print(i,end=" ") else: print("*",end=" ") print() # Sample Input :- 5 # Output :- # 0 # * 1 # * * 2 # * * * 3 # * * * * 4 # * * * * * 5
statement_one = False statement_two = True credits = 120 gpa = 1.8 if not credits >= 120: print('You do not have enough credits to graduate.') if not gpa >= 2.0: print('Your GPA is not high enough to graduate.') if not (credits >= 120) and not (gpa >= 2.0): print('You do not meet either requirement to graduate!')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Day 8: Dictionaries and Maps Source : https://www.hackerrank.com/challenges/30-dictionaries-and-maps/problem """ n = int(input()) book = dict([input().split() for _ in range(n)]) for _ in range(n): name = input() print("%s=%s" % (name, book[name]) if name in book else "Not found")
LOCALHOST_EQUIVALENTS = frozenset(( 'localhost', '127.0.0.1', '0.0.0.0', '0:0:0:0:0:0:0:0', '0:0:0:0:0:0:0:1', '::1', '::', ))
"""The Carian alphabet. Sources: - `<https://www.unicode.org/charts/PDF/U102A0.pdf>` - Adiego, Ignacio, J. (2007) The Carian Language """ __author__ = [ "Caio Geraldes <caio.geraldes@usp.br>"] VOWELS = [ "\U000102A0", # 𐊠 CARIAN LETTER A "\U000102A7", # 𐊧 CARIAN LETTER A2 "\U000102AB", # 𐊫 CARIAN LETTER O "\U000102B2", # 𐊲 CARIAN LETTER U "\U000102B9", # 𐊹 CARIAN LETTER I "\U000102BA", # 𐊺 CARIAN LETTER E "\U000102BF", # 𐊿 CARIAN LETTER UU "\U000102C5", # 𐋅 CARIAN LETTER II "\U000102C8", # 𐋈 CARIAN LETTER UUU2 "\U000102CF", # 𐋏 CARIAN LETTER E2 "\U000102D0", # 𐋐 CARIAN LETTER UUU3 ] CONSONANTS = [ "\U000102A1", # 𐊡 CARIAN LETTER P2 "\U000102A2", # 𐊢 CARIAN LETTER D "\U000102A3", # 𐊣 CARIAN LETTER L "\U000102A4", # 𐊤 CARIAN LETTER UUU "\U000102A5", # 𐊥 CARIAN LETTER R "\U000102A6", # 𐊦 CARIAN LETTER LD "\U000102A8", # 𐊨 CARIAN LETTER Q "\U000102A9", # 𐊩 CARIAN LETTER B "\U000102AA", # 𐊪 CARIAN LETTER M "\U000102AC", # 𐊬 CARIAN LETTER D2 "\U000102AD", # 𐊭 CARIAN LETTER T "\U000102AE", # 𐊮 CARIAN LETTER SH "\U000102AF", # 𐊯 CARIAN LETTER SH2 "\U000102B0", # 𐊰 CARIAN LETTER S "\U000102B1", # 𐊱 CARIAN LETTER C-18 "\U000102B3", # 𐊳 CARIAN LETTER NN "\U000102B4", # 𐊴 CARIAN LETTER X "\U000102B5", # 𐊵 CARIAN LETTER N "\U000102B6", # 𐊶 CARIAN LETTER TT2 "\U000102B7", # 𐊷 CARIAN LETTER P "\U000102B8", # 𐊸 CARIAN LETTER SS "\U000102BB", # 𐊻 CARIAN LETTER UUUU "\U000102BC", # 𐊼 CARIAN LETTER K "\U000102BD", # 𐊽 CARIAN LETTER K2 "\U000102BE", # 𐊾 CARIAN LETTER ND "\U000102C0", # 𐋀 CARIAN LETTER G "\U000102C1", # 𐋁 CARIAN LETTER G2 "\U000102C2", # 𐋂 CARIAN LETTER ST "\U000102C3", # 𐋃 CARIAN LETTER ST2 "\U000102C4", # 𐋄 CARIAN LETTER NG "\U000102C6", # 𐋆 CARIAN LETTER C-39 "\U000102C7", # 𐋇 CARIAN LETTER TT "\U000102C9", # 𐋉 CARIAN LETTER RR "\U000102CA", # 𐋊 CARIAN LETTER MB "\U000102CB", # 𐋋 CARIAN LETTER MB2 "\U000102CC", # 𐋌 CARIAN LETTER MB3 "\U000102CD", # 𐋍 CARIAN LETTER MB4 "\U000102CE", # 𐋎 CARIAN LETTER LD2 ] # The i and r used at Hyllarima are not represented as a glyph # of their own yet. HYLLARIMA = [ "\U000102A0", # 𐊠 a "\U000102A2", # 𐊢 d "\U000102A3", # 𐊣 l "\U000102A4", # 𐊤 y "\U000102A5", # 𐊥 r "\U000102CE", # 𐋎 λ "\U000102A8", # 𐊨 q "\U000102A9", # 𐊩 b "\U000102AA", # 𐊪 m "\U000102AB", # 𐊫 o "\U000102AD", # 𐊭 t "\U000102AE", # 𐊮 sh "\U000102B0", # 𐊰 s "\U000102B2", # 𐊲 u "\U000102B3", # 𐊳 ñ "\U000102B5", # 𐊵 n "\U000102B7", # 𐊷 p "\U000102B8", # 𐊸 ś "\U000102B9", # 𐊹 i "\U000102CF", # 𐋏 e "\U000102BD", # 𐊽 k "\U000102BE", # 𐊾 δ "\U000102C3", # 𐋃 z "\U000102C7", # 𐋇 τ ] # The q and r used at Euromos are not represented as a glyph of their own yet. EUROMOS = [ "\U000102A0", # 𐊠 a "\U000102A2", # 𐊢 d "\U000102A3", # 𐊣 l "\U000102A4", # 𐊤 y "\U000102A5", # 𐊥 r "\U000102CE", # 𐋎 λ "\U000102A8", # 𐊨 q "\U000102A9", # 𐊩 b "\U000102AA", # 𐊪 m "\U000102AB", # 𐊫 o "\U000102AD", # 𐊭 t "\U000102B0", # 𐊰 s "\U000102B2", # 𐊲 u "\U000102B4", # 𐊴 ḱ "\U000102B5", # 𐊵 n "\U000102B8", # 𐊸 ś "\U000102B9", # 𐊹 i "\U000102CF", # 𐋏 e "\U000102BD", # 𐊽 k "\U000102BC", # 𐊼 k2 "\U000102BE", # 𐊾 δ "\U000102C3", # 𐋃 z ] # The β, i, q and z used at Mylasa are not represented as a glyph # of their own yet. MYLASA = [ "\U000102A0", # 𐊠 a "\U000102A2", # 𐊢 d "\U000102A3", # 𐊣 l "\U000102D0", # 𐋐 y "\U000102A5", # 𐊥 r "\U000102A8", # 𐊨 q "\U000102A9", # 𐊩 b "\U000102AA", # 𐊪 m "\U000102AB", # 𐊫 o "\U000102AD", # 𐊭 t "\U000102AE", # 𐊮 sh "\U000102B0", # 𐊰 s "\U000102B2", # 𐊲 u "\U000102B4", # 𐊴 ḱ "\U000102B5", # 𐊵 n "\U000102B7", # 𐊷 p "\U000102B8", # 𐊸 ś "\U000102B9", # 𐊹 i "\U000102CF", # 𐋏 e "\U000102BD", # 𐊽 k "\U000102BE", # 𐊾 δ "\U000102C3", # 𐋃 z ] # The ḱ and β used at Stratonikeia are not represented as a glyph # of their own yet. STRATONIKEIA = [ "\U000102A0", # 𐊠 a "\U000102A2", # 𐊢 d "\U000102A3", # 𐊣 l "\U000102A4", # 𐊤 y "\U000102A5", # 𐊥 r "\U000102A6", # 𐊦 λ "\U000102A8", # 𐊨 q "\U000102AA", # 𐊪 m "\U000102AB", # 𐊫 o "\U000102AD", # 𐊭 t "\U000102AE", # 𐊮 sh "\U000102B0", # 𐊰 s "\U000102B1", # 𐊱 ? "\U000102B2", # 𐊲 u "\U000102B3", # 𐊳 ñ "\U000102B4", # 𐊴 ḱ "\U000102B5", # 𐊵 n "\U000102B7", # 𐊷 p "\U000102B8", # 𐊸 ś "\U000102B9", # 𐊹 i "\U000102BA", # 𐊺 e "\U000102BD", # 𐊽 k "\U000102BE", # 𐊾 δ "\U000102C3", # 𐋃 z ] # The a used at Sinuri-Kildara is not represented as a glyph of its own yet. SINURI_KILDARA = [ "\U000102A0", # 𐊠 a "\U000102A2", # 𐊢 d "\U000102A3", # 𐊣 l "\U000102D0", # 𐋐 y "\U000102A5", # 𐊥 r "\U000102A6", # 𐊦 λ "\U000102A8", # 𐊨 q "\U000102A9", # 𐊩 b "\U000102AA", # 𐊪 m "\U000102AB", # 𐊫 o "\U000102AD", # 𐊭 t "\U000102AE", # 𐊮 sh "\U000102B0", # 𐊰 s "\U000102B1", # 𐊱 ? "\U000102B2", # 𐊲 u "\U000102B3", # 𐊳 ñ "\U000102B4", # 𐊴 ḱ "\U000102B5", # 𐊵 n "\U000102B7", # 𐊷 p "\U000102B8", # 𐊸 ś "\U000102B9", # 𐊹 i "\U000102BA", # 𐊺 e "\U000102BC", # 𐊼 k "\U000102BE", # 𐊾 δ "\U000102C3", # 𐋃 z "\U000102C4", # 𐋄 ŋ? ] # Kaunos, C.series, Memphis
count = int(input()) for i in range(count): print("@"*(count*5)) for i in range(count*3): print("@"*(count)," "*(count*3),"@"*(count),sep="") for i in range(count): print("@"*(count*5))
des = ('Desafio-005 número antecessor e sucessor') print ('{}.'.format(des)) #Desafio-05 >>> Faça um programa que leia um numero inteiro e mostre na tela o seu antecessor e seu sucessor. n1 = int(input('Digite um número: ')) n2 = (1) s1 = (n1+n2) s2 = (n1-n2) print ('Você digitou o número {}, \nO número antecessor dele é {} \nE seu sucessor é {}.'.format(n1, s2, s1)) print ('The End')
# Altere o programa anterior permitindo ao usuario informar as populações e as taxas de crescimento iniciais. Valide a entrada # e permita repetir a operação def calculo_populacional(pais_A, pais_B, cresc_A, cresc_B): cont_anos = 0 if (pais_A < pais_B): validar = True if (pais_A >= pais_B) else False while (validar != True): pais_A = pais_A + ((pais_A * cresc_A) / 100) pais_B = pais_B + ((pais_B * cresc_B) / 100) cont_anos += 1 validar = True if (pais_A >= pais_B) else False return print(f'O pais A vai ultrapassar o Pais B em {cont_anos} anos.') else: validar = True if (pais_B >= pais_A) else False while (validar != True): pais_A = pais_A + ((pais_A * cresc_A) / 100) pais_B = pais_B + ((pais_B * cresc_B) / 100) cont_anos += 1 validar = True if (pais_B >= pais_A) else False return print(f'O pais B vai ultrapassar o Pais A em {cont_anos} anos.') def validar_entrada(validar1, validar2): validar = True if ((validar1 != 0) and (validar2 != 0)) else False if validar: return True else: return False continuar = 1 while (continuar != 2): paisA = int(input('Informe quantidade de HABITANTES da população do Pais A: ')) paisB = int(input('Informe quantidade de HABITANTES da população do Pais B: ')) validar_pais = validar_entrada(paisA, paisB) while validar_pais != True: paisA = int(input('Informe quantidade de HABITANTES da população do Pais A: ')) paisB = int(input('Informe quantidade de HABITANTES da população do Pais B: ')) validar_pais = validar_entrada(paisA, paisB) print() taxaA = float(input('Informe a TAXA de crescimento do Pais A: ')) taxaB = float(input('Informe a TAXA de crescimento do Pais B: ')) validar_taxa = validar_entrada(taxaA, taxaB) while validar_taxa != True: taxaA = float(input('Informe a TAXA de crescimento do Pais A: ')) taxaB = float(input('Informe a TAXA de crescimento do Pais B: ')) validar_taxa = validar_entrada(taxaA, taxaB) print() calculo_populacional(paisA, paisB, taxaA, taxaB) print() continuar = int(input('Escolha a opção do Menu\n' '1 - Deseja continuar ?\n' '2 - Deseja Sair?: \n' ''))
a = input("Enter some list of numbers =") for i in a: print(i) print(type(a))