content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def load_framework_dependencies(): http_archive( name = "TensorFlowLiteC", url = "https://dl.google.com/dl/cpdc/3895e5bf508673ae/TensorFlowLiteC-2.6.0.tar.gz", sha256 = "a28ce764da496830c0a145b46e5403fb486b5b6231c72337aaa8eaf3d762cc8d", build_file = "@//tests/ios/unit-test/test-imports-app:BUILD.TensorFlowLiteC", strip_prefix = "TensorFlowLiteC-2.6.0", ) http_archive( name = "GoogleMobileAdsSDK", url = "https://dl.google.com/dl/cpdc/e0dda986a9f84d14/Google-Mobile-Ads-SDK-8.10.0.tar.gz", sha256 = "0726df5d92165912c9e60a79504a159ad9b7231dda851abede8f8792b266dba5", build_file = "@//tests/ios/unit-test/test-imports-app:BUILD.GoogleMobileAds", )
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive') def load_framework_dependencies(): http_archive(name='TensorFlowLiteC', url='https://dl.google.com/dl/cpdc/3895e5bf508673ae/TensorFlowLiteC-2.6.0.tar.gz', sha256='a28ce764da496830c0a145b46e5403fb486b5b6231c72337aaa8eaf3d762cc8d', build_file='@//tests/ios/unit-test/test-imports-app:BUILD.TensorFlowLiteC', strip_prefix='TensorFlowLiteC-2.6.0') http_archive(name='GoogleMobileAdsSDK', url='https://dl.google.com/dl/cpdc/e0dda986a9f84d14/Google-Mobile-Ads-SDK-8.10.0.tar.gz', sha256='0726df5d92165912c9e60a79504a159ad9b7231dda851abede8f8792b266dba5', build_file='@//tests/ios/unit-test/test-imports-app:BUILD.GoogleMobileAds')
def initials(name): names = name.title().split() length = len(names) - 1 return '.'.join(a[0] if length != i else a for i, a in enumerate(names))
def initials(name): names = name.title().split() length = len(names) - 1 return '.'.join((a[0] if length != i else a for (i, a) in enumerate(names)))
class Infinite_memory(list): def __init__(self,*args): list.__init__(self,*args) def __getitem__(self, index): if index>=len(self): for _ in range((index-len(self))+1): self.append(0) return super().__getitem__(index) def __setitem__(self, key, value): if key>=len(self): for _ in range((key-len(self))+1): self.append(0) return super().__setitem__(key, value) def run_intcode(memory,input_stream=None,output_l=None): global relative_base relative_base=0 def suma(args): memory[args[2]]=args[0]+args[1] def mult(args): memory[args[2]]=args[0]*args[1] def inpt(args): if input_stream: memory[args[0]]=input_stream.pop(0) else: memory[args[0]]=int(input("escribe un numero, puto (1 para parte 1 2 para parte 2):")) def output(args): if output_l==None: print(args[0]) else: output_l.append(args[0]) def j_if_t(args): if args[0]!=0: return args[1] def j_if_f(args): if args[0]==0: return args[1] def less_than(args): memory[args[2]]=int(args[0]<args[1]) def equals(args): memory[args[2]]=int(args[0]==args[1]) def inc_rel_base(args): global relative_base relative_base+=args[0] func_dict={1:suma,2:mult,3:inpt,4:output,5:j_if_t,6:j_if_f,7:less_than,8:equals,9:inc_rel_base} writes_to_mem=[1,2,3,7,8]#instructions that write to memory inc_dict={1:4,2:4,3:2,4:2,5:3,6:3,7:4,8:4,9:2} i=0 while True: opcode=str(memory[i]) param_bits=list(opcode[:-2]) opcode=int(opcode[-2:]) if opcode==99: break params=[] for p in range(1,inc_dict[opcode]): bit=0 if len(param_bits)>0: bit=int(param_bits.pop()) if bit==2: if (p==inc_dict[opcode]-1 and opcode in writes_to_mem): #write relative params.append(relative_base+memory[i+p]) else: #read relative params.append(memory[relative_base+memory[i+p]]) elif (p==inc_dict[opcode]-1 and opcode in writes_to_mem) or (bit==1): #read immediate or write positional params.append(memory[i+p]) else: #default read positional params.append(memory[memory[i+p]]) instruction=func_dict[opcode](params) if instruction: i=instruction else: i+=inc_dict[opcode] with open("input1.txt","r") as f: code=Infinite_memory(map(int,f.readline().split(","))) out=[] run_intcode(code,output_l=out) print(len([out[i] for i in range(2,len(out),3) if out[i]==2]))
class Infinite_Memory(list): def __init__(self, *args): list.__init__(self, *args) def __getitem__(self, index): if index >= len(self): for _ in range(index - len(self) + 1): self.append(0) return super().__getitem__(index) def __setitem__(self, key, value): if key >= len(self): for _ in range(key - len(self) + 1): self.append(0) return super().__setitem__(key, value) def run_intcode(memory, input_stream=None, output_l=None): global relative_base relative_base = 0 def suma(args): memory[args[2]] = args[0] + args[1] def mult(args): memory[args[2]] = args[0] * args[1] def inpt(args): if input_stream: memory[args[0]] = input_stream.pop(0) else: memory[args[0]] = int(input('escribe un numero, puto (1 para parte 1 2 para parte 2):')) def output(args): if output_l == None: print(args[0]) else: output_l.append(args[0]) def j_if_t(args): if args[0] != 0: return args[1] def j_if_f(args): if args[0] == 0: return args[1] def less_than(args): memory[args[2]] = int(args[0] < args[1]) def equals(args): memory[args[2]] = int(args[0] == args[1]) def inc_rel_base(args): global relative_base relative_base += args[0] func_dict = {1: suma, 2: mult, 3: inpt, 4: output, 5: j_if_t, 6: j_if_f, 7: less_than, 8: equals, 9: inc_rel_base} writes_to_mem = [1, 2, 3, 7, 8] inc_dict = {1: 4, 2: 4, 3: 2, 4: 2, 5: 3, 6: 3, 7: 4, 8: 4, 9: 2} i = 0 while True: opcode = str(memory[i]) param_bits = list(opcode[:-2]) opcode = int(opcode[-2:]) if opcode == 99: break params = [] for p in range(1, inc_dict[opcode]): bit = 0 if len(param_bits) > 0: bit = int(param_bits.pop()) if bit == 2: if p == inc_dict[opcode] - 1 and opcode in writes_to_mem: params.append(relative_base + memory[i + p]) else: params.append(memory[relative_base + memory[i + p]]) elif p == inc_dict[opcode] - 1 and opcode in writes_to_mem or bit == 1: params.append(memory[i + p]) else: params.append(memory[memory[i + p]]) instruction = func_dict[opcode](params) if instruction: i = instruction else: i += inc_dict[opcode] with open('input1.txt', 'r') as f: code = infinite_memory(map(int, f.readline().split(','))) out = [] run_intcode(code, output_l=out) print(len([out[i] for i in range(2, len(out), 3) if out[i] == 2]))
# Python function to compute GCD of two numbers using recursion def gcd(a,b): if(b==0): # Base case return a else: return gcd(b,a%b) # Recursive call # Tester code a=int(input("Enter first number:")) b=int(input("Enter second number:")) GCD=gcd(a,b) print("GCD is: ") print(GCD)
def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) a = int(input('Enter first number:')) b = int(input('Enter second number:')) gcd = gcd(a, b) print('GCD is: ') print(GCD)
def dpMakeChange(coinValueList,change,minCoins,coinsUsed): for cents in range(change+1): coinCount = cents newCoin = 1 for j in [c for c in coinValueList if c <= cents]: if minCoins[cents-j] + 1 < coinCount: coinCount = minCoins[cents-j]+1 newCoin = j minCoins[cents] = coinCount coinsUsed[cents] = newCoin return minCoins[change] def printCoins(coinsUsed,change): coin = change while coin > 0: thisCoin = coinsUsed[coin] print(thisCoin) coin = coin - thisCoin def main(): amnt = 63 clist = [1,5,10,21,25] coinsUsed = [0]*(amnt+1) coinCount = [0]*(amnt+1) print("Making change for",amnt,"requires") print(dpMakeChange(clist,amnt,coinCount,coinsUsed),"coins") print("They are:") printCoins(coinsUsed,amnt) print("The used list is as follows:") print(coinsUsed) main()
def dp_make_change(coinValueList, change, minCoins, coinsUsed): for cents in range(change + 1): coin_count = cents new_coin = 1 for j in [c for c in coinValueList if c <= cents]: if minCoins[cents - j] + 1 < coinCount: coin_count = minCoins[cents - j] + 1 new_coin = j minCoins[cents] = coinCount coinsUsed[cents] = newCoin return minCoins[change] def print_coins(coinsUsed, change): coin = change while coin > 0: this_coin = coinsUsed[coin] print(thisCoin) coin = coin - thisCoin def main(): amnt = 63 clist = [1, 5, 10, 21, 25] coins_used = [0] * (amnt + 1) coin_count = [0] * (amnt + 1) print('Making change for', amnt, 'requires') print(dp_make_change(clist, amnt, coinCount, coinsUsed), 'coins') print('They are:') print_coins(coinsUsed, amnt) print('The used list is as follows:') print(coinsUsed) main()
DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'db.sqlite3', # Or path to database file if using sqlite3. } } # Make this unique, and don't share it with anybody. SECRET_KEY = '^n4-$%m-w((n4=7g4j!(x3%=l68t=__j!24-3)0%bjd8i2e5th' MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'hostproof_auth.urls' INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'hostproof_auth', ) AUTH_USER_MODEL = 'hostproof_auth.User' AUTHENTICATION_BACKENDS = ( 'hostproof_auth.auth.ModelBackend', )
debug = True databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db.sqlite3'}} secret_key = '^n4-$%m-w((n4=7g4j!(x3%=l68t=__j!24-3)0%bjd8i2e5th' middleware_classes = ('django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware') root_urlconf = 'hostproof_auth.urls' installed_apps = ('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'hostproof_auth') auth_user_model = 'hostproof_auth.User' authentication_backends = ('hostproof_auth.auth.ModelBackend',)
x,y = input().split() x,y = [float(x),float(y)] if x == y == 0: print("Origem") elif x == 0: print("Eixo Y") elif y == 0: print("Eixo X") elif x > 0 and y > 0: print("Q1") elif x < 0 and y > 0: print("Q2") elif x < 0 and y < 0: print("Q3") else: print("Q4")
(x, y) = input().split() (x, y) = [float(x), float(y)] if x == y == 0: print('Origem') elif x == 0: print('Eixo Y') elif y == 0: print('Eixo X') elif x > 0 and y > 0: print('Q1') elif x < 0 and y > 0: print('Q2') elif x < 0 and y < 0: print('Q3') else: print('Q4')
""" Good morning! Here's your coding interview problem for today. This problem was asked by Apple. Implement a queue using two stacks. Recall that a queue is a FIFO (first-in, first-out) data structure with the following methods: enqueue, which inserts an element into the queue, and dequeue, which removes it. https://www.youtube.com/watch?v=AN0axYeLue0 https://www.geeksforgeeks.org/queue-using-stacks/ https://coderbyte.com/algorithm/implement-queue-using-two-stacks """ # implement stacks using plain lists with push and pop functions stack1 = [] stack2 = [] # implement enqueue method by using only stacks # and the append and pop functions def enqueue(element): stack1.append(element) # implement dequeue method by pushing all elements # from stack 1 into stack 2, which reverses the order # and then popping from stack 2 def dequeue(): if len(stack2) == 0: if len(stack1) == 0: return 'Cannot dequeue because queue is empty' while len(stack1) > 0: stack2.append(stack1.pop()) return stack2.pop() enqueue('a') enqueue('b') enqueue('c') print(dequeue()) print(dequeue())
""" Good morning! Here's your coding interview problem for today. This problem was asked by Apple. Implement a queue using two stacks. Recall that a queue is a FIFO (first-in, first-out) data structure with the following methods: enqueue, which inserts an element into the queue, and dequeue, which removes it. https://www.youtube.com/watch?v=AN0axYeLue0 https://www.geeksforgeeks.org/queue-using-stacks/ https://coderbyte.com/algorithm/implement-queue-using-two-stacks """ stack1 = [] stack2 = [] def enqueue(element): stack1.append(element) def dequeue(): if len(stack2) == 0: if len(stack1) == 0: return 'Cannot dequeue because queue is empty' while len(stack1) > 0: stack2.append(stack1.pop()) return stack2.pop() enqueue('a') enqueue('b') enqueue('c') print(dequeue()) print(dequeue())
class Solution: def countOrders(self, n: int) -> int: kMod = int(1e9) + 7 ans = 1 for i in range(1, n + 1): ans = ans * i * (i * 2 - 1) % kMod return ans
class Solution: def count_orders(self, n: int) -> int: k_mod = int(1000000000.0) + 7 ans = 1 for i in range(1, n + 1): ans = ans * i * (i * 2 - 1) % kMod return ans
######################################### # InMoovArm.py # more info @: http://myrobotlab.org/service/InMoovArm ######################################### # this script is provided as a basic scripting guide # most parts can be run by uncommenting them # InMoov now can be started in modular pieces through the .config files from full script # although this script is very short you can still # do voice control of a InMoov head # It uses WebkitSpeechRecognition, so you need to use Chrome as your default browser for this script t #leftPort = "COM20" #modify port according to your board rightPort = "COM7" #modify port according to your board # start optional virtual arduino service, used for internal test and virtual inmoov # virtual=True if ('virtual' in globals() and virtual): virtualArduinoRight = Runtime.start("virtualArduinoRight", "VirtualArduino") virtualArduinoRight.connect(rightPort) # end used for internal test #to tweak the default voice Voice="cmu-bdl-hsmm" #Male US voice #Voice="cmu-slt-hsmm" #Default female for MarySpeech mouth = Runtime.createAndStart("i01.mouth", "MarySpeech") #mouth.installComponentsAcceptLicense(Voice) mouth.setVoice(Voice) ############## # starting InMoov service i01 = Runtime.create("i01", "InMoov") #Force Arduino to connect (fix Todo) #left = Runtime.createAndStart("i01.left", "Arduino") #left.connect(leftPort) right = Runtime.createAndStart("i01.right", "Arduino") right.connect(rightPort) ############## # starting parts i01.startEar() # Start the webgui service without starting the browser webgui = Runtime.create("WebGui","WebGui") webgui.autoStartBrowser(False) webgui.startService() # Then start the browsers and show the WebkitSpeechRecognition service named i01.ear webgui.startBrowser("http://localhost:8888/#/service/i01.ear") # As an alternative you can use the line below to show all services in the browser. In that case you should comment out all lines above that starts with webgui. # webgui = Runtime.createAndStart("webgui","WebGui") i01.startMouth() ############## #leftArm = Runtime.create("i01.leftArm","InMoovArm") #tweak defaults LeftArm #Velocity #leftArm.bicep.setVelocity(-1) #leftArm.rotate.setVelocity(-1) #leftArm.shoulder.setVelocity(-1) #leftArm.omoplate.setVelocity(-1) #Mapping #leftArm.bicep.map(0,90,45,96) #leftArm.rotate.map(40,180,60,142) #leftArm.shoulder.map(0,180,44,150) #leftArm.omoplate.map(10,80,42,80) #Rest position #leftArm.bicep.setRest(5) #leftArm.rotate.setRest(90) #leftArm.shoulder.setRest(30) #leftArm.omoplate.setRest(10) ################# rightArm = Runtime.create("i01.rightArm","InMoovArm") # tweak default RightArm #Velocity rightArm.bicep.setVelocity(-1) rightArm.rotate.setVelocity(-1) rightArm.shoulder.setVelocity(-1) rightArm.omoplate.setVelocity(-1) #Mapping rightArm.bicep.map(0,90,45,96) rightArm.rotate.map(40,180,75,130) rightArm.shoulder.map(0,180,44,150) rightArm.omoplate.map(10,80,43,80) #Rest position rightArm.bicep.setRest(5) rightArm.rotate.setRest(90) rightArm.shoulder.setRest(30) rightArm.omoplate.setRest(10) ################# i01 = Runtime.start("i01","InMoov") ################# #i01.startLeftArm(leftPort) i01.startRightArm(rightPort) ################# #i01.leftArm.setAutoDisable(True) i01.rightArm.setAutoDisable(True) ################# # verbal commands ear = i01.ear ear.addCommand("attach everything", "i01", "enable") ear.addCommand("disconnect everything", "i01", "disable") ear.addCommand("attach left arm", "i01.leftArm", "enable") ear.addCommand("disconnect left arm", "i01.leftArm", "disable") ear.addCommand("attach right arm", "i01.rightArm", "enable") ear.addCommand("disconnect right arm", "i01.rightArm", "disable") ear.addCommand("rest", "python", "rest") ear.addCommand("full speed", "python", "fullspeed") ear.addCommand("arms front", "python", "armsFront") ear.addCommand("da vinci", "python", "daVinci") ear.addCommand("capture gesture", ear.getName(), "captureGesture") ear.addCommand("manual", ear.getName(), "lockOutAllGrammarExcept", "voice control") ear.addCommand("voice control", ear.getName(), "clearLock") # Confirmations and Negations are not supported yet in WebkitSpeechRecognition # So commands will execute immediatley ear.addComfirmations("yes","correct","ya","yeah", "yes please", "yes of course") ear.addNegations("no","wrong","nope","nah","no thank you", "no thanks") ############ ear.startListening() def rest(): #i01.setArmVelocity("left", -1, -1, -1, -1) i01.setArmVelocity("right", -1, -1, -1, -1) #i01.moveArm("left",5,90,30,10) i01.moveArm("right",5,90,30,10) i01.mouth.speak("Ok, taking rest") def fullspeed(): #i01.setArmVelocity("left", -1, -1, -1, -1) i01.setArmVelocity("right", -1, -1, -1, -1) i01.mouth.speak("All my servos are set to full speed") def armsFront(): #i01.moveArm("left",13,115,100,20) i01.moveArm("right",13,115,100,20) i01.mouth.speak("Moving my arms in front of me") def daVinci(): i01.startedGesture() #i01.setArmSpeed("left", 0.80, 0.80, 0.80, 0.80) i01.setArmVelocity("right", 40, 40, 40, 40) #i01.moveArm("left",0,118,29,74) i01.moveArm("right",0,118,29,74) i01.mouth.speak("This is the pose of Leonardo Da Vinci") sleep(10) i01.finishedGesture() #i01.setArmSpeed("left", 0.70, 0.70, 0.70, 0.70) i01.setArmSpeed("right", 30, 30, 30, 30) #i01.moveArm("left",5,90,30,10) i01.moveArm("right",5,90,30,10)
right_port = 'COM7' if 'virtual' in globals() and virtual: virtual_arduino_right = Runtime.start('virtualArduinoRight', 'VirtualArduino') virtualArduinoRight.connect(rightPort) voice = 'cmu-bdl-hsmm' mouth = Runtime.createAndStart('i01.mouth', 'MarySpeech') mouth.setVoice(Voice) i01 = Runtime.create('i01', 'InMoov') right = Runtime.createAndStart('i01.right', 'Arduino') right.connect(rightPort) i01.startEar() webgui = Runtime.create('WebGui', 'WebGui') webgui.autoStartBrowser(False) webgui.startService() webgui.startBrowser('http://localhost:8888/#/service/i01.ear') i01.startMouth() right_arm = Runtime.create('i01.rightArm', 'InMoovArm') rightArm.bicep.setVelocity(-1) rightArm.rotate.setVelocity(-1) rightArm.shoulder.setVelocity(-1) rightArm.omoplate.setVelocity(-1) rightArm.bicep.map(0, 90, 45, 96) rightArm.rotate.map(40, 180, 75, 130) rightArm.shoulder.map(0, 180, 44, 150) rightArm.omoplate.map(10, 80, 43, 80) rightArm.bicep.setRest(5) rightArm.rotate.setRest(90) rightArm.shoulder.setRest(30) rightArm.omoplate.setRest(10) i01 = Runtime.start('i01', 'InMoov') i01.startRightArm(rightPort) i01.rightArm.setAutoDisable(True) ear = i01.ear ear.addCommand('attach everything', 'i01', 'enable') ear.addCommand('disconnect everything', 'i01', 'disable') ear.addCommand('attach left arm', 'i01.leftArm', 'enable') ear.addCommand('disconnect left arm', 'i01.leftArm', 'disable') ear.addCommand('attach right arm', 'i01.rightArm', 'enable') ear.addCommand('disconnect right arm', 'i01.rightArm', 'disable') ear.addCommand('rest', 'python', 'rest') ear.addCommand('full speed', 'python', 'fullspeed') ear.addCommand('arms front', 'python', 'armsFront') ear.addCommand('da vinci', 'python', 'daVinci') ear.addCommand('capture gesture', ear.getName(), 'captureGesture') ear.addCommand('manual', ear.getName(), 'lockOutAllGrammarExcept', 'voice control') ear.addCommand('voice control', ear.getName(), 'clearLock') ear.addComfirmations('yes', 'correct', 'ya', 'yeah', 'yes please', 'yes of course') ear.addNegations('no', 'wrong', 'nope', 'nah', 'no thank you', 'no thanks') ear.startListening() def rest(): i01.setArmVelocity('right', -1, -1, -1, -1) i01.moveArm('right', 5, 90, 30, 10) i01.mouth.speak('Ok, taking rest') def fullspeed(): i01.setArmVelocity('right', -1, -1, -1, -1) i01.mouth.speak('All my servos are set to full speed') def arms_front(): i01.moveArm('right', 13, 115, 100, 20) i01.mouth.speak('Moving my arms in front of me') def da_vinci(): i01.startedGesture() i01.setArmVelocity('right', 40, 40, 40, 40) i01.moveArm('right', 0, 118, 29, 74) i01.mouth.speak('This is the pose of Leonardo Da Vinci') sleep(10) i01.finishedGesture() i01.setArmSpeed('right', 30, 30, 30, 30) i01.moveArm('right', 5, 90, 30, 10)
MODE_PLANNING = "Planning" MODE_NLP = "NLP" ROWS = 8 # rows in maze COLS = 8 # columns in maze GRID_DX = 20.0#20.0 # x-dimension of the grid world GRID_DY = 10.0#20.0 # y-dimension of the grid world GRID_DZ = 3.0 * .75 * .5# z-dimension of the grid world MAX_STEPS = ROWS * COLS * 2 * 90# max number of steps - no need to visit each cell more then twice! STEP_DELAY = 3.0 # number of seconds to wait between the sense-act-step repeats NUDGE_X = -5.0 # shift the island in +x by ... NUDGE_Y = -5.0 # shift the island in +y by ... WALL_TEMPLATE = "data/shapes/wall/BrickWall.xml" HISTORY_LENGTH = 5 # number of state-action pairs used to determine if the agent is stuck OBSTACLE_MASK = 1 #0b0001 AGENT_MASK = 2 #0b0010
mode_planning = 'Planning' mode_nlp = 'NLP' rows = 8 cols = 8 grid_dx = 20.0 grid_dy = 10.0 grid_dz = 3.0 * 0.75 * 0.5 max_steps = ROWS * COLS * 2 * 90 step_delay = 3.0 nudge_x = -5.0 nudge_y = -5.0 wall_template = 'data/shapes/wall/BrickWall.xml' history_length = 5 obstacle_mask = 1 agent_mask = 2
""" """ class Order: pass
""" """ class Order: pass
# Copyright (C) 2016 Goban authors # # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. class ColoredStone: def __init__(self, color): if color < 0: raise Exception("invalid stone color") self.__color = color def get_color(self): return self.__color def set_color(self, color): if color < 0: raise Exception("invalid stone color") self.__color = color
class Coloredstone: def __init__(self, color): if color < 0: raise exception('invalid stone color') self.__color = color def get_color(self): return self.__color def set_color(self, color): if color < 0: raise exception('invalid stone color') self.__color = color
# MULTIPLY STRINGS LEETCODE SOLUTION: # creating a class. class Solution(object): # creating a function to solve the problem. def multiply(self, num1, num2): # converting the given strings to integers. num1 = int(num1) num2 = int(num2) # code to find the product of the integers. product = num1 * num2 # returning the product as a string. return str(product)
class Solution(object): def multiply(self, num1, num2): num1 = int(num1) num2 = int(num2) product = num1 * num2 return str(product)
def fibonacci(N): """Return all fibonacci numbers up to N. """ yield 0 if N == 0: return a = 0 b = 1 while b <= N: yield b a, b = b, a + b print(list(fibonacci(0))) # [0] print(list(fibonacci(1))) # [0, 1, 1] print(list(fibonacci(50))) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
def fibonacci(N): """Return all fibonacci numbers up to N. """ yield 0 if N == 0: return a = 0 b = 1 while b <= N: yield b (a, b) = (b, a + b) print(list(fibonacci(0))) print(list(fibonacci(1))) print(list(fibonacci(50)))
def stream_audio(p, chunk, job): wf = wave.open(job, 'rb') stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True) data = wf.readframes(chunk) while data != b'': print(calculate_position_percent(wf.tell(), wf.getnframes())) stream.write(data) data = wf.readframes(chunk) # Check queue and load next element # stop stream (6) stream.stop_stream() stream.close() wf.close() return True def check_audio_device(p): p.get_default_output_device_info() device_count = p.get_device_count() for i in range(0, device_count): yield p.get_device_info_by_index(i)["name"],p.get_device_info_by_index(i)["index"]
def stream_audio(p, chunk, job): wf = wave.open(job, 'rb') stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), channels=wf.getnchannels(), rate=wf.getframerate(), output=True) data = wf.readframes(chunk) while data != b'': print(calculate_position_percent(wf.tell(), wf.getnframes())) stream.write(data) data = wf.readframes(chunk) stream.stop_stream() stream.close() wf.close() return True def check_audio_device(p): p.get_default_output_device_info() device_count = p.get_device_count() for i in range(0, device_count): yield (p.get_device_info_by_index(i)['name'], p.get_device_info_by_index(i)['index'])
# i = 1 # # while i <= 5: # print(i) # i = i + 1 # # print("Done") secret_number = 9 guess_count = 0 guess_limit = 3 while guess_count < guess_limit: guess = int(input('Guess: ')) guess_count += 1 if guess == secret_number: print('You won!') break else: print("Sorry, you failed to guess the number")
secret_number = 9 guess_count = 0 guess_limit = 3 while guess_count < guess_limit: guess = int(input('Guess: ')) guess_count += 1 if guess == secret_number: print('You won!') break else: print('Sorry, you failed to guess the number')
# Tic-Tac-Toe CROSS = "X" CIRCLE = "O" def make_grid(): return list(range(1, 10)) def print_start(): print("Welcome to tic-tac-toe!!!!") def print_end(winner): print(winner, "was the winner!!!") def three_horizontal(grid, player): for i in range(0,9,3): if grid[i] == player and grid[i + 1] == player and grid[i + 2] == player: return True return False def three_vertical(grid, player): for i in range(3): if grid[i] == player and grid[i + 3] == player and grid[i + 6] == player: return True return False def three_diagonal(grid, player): first_diagonal = grid[0] == player and grid[4] == player and grid[8] == player second_diagonal = grid[2] == player and grid[4] == player and grid[6] == player return first_diagonal or second_diagonal def is_win(grid, player): return (three_vertical(grid, player) or three_horizontal(grid, player) or three_diagonal(grid, player)) def is_tie(grid): for i in grid: if i is not CROSS and i is not CIRCLE: return False return True def draw_grid(grid): for i in range(0,9,3): print(str(grid[i]) + "|" + str(grid[i + 1]) + "|" + str(grid[i + 2])) if i < 6: print("-----") print("") def is_empty(grid, location): if str(grid[location]) not in CROSS + CIRCLE: return True return False def input_step(player, board): location = int(input("Where do you want to put your token? ")) if location < 1 or location > 9 or not is_empty(grid, location - 1): print("Your input was not valid!") input_step(player, board) else: set_board_value(board, player, location - 1) def set_board_value(board, value, index): board[index] = value def change_players(player): if player == CROSS: return CIRCLE else: return CROSS grid = make_grid() current_player = CROSS print_start() while not (is_win(grid, change_players(current_player)) or is_tie(grid)): draw_grid(grid) input_step(current_player, grid) current_player = change_players(current_player) draw_grid(grid) print_end(change_players(current_player))
cross = 'X' circle = 'O' def make_grid(): return list(range(1, 10)) def print_start(): print('Welcome to tic-tac-toe!!!!') def print_end(winner): print(winner, 'was the winner!!!') def three_horizontal(grid, player): for i in range(0, 9, 3): if grid[i] == player and grid[i + 1] == player and (grid[i + 2] == player): return True return False def three_vertical(grid, player): for i in range(3): if grid[i] == player and grid[i + 3] == player and (grid[i + 6] == player): return True return False def three_diagonal(grid, player): first_diagonal = grid[0] == player and grid[4] == player and (grid[8] == player) second_diagonal = grid[2] == player and grid[4] == player and (grid[6] == player) return first_diagonal or second_diagonal def is_win(grid, player): return three_vertical(grid, player) or three_horizontal(grid, player) or three_diagonal(grid, player) def is_tie(grid): for i in grid: if i is not CROSS and i is not CIRCLE: return False return True def draw_grid(grid): for i in range(0, 9, 3): print(str(grid[i]) + '|' + str(grid[i + 1]) + '|' + str(grid[i + 2])) if i < 6: print('-----') print('') def is_empty(grid, location): if str(grid[location]) not in CROSS + CIRCLE: return True return False def input_step(player, board): location = int(input('Where do you want to put your token? ')) if location < 1 or location > 9 or (not is_empty(grid, location - 1)): print('Your input was not valid!') input_step(player, board) else: set_board_value(board, player, location - 1) def set_board_value(board, value, index): board[index] = value def change_players(player): if player == CROSS: return CIRCLE else: return CROSS grid = make_grid() current_player = CROSS print_start() while not (is_win(grid, change_players(current_player)) or is_tie(grid)): draw_grid(grid) input_step(current_player, grid) current_player = change_players(current_player) draw_grid(grid) print_end(change_players(current_player))
# https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/ # Given a string s and a string array dictionary, return the longest string in the # dictionary that can be formed by deleting some of the given string characters. # If there is more than one possible result, return the longest word with the # smallest lexicographical order. If there is no possible result, return the empty # string. ################################################################################ # sort dict and check if key can be substr class Solution: def findLongestWord(self, s: str, dictionary: List[str]) -> str: dictionary.sort(key=lambda x: (-len(x), x)) for key in dictionary: # if key is a substr of s if self.is_substr(key, s): return key return '' def is_substr(self, substr, s): i = j = 0 while i < len(substr) and j < len(s): if substr[i] == s[j]: # move i only when there is a match i += 1 j += 1 return i == len(substr)
class Solution: def find_longest_word(self, s: str, dictionary: List[str]) -> str: dictionary.sort(key=lambda x: (-len(x), x)) for key in dictionary: if self.is_substr(key, s): return key return '' def is_substr(self, substr, s): i = j = 0 while i < len(substr) and j < len(s): if substr[i] == s[j]: i += 1 j += 1 return i == len(substr)
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. class Failure(Exception): """StoryTest Exception raised when an undesired but designed-for problem.""" class StoryTest(object): """A class for creating story tests. The overall test run control flow follows this order: test.WillRunStory state.WillRunStory state.RunStory test.Measure state.DidRunStory test.DidRunStory """ def WillRunStory(self, platform): """Override to do any action before running the story. This is run before state.WillRunStory. Args: platform: The platform that the story will run on. """ raise NotImplementedError() def Measure(self, platform, results): """Override to take the measurement. This is run only if state.RunStory is successful. Args: platform: The platform that the story will run on. results: The results of running the story. """ raise NotImplementedError() def DidRunStory(self, platform, results): """Override to do any action after running the story, e.g., clean up. This is run after state.DidRunStory. And this is always called even if the test run failed. The |results| object can be used to stored debugging info related to run. Args: platform: The platform that the story will run on. results: The results of running the story. """ raise NotImplementedError()
class Failure(Exception): """StoryTest Exception raised when an undesired but designed-for problem.""" class Storytest(object): """A class for creating story tests. The overall test run control flow follows this order: test.WillRunStory state.WillRunStory state.RunStory test.Measure state.DidRunStory test.DidRunStory """ def will_run_story(self, platform): """Override to do any action before running the story. This is run before state.WillRunStory. Args: platform: The platform that the story will run on. """ raise not_implemented_error() def measure(self, platform, results): """Override to take the measurement. This is run only if state.RunStory is successful. Args: platform: The platform that the story will run on. results: The results of running the story. """ raise not_implemented_error() def did_run_story(self, platform, results): """Override to do any action after running the story, e.g., clean up. This is run after state.DidRunStory. And this is always called even if the test run failed. The |results| object can be used to stored debugging info related to run. Args: platform: The platform that the story will run on. results: The results of running the story. """ raise not_implemented_error()
def process_bike_count_data(df): """ Process the provided dataframe: parse datetimes and rename columns. """ df.index = pd.to_datetime(df['dag'] + ' ' + df['tijdstip'], format="%d.%m.%y %H:%M:%S") df = df.drop(['dag', 'tijdstip'], axis=1) df = df.rename(columns={'noord': 'north', 'zuid':'south', 'actief': 'active'}) return df
def process_bike_count_data(df): """ Process the provided dataframe: parse datetimes and rename columns. """ df.index = pd.to_datetime(df['dag'] + ' ' + df['tijdstip'], format='%d.%m.%y %H:%M:%S') df = df.drop(['dag', 'tijdstip'], axis=1) df = df.rename(columns={'noord': 'north', 'zuid': 'south', 'actief': 'active'}) return df
def print_function(args, fun): for x in args: print('f(', x,')=', fun(x), sep='') def poly(x): return 2 * x**2 - 4 * x + 2 print_function([x for x in range(-2, 3)], poly) # [-2, -1, 0, 1, 2]
def print_function(args, fun): for x in args: print('f(', x, ')=', fun(x), sep='') def poly(x): return 2 * x ** 2 - 4 * x + 2 print_function([x for x in range(-2, 3)], poly)
def staircase(size: int = 0) -> str: """Generates a staircase of '#', ascending to the right Args: size: Width and height of staircase. Returns: A string composed of '#' and ' ', separated by '\n'. When printed to console, renders the following (given 'size' of 5). # ## ### #### ##### """ result = [] for num in range(1, size + 1): result.append(' ' * (size - num) + '#' * num) return '\n'.join(result)
def staircase(size: int=0) -> str: """Generates a staircase of '#', ascending to the right Args: size: Width and height of staircase. Returns: A string composed of '#' and ' ', separated by ' '. When printed to console, renders the following (given 'size' of 5). # ## ### #### ##### """ result = [] for num in range(1, size + 1): result.append(' ' * (size - num) + '#' * num) return '\n'.join(result)
class ObjDiff(object): """Represents a difference between two `CopyDiff` objects. Contains a list of `DiffField` objects that represent the changes to each field in the object. Also contains the `children` field which may be be a `ChildListField`. """ def __init__(self, old, new, changes, children=None): self.old = old self.new = new self.changes = changes self.children = children def get(self, name): """Gets a scalar field with the given name.""" for field in self.changes: if field.name == name: return field return None class DiffField(object): """Represents a generic field in a diff.""" def __init__(self, name): self.name = name class ScalarField(DiffField): """Represents a change to a scalar field (i.e., not a list or dict)""" def __init__(self, name, old, new): super().__init__(name) self.new = new self.old = old class ChildListField(DiffField): """Represents a change to a list of child objects whose changes are also tracked.""" def __init__(self, name, added, removed, changed): super().__init__(name) self.added = added self.removed = removed self.changed = changed class CopyDiff(object): """Base class providing copy and diff functions""" def copy(self, **kwargs): copy = self.blank(**kwargs) copy.copy_from(self) return copy def copy_from(self, other): """Copies changes from `other` to this object.""" # Copy changes to this object for f in self.copydiff_fields(): setattr(self, f, getattr(other, f)) # Remove children deleted in other for schild in self.get_children(): if not any(map(lambda o: o.same_as(schild), other.get_children())): self.rm_child(schild) # Copy children and add new children to self for ochild in other.get_children(): # Find a matching child in this object schild = next(filter(lambda s: ochild.same_as(s), self.get_children()), None) if schild: schild.copy_from(ochild) else: newchild = self.blank_child() newchild.copy_from(ochild) self.add_child(newchild) def diff(self, new, prefix=[]): """ Returns a dict representing the differences between this mod and `new`. Return value is an `ObjDiff` representing the differences between the objects. Note: At the moment tracked children are always represented by a field called `children` and there can only be one. This can be fixed later, but it's not really needed. """ changes = [] for f in self.copydiff_fields(): o = getattr(self, f) n = getattr(new, f) if o != n: changes.append(ScalarField(f, old=o, new=n)) # List removed children added = [] removed = [] changed = [] # List removed children. for schild in self.get_children(): if not any(map(lambda n: n.same_as(schild), new.get_children())): removed.append(schild) # List added and changed children for nchild in new.get_children(): # Find a matching child in the old object ochild = next(filter(lambda s: nchild.same_as(s), self.get_children()), None) if ochild: chdiff = ochild.diff(nchild) if len(chdiff.changes) > 0: changed.append(chdiff) else: added.append(nchild) # If children changed, add a `ChildListField` to the diff. if len(added) > 0 or len(removed) > 0 or len(changed) > 0: children = ChildListField('children', added, removed, changed) else: children = None print(changes) return ObjDiff(self, new, changes, children) def blank(self, **kwargs): """Creates an "empty" instance of this object""" raise NotImplementedError def blank_child(self, **kwargs): """Creates an "empty" instance of a child of this object. None if this object can't have children""" return None def copydiff_fields(self): """Returns a list of fields to be copied or diffed""" return [] def same_as(self, other): scur = hasattr(self, 'cur_id') ocur = hasattr(other, 'cur_id') if self.id == other.id: return True if scur and ocur: return self.cur_id == other.cur_id elif scur: return self.cur_id == other.id elif ocur: return other.cur_id == self.id else: return False def get_children(self): raise NotImplementedError def add_child(self, ch): raise NotImplementedError def rm_child(self, ch): raise NotImplementedError
class Objdiff(object): """Represents a difference between two `CopyDiff` objects. Contains a list of `DiffField` objects that represent the changes to each field in the object. Also contains the `children` field which may be be a `ChildListField`. """ def __init__(self, old, new, changes, children=None): self.old = old self.new = new self.changes = changes self.children = children def get(self, name): """Gets a scalar field with the given name.""" for field in self.changes: if field.name == name: return field return None class Difffield(object): """Represents a generic field in a diff.""" def __init__(self, name): self.name = name class Scalarfield(DiffField): """Represents a change to a scalar field (i.e., not a list or dict)""" def __init__(self, name, old, new): super().__init__(name) self.new = new self.old = old class Childlistfield(DiffField): """Represents a change to a list of child objects whose changes are also tracked.""" def __init__(self, name, added, removed, changed): super().__init__(name) self.added = added self.removed = removed self.changed = changed class Copydiff(object): """Base class providing copy and diff functions""" def copy(self, **kwargs): copy = self.blank(**kwargs) copy.copy_from(self) return copy def copy_from(self, other): """Copies changes from `other` to this object.""" for f in self.copydiff_fields(): setattr(self, f, getattr(other, f)) for schild in self.get_children(): if not any(map(lambda o: o.same_as(schild), other.get_children())): self.rm_child(schild) for ochild in other.get_children(): schild = next(filter(lambda s: ochild.same_as(s), self.get_children()), None) if schild: schild.copy_from(ochild) else: newchild = self.blank_child() newchild.copy_from(ochild) self.add_child(newchild) def diff(self, new, prefix=[]): """ Returns a dict representing the differences between this mod and `new`. Return value is an `ObjDiff` representing the differences between the objects. Note: At the moment tracked children are always represented by a field called `children` and there can only be one. This can be fixed later, but it's not really needed. """ changes = [] for f in self.copydiff_fields(): o = getattr(self, f) n = getattr(new, f) if o != n: changes.append(scalar_field(f, old=o, new=n)) added = [] removed = [] changed = [] for schild in self.get_children(): if not any(map(lambda n: n.same_as(schild), new.get_children())): removed.append(schild) for nchild in new.get_children(): ochild = next(filter(lambda s: nchild.same_as(s), self.get_children()), None) if ochild: chdiff = ochild.diff(nchild) if len(chdiff.changes) > 0: changed.append(chdiff) else: added.append(nchild) if len(added) > 0 or len(removed) > 0 or len(changed) > 0: children = child_list_field('children', added, removed, changed) else: children = None print(changes) return obj_diff(self, new, changes, children) def blank(self, **kwargs): """Creates an "empty" instance of this object""" raise NotImplementedError def blank_child(self, **kwargs): """Creates an "empty" instance of a child of this object. None if this object can't have children""" return None def copydiff_fields(self): """Returns a list of fields to be copied or diffed""" return [] def same_as(self, other): scur = hasattr(self, 'cur_id') ocur = hasattr(other, 'cur_id') if self.id == other.id: return True if scur and ocur: return self.cur_id == other.cur_id elif scur: return self.cur_id == other.id elif ocur: return other.cur_id == self.id else: return False def get_children(self): raise NotImplementedError def add_child(self, ch): raise NotImplementedError def rm_child(self, ch): raise NotImplementedError
{ "targets": [ { "target_name": "memcpy", "sources": [ "src/memcpy.cc" ], "include_dirs" : [ "<!(node -e \"require('nan')\")", "<!(node -e \"require('node-arraybuffer')\")" ] } ] }
{'targets': [{'target_name': 'memcpy', 'sources': ['src/memcpy.cc'], 'include_dirs': ['<!(node -e "require(\'nan\')")', '<!(node -e "require(\'node-arraybuffer\')")']}]}
# extracting filter information c_ang = 2.99792458e18 # speed of light in Angstroms/s # galex filters ffuv = open('splash/filters/galex1500.res','r') fuv_band = array([]) fuv_band_sens = array([]) for line in ffuv: columns = line.strip().split() columns = array(columns).astype(float) fuv_band = append(fuv_band,columns[0]) fuv_band_sens = append(fuv_band_sens,columns[1]) ffuv.close() #ln_band_nu = numpy.log(c_ang/fuv_band) #ln_band = numpy.log(fuv_band) #upper = trapz(ln_band*fuv_band_sens,ln_band_nu) #lower = trapz(fuv_band_sens,ln_band_nu) #lambda_eff = exp(upper/lower) fnuv = open('splash/filters/galex2500.res','r') nuv_band = array([]) nuv_band_sens = array([]) for line in fnuv: columns = line.strip().split() columns = array(columns).astype(float) nuv_band = append(nuv_band,columns[0]) nuv_band_sens = append(nuv_band_sens,columns[1]) fnuv.close() # hubble filter f = open('splash/filters/ACS_F814W.res','r') f814w_band = array([]) f814w_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) f814w_band = append(f814w_band,columns[0]) f814w_band_sens = append(f814w_band_sens,columns[1]) f.close() # CFHT fu = open('splash/filters/u_megaprime_sagem.res','r') u_band = array([]) u_band_sens = array([]) for line in fu: columns = line.strip().split() columns = array(columns).astype(float) u_band = append(u_band,columns[0]) u_band_sens = append(u_band_sens,columns[1]) fu.close() # subaru fb = open('splash/filters/B_subaru.res','r') bp_band = array([]) bp_band_sens = array([]) for line in fb: columns = line.strip().split() columns = array(columns).astype(float) bp_band = append(bp_band,columns[0]) bp_band_sens = append(bp_band_sens,columns[1]) fb.close() fv = open('splash/filters/V_subaru.res','r') vp_band = array([]) vp_band_sens = array([]) for line in fv: columns = line.strip().split() columns = array(columns).astype(float) vp_band = append(vp_band,columns[0]) vp_band_sens = append(vp_band_sens,columns[1]) fv.close() fg = open('splash/filters/g_subaru.res','r') gp_band = array([]) gp_band_sens = array([]) for line in fg: columns = line.strip().split() columns = array(columns).astype(float) gp_band = append(gp_band,columns[0]) gp_band_sens = append(gp_band_sens,columns[1]) fg.close() fr = open('splash/filters/r_subaru.res','r') rp_band = array([]) rp_band_sens = array([]) for line in fr: columns = line.strip().split() columns = array(columns).astype(float) rp_band = append(rp_band,columns[0]) rp_band_sens = append(rp_band_sens,columns[1]) fr.close() fi = open('splash/filters/i_subaru.res','r') ip_band = array([]) ip_band_sens = array([]) for line in fi: columns = line.strip().split() columns = array(columns).astype(float) ip_band = append(ip_band,columns[0]) ip_band_sens = append(ip_band_sens,columns[1]) fi.close() fi = open('splash/filters/i_subaru.res','r') ic_band = array([]) ic_band_sens = array([]) for line in fi: columns = line.strip().split() columns = array(columns).astype(float) ic_band = append(ic_band,columns[0]) ic_band_sens = append(ic_band_sens,columns[1]) fi.close() f = open('splash/filters/z_subaru.res','r') zp_band = array([]) zp_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) zp_band = append(zp_band,columns[0]) zp_band_sens = append(zp_band_sens,columns[1]) f.close() fz = open('splash/filters/suprime_FDCCD_z.res','r') zpp_band = array([]) zpp_band_sens = array([]) for line in fz: columns = line.strip().split() columns = array(columns).astype(float) zpp_band = append(zpp_band,columns[0]) zpp_band_sens = append(zpp_band_sens,columns[1]) fz.close() # CFHT/UKIRT WFcam/wircam or whatever fj = open('splash/filters/J_wfcam.res','r') j_band = array([]) j_band_sens = array([]) for line in fj: columns = line.strip().split() columns = array(columns).astype(float) j_band = append(j_band,columns[0]) j_band_sens = append(j_band_sens,columns[1]) fj.close() fh = open('splash/filters/wircam_H.res','r') h_band = array([]) h_band_sens = array([]) for line in fh: columns = line.strip().split() columns = array(columns).astype(float) h_band = append(h_band,columns[0]) h_band_sens = append(h_band_sens,columns[1]) fh.close() fk = open('splash/filters/flamingos_Ks.res','r') ks_band = array([]) ks_band_sens = array([]) for line in fk: columns = line.strip().split() columns = array(columns).astype(float) ks_band = append(ks_band,columns[0]) ks_band_sens = append(ks_band_sens,columns[1]) fk.close() fk = open('splash/filters/wircam_Ks.res','r') kc_band = array([]) kc_band_sens = array([]) for line in fk: columns = line.strip().split() columns = array(columns).astype(float) kc_band = append(kc_band,columns[0]) kc_band_sens = append(kc_band_sens,columns[1]) fk.close() # ultravista f = open('splash/filters/Y_uv.res','r') y_uv_band = array([]) y_uv_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) y_uv_band = append(y_uv_band,columns[0]) y_uv_band_sens = append(y_uv_band_sens,columns[1]) f.close() f = open('splash/filters/J_uv.res','r') j_uv_band = array([]) j_uv_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) j_uv_band = append(j_uv_band,columns[0]) j_uv_band_sens = append(j_uv_band_sens,columns[1]) f.close() f = open('splash/filters/H_uv.res','r') h_uv_band = array([]) h_uv_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) h_uv_band = append(h_uv_band,columns[0]) h_uv_band_sens = append(h_uv_band_sens,columns[1]) f.close() f = open('splash/filters/K_uv.res','r') k_uv_band = array([]) k_uv_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) k_uv_band = append(k_uv_band,columns[0]) k_uv_band_sens = append(k_uv_band_sens,columns[1]) f.close() # sloan data f = open('splash/filters/u_SDSS.res','r') u_s_band = array([]) u_s_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) u_s_band = append(u_s_band,columns[0]) u_s_band_sens = append(u_s_band_sens,columns[1]) f.close() f = open('splash/filters/g_SDSS.res','r') g_s_band = array([]) g_s_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) g_s_band = append(g_s_band,columns[0]) g_s_band_sens = append(g_s_band_sens,columns[1]) f.close() f = open('splash/filters/r_SDSS.res','r') r_s_band = array([]) r_s_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) r_s_band = append(r_s_band,columns[0]) r_s_band_sens = append(r_s_band_sens,columns[1]) f.close() f = open('splash/filters/i_SDSS.res','r') i_s_band = array([]) i_s_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) i_s_band = append(i_s_band,columns[0]) i_s_band_sens = append(i_s_band_sens,columns[1]) f.close() f = open('splash/filters/z_SDSS.res','r') z_s_band = array([]) z_s_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) z_s_band = append(z_s_band,columns[0]) z_s_band_sens = append(z_s_band_sens,columns[1]) f.close() # subaru intermediate bands f = open('splash/filters/IB427.SuprimeCam.pb','r') IB427_band = array([]) IB427_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB427_band = append(IB427_band,columns[0]) IB427_band_sens = append(IB427_band_sens,columns[1]) f.close() f = open('splash/filters/IB464.SuprimeCam.pb','r') IB464_band = array([]) IB464_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB464_band = append(IB464_band,columns[0]) IB464_band_sens = append(IB464_band_sens,columns[1]) f.close() f = open('splash/filters/IB484.SuprimeCam.pb','r') IB484_band = array([]) IB484_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB484_band = append(IB484_band,columns[0]) IB484_band_sens = append(IB484_band_sens,columns[1]) f.close() f = open('splash/filters/IB505.SuprimeCam.pb','r') IB505_band = array([]) IB505_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB505_band = append(IB505_band,columns[0]) IB505_band_sens = append(IB505_band_sens,columns[1]) f.close() f = open('splash/filters/IB527.SuprimeCam.pb','r') IB527_band = array([]) IB527_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB527_band = append(IB527_band,columns[0]) IB527_band_sens = append(IB527_band_sens,columns[1]) f.close() f = open('splash/filters/IB574.SuprimeCam.pb','r') IB574_band = array([]) IB574_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB574_band = append(IB574_band,columns[0]) IB574_band_sens = append(IB574_band_sens,columns[1]) f.close() f = open('splash/filters/IB624.SuprimeCam.pb','r') IB624_band = array([]) IB624_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB624_band = append(IB624_band,columns[0]) IB624_band_sens = append(IB624_band_sens,columns[1]) f.close() f = open('splash/filters/IB679.SuprimeCam.pb','r') IB679_band = array([]) IB679_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB679_band = append(IB679_band,columns[0]) IB679_band_sens = append(IB679_band_sens,columns[1]) f.close() f = open('splash/filters/IB709.SuprimeCam.pb','r') IB709_band = array([]) IB709_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB709_band = append(IB709_band,columns[0]) IB709_band_sens = append(IB709_band_sens,columns[1]) f.close() f = open('splash/filters/IB738.SuprimeCam.pb','r') IB738_band = array([]) IB738_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB738_band = append(IB738_band,columns[0]) IB738_band_sens = append(IB738_band_sens,columns[1]) f.close() f = open('splash/filters/IB767.SuprimeCam.pb','r') IB767_band = array([]) IB767_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB767_band = append(IB767_band,columns[0]) IB767_band_sens = append(IB767_band_sens,columns[1]) f.close() f = open('splash/filters/IB827.SuprimeCam.pb','r') IB827_band = array([]) IB827_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) IB827_band = append(IB827_band,columns[0]) IB827_band_sens = append(IB827_band_sens,columns[1]) f.close() # newfirm bands f = open('splash/filters/J1.res','r') j1_band = array([]) j1_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) j1_band = append(j1_band,columns[0]) j1_band_sens = append(j1_band_sens,columns[1]) f.close() f = open('splash/filters/J2.res','r') j2_band = array([]) j2_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) j2_band = append(j2_band,columns[0]) j2_band_sens = append(j2_band_sens,columns[1]) f.close() f = open('splash/filters/J3.res','r') j3_band = array([]) j3_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) j3_band = append(j3_band,columns[0]) j3_band_sens = append(j3_band_sens,columns[1]) f.close() f = open('splash/filters/H1.res','r') h1_band = array([]) h1_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) h1_band = append(h1_band,columns[0]) h1_band_sens = append(h1_band_sens,columns[1]) f.close() f = open('splash/filters/H2.res','r') h2_band = array([]) h2_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) h2_band = append(h2_band,columns[0]) h2_band_sens = append(h2_band_sens,columns[1]) f.close() f = open('splash/filters/Ks_newfirm.res','r') knf_band = array([]) knf_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) knf_band = append(knf_band,columns[0]) knf_band_sens = append(knf_band_sens,columns[1]) f.close() # subaru narrow bands f = open('splash/filters/NB711.SuprimeCam.pb','r') NB711_band = array([]) NB711_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) NB711_band = append(NB711_band,columns[0]) NB711_band_sens = append(NB711_band_sens,columns[1]) f.close() f = open('splash/filters/NB816.SuprimeCam.pb','r') NB816_band = array([]) NB816_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) NB816_band = append(NB816_band,columns[0]) NB816_band_sens = append(NB816_band_sens,columns[1]) f.close() # spitzer bands fch1 = open('splash/filters/irac_ch1.res','r') ch1_band = array([]) ch1_band_sens = array([]) for line in fch1: columns = line.strip().split() columns = array(columns).astype(float) ch1_band = append(ch1_band,columns[0]) ch1_band_sens = append(ch1_band_sens,columns[1]) fch1.close() fch2 = open('splash/filters/irac_ch2.res','r') ch2_band = array([]) ch2_band_sens = array([]) for line in fch2: columns = line.strip().split() columns = array(columns).astype(float) ch2_band = append(ch2_band,columns[0]) ch2_band_sens = append(ch2_band_sens,columns[1]) fch2.close() fch3 = open('splash/filters/irac_ch3.res','r') ch3_band = array([]) ch3_band_sens = array([]) for line in fch3: columns = line.strip().split() columns = array(columns).astype(float) ch3_band = append(ch3_band,columns[0]) ch3_band_sens = append(ch3_band_sens,columns[1]) fch3.close() fch4 = open('splash/filters/irac_ch4.res','r') ch4_band = array([]) ch4_band_sens = array([]) for line in fch4: columns = line.strip().split() columns = array(columns).astype(float) ch4_band = append(ch4_band,columns[0]) ch4_band_sens = append(ch4_band_sens,columns[1]) fch4.close() ##### Extracting filter effective band centers # centers of the relevant bands (taken from Olivier+09, VISTA filter page, # Fukugita+96, newfirm filter doc, and stsci WFC3 handbook c06_uvis06 table 6.2) # Includes: # Galex # u (CFHT), b-z (subaru), zpp (subaru - calculated, but might be a bit off) # IB,NB subaru # i (CFHT) # wfcam (J), wircam (H,Kc), flamingos (Ks) # spitzer # ultravista # sloan # newfirm # hubble f814w ## ALL OF THESE HAVE BEEN PAINSTAKINGLY ORDERED - KEEP THEM THIS WAY fuv_cent = 1551.3 nuv_cent = 2306.5 u_s_cent = 3540.0 u_cent = 3911.0 ib427_cent = 4256.3 b_cent = 4439.6 ib464_cent = 4633.3 gp_cent = 4728.3 g_s_cent = 4770.0 ib484_cent = 4845.9 ib505_cent = 5060.7 ib527_cent = 5258.9 vp_cent = 5448.9 ib574_cent = 5762.1 r_s_cent = 6222.0 ib624_cent = 6230.0 rp_cent = 6231.8 ib679_cent = 6778.8 ib709_cent = 7070.7 nb711_cent = 7119.6 ib738_cent = 7358.7 ic_cent = 7628.9 ip_cent = 7629.1 i_s_cent = 7632.0 ib767_cent = 7681.2 f814w_cent = 8024 nb816_cent = 8149.0 ib827_cent = 8240.9 zp_cent = 9021.6 z_s_cent = 9049.0 zpp_cent = 9077.4 y_uv_cent = 10210.0 j1_cent = 10484.0 j2_cent = 11903.0 j_cent = 12444.1 j_uv_cent = 12540.0 j3_cent = 12837.0 h1_cent = 15557.0 h_uv_cent = 16460.0 h2_cent = 17059.0 ks_cent = 21434.8 kc_cent = 21480.2 k_uv_cent = 21490.0 knf_cent = 21500.0 ch1_cent = 35262.5 ch2_cent = 44606.7 ch3_cent = 56762.4 ch4_cent = 77030.1
c_ang = 2.99792458e+18 ffuv = open('splash/filters/galex1500.res', 'r') fuv_band = array([]) fuv_band_sens = array([]) for line in ffuv: columns = line.strip().split() columns = array(columns).astype(float) fuv_band = append(fuv_band, columns[0]) fuv_band_sens = append(fuv_band_sens, columns[1]) ffuv.close() fnuv = open('splash/filters/galex2500.res', 'r') nuv_band = array([]) nuv_band_sens = array([]) for line in fnuv: columns = line.strip().split() columns = array(columns).astype(float) nuv_band = append(nuv_band, columns[0]) nuv_band_sens = append(nuv_band_sens, columns[1]) fnuv.close() f = open('splash/filters/ACS_F814W.res', 'r') f814w_band = array([]) f814w_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) f814w_band = append(f814w_band, columns[0]) f814w_band_sens = append(f814w_band_sens, columns[1]) f.close() fu = open('splash/filters/u_megaprime_sagem.res', 'r') u_band = array([]) u_band_sens = array([]) for line in fu: columns = line.strip().split() columns = array(columns).astype(float) u_band = append(u_band, columns[0]) u_band_sens = append(u_band_sens, columns[1]) fu.close() fb = open('splash/filters/B_subaru.res', 'r') bp_band = array([]) bp_band_sens = array([]) for line in fb: columns = line.strip().split() columns = array(columns).astype(float) bp_band = append(bp_band, columns[0]) bp_band_sens = append(bp_band_sens, columns[1]) fb.close() fv = open('splash/filters/V_subaru.res', 'r') vp_band = array([]) vp_band_sens = array([]) for line in fv: columns = line.strip().split() columns = array(columns).astype(float) vp_band = append(vp_band, columns[0]) vp_band_sens = append(vp_band_sens, columns[1]) fv.close() fg = open('splash/filters/g_subaru.res', 'r') gp_band = array([]) gp_band_sens = array([]) for line in fg: columns = line.strip().split() columns = array(columns).astype(float) gp_band = append(gp_band, columns[0]) gp_band_sens = append(gp_band_sens, columns[1]) fg.close() fr = open('splash/filters/r_subaru.res', 'r') rp_band = array([]) rp_band_sens = array([]) for line in fr: columns = line.strip().split() columns = array(columns).astype(float) rp_band = append(rp_band, columns[0]) rp_band_sens = append(rp_band_sens, columns[1]) fr.close() fi = open('splash/filters/i_subaru.res', 'r') ip_band = array([]) ip_band_sens = array([]) for line in fi: columns = line.strip().split() columns = array(columns).astype(float) ip_band = append(ip_band, columns[0]) ip_band_sens = append(ip_band_sens, columns[1]) fi.close() fi = open('splash/filters/i_subaru.res', 'r') ic_band = array([]) ic_band_sens = array([]) for line in fi: columns = line.strip().split() columns = array(columns).astype(float) ic_band = append(ic_band, columns[0]) ic_band_sens = append(ic_band_sens, columns[1]) fi.close() f = open('splash/filters/z_subaru.res', 'r') zp_band = array([]) zp_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) zp_band = append(zp_band, columns[0]) zp_band_sens = append(zp_band_sens, columns[1]) f.close() fz = open('splash/filters/suprime_FDCCD_z.res', 'r') zpp_band = array([]) zpp_band_sens = array([]) for line in fz: columns = line.strip().split() columns = array(columns).astype(float) zpp_band = append(zpp_band, columns[0]) zpp_band_sens = append(zpp_band_sens, columns[1]) fz.close() fj = open('splash/filters/J_wfcam.res', 'r') j_band = array([]) j_band_sens = array([]) for line in fj: columns = line.strip().split() columns = array(columns).astype(float) j_band = append(j_band, columns[0]) j_band_sens = append(j_band_sens, columns[1]) fj.close() fh = open('splash/filters/wircam_H.res', 'r') h_band = array([]) h_band_sens = array([]) for line in fh: columns = line.strip().split() columns = array(columns).astype(float) h_band = append(h_band, columns[0]) h_band_sens = append(h_band_sens, columns[1]) fh.close() fk = open('splash/filters/flamingos_Ks.res', 'r') ks_band = array([]) ks_band_sens = array([]) for line in fk: columns = line.strip().split() columns = array(columns).astype(float) ks_band = append(ks_band, columns[0]) ks_band_sens = append(ks_band_sens, columns[1]) fk.close() fk = open('splash/filters/wircam_Ks.res', 'r') kc_band = array([]) kc_band_sens = array([]) for line in fk: columns = line.strip().split() columns = array(columns).astype(float) kc_band = append(kc_band, columns[0]) kc_band_sens = append(kc_band_sens, columns[1]) fk.close() f = open('splash/filters/Y_uv.res', 'r') y_uv_band = array([]) y_uv_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) y_uv_band = append(y_uv_band, columns[0]) y_uv_band_sens = append(y_uv_band_sens, columns[1]) f.close() f = open('splash/filters/J_uv.res', 'r') j_uv_band = array([]) j_uv_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) j_uv_band = append(j_uv_band, columns[0]) j_uv_band_sens = append(j_uv_band_sens, columns[1]) f.close() f = open('splash/filters/H_uv.res', 'r') h_uv_band = array([]) h_uv_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) h_uv_band = append(h_uv_band, columns[0]) h_uv_band_sens = append(h_uv_band_sens, columns[1]) f.close() f = open('splash/filters/K_uv.res', 'r') k_uv_band = array([]) k_uv_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) k_uv_band = append(k_uv_band, columns[0]) k_uv_band_sens = append(k_uv_band_sens, columns[1]) f.close() f = open('splash/filters/u_SDSS.res', 'r') u_s_band = array([]) u_s_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) u_s_band = append(u_s_band, columns[0]) u_s_band_sens = append(u_s_band_sens, columns[1]) f.close() f = open('splash/filters/g_SDSS.res', 'r') g_s_band = array([]) g_s_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) g_s_band = append(g_s_band, columns[0]) g_s_band_sens = append(g_s_band_sens, columns[1]) f.close() f = open('splash/filters/r_SDSS.res', 'r') r_s_band = array([]) r_s_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) r_s_band = append(r_s_band, columns[0]) r_s_band_sens = append(r_s_band_sens, columns[1]) f.close() f = open('splash/filters/i_SDSS.res', 'r') i_s_band = array([]) i_s_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) i_s_band = append(i_s_band, columns[0]) i_s_band_sens = append(i_s_band_sens, columns[1]) f.close() f = open('splash/filters/z_SDSS.res', 'r') z_s_band = array([]) z_s_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) z_s_band = append(z_s_band, columns[0]) z_s_band_sens = append(z_s_band_sens, columns[1]) f.close() f = open('splash/filters/IB427.SuprimeCam.pb', 'r') ib427_band = array([]) ib427_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) ib427_band = append(IB427_band, columns[0]) ib427_band_sens = append(IB427_band_sens, columns[1]) f.close() f = open('splash/filters/IB464.SuprimeCam.pb', 'r') ib464_band = array([]) ib464_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) ib464_band = append(IB464_band, columns[0]) ib464_band_sens = append(IB464_band_sens, columns[1]) f.close() f = open('splash/filters/IB484.SuprimeCam.pb', 'r') ib484_band = array([]) ib484_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) ib484_band = append(IB484_band, columns[0]) ib484_band_sens = append(IB484_band_sens, columns[1]) f.close() f = open('splash/filters/IB505.SuprimeCam.pb', 'r') ib505_band = array([]) ib505_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) ib505_band = append(IB505_band, columns[0]) ib505_band_sens = append(IB505_band_sens, columns[1]) f.close() f = open('splash/filters/IB527.SuprimeCam.pb', 'r') ib527_band = array([]) ib527_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) ib527_band = append(IB527_band, columns[0]) ib527_band_sens = append(IB527_band_sens, columns[1]) f.close() f = open('splash/filters/IB574.SuprimeCam.pb', 'r') ib574_band = array([]) ib574_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) ib574_band = append(IB574_band, columns[0]) ib574_band_sens = append(IB574_band_sens, columns[1]) f.close() f = open('splash/filters/IB624.SuprimeCam.pb', 'r') ib624_band = array([]) ib624_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) ib624_band = append(IB624_band, columns[0]) ib624_band_sens = append(IB624_band_sens, columns[1]) f.close() f = open('splash/filters/IB679.SuprimeCam.pb', 'r') ib679_band = array([]) ib679_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) ib679_band = append(IB679_band, columns[0]) ib679_band_sens = append(IB679_band_sens, columns[1]) f.close() f = open('splash/filters/IB709.SuprimeCam.pb', 'r') ib709_band = array([]) ib709_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) ib709_band = append(IB709_band, columns[0]) ib709_band_sens = append(IB709_band_sens, columns[1]) f.close() f = open('splash/filters/IB738.SuprimeCam.pb', 'r') ib738_band = array([]) ib738_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) ib738_band = append(IB738_band, columns[0]) ib738_band_sens = append(IB738_band_sens, columns[1]) f.close() f = open('splash/filters/IB767.SuprimeCam.pb', 'r') ib767_band = array([]) ib767_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) ib767_band = append(IB767_band, columns[0]) ib767_band_sens = append(IB767_band_sens, columns[1]) f.close() f = open('splash/filters/IB827.SuprimeCam.pb', 'r') ib827_band = array([]) ib827_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) ib827_band = append(IB827_band, columns[0]) ib827_band_sens = append(IB827_band_sens, columns[1]) f.close() f = open('splash/filters/J1.res', 'r') j1_band = array([]) j1_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) j1_band = append(j1_band, columns[0]) j1_band_sens = append(j1_band_sens, columns[1]) f.close() f = open('splash/filters/J2.res', 'r') j2_band = array([]) j2_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) j2_band = append(j2_band, columns[0]) j2_band_sens = append(j2_band_sens, columns[1]) f.close() f = open('splash/filters/J3.res', 'r') j3_band = array([]) j3_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) j3_band = append(j3_band, columns[0]) j3_band_sens = append(j3_band_sens, columns[1]) f.close() f = open('splash/filters/H1.res', 'r') h1_band = array([]) h1_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) h1_band = append(h1_band, columns[0]) h1_band_sens = append(h1_band_sens, columns[1]) f.close() f = open('splash/filters/H2.res', 'r') h2_band = array([]) h2_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) h2_band = append(h2_band, columns[0]) h2_band_sens = append(h2_band_sens, columns[1]) f.close() f = open('splash/filters/Ks_newfirm.res', 'r') knf_band = array([]) knf_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) knf_band = append(knf_band, columns[0]) knf_band_sens = append(knf_band_sens, columns[1]) f.close() f = open('splash/filters/NB711.SuprimeCam.pb', 'r') nb711_band = array([]) nb711_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) nb711_band = append(NB711_band, columns[0]) nb711_band_sens = append(NB711_band_sens, columns[1]) f.close() f = open('splash/filters/NB816.SuprimeCam.pb', 'r') nb816_band = array([]) nb816_band_sens = array([]) for line in f: columns = line.strip().split() columns = array(columns).astype(float) nb816_band = append(NB816_band, columns[0]) nb816_band_sens = append(NB816_band_sens, columns[1]) f.close() fch1 = open('splash/filters/irac_ch1.res', 'r') ch1_band = array([]) ch1_band_sens = array([]) for line in fch1: columns = line.strip().split() columns = array(columns).astype(float) ch1_band = append(ch1_band, columns[0]) ch1_band_sens = append(ch1_band_sens, columns[1]) fch1.close() fch2 = open('splash/filters/irac_ch2.res', 'r') ch2_band = array([]) ch2_band_sens = array([]) for line in fch2: columns = line.strip().split() columns = array(columns).astype(float) ch2_band = append(ch2_band, columns[0]) ch2_band_sens = append(ch2_band_sens, columns[1]) fch2.close() fch3 = open('splash/filters/irac_ch3.res', 'r') ch3_band = array([]) ch3_band_sens = array([]) for line in fch3: columns = line.strip().split() columns = array(columns).astype(float) ch3_band = append(ch3_band, columns[0]) ch3_band_sens = append(ch3_band_sens, columns[1]) fch3.close() fch4 = open('splash/filters/irac_ch4.res', 'r') ch4_band = array([]) ch4_band_sens = array([]) for line in fch4: columns = line.strip().split() columns = array(columns).astype(float) ch4_band = append(ch4_band, columns[0]) ch4_band_sens = append(ch4_band_sens, columns[1]) fch4.close() fuv_cent = 1551.3 nuv_cent = 2306.5 u_s_cent = 3540.0 u_cent = 3911.0 ib427_cent = 4256.3 b_cent = 4439.6 ib464_cent = 4633.3 gp_cent = 4728.3 g_s_cent = 4770.0 ib484_cent = 4845.9 ib505_cent = 5060.7 ib527_cent = 5258.9 vp_cent = 5448.9 ib574_cent = 5762.1 r_s_cent = 6222.0 ib624_cent = 6230.0 rp_cent = 6231.8 ib679_cent = 6778.8 ib709_cent = 7070.7 nb711_cent = 7119.6 ib738_cent = 7358.7 ic_cent = 7628.9 ip_cent = 7629.1 i_s_cent = 7632.0 ib767_cent = 7681.2 f814w_cent = 8024 nb816_cent = 8149.0 ib827_cent = 8240.9 zp_cent = 9021.6 z_s_cent = 9049.0 zpp_cent = 9077.4 y_uv_cent = 10210.0 j1_cent = 10484.0 j2_cent = 11903.0 j_cent = 12444.1 j_uv_cent = 12540.0 j3_cent = 12837.0 h1_cent = 15557.0 h_uv_cent = 16460.0 h2_cent = 17059.0 ks_cent = 21434.8 kc_cent = 21480.2 k_uv_cent = 21490.0 knf_cent = 21500.0 ch1_cent = 35262.5 ch2_cent = 44606.7 ch3_cent = 56762.4 ch4_cent = 77030.1
class Move: """ A Player where the user chooses its moves. === Public Attributes === row: The row that move takes place. col: The column that move takes place. """ row: int col: int def __init__(self, row: int, col: int) -> None: """ Creates Move with <row> row and <col> column. """ self.row = row self.col = col def get_row(self) -> int: """ Returns the row. """ return self.row def get_col(self) -> int: """ Returns the column. """ return self.col def to_string(self) -> str: """ Returns the string representation of Move in (row, column). """ return "(" + str(self.row) + "," + str(self.col) + ")"
class Move: """ A Player where the user chooses its moves. === Public Attributes === row: The row that move takes place. col: The column that move takes place. """ row: int col: int def __init__(self, row: int, col: int) -> None: """ Creates Move with <row> row and <col> column. """ self.row = row self.col = col def get_row(self) -> int: """ Returns the row. """ return self.row def get_col(self) -> int: """ Returns the column. """ return self.col def to_string(self) -> str: """ Returns the string representation of Move in (row, column). """ return '(' + str(self.row) + ',' + str(self.col) + ')'
def calculate_subsidy(income, children_count): if 30_000 <= income < 40_000 and children_count >= 3: return 1000 * children_count elif 20_000 <= income < 30_000 and children_count >= 2: return 1500 * children_count elif income < 20_000: return 2000 * children_count return 0 income = float(input("Inserire il reddito annuo (-1 per uscire): ")) while income >= 0: children = int(input("Inserire il numero di figli: ")) subsidy = round(calculate_subsidy(income, children), 2) if subsidy == 0: print("La famiglia non ha diritto ad un sussidio annuo.") else: print(f"La famiglia ha diritto a {subsidy}$ di sussidio annuo.") income = float(input("Inserire il reddito annuo (-1 per uscire): "))
def calculate_subsidy(income, children_count): if 30000 <= income < 40000 and children_count >= 3: return 1000 * children_count elif 20000 <= income < 30000 and children_count >= 2: return 1500 * children_count elif income < 20000: return 2000 * children_count return 0 income = float(input('Inserire il reddito annuo (-1 per uscire): ')) while income >= 0: children = int(input('Inserire il numero di figli: ')) subsidy = round(calculate_subsidy(income, children), 2) if subsidy == 0: print('La famiglia non ha diritto ad un sussidio annuo.') else: print(f'La famiglia ha diritto a {subsidy}$ di sussidio annuo.') income = float(input('Inserire il reddito annuo (-1 per uscire): '))
#Let's teach the Robots to distinguish words and numbers. #You are given a string with words and numbers separated by whitespaces (one space). #The words contains only letters. You should check if the string contains three words in succession. #For example, the string "start 5 one two three 7 end" contains three words in succession. def checkio(string): string = string.split() lista = [] for c in string: if c.isalpha(): lista.append(c) if len(lista)==3: break else: lista.clear() if len(lista)==3: return True else: return False if __name__ == '__main__': print('Example:') print(checkio("Hello World hello")) print(checkio("haaas h366lo hello")) print(checkio('o 111 rato roeu a 111roupa do rei de roma')) print(checkio('he is 123 man')) print(checkio('one two 3 four five six 7 eight 9 ten eleven 12'))
def checkio(string): string = string.split() lista = [] for c in string: if c.isalpha(): lista.append(c) if len(lista) == 3: break else: lista.clear() if len(lista) == 3: return True else: return False if __name__ == '__main__': print('Example:') print(checkio('Hello World hello')) print(checkio('haaas h366lo hello')) print(checkio('o 111 rato roeu a 111roupa do rei de roma')) print(checkio('he is 123 man')) print(checkio('one two 3 four five six 7 eight 9 ten eleven 12'))
# Time: O(logn) # Space: O(1) class Solution(object): def singleNonDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ left, right = 0, len(nums)-1 while left <= right: mid = left + (right - left) / 2 if not (mid%2 == 0 and mid+1 < len(nums) and \ nums[mid] == nums[mid+1]) and \ not (mid%2 == 1 and nums[mid] == nums[mid-1]): right = mid-1 else: left = mid+1 return nums[left]
class Solution(object): def single_non_duplicate(self, nums): """ :type nums: List[int] :rtype: int """ (left, right) = (0, len(nums) - 1) while left <= right: mid = left + (right - left) / 2 if not (mid % 2 == 0 and mid + 1 < len(nums) and (nums[mid] == nums[mid + 1])) and (not (mid % 2 == 1 and nums[mid] == nums[mid - 1])): right = mid - 1 else: left = mid + 1 return nums[left]
class resolutions(object): res_1080p = '1080p' res_720p = '720p' res_1080i = '1080i' res_1024x768 = '1024x768' res_1360x768 = '1360x768' class modes(object): single = 'single' pip = 'pip' side_full = 'side_full' side_scale = 'side_scale' class ports(object): port_1 = '1' port_2 = '2' class pip_positions(object): top_left = 'top_left' top_right = 'top_right' bottom_left = 'bottom_left' bottom_right = 'bottom_right' class pip_sizes(object): small = 'small' medium = 'medium' large = 'large' class pip_borders(object): show = 'show' hide = 'hide'
class Resolutions(object): res_1080p = '1080p' res_720p = '720p' res_1080i = '1080i' res_1024x768 = '1024x768' res_1360x768 = '1360x768' class Modes(object): single = 'single' pip = 'pip' side_full = 'side_full' side_scale = 'side_scale' class Ports(object): port_1 = '1' port_2 = '2' class Pip_Positions(object): top_left = 'top_left' top_right = 'top_right' bottom_left = 'bottom_left' bottom_right = 'bottom_right' class Pip_Sizes(object): small = 'small' medium = 'medium' large = 'large' class Pip_Borders(object): show = 'show' hide = 'hide'
#!/usr/bin/env python # -*- coding: utf-8 -*- """ :Purpose: This module contains various low-level conversion functions. :Platform: Linux/Windows | Python 3.8 :Developer: J Berendt :Email: development@s3dev.uk :Comments: These functions are designed to be as close to core Python, or a C-esque implementation, as possible. """ # TODO: Move repeated messages into a central messaging class. def ascii2bin(asciistring: str) -> str: """Convert an ASCII string into a binary string representation. Args: asciistring (str): ASCII string to be converted. Returns: str: A binary string representation for the passed ASCII text. """ return ''.join(map(int2bin, ascii2int(asciistring))) def ascii2hex(asciistring: str) -> str: """Convert an ASCII string into a hexidecimal string. Args: asciistring (str): ASCII string to be converted. Returns: str: A hexidecimal string representation of the passed ASCII text. """ return ''.join(map(int2hex, ascii2int(asciistring))) def ascii2int(asciistring: str) -> list: """Convert an ASCII string to a list of integers. Args: asciistring (str): ASCII string to be converted. Returns: list: A list of integers, as converted from he ASCII string. """ return [ord(i) for i in asciistring] def bin2ascii(binstring: str, bits: int=8) -> str: """Convert a binary string representation into ASCII text. Args: binstring (str): Binary string to be converted. bits (int, optional): Bit chunks into which the binary string is broken for conversion. Defaults to 8. Returns: str: An ASCII string representation of the passed binary string. """ if len(binstring) % bits: raise ValueError('The string length cannot be broken into ' f'{bits}-bit chunks.') ints = [] for chunk in range(0, len(binstring), bits): byte_ = binstring[chunk:chunk+bits] ints.append(bin2int(byte_, bits=bits)[0]) text = ''.join(map(int2ascii, ints)) return text def bin2int(binstring: str, bits: int=8) -> int: """Convert a binary string representation into an integer. Args: binstring (str): Binary string to be converted. bits (int, optional): Bit chunks into which the binary string is broken for conversion. Defaults to 8. Returns: int: Integer value from the binary string. """ if len(binstring) % bits: raise ValueError('The string length cannot be broken into ' f'{bits}-bit chunks.') ints = [] for chunk in range(0, len(binstring), bits): int_ = 0 s = 0 byte = binstring[chunk:chunk+bits] for b in range(len(byte)-1, -1, -1): int_ += int(byte[b]) << s s += 1 ints.append(int_) return ints def bin2hex(binstring: str, bits: int=8) -> str: """Convert a binary string representation into a hex string. Args: binstring (str): Binary string to be converted. bits (int, optional): Bit chunks into which the binary string is broken for conversion. Defaults to 8. Returns: A hexidecimal string representation of the passed binary string. """ if len(binstring) % bits: raise ValueError('The string length cannot be broken into ' f'{bits}-bit chunks.') return ''.join(int2hex(i) for i in bin2int(binstring, bits=bits)) def hex2ascii(hexstring: str) -> str: """Convert a hexidecimal string to ASCII text. Args: hexstring (str): Hex string to be converted. Returns: str: An ASCII string representation for the passed hex string. """ return ''.join(map(int2ascii, hex2int(hexstring))) def hex2bin(hexstring: str) -> str: """Convert a hexidecimal string into a binary string representation. Args: hexstring (str): Hex string to be converted. Returns: str: A binary string representation of the passed hex string. """ return ''.join(map(int2bin, hex2int(hexstring))) def hex2int(hexstring: str, nbytes: int=1) -> int: """Convert a hexidecimal string to an integer. Args: hexstring (str): Hex string to be converted. nbytes (int, optional): Number of bytes to consider for each decimal value. Defaults to 1. :Examples: Example usage:: hex2int(hexstring='c0ffee', nbytes=1) >>> [192, 255, 238] hex2int(hexstring='c0ffee', nbytes=2) >>> [49407, 238] hex2int(hexstring='c0ffee', nbytes=3) >>> [12648430] Returns: list: A list of decimal values, as converted from the hex string. """ nbytes *= 2 out = [] # Split hex string into (n)-byte size chunks. for chunk in range(0, len(hexstring), nbytes): i = 0 for char in hexstring[chunk:nbytes+chunk]: if (char >= '0') & (char <= '9'): nib = ord(char) if (char >= 'a') & (char <= 'f'): nib = ord(char) + 9 if (char >= 'A') & (char <= 'F'): nib = ord(char) + 9 i = (i << 4) | (nib & 0xf) out.append(i) return out def int2ascii(i: int) -> str: """Convert an integer to an ASCII character. Args: i (int): Integer value to be converted to ASCII text. Note: The passed integer value must be <= 127. Raises: ValueError: If the passed integer is > 127. Returns: str: The ASCII character associated to the passed integer. """ if i > 127: raise ValueError('The passed integer value must be <= 127.') return chr(i) def int2bin(i: int) -> str: """Convert an 8-bit integer to a binary string. Args: i (int): Integer value to be converted. Note: The passed integer value must be <= 255. Raises: ValueError: If the passed integer is > 255. Returns: str: A binary string representation of the passed integer. """ if i > 255: # Limited to 1 byte. raise ValueError(f'Passed value exceeds 1 byte: {i=}') return ''.join(str((i >> shift) & 1) for shift in range(7, -1, -1)) def int2hex(i: int) -> str: """Convert an integer into a hexidecimal string. Args: i (int): Integer value to be converted. Returns: str: A two character hexidecimal string for the passed integer value. """ chars = '0123456789abcdef' out = '' out_ = '' while i > 0: out_ += chars[i % 16] i //= 16 # Output string must be reversed. for x in range(len(out_)-1, -1, -1): out += out_[x] # Pad so all hex values are two characters. if len(out) < 2: out = '0' + out return out
""" :Purpose: This module contains various low-level conversion functions. :Platform: Linux/Windows | Python 3.8 :Developer: J Berendt :Email: development@s3dev.uk :Comments: These functions are designed to be as close to core Python, or a C-esque implementation, as possible. """ def ascii2bin(asciistring: str) -> str: """Convert an ASCII string into a binary string representation. Args: asciistring (str): ASCII string to be converted. Returns: str: A binary string representation for the passed ASCII text. """ return ''.join(map(int2bin, ascii2int(asciistring))) def ascii2hex(asciistring: str) -> str: """Convert an ASCII string into a hexidecimal string. Args: asciistring (str): ASCII string to be converted. Returns: str: A hexidecimal string representation of the passed ASCII text. """ return ''.join(map(int2hex, ascii2int(asciistring))) def ascii2int(asciistring: str) -> list: """Convert an ASCII string to a list of integers. Args: asciistring (str): ASCII string to be converted. Returns: list: A list of integers, as converted from he ASCII string. """ return [ord(i) for i in asciistring] def bin2ascii(binstring: str, bits: int=8) -> str: """Convert a binary string representation into ASCII text. Args: binstring (str): Binary string to be converted. bits (int, optional): Bit chunks into which the binary string is broken for conversion. Defaults to 8. Returns: str: An ASCII string representation of the passed binary string. """ if len(binstring) % bits: raise value_error(f'The string length cannot be broken into {bits}-bit chunks.') ints = [] for chunk in range(0, len(binstring), bits): byte_ = binstring[chunk:chunk + bits] ints.append(bin2int(byte_, bits=bits)[0]) text = ''.join(map(int2ascii, ints)) return text def bin2int(binstring: str, bits: int=8) -> int: """Convert a binary string representation into an integer. Args: binstring (str): Binary string to be converted. bits (int, optional): Bit chunks into which the binary string is broken for conversion. Defaults to 8. Returns: int: Integer value from the binary string. """ if len(binstring) % bits: raise value_error(f'The string length cannot be broken into {bits}-bit chunks.') ints = [] for chunk in range(0, len(binstring), bits): int_ = 0 s = 0 byte = binstring[chunk:chunk + bits] for b in range(len(byte) - 1, -1, -1): int_ += int(byte[b]) << s s += 1 ints.append(int_) return ints def bin2hex(binstring: str, bits: int=8) -> str: """Convert a binary string representation into a hex string. Args: binstring (str): Binary string to be converted. bits (int, optional): Bit chunks into which the binary string is broken for conversion. Defaults to 8. Returns: A hexidecimal string representation of the passed binary string. """ if len(binstring) % bits: raise value_error(f'The string length cannot be broken into {bits}-bit chunks.') return ''.join((int2hex(i) for i in bin2int(binstring, bits=bits))) def hex2ascii(hexstring: str) -> str: """Convert a hexidecimal string to ASCII text. Args: hexstring (str): Hex string to be converted. Returns: str: An ASCII string representation for the passed hex string. """ return ''.join(map(int2ascii, hex2int(hexstring))) def hex2bin(hexstring: str) -> str: """Convert a hexidecimal string into a binary string representation. Args: hexstring (str): Hex string to be converted. Returns: str: A binary string representation of the passed hex string. """ return ''.join(map(int2bin, hex2int(hexstring))) def hex2int(hexstring: str, nbytes: int=1) -> int: """Convert a hexidecimal string to an integer. Args: hexstring (str): Hex string to be converted. nbytes (int, optional): Number of bytes to consider for each decimal value. Defaults to 1. :Examples: Example usage:: hex2int(hexstring='c0ffee', nbytes=1) >>> [192, 255, 238] hex2int(hexstring='c0ffee', nbytes=2) >>> [49407, 238] hex2int(hexstring='c0ffee', nbytes=3) >>> [12648430] Returns: list: A list of decimal values, as converted from the hex string. """ nbytes *= 2 out = [] for chunk in range(0, len(hexstring), nbytes): i = 0 for char in hexstring[chunk:nbytes + chunk]: if (char >= '0') & (char <= '9'): nib = ord(char) if (char >= 'a') & (char <= 'f'): nib = ord(char) + 9 if (char >= 'A') & (char <= 'F'): nib = ord(char) + 9 i = i << 4 | nib & 15 out.append(i) return out def int2ascii(i: int) -> str: """Convert an integer to an ASCII character. Args: i (int): Integer value to be converted to ASCII text. Note: The passed integer value must be <= 127. Raises: ValueError: If the passed integer is > 127. Returns: str: The ASCII character associated to the passed integer. """ if i > 127: raise value_error('The passed integer value must be <= 127.') return chr(i) def int2bin(i: int) -> str: """Convert an 8-bit integer to a binary string. Args: i (int): Integer value to be converted. Note: The passed integer value must be <= 255. Raises: ValueError: If the passed integer is > 255. Returns: str: A binary string representation of the passed integer. """ if i > 255: raise value_error(f'Passed value exceeds 1 byte: i={i!r}') return ''.join((str(i >> shift & 1) for shift in range(7, -1, -1))) def int2hex(i: int) -> str: """Convert an integer into a hexidecimal string. Args: i (int): Integer value to be converted. Returns: str: A two character hexidecimal string for the passed integer value. """ chars = '0123456789abcdef' out = '' out_ = '' while i > 0: out_ += chars[i % 16] i //= 16 for x in range(len(out_) - 1, -1, -1): out += out_[x] if len(out) < 2: out = '0' + out return out
# Please complete the following exercise this week. Write a Python script containing a function called factorial() # that takes a single input/argument (x) which is a positive integer and returns its factorial. # The factorial of a number is that number multiplied by all of the positive numbers less than it. # For example, the factorial of 5 is 5x4x3x2x1 which equals 120. # You should, in your script, test the function by calling it with the values 5, 7, and 10. # First define function factorial(x) returning factorial of input x def factorial(x): result = x for a in range(x-1,1,-1): result = result * a return result # Test for numbers 5,7,10 for x in (5,7,10): print(f"{x}! = ",factorial(x)) # Results checked using scientifict calculator factorial function
def factorial(x): result = x for a in range(x - 1, 1, -1): result = result * a return result for x in (5, 7, 10): print(f'{x}! = ', factorial(x))
class Generic: def __init__(self, **kwargs): self.__dict__.update(kwargs)
class Generic: def __init__(self, **kwargs): self.__dict__.update(kwargs)
while True: if hero.canCast("regen"): bernardDistance = hero.distanceTo("Bernard") if bernardDistance < 10: hero.cast("regen", "Bernard") chandraDistance = hero.distanceTo("Chandra") if chandraDistance < 10: hero.cast("regen", "Chandra") else: enemy = hero.findNearestEnemy() if enemy and hero.distanceTo(enemy) <= hero.attackRange: hero.attack(enemy);
while True: if hero.canCast('regen'): bernard_distance = hero.distanceTo('Bernard') if bernardDistance < 10: hero.cast('regen', 'Bernard') chandra_distance = hero.distanceTo('Chandra') if chandraDistance < 10: hero.cast('regen', 'Chandra') else: enemy = hero.findNearestEnemy() if enemy and hero.distanceTo(enemy) <= hero.attackRange: hero.attack(enemy)
m=0 n=120120 while 1: c=0 for i in range(1,n+1): if (n*n)%i==0: #print("--------",i,(n*n)%i,(n*(n+i))%i) c+=1 if c>m: m=c print(n,m) if(m>=1000): break else: n+=20
m = 0 n = 120120 while 1: c = 0 for i in range(1, n + 1): if n * n % i == 0: c += 1 if c > m: m = c print(n, m) if m >= 1000: break else: n += 20
"""Configuration File for pyCon server and client""" HOST = '127.0.0.1' PORT = 8000 SERVER_ADDRESS = 'http://127.0.0.1:8000'
"""Configuration File for pyCon server and client""" host = '127.0.0.1' port = 8000 server_address = 'http://127.0.0.1:8000'
# 3Sum fixes one number and uses either the two pointers pattern or a hash set to find complementary pairs. Thus, the time complexity is O(N^2) # Two Pointers class Solution: def threeSumClosest(self, nums: List[int], target: int) -> int: diff = float('inf') nums.sort() for i in range(len(nums)): # set up two pointers lo, hi = i+1,len(nums)-1 while (lo<hi): sum = nums[i]+nums[lo]+nums[hi] if abs(target - sum) < abs(diff): diff = target - sum if sum < target: lo+=1 else: hi-=1 if diff == 0: break return target - diff # Time: O(N^2): O(NlogN + N^2) # Space:O(logN) to O(N)
class Solution: def three_sum_closest(self, nums: List[int], target: int) -> int: diff = float('inf') nums.sort() for i in range(len(nums)): (lo, hi) = (i + 1, len(nums) - 1) while lo < hi: sum = nums[i] + nums[lo] + nums[hi] if abs(target - sum) < abs(diff): diff = target - sum if sum < target: lo += 1 else: hi -= 1 if diff == 0: break return target - diff
# mypy: allow-untyped-defs class EventListener: def __init__(self, dispatcher_token): super().__init__() self.dispatcher_token = dispatcher_token self.token = None def send_message(self, message): raise Exception("Client.send_message(message) not implemented!")
class Eventlistener: def __init__(self, dispatcher_token): super().__init__() self.dispatcher_token = dispatcher_token self.token = None def send_message(self, message): raise exception('Client.send_message(message) not implemented!')
class SkuItem(): def __init__(self, id, lookup, other_offers=None) -> None: self._id = id self._lookup = lookup self._unrelated_offers = other_offers if other_offers is not None else {} def _calc_free_unrealted_items(self, count): res = {} for other_id, other_count in self._unrelated_offers.items(): if other_id == self._id: continue # count how many free there should be res[other_id] = count//other_count return res def calculate_cost(self, items_count: int) -> int: items_cost = 0 if self._id in self._unrelated_offers: # check how many free Fs by checking groups of (2+1) offer_counts = items_count // (self._unrelated_offers[self._id] + 1) # apply cost with reduced effective count items_cost += self._lookup[1]*(items_count - offer_counts) else: remaining_count = items_count offer_amounts = list(self._lookup.keys()) offer_amounts.sort(reverse=True) for offer_units in offer_amounts: offer_collection_price = self._lookup[offer_units] speacials_count = remaining_count // offer_units remaining_count = remaining_count % offer_units items_cost += speacials_count*offer_collection_price assert remaining_count == 0 return items_cost, self._calc_free_unrealted_items(items_count)
class Skuitem: def __init__(self, id, lookup, other_offers=None) -> None: self._id = id self._lookup = lookup self._unrelated_offers = other_offers if other_offers is not None else {} def _calc_free_unrealted_items(self, count): res = {} for (other_id, other_count) in self._unrelated_offers.items(): if other_id == self._id: continue res[other_id] = count // other_count return res def calculate_cost(self, items_count: int) -> int: items_cost = 0 if self._id in self._unrelated_offers: offer_counts = items_count // (self._unrelated_offers[self._id] + 1) items_cost += self._lookup[1] * (items_count - offer_counts) else: remaining_count = items_count offer_amounts = list(self._lookup.keys()) offer_amounts.sort(reverse=True) for offer_units in offer_amounts: offer_collection_price = self._lookup[offer_units] speacials_count = remaining_count // offer_units remaining_count = remaining_count % offer_units items_cost += speacials_count * offer_collection_price assert remaining_count == 0 return (items_cost, self._calc_free_unrealted_items(items_count))
n = int(input()) values = [int(input()) for _ in range(n)] values_10_20 = [value for value in values if value >= 10 and value <= 20] print('{} in'.format(len(values_10_20))) print('{} out'.format(len(values) - len(values_10_20)))
n = int(input()) values = [int(input()) for _ in range(n)] values_10_20 = [value for value in values if value >= 10 and value <= 20] print('{} in'.format(len(values_10_20))) print('{} out'.format(len(values) - len(values_10_20)))
class SessionHelper: def __init__(self, app): self.app = app def login(self, username, password): driver = self.app.driver self.app.open_page() driver.find_element_by_name("username").click() driver.find_element_by_name("username").clear() driver.find_element_by_name("username").send_keys(username) driver.find_element_by_xpath("//div/div").click() driver.find_element_by_name("password").click() driver.find_element_by_name("password").clear() driver.find_element_by_name("password").send_keys(password) driver.find_element_by_xpath("//button[@type='submit']").click() def logout(self): driver = self.app.driver driver.find_element_by_xpath("//div[@id='app']/aside/div[2]/div/div[2]/div/div/div/div").click() driver.find_element_by_xpath("//button[@type='submit']").click() def is_logged_in(self): driver = self.app.driver return len(driver.find_elements_by_xpath("//button[@type='submit']")) > 0 def is_logged_in_as(self, username): driver = self.app.driver return driver.find_element_by_xpath("//div[@id='app']/aside/div[2]/div/div[2]/div/div/div/div").text == username def ensure_logout(self): driver = self.app.driver if self.is_logged_in(): self.logout() def ensure_login(self, username, password): driver = self.app.driver if self.is_logged_in(): if self.is_logged_in_as(username): return else: self.logout() self.login(username, password)
class Sessionhelper: def __init__(self, app): self.app = app def login(self, username, password): driver = self.app.driver self.app.open_page() driver.find_element_by_name('username').click() driver.find_element_by_name('username').clear() driver.find_element_by_name('username').send_keys(username) driver.find_element_by_xpath('//div/div').click() driver.find_element_by_name('password').click() driver.find_element_by_name('password').clear() driver.find_element_by_name('password').send_keys(password) driver.find_element_by_xpath("//button[@type='submit']").click() def logout(self): driver = self.app.driver driver.find_element_by_xpath("//div[@id='app']/aside/div[2]/div/div[2]/div/div/div/div").click() driver.find_element_by_xpath("//button[@type='submit']").click() def is_logged_in(self): driver = self.app.driver return len(driver.find_elements_by_xpath("//button[@type='submit']")) > 0 def is_logged_in_as(self, username): driver = self.app.driver return driver.find_element_by_xpath("//div[@id='app']/aside/div[2]/div/div[2]/div/div/div/div").text == username def ensure_logout(self): driver = self.app.driver if self.is_logged_in(): self.logout() def ensure_login(self, username, password): driver = self.app.driver if self.is_logged_in(): if self.is_logged_in_as(username): return else: self.logout() self.login(username, password)
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None """ timecomplexity= O(n) spacecomplexity = O(n) serialize construct recusive function to covert tree into string replace None by '# ' and use ' ' to separate each node deserialize At first, define a list which element is from the string split ' ', then check special tase if len is 0 or only '#' in the List construct recusive function to get tree node from the List by pop the [0] from it. """ class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ def rserialize(root,string): if root == None: string += '# ' else: string += str(root.val) + ' ' string = rserialize(root.left,string) string = rserialize(root.right, string) return string string = rserialize(root, '') return string def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ def rdeserialize(l): if len(l) == 0: return if l[0] == '#': l.pop(0) return None root = TreeNode(l[0]) l.pop(0) root.left = rdeserialize(l) root.right = rdeserialize(l) return root data_list = data.split(' ') return rdeserialize(data_list) # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.deserialize(codec.serialize(root))
""" timecomplexity= O(n) spacecomplexity = O(n) serialize construct recusive function to covert tree into string replace None by '# ' and use ' ' to separate each node deserialize At first, define a list which element is from the string split ' ', then check special tase if len is 0 or only '#' in the List construct recusive function to get tree node from the List by pop the [0] from it. """ class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str """ def rserialize(root, string): if root == None: string += '# ' else: string += str(root.val) + ' ' string = rserialize(root.left, string) string = rserialize(root.right, string) return string string = rserialize(root, '') return string def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ def rdeserialize(l): if len(l) == 0: return if l[0] == '#': l.pop(0) return None root = tree_node(l[0]) l.pop(0) root.left = rdeserialize(l) root.right = rdeserialize(l) return root data_list = data.split(' ') return rdeserialize(data_list)
# -*- coding: utf-8 -*- __version__ = '0.0.2' __author__ = 'matteo vezzola <matteo@studioripiu.it>' default_app_config = 'ripiu.cmsplugin_vivus.apps.VivusConfig'
__version__ = '0.0.2' __author__ = 'matteo vezzola <matteo@studioripiu.it>' default_app_config = 'ripiu.cmsplugin_vivus.apps.VivusConfig'
''' Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram. Time Complexity : O(N^2) ''' def Largest_Rectangle_In_Histogram(height): height.append(0) res = 0 st = [-1] for i in range(len(height)): # store the heights in increasing order in the stack while height[i]<height[st[-1]]: h = height[st.pop()] w = i - st[-1] - 1 res = max(res,h*w) st.append(i) height.pop() return res height = [2,1,5,6,2,3] print(Largest_Rectangle_In_Histogram(height))
""" Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram. Time Complexity : O(N^2) """ def largest__rectangle__in__histogram(height): height.append(0) res = 0 st = [-1] for i in range(len(height)): while height[i] < height[st[-1]]: h = height[st.pop()] w = i - st[-1] - 1 res = max(res, h * w) st.append(i) height.pop() return res height = [2, 1, 5, 6, 2, 3] print(largest__rectangle__in__histogram(height))
"""Gazebo colors. https://bitbucket.org/osrf/gazebo/src/default/media/materials/scripts/gazebo.material?fileviewer=file-view-default#gazebo.material-129 """ materials = { 'Gazebo/Grey': { 'ambient': [0.3, 0.3, 0.3, 1.0], 'diffuse': [0.7, 0.7, 0.7, 1.0], 'specular': [0.01, 0.01, 0.01, 1.0] }, 'Gazebo/Gray': { 'ambient': [0.3, 0.3, 0.3, 1.0], 'diffuse': [0.7, 0.7, 0.7, 1.0], 'specular': [0.01, 0.01, 0.01, 1.0] }, 'Gazebo/DarkGrey': { 'ambient': [0.175, 0.175, 0.175, 1.0], 'diffuse': [0.175, 0.175, 0.175, 1.0], 'specular': [0.175, 0.175, 0.175, 1.0] }, 'Gazebo/DarkGray': { 'ambient': [0.175, 0.175, 0.175, 1.0], 'diffuse': [0.175, 0.175, 0.175, 1.0], 'specular': [0.175, 0.175, 0.175, 1.0] }, 'Gazebo/White': { 'ambient': [1, 1, 1, 1], 'diffuse': [1, 1, 1, 1], 'specular': [0.1, 0.1, 0.1, 1] }, 'Gazebo/FlatBlack': { 'ambient': [0.1, 0.1, 0.1, 1], 'diffuse': [0.1, 0.1, 0.1, 1], 'specular': [0.01, 0.01, 0.01, 1.0] }, 'Gazebo/Black': { 'ambient': [0, 0, 0, 1], 'diffuse': [0, 0, 0, 1], 'specular': [0.1, 0.1, 0.1, 1] }, 'Gazebo/Red': { 'ambient': [1, 0, 0, 1], 'diffuse': [1, 0, 0, 1], 'specular': [0.1, 0.1, 0.1, 1] }, 'Gazebo/RedBright': { 'ambient': [0.87, 0.26, 0.07, 1], 'diffuse': [0.87, 0.26, 0.07, 1], 'specular': [0.87, 0.26, 0.07, 1] }, 'Gazebo/Green': { 'ambient': [0, 1, 0, 1], 'diffuse': [0, 1, 0, 1], 'specular': [0.1, 0.1, 0.1, 1] }, 'Gazebo/Blue': { 'ambient': [0, 0, 1, 1], 'diffuse': [0, 0, 1, 1], 'specular': [0.1, 0.1, 0.1, 1] }, 'Gazebo/SkyBlue': { 'ambient': [0.13, 0.44, 0.70, 1], 'diffuse': [0, 0, 1, 1], 'specular': [0.1, 0.1, 0.1, 1] }, 'Gazebo/Yellow': { 'ambient': [1, 1, 0, 1], 'diffuse': [1, 1, 0, 1], 'specular': [0, 0, 0, 1] }, 'Gazebo/ZincYellow': { 'ambient': [0.9725, 0.9529, 0.2078, 1], 'diffuse': [0.9725, 0.9529, 0.2078, 1], 'specular': [0.9725, 0.9529, 0.2078, 1] }, 'Gazebo/DarkYellow': { 'ambient': [0.7, 0.7, 0, 1], 'diffuse': [0.7, 0.7, 0, 1], 'specular': [0, 0, 0, 1] }, 'Gazebo/Purple': { 'ambient': [1, 0, 1, 1], 'diffuse': [1, 0, 1, 1], 'emissive': [1, 0, 1, 1] }, 'Gazebo/Turquoise': { 'ambient': [0, 1, 1, 1], 'diffuse': [0, 1, 1, 1], 'specular': [0.1, 0.1, 0.1, 1] }, 'Gazebo/Orange': { 'ambient': [1, 0.5088, 0.0468, 1], 'diffuse': [1, 0.5088, 0.0468, 1], 'specular': [0.5, 0.5, 0.5, 1] }, 'Gazebo/Indigo': { 'ambient': [0.33, 0.0, 0.5, 1], 'diffuse': [0.33, 0.0, 0.5, 1], 'specular': [0.1, 0.1, 0.1, 1] } }
"""Gazebo colors. https://bitbucket.org/osrf/gazebo/src/default/media/materials/scripts/gazebo.material?fileviewer=file-view-default#gazebo.material-129 """ materials = {'Gazebo/Grey': {'ambient': [0.3, 0.3, 0.3, 1.0], 'diffuse': [0.7, 0.7, 0.7, 1.0], 'specular': [0.01, 0.01, 0.01, 1.0]}, 'Gazebo/Gray': {'ambient': [0.3, 0.3, 0.3, 1.0], 'diffuse': [0.7, 0.7, 0.7, 1.0], 'specular': [0.01, 0.01, 0.01, 1.0]}, 'Gazebo/DarkGrey': {'ambient': [0.175, 0.175, 0.175, 1.0], 'diffuse': [0.175, 0.175, 0.175, 1.0], 'specular': [0.175, 0.175, 0.175, 1.0]}, 'Gazebo/DarkGray': {'ambient': [0.175, 0.175, 0.175, 1.0], 'diffuse': [0.175, 0.175, 0.175, 1.0], 'specular': [0.175, 0.175, 0.175, 1.0]}, 'Gazebo/White': {'ambient': [1, 1, 1, 1], 'diffuse': [1, 1, 1, 1], 'specular': [0.1, 0.1, 0.1, 1]}, 'Gazebo/FlatBlack': {'ambient': [0.1, 0.1, 0.1, 1], 'diffuse': [0.1, 0.1, 0.1, 1], 'specular': [0.01, 0.01, 0.01, 1.0]}, 'Gazebo/Black': {'ambient': [0, 0, 0, 1], 'diffuse': [0, 0, 0, 1], 'specular': [0.1, 0.1, 0.1, 1]}, 'Gazebo/Red': {'ambient': [1, 0, 0, 1], 'diffuse': [1, 0, 0, 1], 'specular': [0.1, 0.1, 0.1, 1]}, 'Gazebo/RedBright': {'ambient': [0.87, 0.26, 0.07, 1], 'diffuse': [0.87, 0.26, 0.07, 1], 'specular': [0.87, 0.26, 0.07, 1]}, 'Gazebo/Green': {'ambient': [0, 1, 0, 1], 'diffuse': [0, 1, 0, 1], 'specular': [0.1, 0.1, 0.1, 1]}, 'Gazebo/Blue': {'ambient': [0, 0, 1, 1], 'diffuse': [0, 0, 1, 1], 'specular': [0.1, 0.1, 0.1, 1]}, 'Gazebo/SkyBlue': {'ambient': [0.13, 0.44, 0.7, 1], 'diffuse': [0, 0, 1, 1], 'specular': [0.1, 0.1, 0.1, 1]}, 'Gazebo/Yellow': {'ambient': [1, 1, 0, 1], 'diffuse': [1, 1, 0, 1], 'specular': [0, 0, 0, 1]}, 'Gazebo/ZincYellow': {'ambient': [0.9725, 0.9529, 0.2078, 1], 'diffuse': [0.9725, 0.9529, 0.2078, 1], 'specular': [0.9725, 0.9529, 0.2078, 1]}, 'Gazebo/DarkYellow': {'ambient': [0.7, 0.7, 0, 1], 'diffuse': [0.7, 0.7, 0, 1], 'specular': [0, 0, 0, 1]}, 'Gazebo/Purple': {'ambient': [1, 0, 1, 1], 'diffuse': [1, 0, 1, 1], 'emissive': [1, 0, 1, 1]}, 'Gazebo/Turquoise': {'ambient': [0, 1, 1, 1], 'diffuse': [0, 1, 1, 1], 'specular': [0.1, 0.1, 0.1, 1]}, 'Gazebo/Orange': {'ambient': [1, 0.5088, 0.0468, 1], 'diffuse': [1, 0.5088, 0.0468, 1], 'specular': [0.5, 0.5, 0.5, 1]}, 'Gazebo/Indigo': {'ambient': [0.33, 0.0, 0.5, 1], 'diffuse': [0.33, 0.0, 0.5, 1], 'specular': [0.1, 0.1, 0.1, 1]}}
class SetSettings: def __init__(self, token: str, version: int = 1): self.token: str = token self.version: int = version self.headers: dict = dict(Authorization=self.token) self.url: str = 'http://devapi.set.uz' self.main_api: str = f'{self.url}/api/v{self.version}/integration'
class Setsettings: def __init__(self, token: str, version: int=1): self.token: str = token self.version: int = version self.headers: dict = dict(Authorization=self.token) self.url: str = 'http://devapi.set.uz' self.main_api: str = f'{self.url}/api/v{self.version}/integration'
#!/usr/bin/env python # -*- coding:utf-8 -*- # file:__init__.py.py # author:PigKinght # datetime:2021/8/26 15:26 # software: PyCharm """ this is function description """
""" this is function description """
def trailingZeroes(n): res = 0 i = 5 while i <= n: res+= n//i i*=5 return res n = 30 print("Number of Zeros in factorial of {0} is ".format(n),trailingZeroes(n))
def trailing_zeroes(n): res = 0 i = 5 while i <= n: res += n // i i *= 5 return res n = 30 print('Number of Zeros in factorial of {0} is '.format(n), trailing_zeroes(n))
# Given the names and grades for each student in a Physics class of N students, # store them in a nested list and print the name(s) of any student(s) having the second lowest grade. # Note: If there are multiple students with the same grade, order their names alphabetically # and print each name on a new line. # # Input Format # The first line contains an integer, N, the number of students. # The 2N subsequent lines describe each student over 2 lines; # the first line contains a student's name, and the second line contains their grade. # # Constraints # 2 <= N <= 5 # There will always be one or more students having the second lowest grade. # Output Format # Print the name(s) of any student(s) having the second lowest grade in Physics; # if there are multiple students, order their names alphabetically and print each one on a new line. # # Sample Input # 5 # Harry # 37.21 # Berry # 37.21 # Tina # 37.2 # Akriti # 41 # Harsh # 39 # # Sample Output # Berry # Harry # inputs students_quantity = int(input()) students = [[str(input()), float(input())] for i in range(students_quantity)] # get the lowest grade and remove all occurences of it from the list of grades lowest_grade = min([grade for name, grade in students]) grades = [grade for name, grade in students] lowest_grade_count = grades.count(lowest_grade) for i in range(lowest_grade_count): grades.remove(lowest_grade) # get the second lowest grade and # check which students have this grade second_lowest_grade = min(grades) second_lowest_grade_students = [name for name, grade in students if grade == second_lowest_grade] second_lowest_grade_students.sort() # print in alphabetical order the students names for student_name in second_lowest_grade_students: print(student_name)
students_quantity = int(input()) students = [[str(input()), float(input())] for i in range(students_quantity)] lowest_grade = min([grade for (name, grade) in students]) grades = [grade for (name, grade) in students] lowest_grade_count = grades.count(lowest_grade) for i in range(lowest_grade_count): grades.remove(lowest_grade) second_lowest_grade = min(grades) second_lowest_grade_students = [name for (name, grade) in students if grade == second_lowest_grade] second_lowest_grade_students.sort() for student_name in second_lowest_grade_students: print(student_name)
class Joueur(): def __init__(self, tour): self._score = 0 self._tour = tour self.listeCouleurs = [] def getScore(self): return self._score def ajouterScore(self, valeur): self._score += valeur def getTour(self): return self._tour def setTour(self, tour): self._tour = tour def getCouleurs(self): return self.listeCouleurs def ajouterCouleur(self, couleur): self.listeCouleurs.append(couleur) def getNombreCouleurs(self): return len(self.listeCouleurs)
class Joueur: def __init__(self, tour): self._score = 0 self._tour = tour self.listeCouleurs = [] def get_score(self): return self._score def ajouter_score(self, valeur): self._score += valeur def get_tour(self): return self._tour def set_tour(self, tour): self._tour = tour def get_couleurs(self): return self.listeCouleurs def ajouter_couleur(self, couleur): self.listeCouleurs.append(couleur) def get_nombre_couleurs(self): return len(self.listeCouleurs)
__all__ = [ 'base_controller', 'mail_send_controller', 'events_controller', 'stats_controller', 'subaccounts_controller', 'subaccounts_delete_controller', 'subaccounts_get_sub_accounts_controller', 'setrecurringcreditddetails_controller', 'subaccounts_setsubaccountcredit_controller', 'subaccounts_update_subaccount_controller', 'subaccounts_create_subaccount_controller', 'suppression_controller', 'domain_delete_controller', 'domain_controller', ]
__all__ = ['base_controller', 'mail_send_controller', 'events_controller', 'stats_controller', 'subaccounts_controller', 'subaccounts_delete_controller', 'subaccounts_get_sub_accounts_controller', 'setrecurringcreditddetails_controller', 'subaccounts_setsubaccountcredit_controller', 'subaccounts_update_subaccount_controller', 'subaccounts_create_subaccount_controller', 'suppression_controller', 'domain_delete_controller', 'domain_controller']
def upper_case_name(name): return name.upper() if __name__ == "__main__": name = "Nina" name_upper = upper_case_name(name) print(f"Upper case name is {name_upper}") print("dunder name", __name__)
def upper_case_name(name): return name.upper() if __name__ == '__main__': name = 'Nina' name_upper = upper_case_name(name) print(f'Upper case name is {name_upper}') print('dunder name', __name__)
# Source : https://leetcode.com/problems/find-all-the-lonely-nodes/ # Author : foxfromworld # Date : 13/11/2021 # First attempt # 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 getLonelyNodes(self, root: Optional[TreeNode]) -> List[int]: def help(node, ret): if not node: return if not node.left and node.right: ret.append(node.right.val) if not node.right and node.left: ret.append(node.left.val) help(node.left, ret) help(node.right, ret) ret = [] help(root, ret) return ret
class Solution: def get_lonely_nodes(self, root: Optional[TreeNode]) -> List[int]: def help(node, ret): if not node: return if not node.left and node.right: ret.append(node.right.val) if not node.right and node.left: ret.append(node.left.val) help(node.left, ret) help(node.right, ret) ret = [] help(root, ret) return ret
class Solution: def numSquareSum(self, n): squareSum = 0 while(n): squareSum += (n % 10) * (n % 10) n = int(n / 10) return squareSum def isHappy(self, n: int) -> bool: # initialize slow # and fast by n slow, fast = n while(True): # move slow number # by one iteration slow = self.numSquareSum(slow) # move fast number # by two iteration fast = self.numSquareSum(self.numSquareSum(fast)) if(slow != fast): continue else: break # if both number meet at 1, # then return true return (slow == 1)
class Solution: def num_square_sum(self, n): square_sum = 0 while n: square_sum += n % 10 * (n % 10) n = int(n / 10) return squareSum def is_happy(self, n: int) -> bool: (slow, fast) = n while True: slow = self.numSquareSum(slow) fast = self.numSquareSum(self.numSquareSum(fast)) if slow != fast: continue else: break return slow == 1
# Patick Corcoran # Chekc if a number is prime. # The primes are 2, 3, 5, 7, 11, 13, ... p = 347 isprime = True for m in range(2, p-1): if p % m == 0: isprime = False break if isprime: print(p, "is a prime number.") else: print(p, "is not prime,")
p = 347 isprime = True for m in range(2, p - 1): if p % m == 0: isprime = False break if isprime: print(p, 'is a prime number.') else: print(p, 'is not prime,')
# Leo colorizer control file for yaml mode. # This file is in the public domain. # Properties for yaml mode. properties = { "indentNextLines": "\\s*([^\\s]+\\s*:|-)\\s*$", "indentSize": "2", "noTabs": "true", "tabSize": "2", "lineComment": "#", } # Attributes dict for yaml_main ruleset. yaml_main_attributes_dict = { "default": "null", "digit_re": "", "escape": "", "highlight_digits": "true", "ignore_case": "true", "no_word_sep": "", } # Dictionary of attributes dictionaries for yaml mode. attributesDictDict = { "yaml_main": yaml_main_attributes_dict, } # Keywords dict for yaml_main ruleset. yaml_main_keywords_dict = {} # Dictionary of keywords dictionaries for yaml mode. keywordsDictDict = { "yaml_main": yaml_main_keywords_dict, } # Rules for yaml_main ruleset. def yaml_rule0(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="comment1", regexp="\\s*#.*$", at_line_start=True, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule1(colorer, s, i): return colorer.match_seq(s, i, kind="label", seq="---", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule2(colorer, s, i): return colorer.match_seq(s, i, kind="label", seq="...", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule3(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="]", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule4(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="[", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule5(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="{", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule6(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="}", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule7(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="-", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule8(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="+", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule9(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="|", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule10(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq=">", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule11(colorer, s, i): return colorer.match_mark_following(s, i, kind="keyword2", pattern="&", at_line_start=False, at_whitespace_end=False, at_word_start=False, exclude_match=False) def yaml_rule12(colorer, s, i): return colorer.match_mark_following(s, i, kind="keyword2", pattern="*", at_line_start=False, at_whitespace_end=False, at_word_start=False, exclude_match=False) def yaml_rule13(colorer, s, i): # Fix #1082: # Old: regexp="\\s*(-|)?\\s*[^\\s]+\\s*:(\\s|$)" # Old: at_line_start=True. return colorer.match_seq_regexp(s, i, kind="keyword1", regexp=r"\s*-?\s*\w+:", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule14(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="literal2", regexp="\\s+~\\s*$", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule15(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="literal2", regexp="\\s+null\\s*$", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule16(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="literal2", regexp="\\s+true\\s*$", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule17(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="literal2", regexp="\\s+false\\s*$", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule18(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="literal2", regexp="\\s+yes\\s*$", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule19(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="literal2", regexp="\\s+no\\s*$", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule20(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="literal2", regexp="\\s+on\\s*$", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule21(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="literal2", regexp="\\s+off\\s*$", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule22(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="keyword2", regexp="!!(map|seq|str|set|omap|binary)", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule23(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="keyword3", regexp="!![^\\s]+", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def yaml_rule24(colorer, s, i): return colorer.match_seq_regexp(s, i, kind="keyword4", regexp="![^\\s]+", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") # Rules dict for yaml_main ruleset. rulesDict1 = { # EKR: \\s represents [\t\n\r\f\v], so the whitespace characters themselves, rather than a backspace, must be the leadin characters! # This is a bug in jEdit2py. "\t":[yaml_rule13,yaml_rule14,yaml_rule15,yaml_rule16,yaml_rule17,yaml_rule18,yaml_rule19,yaml_rule20,yaml_rule21,], "\n":[yaml_rule13,yaml_rule14,yaml_rule15,yaml_rule16,yaml_rule17,yaml_rule18,yaml_rule19,yaml_rule20,yaml_rule21,], " ": [yaml_rule13,yaml_rule14,yaml_rule15,yaml_rule16,yaml_rule17,yaml_rule18,yaml_rule19,yaml_rule20,yaml_rule21,], "#":[yaml_rule0,], "!": [yaml_rule22,yaml_rule23,yaml_rule24,], "&": [yaml_rule11,], "*": [yaml_rule12,], "+": [yaml_rule8,], "-": [yaml_rule1,yaml_rule7,yaml_rule13], # Fix #1082. ".": [yaml_rule2,], ">": [yaml_rule10,], "[": [yaml_rule4,], ## "\\": [yaml_rule13,yaml_rule14,yaml_rule15,yaml_rule16,yaml_rule17,yaml_rule18,yaml_rule19,yaml_rule20,yaml_rule21,], "]": [yaml_rule3,], "{": [yaml_rule5,], "|": [yaml_rule9,], "}": [yaml_rule6,], # Fix #1082. "A": [yaml_rule13,], "B": [yaml_rule13,], "C": [yaml_rule13,], "D": [yaml_rule13,], "E": [yaml_rule13,], "F": [yaml_rule13,], "G": [yaml_rule13,], "H": [yaml_rule13,], "I": [yaml_rule13,], "J": [yaml_rule13,], "K": [yaml_rule13,], "L": [yaml_rule13,], "M": [yaml_rule13,], "N": [yaml_rule13,], "O": [yaml_rule13,], "P": [yaml_rule13,], "Q": [yaml_rule13,], "R": [yaml_rule13,], "S": [yaml_rule13,], "T": [yaml_rule13,], "U": [yaml_rule13,], "V": [yaml_rule13,], "W": [yaml_rule13,], "X": [yaml_rule13,], "Y": [yaml_rule13,], "Z": [yaml_rule13,], "_": [yaml_rule13,], "a": [yaml_rule13,], "b": [yaml_rule13,], "c": [yaml_rule13,], "d": [yaml_rule13,], "e": [yaml_rule13,], "f": [yaml_rule13,], "g": [yaml_rule13,], "h": [yaml_rule13,], "i": [yaml_rule13,], "j": [yaml_rule13,], "k": [yaml_rule13,], "l": [yaml_rule13,], "m": [yaml_rule13,], "n": [yaml_rule13,], "o": [yaml_rule13,], "p": [yaml_rule13,], "q": [yaml_rule13,], "r": [yaml_rule13,], "s": [yaml_rule13,], "t": [yaml_rule13,], "u": [yaml_rule13,], "v": [yaml_rule13,], "w": [yaml_rule13,], "x": [yaml_rule13,], "y": [yaml_rule13,], "z": [yaml_rule13,], } # x.rulesDictDict for yaml mode. rulesDictDict = { "yaml_main": rulesDict1, } # Import dict for yaml mode. importDict = {}
properties = {'indentNextLines': '\\s*([^\\s]+\\s*:|-)\\s*$', 'indentSize': '2', 'noTabs': 'true', 'tabSize': '2', 'lineComment': '#'} yaml_main_attributes_dict = {'default': 'null', 'digit_re': '', 'escape': '', 'highlight_digits': 'true', 'ignore_case': 'true', 'no_word_sep': ''} attributes_dict_dict = {'yaml_main': yaml_main_attributes_dict} yaml_main_keywords_dict = {} keywords_dict_dict = {'yaml_main': yaml_main_keywords_dict} def yaml_rule0(colorer, s, i): return colorer.match_seq_regexp(s, i, kind='comment1', regexp='\\s*#.*$', at_line_start=True, at_whitespace_end=False, at_word_start=False, delegate='') def yaml_rule1(colorer, s, i): return colorer.match_seq(s, i, kind='label', seq='---', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def yaml_rule2(colorer, s, i): return colorer.match_seq(s, i, kind='label', seq='...', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def yaml_rule3(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq=']', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def yaml_rule4(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='[', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def yaml_rule5(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='{', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def yaml_rule6(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='}', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def yaml_rule7(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='-', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def yaml_rule8(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='+', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def yaml_rule9(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='|', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def yaml_rule10(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='>', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def yaml_rule11(colorer, s, i): return colorer.match_mark_following(s, i, kind='keyword2', pattern='&', at_line_start=False, at_whitespace_end=False, at_word_start=False, exclude_match=False) def yaml_rule12(colorer, s, i): return colorer.match_mark_following(s, i, kind='keyword2', pattern='*', at_line_start=False, at_whitespace_end=False, at_word_start=False, exclude_match=False) def yaml_rule13(colorer, s, i): return colorer.match_seq_regexp(s, i, kind='keyword1', regexp='\\s*-?\\s*\\w+:', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def yaml_rule14(colorer, s, i): return colorer.match_seq_regexp(s, i, kind='literal2', regexp='\\s+~\\s*$', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def yaml_rule15(colorer, s, i): return colorer.match_seq_regexp(s, i, kind='literal2', regexp='\\s+null\\s*$', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def yaml_rule16(colorer, s, i): return colorer.match_seq_regexp(s, i, kind='literal2', regexp='\\s+true\\s*$', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def yaml_rule17(colorer, s, i): return colorer.match_seq_regexp(s, i, kind='literal2', regexp='\\s+false\\s*$', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def yaml_rule18(colorer, s, i): return colorer.match_seq_regexp(s, i, kind='literal2', regexp='\\s+yes\\s*$', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def yaml_rule19(colorer, s, i): return colorer.match_seq_regexp(s, i, kind='literal2', regexp='\\s+no\\s*$', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def yaml_rule20(colorer, s, i): return colorer.match_seq_regexp(s, i, kind='literal2', regexp='\\s+on\\s*$', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def yaml_rule21(colorer, s, i): return colorer.match_seq_regexp(s, i, kind='literal2', regexp='\\s+off\\s*$', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def yaml_rule22(colorer, s, i): return colorer.match_seq_regexp(s, i, kind='keyword2', regexp='!!(map|seq|str|set|omap|binary)', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def yaml_rule23(colorer, s, i): return colorer.match_seq_regexp(s, i, kind='keyword3', regexp='!![^\\s]+', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def yaml_rule24(colorer, s, i): return colorer.match_seq_regexp(s, i, kind='keyword4', regexp='![^\\s]+', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') rules_dict1 = {'\t': [yaml_rule13, yaml_rule14, yaml_rule15, yaml_rule16, yaml_rule17, yaml_rule18, yaml_rule19, yaml_rule20, yaml_rule21], '\n': [yaml_rule13, yaml_rule14, yaml_rule15, yaml_rule16, yaml_rule17, yaml_rule18, yaml_rule19, yaml_rule20, yaml_rule21], ' ': [yaml_rule13, yaml_rule14, yaml_rule15, yaml_rule16, yaml_rule17, yaml_rule18, yaml_rule19, yaml_rule20, yaml_rule21], '#': [yaml_rule0], '!': [yaml_rule22, yaml_rule23, yaml_rule24], '&': [yaml_rule11], '*': [yaml_rule12], '+': [yaml_rule8], '-': [yaml_rule1, yaml_rule7, yaml_rule13], '.': [yaml_rule2], '>': [yaml_rule10], '[': [yaml_rule4], ']': [yaml_rule3], '{': [yaml_rule5], '|': [yaml_rule9], '}': [yaml_rule6], 'A': [yaml_rule13], 'B': [yaml_rule13], 'C': [yaml_rule13], 'D': [yaml_rule13], 'E': [yaml_rule13], 'F': [yaml_rule13], 'G': [yaml_rule13], 'H': [yaml_rule13], 'I': [yaml_rule13], 'J': [yaml_rule13], 'K': [yaml_rule13], 'L': [yaml_rule13], 'M': [yaml_rule13], 'N': [yaml_rule13], 'O': [yaml_rule13], 'P': [yaml_rule13], 'Q': [yaml_rule13], 'R': [yaml_rule13], 'S': [yaml_rule13], 'T': [yaml_rule13], 'U': [yaml_rule13], 'V': [yaml_rule13], 'W': [yaml_rule13], 'X': [yaml_rule13], 'Y': [yaml_rule13], 'Z': [yaml_rule13], '_': [yaml_rule13], 'a': [yaml_rule13], 'b': [yaml_rule13], 'c': [yaml_rule13], 'd': [yaml_rule13], 'e': [yaml_rule13], 'f': [yaml_rule13], 'g': [yaml_rule13], 'h': [yaml_rule13], 'i': [yaml_rule13], 'j': [yaml_rule13], 'k': [yaml_rule13], 'l': [yaml_rule13], 'm': [yaml_rule13], 'n': [yaml_rule13], 'o': [yaml_rule13], 'p': [yaml_rule13], 'q': [yaml_rule13], 'r': [yaml_rule13], 's': [yaml_rule13], 't': [yaml_rule13], 'u': [yaml_rule13], 'v': [yaml_rule13], 'w': [yaml_rule13], 'x': [yaml_rule13], 'y': [yaml_rule13], 'z': [yaml_rule13]} rules_dict_dict = {'yaml_main': rulesDict1} import_dict = {}
# https://adventofcode.com/2020/day/8 def execute_code(code_lines: list[str]): """ Execute program code :param code_lines: code to execute given as lines of strings :return: (True, accumulator) if execution terminates; (False, accumulator) if it goes into an infinite loop """ accumulator = 0 code_pointer = 0 lines_executed = [] while True: if code_pointer in lines_executed: return False, accumulator if code_pointer == len(code_lines): return True, accumulator code_line = code_lines[code_pointer] instruction = code_line[:3] operand = int(code_line[4:]) lines_executed.append(code_pointer) if instruction == 'nop': code_pointer += 1 continue if instruction == 'acc': accumulator += operand code_pointer += 1 continue if instruction == 'jmp': code_pointer += operand continue exit(-1) infile = open('input.txt', 'r') lines = infile.readlines() infile.close() for i in range(len(lines)): line = lines[i] line_instruction = line[:3] if line_instruction == 'jmp': lines[i] = 'nop' + line[4:] execution_result, accumulator_result = execute_code(lines) if execution_result: print(accumulator_result) exit(0) lines[i] = line continue if line_instruction == 'nop': lines[i] = 'jmp' + line[4:] execution_result, accumulator_result = execute_code(lines) if execution_result: print(accumulator_result) exit(0) lines[i] = line continue exit(-1)
def execute_code(code_lines: list[str]): """ Execute program code :param code_lines: code to execute given as lines of strings :return: (True, accumulator) if execution terminates; (False, accumulator) if it goes into an infinite loop """ accumulator = 0 code_pointer = 0 lines_executed = [] while True: if code_pointer in lines_executed: return (False, accumulator) if code_pointer == len(code_lines): return (True, accumulator) code_line = code_lines[code_pointer] instruction = code_line[:3] operand = int(code_line[4:]) lines_executed.append(code_pointer) if instruction == 'nop': code_pointer += 1 continue if instruction == 'acc': accumulator += operand code_pointer += 1 continue if instruction == 'jmp': code_pointer += operand continue exit(-1) infile = open('input.txt', 'r') lines = infile.readlines() infile.close() for i in range(len(lines)): line = lines[i] line_instruction = line[:3] if line_instruction == 'jmp': lines[i] = 'nop' + line[4:] (execution_result, accumulator_result) = execute_code(lines) if execution_result: print(accumulator_result) exit(0) lines[i] = line continue if line_instruction == 'nop': lines[i] = 'jmp' + line[4:] (execution_result, accumulator_result) = execute_code(lines) if execution_result: print(accumulator_result) exit(0) lines[i] = line continue exit(-1)
def maybeBuildTrap(x, y): hero.moveXY(x, y) item = hero.findNearestItem() if item and item.type == "coin": hero.buildXY("fire-trap", x, y) while True: maybeBuildTrap(12, 56) maybeBuildTrap(68, 56) maybeBuildTrap(68, 12) maybeBuildTrap(12, 12)
def maybe_build_trap(x, y): hero.moveXY(x, y) item = hero.findNearestItem() if item and item.type == 'coin': hero.buildXY('fire-trap', x, y) while True: maybe_build_trap(12, 56) maybe_build_trap(68, 56) maybe_build_trap(68, 12) maybe_build_trap(12, 12)
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ n,m=map(int,input().split()) print(*[n//m]*(m-n%m)+[n//m+1]*(n%m))
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ (n, m) = map(int, input().split()) print(*[n // m] * (m - n % m) + [n // m + 1] * (n % m))
# The minimal set of static libraries for basic Skia functionality. { 'variables': { 'component_libs': [ 'core.gyp:core', 'effects.gyp:effects', 'images.gyp:images', 'opts.gyp:opts', 'ports.gyp:ports', 'sfnt.gyp:sfnt', 'utils.gyp:utils', ], 'conditions': [ [ 'skia_arch_type == "x86" and skia_os != "android"', { 'component_libs': [ 'opts.gyp:opts_ssse3', ], }], [ 'arm_neon == 1', { 'component_libs': [ 'opts.gyp:opts_neon', ], }], [ 'skia_gpu', { 'component_libs': [ 'gpu.gyp:skgpu', ], }], ], }, 'targets': [ { 'target_name': 'skia_lib', 'conditions': [ [ 'skia_shared_lib', { 'conditions': [ [ 'skia_os == "android"', { # The name skia will confuse the linker on android into using the system's libskia.so # instead of the one packaged with the apk. We simply choose a different name to fix # this. 'product_name': 'skia_android', }, { 'product_name': 'skia', }], ], 'type': 'shared_library', }, { 'type': 'none', }], ], 'dependencies': [ '<@(component_libs)', ], 'export_dependent_settings': [ '<@(component_libs)', ], }, ], } # Local Variables: # tab-width:2 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=2 shiftwidth=2:
{'variables': {'component_libs': ['core.gyp:core', 'effects.gyp:effects', 'images.gyp:images', 'opts.gyp:opts', 'ports.gyp:ports', 'sfnt.gyp:sfnt', 'utils.gyp:utils'], 'conditions': [['skia_arch_type == "x86" and skia_os != "android"', {'component_libs': ['opts.gyp:opts_ssse3']}], ['arm_neon == 1', {'component_libs': ['opts.gyp:opts_neon']}], ['skia_gpu', {'component_libs': ['gpu.gyp:skgpu']}]]}, 'targets': [{'target_name': 'skia_lib', 'conditions': [['skia_shared_lib', {'conditions': [['skia_os == "android"', {'product_name': 'skia_android'}, {'product_name': 'skia'}]], 'type': 'shared_library'}, {'type': 'none'}]], 'dependencies': ['<@(component_libs)'], 'export_dependent_settings': ['<@(component_libs)']}]}
# Memory reference instructions MRI = {"AND": ["0", "8"], "ADD": ["1", "9"], "LDA": ["2", "A"], "STA": ["3", "B"], "BUN": ["4", "C"], "BSA": ["5", "D"], "ISZ": ["6", "E"]} # Register reference instructions NON_MRI = {"CLA": 0x7800, "CLE": 0x7400, "CMA": 0x7200, "CME": 0x7100, "CIR": 0x7080, "CIL": 0x7040, "INC": 0x7020, "SPA": 0x7010, "SNA": 0x7008, "SZA": 0x7004, "SZE": 0x7002, "HLT": 0x7001, "INP": 0xF800, "OUT": 0xF400, "SKI": 0xF200, "SKO": 0xF100, "ION": 0xF080, "IOF": 0xF040} PSEUDO = ["ORG", "HEX", "DEC", "END"] ALONE_IN_LINE = ["CLA", "CLE", "CMA", "CME", "CIR", "CIL", "INC", "SPA", "SNA", "SZA", "SZE", "HLT", "INP", "OUT", "SKI", "SKO", "ION", "IOF", "END"]
mri = {'AND': ['0', '8'], 'ADD': ['1', '9'], 'LDA': ['2', 'A'], 'STA': ['3', 'B'], 'BUN': ['4', 'C'], 'BSA': ['5', 'D'], 'ISZ': ['6', 'E']} non_mri = {'CLA': 30720, 'CLE': 29696, 'CMA': 29184, 'CME': 28928, 'CIR': 28800, 'CIL': 28736, 'INC': 28704, 'SPA': 28688, 'SNA': 28680, 'SZA': 28676, 'SZE': 28674, 'HLT': 28673, 'INP': 63488, 'OUT': 62464, 'SKI': 61952, 'SKO': 61696, 'ION': 61568, 'IOF': 61504} pseudo = ['ORG', 'HEX', 'DEC', 'END'] alone_in_line = ['CLA', 'CLE', 'CMA', 'CME', 'CIR', 'CIL', 'INC', 'SPA', 'SNA', 'SZA', 'SZE', 'HLT', 'INP', 'OUT', 'SKI', 'SKO', 'ION', 'IOF', 'END']
nome = "Cristiano" for letra in nome: print(letra)
nome = 'Cristiano' for letra in nome: print(letra)
def square(aList): return map(lambda x: x**2, aList) def merge(listOne, listTwo): result = [] while listOne and listTwo: #while both the lists still have elements if listOne[0] < listTwo[0]: result.append(listOne.pop(0)) #pops the first element from listOne from listOne and adds it to result else: #listOne[0] == listTwo[0] or listTwo[0] < listOne[0] result.append(listTwo.pop(0)) #now one of the lists is empty and we can just add all the remaining contents of the nonempty list into result if listOne: result += listOne #concatenating lists is done with plus operator if listTwo: result += listTwo return result def get_break_index(aList): index = 0 #this will be the index at which we break the list in two for i in range(len(aList)): if aList[i] > 0: #it's a positive number! index = i #this is where the first positive number in the list is break #we break here so that index remains the first positive number in the list return index def challenge9(aList): break_index = get_break_index(aList) listOne = aList[0:break_index] #we know this will be the negative half listTwo = aList[break_index:] a = square(listOne)[::-1] #we need to reverse this since [-3,-2,-1] --> square --> [9,4,1] b = square(listTwo) return merge(a,b) # a = [-3,-2,0,3,4,6] # print challenge9(a)
def square(aList): return map(lambda x: x ** 2, aList) def merge(listOne, listTwo): result = [] while listOne and listTwo: if listOne[0] < listTwo[0]: result.append(listOne.pop(0)) else: result.append(listTwo.pop(0)) if listOne: result += listOne if listTwo: result += listTwo return result def get_break_index(aList): index = 0 for i in range(len(aList)): if aList[i] > 0: index = i break return index def challenge9(aList): break_index = get_break_index(aList) list_one = aList[0:break_index] list_two = aList[break_index:] a = square(listOne)[::-1] b = square(listTwo) return merge(a, b)
# Operators print('Module', 10%3) print('Exponential', 5**3) print('Floor division', 9//2) # Data types print(type(5)) print(type("Luis")) print(type(5.2)) # Condition num1 = 5 num2 = 7 if num1 > num2: print(num1, 'is bigger') else: print(num2, 'is bigger')
print('Module', 10 % 3) print('Exponential', 5 ** 3) print('Floor division', 9 // 2) print(type(5)) print(type('Luis')) print(type(5.2)) num1 = 5 num2 = 7 if num1 > num2: print(num1, 'is bigger') else: print(num2, 'is bigger')
class BaseCommand(): def __init__(self): self.pre_command() self.exec_command() self.post_command() def pre_command(self): return 0 def exec_command(self): return 0 def post_command(self): return 0 if __name__ == '__main__': cmd = BaseCommand()
class Basecommand: def __init__(self): self.pre_command() self.exec_command() self.post_command() def pre_command(self): return 0 def exec_command(self): return 0 def post_command(self): return 0 if __name__ == '__main__': cmd = base_command()
class MergeSort: def __init__(self): pass def sort(self, arr): self.mergesort(arr, 0, len(arr)-1) def mergesort(self, arr, left, right): if(left >= right): return mid = int((left+right)/2) self.mergesort(arr, left, mid) self.mergesort(arr, mid+1, right) self.merge(arr,left, right, mid) def merge(self, arr, left, right, mid): i = left j = mid+1 k = left temp = [0 for i in range(right+1)] while(i <= mid and j <= right): if(arr[i] < arr[j]): temp[k] = arr[i] k += 1 i += 1 else: temp[k] = arr[j] k += 1 j += 1 while(i <= mid): temp[k] = arr[i] k += 1 i += 1 while(j <= right): temp[k] = arr[j] k += 1 j += 1 for i in range(left, right+1): arr[i] = temp[i]
class Mergesort: def __init__(self): pass def sort(self, arr): self.mergesort(arr, 0, len(arr) - 1) def mergesort(self, arr, left, right): if left >= right: return mid = int((left + right) / 2) self.mergesort(arr, left, mid) self.mergesort(arr, mid + 1, right) self.merge(arr, left, right, mid) def merge(self, arr, left, right, mid): i = left j = mid + 1 k = left temp = [0 for i in range(right + 1)] while i <= mid and j <= right: if arr[i] < arr[j]: temp[k] = arr[i] k += 1 i += 1 else: temp[k] = arr[j] k += 1 j += 1 while i <= mid: temp[k] = arr[i] k += 1 i += 1 while j <= right: temp[k] = arr[j] k += 1 j += 1 for i in range(left, right + 1): arr[i] = temp[i]
# -*- coding: utf-8 -*- __version__ = '1.2.5' __author__ = 'G Adventures'
__version__ = '1.2.5' __author__ = 'G Adventures'
class Solution: def minDistance(self, word1, word2): """ :type word1: str :type word2: str :rtype: int """ m, n = len(word1)+1, len(word2)+1 dp = [[0 for _ in range(n)] for _ in range(m)] for i in range(m): dp[i][0] = i for i in range(n): dp[0][i] = i for i in range(1, m): for j in range(1, n): dp[i][j] = min(dp[i-1][j]+1, dp[i][j-1]+1) dp[i][j] = min(dp[i][j], dp[i-1][j-1] + (0 if word1[i-1] == word2[j-1] else 1)) return dp[m-1][n-1] if __name__ == "__main__": print(Solution().minDistance("horse", "aaahorse"))
class Solution: def min_distance(self, word1, word2): """ :type word1: str :type word2: str :rtype: int """ (m, n) = (len(word1) + 1, len(word2) + 1) dp = [[0 for _ in range(n)] for _ in range(m)] for i in range(m): dp[i][0] = i for i in range(n): dp[0][i] = i for i in range(1, m): for j in range(1, n): dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1) dp[i][j] = min(dp[i][j], dp[i - 1][j - 1] + (0 if word1[i - 1] == word2[j - 1] else 1)) return dp[m - 1][n - 1] if __name__ == '__main__': print(solution().minDistance('horse', 'aaahorse'))
''' Created on 2012. 8. 10. @author: root ''' class StaticTestingForm: header='' deviceConnection='' def __init__(self): self.header = '''import sys # Imports the monkeyrunner modules used by this program from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage''' self.deviceConnection = ''' # Connects to the current device, returning a MonkeyDevice object device = MonkeyRunner.waitForConnection() if not device: print >> sys.stderr, "Couldn't get connection" sys.exit(1) ''' def header(self): return self.header def deviceConnection(self): return self.deviceConnection
""" Created on 2012. 8. 10. @author: root """ class Statictestingform: header = '' device_connection = '' def __init__(self): self.header = 'import sys\n# Imports the monkeyrunner modules used by this program\nfrom com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage' self.deviceConnection = '\n# Connects to the current device, returning a MonkeyDevice object\ndevice = MonkeyRunner.waitForConnection()\n\nif not device:\n print >> sys.stderr, "Couldn\'t get connection"\n sys.exit(1)\n ' def header(self): return self.header def device_connection(self): return self.deviceConnection
{ 'name': 'prue01', 'description': 'Una aplicacion de facturacion.', 'author': 'Jose Antonio Duarte Perez', 'depends': ['mail'], 'application': True, 'data': ['views/contactos.xml'] }
{'name': 'prue01', 'description': 'Una aplicacion de facturacion.', 'author': 'Jose Antonio Duarte Perez', 'depends': ['mail'], 'application': True, 'data': ['views/contactos.xml']}
stack = [3, 4, 5] stack.append(6) stack.append(7) print(stack) print(stack.pop()) print(stack) print(stack.pop()) print(stack.pop()) print(stack)
stack = [3, 4, 5] stack.append(6) stack.append(7) print(stack) print(stack.pop()) print(stack) print(stack.pop()) print(stack.pop()) print(stack)
print('hi') s1 = input("input s1: ") s2 = input("input s2: ") print(s1) print(s2) shorter_length = 0 longer_s = '' if (len(s1) > len(s2)): shorter_length = len(s2) longer_s = s1 else: shorter_length = len(s1) longer_s = s2 result_s = '' for i in range(shorter_length): result_s += s1[i] + s2[i] for i in range(shorter_length, len(longer_s)): result_s += longer_s[i] print(result_s)
print('hi') s1 = input('input s1: ') s2 = input('input s2: ') print(s1) print(s2) shorter_length = 0 longer_s = '' if len(s1) > len(s2): shorter_length = len(s2) longer_s = s1 else: shorter_length = len(s1) longer_s = s2 result_s = '' for i in range(shorter_length): result_s += s1[i] + s2[i] for i in range(shorter_length, len(longer_s)): result_s += longer_s[i] print(result_s)
def a_function(x, y): if isinstance(x, float): if isinstance(y, float): z = x + y return z
def a_function(x, y): if isinstance(x, float): if isinstance(y, float): z = x + y return z
# mm => make mask dirty_imagename = "dirty/" + "RCrA_13CO_all_cube_dirty.image" beamsize_major = 7.889 beamsize_minor = 4.887 pa = -77.412 # find the RMS of a line free channel chanstat = imstat(imagename=dirty_imagename, chans="1") rms1 = chanstat["rms"][0] chanstat = imstat(imagename=dirty_imagename, chans="38") rms2 = chanstat["rms"][0] rms = 0.5 * (rms1 + rms2) print("rms = " + str(rms) + "Jy/beam") def make_mask(times_sigma): immath( imagename=dirty_imagename, expr="iif(IM0>" + str(times_sigma * rms) + ",1,0)", outfile="mask/" + str(times_sigma) + "sigma.im", ) imsmooth( imagename="mask/" + str(times_sigma) + "sigma.im", major=str(2 * beamsize_major) + "arcsec", minor=str(2 * beamsize_minor) + "arcsec", pa=str(pa) + "deg", outfile="mask/" + str(times_sigma) + "sigma.im.sm", ) immath( imagename="mask/" + str(times_sigma) + "sigma.im.sm", expr="iif(IM0>0.2,1,0)", outfile="mask/" + str(times_sigma) + "sigma_mask.im", ) make_mask(10)
dirty_imagename = 'dirty/' + 'RCrA_13CO_all_cube_dirty.image' beamsize_major = 7.889 beamsize_minor = 4.887 pa = -77.412 chanstat = imstat(imagename=dirty_imagename, chans='1') rms1 = chanstat['rms'][0] chanstat = imstat(imagename=dirty_imagename, chans='38') rms2 = chanstat['rms'][0] rms = 0.5 * (rms1 + rms2) print('rms = ' + str(rms) + 'Jy/beam') def make_mask(times_sigma): immath(imagename=dirty_imagename, expr='iif(IM0>' + str(times_sigma * rms) + ',1,0)', outfile='mask/' + str(times_sigma) + 'sigma.im') imsmooth(imagename='mask/' + str(times_sigma) + 'sigma.im', major=str(2 * beamsize_major) + 'arcsec', minor=str(2 * beamsize_minor) + 'arcsec', pa=str(pa) + 'deg', outfile='mask/' + str(times_sigma) + 'sigma.im.sm') immath(imagename='mask/' + str(times_sigma) + 'sigma.im.sm', expr='iif(IM0>0.2,1,0)', outfile='mask/' + str(times_sigma) + 'sigma_mask.im') make_mask(10)
# pseudo code taken from CLRS book # vertices is list of vertex in graph : [0, 1, 2, 3 ...] (must be continuous) # adjacencyList is the list whose 'i'th element is list of vertices adjacent to vertex i time = 0; class vertex: def __init__(self, adjVertices, color='White', parent='None', discovery_time=float('inf'), finishing_time=float('inf')): self.adjVertices = adjVertices; self.color = color; self.parent = parent; self.discovery_time = discovery_time; self.finishing_time = finishing_time; def topological_sort(vertices, adjacencyList): global time topological_order=[] vertices_objects = [ vertex(adjacencyList[v]) for v in vertices ] time = 0 for vert in vertices: if vertices_objects[vert].color == 'White': DFS_Visit(vert, vertices_objects, adjacencyList, topological_order) topological_order.reverse() for i in range(9): print (vertices_objects[i].discovery_time,vertices_objects[i].finishing_time) return topological_order def DFS_Visit(vertex, vertices, adjacencyList, topo_order): vertex_object = vertices[vertex] vertex_object.color = 'Gray' # Vertex just been discovered global time time = time + 1 vertex_object.discovery_time = time; for vert in adjacencyList[vertex]: if vertices[vert].color == 'White': vertices[vert].parent = vertex DFS_Visit(vert, vertices, adjacencyList, topo_order) vertex_object.color = 'Black' # Discovery of this vertex has been finished time = time + 1 vertex_object.finishing_time = time topo_order.append(vertex)
time = 0 class Vertex: def __init__(self, adjVertices, color='White', parent='None', discovery_time=float('inf'), finishing_time=float('inf')): self.adjVertices = adjVertices self.color = color self.parent = parent self.discovery_time = discovery_time self.finishing_time = finishing_time def topological_sort(vertices, adjacencyList): global time topological_order = [] vertices_objects = [vertex(adjacencyList[v]) for v in vertices] time = 0 for vert in vertices: if vertices_objects[vert].color == 'White': dfs__visit(vert, vertices_objects, adjacencyList, topological_order) topological_order.reverse() for i in range(9): print(vertices_objects[i].discovery_time, vertices_objects[i].finishing_time) return topological_order def dfs__visit(vertex, vertices, adjacencyList, topo_order): vertex_object = vertices[vertex] vertex_object.color = 'Gray' global time time = time + 1 vertex_object.discovery_time = time for vert in adjacencyList[vertex]: if vertices[vert].color == 'White': vertices[vert].parent = vertex dfs__visit(vert, vertices, adjacencyList, topo_order) vertex_object.color = 'Black' time = time + 1 vertex_object.finishing_time = time topo_order.append(vertex)
# Time: O(min(n, h)), per operation # Space: O(min(n, h)) class TrieNode(object): # Initialize your data structure here. def __init__(self): self.is_string = False self.leaves = {} class WordDictionary(object): def __init__(self): self.root = TrieNode() # @param {string} word # @return {void} # Adds a word into the data structure. def addWord(self, word): curr = self.root for c in word: if c not in curr.leaves: curr.leaves[c] = TrieNode() curr = curr.leaves[c] curr.is_string = True # @param {string} word # @return {boolean} # Returns if the word is in the data structure. A word could # contain the dot character '.' to represent any one letter. def search(self, word): return self.searchHelper(word, 0, self.root) def searchHelper(self, word, start, curr): if start == len(word): return curr.is_string if word[start] in curr.leaves: return self.searchHelper(word, start+1, curr.leaves[word[start]]) elif word[start] == '.': for c in curr.leaves: if self.searchHelper(word, start+1, curr.leaves[c]): return True return False
class Trienode(object): def __init__(self): self.is_string = False self.leaves = {} class Worddictionary(object): def __init__(self): self.root = trie_node() def add_word(self, word): curr = self.root for c in word: if c not in curr.leaves: curr.leaves[c] = trie_node() curr = curr.leaves[c] curr.is_string = True def search(self, word): return self.searchHelper(word, 0, self.root) def search_helper(self, word, start, curr): if start == len(word): return curr.is_string if word[start] in curr.leaves: return self.searchHelper(word, start + 1, curr.leaves[word[start]]) elif word[start] == '.': for c in curr.leaves: if self.searchHelper(word, start + 1, curr.leaves[c]): return True return False
""" TESTS is a dict with all you tests. Keys for this will be categories' names. Each test is dict with "input" -- input data for user function "answer" -- your right answer "explanation" -- not necessary key, it's using for additional info in animation. """ TESTS = { "Basics": [ { "input": ('d3', ('d6', 'b6', 'c8', 'g4', 'b8', 'g6')), "answer": 5, "explanation": ('d6', 'g6', 'b6', 'b8', 'c8') }, { "input": ('a2', ('f6', 'f2', 'a6', 'f8', 'h8', 'h6')), "answer": 6, "explanation": ('a6', 'f6', 'h6', 'h8', 'f8', 'f2') }, { "input": ('a2', ('f6', 'f8', 'f2', 'a6', 'h6')), "answer": 4, "explanation": ('a6', 'f6', 'f2', 'f8') }, ], "Extra": [ { "input": ('c5', ('h5',)), "answer": 1, "explanation": ('h5',) }, { "input": ('c5', ('e3', 'b6', 'e7', 'f2', 'd6', 'b4', 'g8', 'd4')), "answer": 0, "explanation": [] }, { "input": ('e5', ('e8', 'e2', 'h8', 'h5', 'b5', 'h2', 'b2', 'b8')), "answer": 8, "explanation": ('b5', 'b8', 'b2', 'e2', 'h2', 'h5', 'h8', 'e8') }, { "input": ('c5', ('a5', 'd5', 'g5', 'h5', 'b5', 'e5', 'f5')), "answer": 7, "explanation": ('b5', 'd5', 'e5', 'f5', 'g5', 'h5', 'a5') }, { "input": ('e1', ('e8', 'h1', 'c2', 'h5', 'e4', 'a1', 'e6', 'a3')), "answer": 3, "explanation": ('a1', 'h1', 'h5') }, { "input": ('h1', ('a5', 'b6', 'e2', 'a2', 'h5', 'e4', 'e6', 'h7')), "answer": 7, "explanation": ('h5', 'a5', 'a2', 'e2', 'e4', 'e6', 'b6') }, { "input": ('c7', ('d5', 'f7', 'e6', 'e7', 'c5', 'd6', 'e5', 'c6')), "answer": 8, "explanation": ('c6', 'd6', 'd5', 'c5', 'e5', 'e6', 'e7', 'f7') }, { "input": ('c7', ('d5', 'f7', 'e7', 'c5', 'd6', 'd4', 'c6', 'c4')), "answer": 6, "explanation": ('c6', 'd6', 'd5', 'd4', 'c4', 'c5') }, ] }
""" TESTS is a dict with all you tests. Keys for this will be categories' names. Each test is dict with "input" -- input data for user function "answer" -- your right answer "explanation" -- not necessary key, it's using for additional info in animation. """ tests = {'Basics': [{'input': ('d3', ('d6', 'b6', 'c8', 'g4', 'b8', 'g6')), 'answer': 5, 'explanation': ('d6', 'g6', 'b6', 'b8', 'c8')}, {'input': ('a2', ('f6', 'f2', 'a6', 'f8', 'h8', 'h6')), 'answer': 6, 'explanation': ('a6', 'f6', 'h6', 'h8', 'f8', 'f2')}, {'input': ('a2', ('f6', 'f8', 'f2', 'a6', 'h6')), 'answer': 4, 'explanation': ('a6', 'f6', 'f2', 'f8')}], 'Extra': [{'input': ('c5', ('h5',)), 'answer': 1, 'explanation': ('h5',)}, {'input': ('c5', ('e3', 'b6', 'e7', 'f2', 'd6', 'b4', 'g8', 'd4')), 'answer': 0, 'explanation': []}, {'input': ('e5', ('e8', 'e2', 'h8', 'h5', 'b5', 'h2', 'b2', 'b8')), 'answer': 8, 'explanation': ('b5', 'b8', 'b2', 'e2', 'h2', 'h5', 'h8', 'e8')}, {'input': ('c5', ('a5', 'd5', 'g5', 'h5', 'b5', 'e5', 'f5')), 'answer': 7, 'explanation': ('b5', 'd5', 'e5', 'f5', 'g5', 'h5', 'a5')}, {'input': ('e1', ('e8', 'h1', 'c2', 'h5', 'e4', 'a1', 'e6', 'a3')), 'answer': 3, 'explanation': ('a1', 'h1', 'h5')}, {'input': ('h1', ('a5', 'b6', 'e2', 'a2', 'h5', 'e4', 'e6', 'h7')), 'answer': 7, 'explanation': ('h5', 'a5', 'a2', 'e2', 'e4', 'e6', 'b6')}, {'input': ('c7', ('d5', 'f7', 'e6', 'e7', 'c5', 'd6', 'e5', 'c6')), 'answer': 8, 'explanation': ('c6', 'd6', 'd5', 'c5', 'e5', 'e6', 'e7', 'f7')}, {'input': ('c7', ('d5', 'f7', 'e7', 'c5', 'd6', 'd4', 'c6', 'c4')), 'answer': 6, 'explanation': ('c6', 'd6', 'd5', 'd4', 'c4', 'c5')}]}
class Damage(): def __init__(self, skill:float=1, added:float=1, dealing:float=1): self.__skill = skill self.__added = added self.__dealing = dealing def get_dmg(self): return (self.__skill, self.__added-1, self.__dealing) if __name__ == '__main__': dmg = Damage(1.15, 1.14, 1.18) print(dmg.get_dmg())
class Damage: def __init__(self, skill: float=1, added: float=1, dealing: float=1): self.__skill = skill self.__added = added self.__dealing = dealing def get_dmg(self): return (self.__skill, self.__added - 1, self.__dealing) if __name__ == '__main__': dmg = damage(1.15, 1.14, 1.18) print(dmg.get_dmg())
class Animal: def __init__(self, name): self.name = name self.fed_times = 0 self.groomed_times = 0 def feed(self, times): print("Fed {}".format(times)) self.fed_times += times return self.fed_times def groom(self, times): print("Groomed {} times".format(times)) self.groomed_times += times return self.groomed_times
class Animal: def __init__(self, name): self.name = name self.fed_times = 0 self.groomed_times = 0 def feed(self, times): print('Fed {}'.format(times)) self.fed_times += times return self.fed_times def groom(self, times): print('Groomed {} times'.format(times)) self.groomed_times += times return self.groomed_times
def main (): entry = int(input("Enter the number you want here : ")) prime = False #prime is defined as false and will change if entry number is a prime number. if entry > 1 : for numbers in range(2, entry): if (entry % numbers) == 0: # Check if entry number has a factor prime = True break if prime : print(entry, 'is not prime number!') else : print(entry, 'is a prime number') start = 0 finish = entry print("All prime numbers between the 0 and the enterded value are : ") for entry in range(start, finish + 1): # all prime numbers are greater than 1 if entry > 1: for numbers in range(2, entry): if (entry % numbers) == 0: break else: print(entry) main()
def main(): entry = int(input('Enter the number you want here : ')) prime = False if entry > 1: for numbers in range(2, entry): if entry % numbers == 0: prime = True break if prime: print(entry, 'is not prime number!') else: print(entry, 'is a prime number') start = 0 finish = entry print('All prime numbers between the 0 and the enterded value are : ') for entry in range(start, finish + 1): if entry > 1: for numbers in range(2, entry): if entry % numbers == 0: break else: print(entry) main()
#MaBe nomes = [] massas = [] while True: nome = input('Digite um nome: ').upper() massa = int(input('Digite a massa: ')) nomes.append(nome) massas.append(massa) r = input('Quer continuar? [s/n] ').lower() if r == 'n': break totcad = len(nomes) pesomai = max(massas) pesomin = min(massas) print(nomes) print(massas) print(f'{totcad} pessoas cadastradas.') print(f'O meior peso foi de {pesomai}kg. {nomes[massas.index(pesomai)]}.') print(f'O menor peso foi de {pesomin}kg. {nomes[massas.index(pesomin)]}.')
nomes = [] massas = [] while True: nome = input('Digite um nome: ').upper() massa = int(input('Digite a massa: ')) nomes.append(nome) massas.append(massa) r = input('Quer continuar? [s/n] ').lower() if r == 'n': break totcad = len(nomes) pesomai = max(massas) pesomin = min(massas) print(nomes) print(massas) print(f'{totcad} pessoas cadastradas.') print(f'O meior peso foi de {pesomai}kg. {nomes[massas.index(pesomai)]}.') print(f'O menor peso foi de {pesomin}kg. {nomes[massas.index(pesomin)]}.')
""" [2017-02-10] Challenge #302 [Hard] ASCII Histogram Maker: Part 2 - The Proper Histogram https://www.reddit.com/r/dailyprogrammer/comments/5t7l07/20170210_challenge_302_hard_ascii_histogram_maker/ # Description Most of us are familiar with the histogram chart - a representation of a frequency distribution by means of rectangles whose widths represent class intervals and whose areas are proportional to the corresponding frequencies. It is similar to a bar chart, but a histogram groups numbers into ranges. The area of the bar is the total frequency of all of the covered values in the range. # Input Description You'll be given four numbers on the first line telling you the start and end of the horizontal (X) axis and the vertical (Y) axis, respectively. The next line tells you the interval for the X-axis to use (the width of the bar). Then you'll have a number on a single line telling you how many records to read. Then you'll be given the data as 2 numbers: the first is the variable, the second number is the frequency of that variable. Example: 1 4 1 10 2 4 1 3 2 3 3 2 4 6 # Challenge Output Your program should emit an ASCII histogram plotting the data according to the specification - the size of the chart and the frequency of the X-axis variables. Example: 10 9 8 7 6 5 4 *** 3*** *** 2*** *** 1*** *** 1 2 3 4 # Challenge Input 0 40 0 100 8 40 1 56 2 40 3 4 4 67 5 34 6 48 7 7 8 45 9 50 10 54 11 20 12 24 13 44 14 44 15 49 16 28 17 94 18 37 19 46 20 64 21 100 22 43 23 23 24 100 25 15 26 81 27 19 28 92 29 9 30 21 31 88 32 31 33 55 34 87 35 63 36 88 37 76 38 41 39 100 40 6 """ def main(): pass if __name__ == "__main__": main()
""" [2017-02-10] Challenge #302 [Hard] ASCII Histogram Maker: Part 2 - The Proper Histogram https://www.reddit.com/r/dailyprogrammer/comments/5t7l07/20170210_challenge_302_hard_ascii_histogram_maker/ # Description Most of us are familiar with the histogram chart - a representation of a frequency distribution by means of rectangles whose widths represent class intervals and whose areas are proportional to the corresponding frequencies. It is similar to a bar chart, but a histogram groups numbers into ranges. The area of the bar is the total frequency of all of the covered values in the range. # Input Description You'll be given four numbers on the first line telling you the start and end of the horizontal (X) axis and the vertical (Y) axis, respectively. The next line tells you the interval for the X-axis to use (the width of the bar). Then you'll have a number on a single line telling you how many records to read. Then you'll be given the data as 2 numbers: the first is the variable, the second number is the frequency of that variable. Example: 1 4 1 10 2 4 1 3 2 3 3 2 4 6 # Challenge Output Your program should emit an ASCII histogram plotting the data according to the specification - the size of the chart and the frequency of the X-axis variables. Example: 10 9 8 7 6 5 4 *** 3*** *** 2*** *** 1*** *** 1 2 3 4 # Challenge Input 0 40 0 100 8 40 1 56 2 40 3 4 4 67 5 34 6 48 7 7 8 45 9 50 10 54 11 20 12 24 13 44 14 44 15 49 16 28 17 94 18 37 19 46 20 64 21 100 22 43 23 23 24 100 25 15 26 81 27 19 28 92 29 9 30 21 31 88 32 31 33 55 34 87 35 63 36 88 37 76 38 41 39 100 40 6 """ def main(): pass if __name__ == '__main__': main()
n = int(input()) for row in range(0, n): if row == 0 or row == n - 1: print('*' * 2 * n + ' ' * n + '*' * 2 * n) else: if row == ((n - 1) // 2): print('*' + '/' * 2 * (n - 1) + '*' + '|' * n + '*' + '/' * 2 * (n - 1) + '*') else: print('*' + '/' * 2 * (n - 1) + '*' + ' ' * n + '*' + '/' * 2 * (n - 1) + '*')
n = int(input()) for row in range(0, n): if row == 0 or row == n - 1: print('*' * 2 * n + ' ' * n + '*' * 2 * n) elif row == (n - 1) // 2: print('*' + '/' * 2 * (n - 1) + '*' + '|' * n + '*' + '/' * 2 * (n - 1) + '*') else: print('*' + '/' * 2 * (n - 1) + '*' + ' ' * n + '*' + '/' * 2 * (n - 1) + '*')
# Configuration file for ipython-kernel. # See <https://ipython.readthedocs.io/en/stable/config/options/kernel.html> # With IPython >= 6.0.0, all outputs to stdout/stderr are captured. # It is the case for subprocesses and output of compiled libraries like Spark. # Those logs now both head to notebook logs and in notebooks outputs. # Logs are particularly verbose with Spark, that is why we turn them off through this flag. # <https://github.com/jupyter/docker-stacks/issues/1423> # Attempt to capture and forward low-level output, e.g. produced by Extension # libraries. # Default: True # type:ignore c.IPKernelApp.capture_fd_output = False # noqa: F821
c.IPKernelApp.capture_fd_output = False
# Copyright (C) 2001 Python Software Foundation __version__ = '0.4' __all__ = ['Errors', 'Generator', 'Image', 'MIMEBase', 'Message', 'MsgReader', 'Parser', 'StringableMixin', 'Text', 'address', 'date', ]
__version__ = '0.4' __all__ = ['Errors', 'Generator', 'Image', 'MIMEBase', 'Message', 'MsgReader', 'Parser', 'StringableMixin', 'Text', 'address', 'date']
""" Search In Sorted Matrix: You're given a two-dimensional array (a matrix) of distinct integers and a target integer. Each row in the matrix is sorted, and each column is also sorted; the matrix doesn't necessarily have the same height and width. Write a function that returns an array of the row and column indices of the target integer if it's contained in the matrix, otherwise [-1, -1]. Sample Input: matrix = [ [1, 4, 7, 12, 15, 1000], [2, 5, 19, 31, 32, 1001], [3, 8, 24, 33, 35, 1002], [40, 41, 42, 44, 45, 1003], [99, 100, 103, 106, 128, 1004], ] target = 44 Sample Output: [3, 3] https://www.algoexpert.io/questions/Search%20In%20Sorted%20Matrix """ def searchInSortedMatrix(matrix, target): # start at top right row = 0 col = len(matrix[0]) - 1 while row < len(matrix) and col >= 0: if matrix[row][col] > target: col -= 1 # move left elif matrix[row][col] < target: row += 1 # move down else: return[row, col] return[-1, -1]
""" Search In Sorted Matrix: You're given a two-dimensional array (a matrix) of distinct integers and a target integer. Each row in the matrix is sorted, and each column is also sorted; the matrix doesn't necessarily have the same height and width. Write a function that returns an array of the row and column indices of the target integer if it's contained in the matrix, otherwise [-1, -1]. Sample Input: matrix = [ [1, 4, 7, 12, 15, 1000], [2, 5, 19, 31, 32, 1001], [3, 8, 24, 33, 35, 1002], [40, 41, 42, 44, 45, 1003], [99, 100, 103, 106, 128, 1004], ] target = 44 Sample Output: [3, 3] https://www.algoexpert.io/questions/Search%20In%20Sorted%20Matrix """ def search_in_sorted_matrix(matrix, target): row = 0 col = len(matrix[0]) - 1 while row < len(matrix) and col >= 0: if matrix[row][col] > target: col -= 1 elif matrix[row][col] < target: row += 1 else: return [row, col] return [-1, -1]
# entrada v1 v1 = float(input()) # entrada v2 v2 = float(input()) # entrada v3 v3 = float(input()) # entrada v4 v4 = float(input()) # entrada v5 v5 = float(input()) # entrada v6 v6 = float(input()) # variaveis count = 0 countJ = 0 media = 0 listV = [] listP = [] # adicionar a lista listV.append(v1) listV.append(v2) listV.append(v3) listV.append(v4) listV.append(v5) listV.append(v6) # percorrer a lista e encontrar numeros positivos for i in listV: if i >= 0: count = count + 1 listP.append(i) # percorrer a lista de positivos e calcular a media for j in listP: media = media + j countJ = countJ + 1 # media total mediaT = media / countJ print('{} valores positivos\n{:.1f}'.format(count, mediaT))
v1 = float(input()) v2 = float(input()) v3 = float(input()) v4 = float(input()) v5 = float(input()) v6 = float(input()) count = 0 count_j = 0 media = 0 list_v = [] list_p = [] listV.append(v1) listV.append(v2) listV.append(v3) listV.append(v4) listV.append(v5) listV.append(v6) for i in listV: if i >= 0: count = count + 1 listP.append(i) for j in listP: media = media + j count_j = countJ + 1 media_t = media / countJ print('{} valores positivos\n{:.1f}'.format(count, mediaT))
# Pretty good, but I golfed the top one even more n=input s="".join(n()for _ in"_"*int(n())) print(s.count("00")+s.count("11")+1)
n = input s = ''.join((n() for _ in '_' * int(n()))) print(s.count('00') + s.count('11') + 1)
"""Provides the repo macro to import google libprotobuf_mutator""" load("//third_party:repo.bzl", "tf_http_archive") def repo(): """Imports libprotobuf_mutator.""" tf_http_archive( name = "com_google_libprotobuf_mutator", sha256 = "792f250fb546bde8590e72d64311ea00a70c175fd77df6bb5e02328fa15fe28e", strip_prefix = "libprotobuf-mutator-1.0", build_file = "//third_party/libprotobuf_mutator:BUILD.bazel", urls = [ "https://storage.googleapis.com/mirror.tensorflow.org/github.com/google/libprotobuf-mutator/archive/v1.0.tar.gz", "https://github.com/google/libprotobuf-mutator/archive/v1.0.tar.gz", ], )
"""Provides the repo macro to import google libprotobuf_mutator""" load('//third_party:repo.bzl', 'tf_http_archive') def repo(): """Imports libprotobuf_mutator.""" tf_http_archive(name='com_google_libprotobuf_mutator', sha256='792f250fb546bde8590e72d64311ea00a70c175fd77df6bb5e02328fa15fe28e', strip_prefix='libprotobuf-mutator-1.0', build_file='//third_party/libprotobuf_mutator:BUILD.bazel', urls=['https://storage.googleapis.com/mirror.tensorflow.org/github.com/google/libprotobuf-mutator/archive/v1.0.tar.gz', 'https://github.com/google/libprotobuf-mutator/archive/v1.0.tar.gz'])
def do_twice(f, v): f(v) f(v) def print_twice(s): print(s) print(s) # do_twice(print_twice, 'spam') def do_four(f, v): do_twice(f, v) do_twice(f, v) do_four(print, 'spam')
def do_twice(f, v): f(v) f(v) def print_twice(s): print(s) print(s) def do_four(f, v): do_twice(f, v) do_twice(f, v) do_four(print, 'spam')
phi_list = {} def naples(num): b_count = 0 rel_list = [] for i in range(1, num+1): count = 0 for j in range(2, i): if num%j==0 and i%j==0: count += 1 break if count==0: b_count += 1 rel_list.append(i) phi_list[num] = b_count for val in rel_list: if val!=1: phi_list[val*num] = phi_list[val] * phi_list[num] return b_count inc = 0 while True: inc += 1 naples(inc) if max(phi_list) > 1000000: break max1 = 0 max2 = 0 for i in phi_list: if i/phi_list[i] > max1: max1 = i/phi_list[i] max2 = i print(max2) # 510510 """ Using the fact that the totient function is multiplicative here. Our answer was not going to be a prime, since n/phi(n) is small for primes. So once we get over 1,000,000 in our list, we know the only values left to be filled in are prime. We don't have to check those. """
phi_list = {} def naples(num): b_count = 0 rel_list = [] for i in range(1, num + 1): count = 0 for j in range(2, i): if num % j == 0 and i % j == 0: count += 1 break if count == 0: b_count += 1 rel_list.append(i) phi_list[num] = b_count for val in rel_list: if val != 1: phi_list[val * num] = phi_list[val] * phi_list[num] return b_count inc = 0 while True: inc += 1 naples(inc) if max(phi_list) > 1000000: break max1 = 0 max2 = 0 for i in phi_list: if i / phi_list[i] > max1: max1 = i / phi_list[i] max2 = i print(max2) "\n\nUsing the fact that the totient function is multiplicative here.\n\nOur answer was not going to be a prime, since n/phi(n) is\nsmall for primes. So once we get over 1,000,000 in our list,\nwe know the only values left to be filled in are prime.\nWe don't have to check those.\n\n"
# -*- coding: utf-8 -*- """ Created on Mon Dec 4 12:31:27 2017 @author: James Jiang """ with open('Data.txt') as f: for line in f: number = line digits = [i for i in str(number)] step = int(len(digits)/2) for i in range(int(len(digits)/2)): digits.append(digits[i]) sum = 0 for i in range(int(len(digits)*2/3)): if digits[i] == digits[i + step]: sum += int(digits[i]) print(sum)
""" Created on Mon Dec 4 12:31:27 2017 @author: James Jiang """ with open('Data.txt') as f: for line in f: number = line digits = [i for i in str(number)] step = int(len(digits) / 2) for i in range(int(len(digits) / 2)): digits.append(digits[i]) sum = 0 for i in range(int(len(digits) * 2 / 3)): if digits[i] == digits[i + step]: sum += int(digits[i]) print(sum)
# https://www.youtube.com/watch?v=OSGv2VnC0go names = ["rouge", "geralt", "blizzard", "yennefer"] colors = ["red", "green", "blue", "yellow"] for color in reversed(colors): print(color) for i, color in enumerate(colors): print(i, "-->", color) for name, color in zip(names, colors): print("{:<12}{:<12}".format(name, color)) for color in sorted(zip(names, colors), key=lambda x: x[0]): print(color)
names = ['rouge', 'geralt', 'blizzard', 'yennefer'] colors = ['red', 'green', 'blue', 'yellow'] for color in reversed(colors): print(color) for (i, color) in enumerate(colors): print(i, '-->', color) for (name, color) in zip(names, colors): print('{:<12}{:<12}'.format(name, color)) for color in sorted(zip(names, colors), key=lambda x: x[0]): print(color)
# -------------------------------------------------------------- # DO NOT EDIT BELOW OF THIS UNLESS REALLY SURE NFDUMP_FIELDS = [] NFDUMP_FIELDS.append( { "ID": "pr", "AggrType_A": "proto", "AggrType_s": "proto", "Name": "Protocol" } ) NFDUMP_FIELDS.append( { "ID": "exp", "AggrType_A": None, "AggrType_s": "sysid", "Name": "Exporter ID" } ) NFDUMP_FIELDS.append( { "ID": "sa", "AggrType_A": "srcip", "AggrType_s": "srcip", "Name": "Source Address", "Details": "IP" } ) NFDUMP_FIELDS.append( { "ID": "da", "AggrType_A": "dstip", "AggrType_s": "dstip", "Name": "Destination Address", "Details": "IP" } ) NFDUMP_FIELDS.append( { "ID": "sp", "AggrType_A": "srcport", "AggrType_s": "srcport", "Name": "Source Port" } ) NFDUMP_FIELDS.append( { "ID": "dp", "AggrType_A": "dstport", "AggrType_s": "dstport", "Name": "Destination Port" } ) NFDUMP_FIELDS.append( { "ID": "nh", "AggrType_A": "next", "AggrType_s": "nhip", "Name": "Next-hop IP Address", "Details": "IP" } ) NFDUMP_FIELDS.append( { "ID": "nhb", "AggrType_A": "bgpnext", "AggrType_s": "nhbip", "Name": "BGP Next-hop IP Address", "Details": "IP" } ) NFDUMP_FIELDS.append( { "ID": "ra", "AggrType_A": "router", "AggrType_s": "router", "Name": "Router IP Address", "Details": "IP" } ) NFDUMP_FIELDS.append( { "ID": "sas", "AggrType_A": "srcas", "AggrType_s": "srcas", "Name": "Source AS", "Details": "AS" } ) NFDUMP_FIELDS.append( { "ID": "das", "AggrType_A": "dstas", "AggrType_s": "dstas", "Name": "Destination AS", "Details": "AS" } ) NFDUMP_FIELDS.append( { "ID": "nas", "AggrType_A": "nextas", "AggrType_s": None, "Name": "Next AS", "Details": "AS" } ) NFDUMP_FIELDS.append( { "ID": "pas", "AggrType_A": "prevas", "AggrType_s": None, "Name": "Previous AS", "Details": "AS" } ) NFDUMP_FIELDS.append( { "ID": "in", "AggrType_A": "inif", "AggrType_s": "inif", "Name": "Input Interface num" } ) NFDUMP_FIELDS.append( { "ID": "out", "AggrType_A": "outif", "AggrType_s": "outif", "Name": "Output Interface num" } ) NFDUMP_FIELDS.append( { "ID": "sn4", "AggrType_A": "srcip4/%s", "AggrType_s": None, "Name": "IPv4 source network", "Details": "IP", "OutputField": "sa", "ArgRequired": True } ) NFDUMP_FIELDS.append( { "ID": "sn6", "AggrType_A": "srcip6/%s", "AggrType_s": None, "Name": "IPv6 source network", "Details": "IP", "OutputField": "sa", "ArgRequired": True } ) NFDUMP_FIELDS.append( { "ID": "dn4", "AggrType_A": "dstip4/%s", "AggrType_s": None, "Name": "IPv4 destination network", "Details": "IP", "OutputField": "da", "ArgRequired": True } ) NFDUMP_FIELDS.append( { "ID": "dn6", "AggrType_A": "dstip6/%s", "AggrType_s": None, "Name": "IPv6 destination network", "Details": "IP", "OutputField": "da", "ArgRequired": True } )
nfdump_fields = [] NFDUMP_FIELDS.append({'ID': 'pr', 'AggrType_A': 'proto', 'AggrType_s': 'proto', 'Name': 'Protocol'}) NFDUMP_FIELDS.append({'ID': 'exp', 'AggrType_A': None, 'AggrType_s': 'sysid', 'Name': 'Exporter ID'}) NFDUMP_FIELDS.append({'ID': 'sa', 'AggrType_A': 'srcip', 'AggrType_s': 'srcip', 'Name': 'Source Address', 'Details': 'IP'}) NFDUMP_FIELDS.append({'ID': 'da', 'AggrType_A': 'dstip', 'AggrType_s': 'dstip', 'Name': 'Destination Address', 'Details': 'IP'}) NFDUMP_FIELDS.append({'ID': 'sp', 'AggrType_A': 'srcport', 'AggrType_s': 'srcport', 'Name': 'Source Port'}) NFDUMP_FIELDS.append({'ID': 'dp', 'AggrType_A': 'dstport', 'AggrType_s': 'dstport', 'Name': 'Destination Port'}) NFDUMP_FIELDS.append({'ID': 'nh', 'AggrType_A': 'next', 'AggrType_s': 'nhip', 'Name': 'Next-hop IP Address', 'Details': 'IP'}) NFDUMP_FIELDS.append({'ID': 'nhb', 'AggrType_A': 'bgpnext', 'AggrType_s': 'nhbip', 'Name': 'BGP Next-hop IP Address', 'Details': 'IP'}) NFDUMP_FIELDS.append({'ID': 'ra', 'AggrType_A': 'router', 'AggrType_s': 'router', 'Name': 'Router IP Address', 'Details': 'IP'}) NFDUMP_FIELDS.append({'ID': 'sas', 'AggrType_A': 'srcas', 'AggrType_s': 'srcas', 'Name': 'Source AS', 'Details': 'AS'}) NFDUMP_FIELDS.append({'ID': 'das', 'AggrType_A': 'dstas', 'AggrType_s': 'dstas', 'Name': 'Destination AS', 'Details': 'AS'}) NFDUMP_FIELDS.append({'ID': 'nas', 'AggrType_A': 'nextas', 'AggrType_s': None, 'Name': 'Next AS', 'Details': 'AS'}) NFDUMP_FIELDS.append({'ID': 'pas', 'AggrType_A': 'prevas', 'AggrType_s': None, 'Name': 'Previous AS', 'Details': 'AS'}) NFDUMP_FIELDS.append({'ID': 'in', 'AggrType_A': 'inif', 'AggrType_s': 'inif', 'Name': 'Input Interface num'}) NFDUMP_FIELDS.append({'ID': 'out', 'AggrType_A': 'outif', 'AggrType_s': 'outif', 'Name': 'Output Interface num'}) NFDUMP_FIELDS.append({'ID': 'sn4', 'AggrType_A': 'srcip4/%s', 'AggrType_s': None, 'Name': 'IPv4 source network', 'Details': 'IP', 'OutputField': 'sa', 'ArgRequired': True}) NFDUMP_FIELDS.append({'ID': 'sn6', 'AggrType_A': 'srcip6/%s', 'AggrType_s': None, 'Name': 'IPv6 source network', 'Details': 'IP', 'OutputField': 'sa', 'ArgRequired': True}) NFDUMP_FIELDS.append({'ID': 'dn4', 'AggrType_A': 'dstip4/%s', 'AggrType_s': None, 'Name': 'IPv4 destination network', 'Details': 'IP', 'OutputField': 'da', 'ArgRequired': True}) NFDUMP_FIELDS.append({'ID': 'dn6', 'AggrType_A': 'dstip6/%s', 'AggrType_s': None, 'Name': 'IPv6 destination network', 'Details': 'IP', 'OutputField': 'da', 'ArgRequired': True})
# # Vivante Cross Toolchain configuration # load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES") load("@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl", "tool_path", "feature", "with_feature_set", "flag_group", "flag_set") load("//:cc_toolchain_base.bzl", "build_cc_toolchain_config", "all_compile_actions", "all_cpp_compile_actions", "all_link_actions") tool_paths = [ tool_path(name = "ar", path = "bin/wrapper-ar",), tool_path(name = "compat-ld", path = "bin/wrapper-ld",), tool_path(name = "cpp", path = "bin/wrapper-cpp",), tool_path(name = "dwp", path = "bin/wrapper-dwp",), tool_path(name = "gcc", path = "bin/wrapper-gcc",), tool_path(name = "gcov", path = "bin/wrapper-gcov",), tool_path(name = "ld", path = "bin/wrapper-ld",), tool_path(name = "nm", path = "bin/wrapper-nm",), tool_path(name = "objcopy", path = "bin/wrapper-objcopy",), tool_path(name = "objdump", path = "bin/wrapper-objdump",), tool_path(name = "strip", path = "bin/wrapper-strip",), ] def _impl(ctx): builtin_sysroot = "external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/aarch64-linux-gnu/libc" compile_flags_feature = feature( name = "compile_flags", enabled = True, flag_sets = [ flag_set( actions = all_compile_actions, flag_groups = [ flag_group( flags = [ "-idirafter", "external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/aarch64-linux-gnu/libc/usr/include", "-idirafter", "external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/lib/gcc/aarch64-linux-gnu/7.3.1/include", "-idirafter", "external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/lib/gcc/aarch64-linux-gnu/7.3.1/include-fixed", "-idirafter", "external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/lib/gcc/aarch64-linux-gnu/7.3.1/install-tools/include", "-idirafter", "external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/lib/gcc/aarch64-linux-gnu/7.3.1/plugin/include", ], ), flag_group( flags = [ "-D__arm64", "-Wall", # All warnings are enabled. "-Wunused-but-set-parameter", # Enable a few more warnings that aren't part of -Wall. "-Wno-free-nonheap-object", # Disable some that are problematic, has false positives "-fno-omit-frame-pointer", # Keep stack frames for debugging, even in opt mode. "-no-canonical-prefixes", "-fstack-protector", "-fPIE", "-fPIC", ], ), ], ), flag_set( actions = all_cpp_compile_actions + [ACTION_NAMES.lto_backend], flag_groups = [ flag_group( flags = [ "-isystem" , "external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/aarch64-linux-gnu/include/c++/7.3.1", "-isystem" , "external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/aarch64-linux-gnu/include/c++/7.3.1/aarch64-linux-gnu", ] ), ], ), flag_set( actions = all_compile_actions, flag_groups = [ flag_group( flags = [ "-g", ], ), ], with_features = [with_feature_set(features = ["dbg"])], ), flag_set( actions = all_compile_actions, flag_groups = [ flag_group( flags = [ "-g0", "-O2", "-DNDEBUG", "-ffunction-sections", "-fdata-sections", ], ), ], with_features = [with_feature_set(features = ["opt"])], ), flag_set( actions = all_link_actions, flag_groups = [ flag_group( flags = [ "-lstdc++", ], ), ], ), flag_set( actions = all_link_actions, flag_groups = [ flag_group( flags = [ "-Wl,--gc-sections", ], ), ], with_features = [with_feature_set(features = ["opt"])], ), flag_set( actions = [ ACTION_NAMES.cpp_link_executable, ], flag_groups = [ flag_group( flags = [ "-pie", ], ), ], ), ], ) cxx_builtin_include_directories = [ "%package(@gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu//aarch64-linux-gnu/libc/usr/include)%", "%package(@gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu//lib/gcc/aarch64-linux-gnu/7.3.1/include)%", "%package(@gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu//lib/gcc/aarch64-linux-gnu/7.3.1/include-fixed)%", "%package(@gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu//lib/gcc/aarch64-linux-gnu/7.3.1/install-tools/include)%", "%package(@gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu//lib/gcc/aarch64-linux-gnu/7.3.1/plugin/include)%", "%package(@gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu//aarch64-linux-gnu/include/c++/7.3.1)%", "%package(@gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu//aarch64-linux-gnu/include/c++/7.3.1/aarch64-linux-gnu)%", ] objcopy_embed_flags_feature = feature( name = "objcopy_embed_flags", enabled = True, flag_sets = [ flag_set( actions = ["objcopy_embed_data"], flag_groups = [ flag_group( flags = [ "-I", "binary", ], ), ], ), ] ) dbg_feature = feature(name = "dbg") opt_feature = feature(name = "opt") return cc_common.create_cc_toolchain_config_info( ctx = ctx, toolchain_identifier = ctx.attr.toolchain_name, host_system_name = "", target_system_name = "linux", target_cpu = ctx.attr.target_cpu, target_libc = ctx.attr.target_cpu, compiler = ctx.attr.compiler, abi_version = ctx.attr.compiler, abi_libc_version = ctx.attr.compiler, tool_paths = tool_paths, features = [compile_flags_feature, objcopy_embed_flags_feature, dbg_feature, opt_feature], cxx_builtin_include_directories = cxx_builtin_include_directories, builtin_sysroot = builtin_sysroot, ) # DON'T MODIFY cc_toolchain_config = build_cc_toolchain_config(_impl) # EOF
load('@bazel_tools//tools/build_defs/cc:action_names.bzl', 'ACTION_NAMES') load('@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl', 'tool_path', 'feature', 'with_feature_set', 'flag_group', 'flag_set') load('//:cc_toolchain_base.bzl', 'build_cc_toolchain_config', 'all_compile_actions', 'all_cpp_compile_actions', 'all_link_actions') tool_paths = [tool_path(name='ar', path='bin/wrapper-ar'), tool_path(name='compat-ld', path='bin/wrapper-ld'), tool_path(name='cpp', path='bin/wrapper-cpp'), tool_path(name='dwp', path='bin/wrapper-dwp'), tool_path(name='gcc', path='bin/wrapper-gcc'), tool_path(name='gcov', path='bin/wrapper-gcov'), tool_path(name='ld', path='bin/wrapper-ld'), tool_path(name='nm', path='bin/wrapper-nm'), tool_path(name='objcopy', path='bin/wrapper-objcopy'), tool_path(name='objdump', path='bin/wrapper-objdump'), tool_path(name='strip', path='bin/wrapper-strip')] def _impl(ctx): builtin_sysroot = 'external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/aarch64-linux-gnu/libc' compile_flags_feature = feature(name='compile_flags', enabled=True, flag_sets=[flag_set(actions=all_compile_actions, flag_groups=[flag_group(flags=['-idirafter', 'external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/aarch64-linux-gnu/libc/usr/include', '-idirafter', 'external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/lib/gcc/aarch64-linux-gnu/7.3.1/include', '-idirafter', 'external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/lib/gcc/aarch64-linux-gnu/7.3.1/include-fixed', '-idirafter', 'external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/lib/gcc/aarch64-linux-gnu/7.3.1/install-tools/include', '-idirafter', 'external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/lib/gcc/aarch64-linux-gnu/7.3.1/plugin/include']), flag_group(flags=['-D__arm64', '-Wall', '-Wunused-but-set-parameter', '-Wno-free-nonheap-object', '-fno-omit-frame-pointer', '-no-canonical-prefixes', '-fstack-protector', '-fPIE', '-fPIC'])]), flag_set(actions=all_cpp_compile_actions + [ACTION_NAMES.lto_backend], flag_groups=[flag_group(flags=['-isystem', 'external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/aarch64-linux-gnu/include/c++/7.3.1', '-isystem', 'external/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/aarch64-linux-gnu/include/c++/7.3.1/aarch64-linux-gnu'])]), flag_set(actions=all_compile_actions, flag_groups=[flag_group(flags=['-g'])], with_features=[with_feature_set(features=['dbg'])]), flag_set(actions=all_compile_actions, flag_groups=[flag_group(flags=['-g0', '-O2', '-DNDEBUG', '-ffunction-sections', '-fdata-sections'])], with_features=[with_feature_set(features=['opt'])]), flag_set(actions=all_link_actions, flag_groups=[flag_group(flags=['-lstdc++'])]), flag_set(actions=all_link_actions, flag_groups=[flag_group(flags=['-Wl,--gc-sections'])], with_features=[with_feature_set(features=['opt'])]), flag_set(actions=[ACTION_NAMES.cpp_link_executable], flag_groups=[flag_group(flags=['-pie'])])]) cxx_builtin_include_directories = ['%package(@gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu//aarch64-linux-gnu/libc/usr/include)%', '%package(@gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu//lib/gcc/aarch64-linux-gnu/7.3.1/include)%', '%package(@gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu//lib/gcc/aarch64-linux-gnu/7.3.1/include-fixed)%', '%package(@gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu//lib/gcc/aarch64-linux-gnu/7.3.1/install-tools/include)%', '%package(@gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu//lib/gcc/aarch64-linux-gnu/7.3.1/plugin/include)%', '%package(@gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu//aarch64-linux-gnu/include/c++/7.3.1)%', '%package(@gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu//aarch64-linux-gnu/include/c++/7.3.1/aarch64-linux-gnu)%'] objcopy_embed_flags_feature = feature(name='objcopy_embed_flags', enabled=True, flag_sets=[flag_set(actions=['objcopy_embed_data'], flag_groups=[flag_group(flags=['-I', 'binary'])])]) dbg_feature = feature(name='dbg') opt_feature = feature(name='opt') return cc_common.create_cc_toolchain_config_info(ctx=ctx, toolchain_identifier=ctx.attr.toolchain_name, host_system_name='', target_system_name='linux', target_cpu=ctx.attr.target_cpu, target_libc=ctx.attr.target_cpu, compiler=ctx.attr.compiler, abi_version=ctx.attr.compiler, abi_libc_version=ctx.attr.compiler, tool_paths=tool_paths, features=[compile_flags_feature, objcopy_embed_flags_feature, dbg_feature, opt_feature], cxx_builtin_include_directories=cxx_builtin_include_directories, builtin_sysroot=builtin_sysroot) cc_toolchain_config = build_cc_toolchain_config(_impl)
dia = input('what day were you born?') mes = input('what month were you born?') ano = input('what year were you born?') saudacaoDia = ('voce nasceu no dia') saudacaoDe = ('de') print(saudacaoDia, dia,saudacaoDe,mes,saudacaoDe,ano)
dia = input('what day were you born?') mes = input('what month were you born?') ano = input('what year were you born?') saudacao_dia = 'voce nasceu no dia' saudacao_de = 'de' print(saudacaoDia, dia, saudacaoDe, mes, saudacaoDe, ano)
#!/usr/bin/env python if __name__ == "__main__": N = int(raw_input()) for i in range(N): print(pow(i,2))
if __name__ == '__main__': n = int(raw_input()) for i in range(N): print(pow(i, 2))
''' 1. Write a Python program to create a tuple. 2. Write a Python program to create a tuple with different data types. 3. Write a Python program to create a tuple with numbers and print one item. 4. Write a Python program to unpack a tuple in several variables. 5. Write a Python program to add an item in a tuple. 6. Write a Python program to convert a tuple to a string. 7. Write a Python program to get the 4th element and 4th element from last of a tuple. 8. Write a Python program to create the colon of a tuple. 9. Write a Python program to find the repeated items of a tuple. 10. Write a Python program to check whether an element exists within a tuple. '''
""" 1. Write a Python program to create a tuple. 2. Write a Python program to create a tuple with different data types. 3. Write a Python program to create a tuple with numbers and print one item. 4. Write a Python program to unpack a tuple in several variables. 5. Write a Python program to add an item in a tuple. 6. Write a Python program to convert a tuple to a string. 7. Write a Python program to get the 4th element and 4th element from last of a tuple. 8. Write a Python program to create the colon of a tuple. 9. Write a Python program to find the repeated items of a tuple. 10. Write a Python program to check whether an element exists within a tuple. """
# Write a program that does the following: ## Prompt the user for their age. Convert it to a number, add one to it, and tell them how old they will be on their next birthday. ## Prompt the user for the number of egg cartons they have. Assume each carton holds 12 eggs, multiply their number by 12, and display the total number of eggs. ## Prompt the user for a number of cookies and a number of people. Then, divide the number of cookies by the number of people to determine how many cookies each person gets. age_now = int(input("How old are you? ")) age_one_year_after = age_now+1 print("Next year you will be " +str(age_one_year_after)) print("\n----------------") egg_cartoons = int(input("How much egg cartoons do you have? ")) total_eggs = egg_cartoons*12 print("Nice! So you have "+ str(total_eggs)+" eggs in total!") print("\n----------------") cookies = int(input("Give me a number of cookies: ")) people = int(input("Now, give a number of people: ")) num_parts_of_cookies = cookies/people print(f"If we divide these {cookies} cookies to these {people} people, each person with have {num_parts_of_cookies} parts of cookies")
age_now = int(input('How old are you? ')) age_one_year_after = age_now + 1 print('Next year you will be ' + str(age_one_year_after)) print('\n----------------') egg_cartoons = int(input('How much egg cartoons do you have? ')) total_eggs = egg_cartoons * 12 print('Nice! So you have ' + str(total_eggs) + ' eggs in total!') print('\n----------------') cookies = int(input('Give me a number of cookies: ')) people = int(input('Now, give a number of people: ')) num_parts_of_cookies = cookies / people print(f'If we divide these {cookies} cookies to these {people} people, each person with have {num_parts_of_cookies} parts of cookies')