content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
WARNING_HEADER = '[\033[1m\033[93mWARNING\033[0m]' def warning_message(message_text): print('{header} {text}'.format(header=WARNING_HEADER, text=message_text))
warning_header = '[\x1b[1m\x1b[93mWARNING\x1b[0m]' def warning_message(message_text): print('{header} {text}'.format(header=WARNING_HEADER, text=message_text))
class WebsocketError(Exception): pass class NoTokenError(WebsocketError): pass
class Websocketerror(Exception): pass class Notokenerror(WebsocketError): pass
a,b=0,1 while b<10: print(b) a,b=b,a+b
(a, b) = (0, 1) while b < 10: print(b) (a, b) = (b, a + b)
def thank_you(donation): if donation >= 1000: print("Thank you for your donation! You have achieved platinum donation status!") elif donation >= 500: print("Thank you for your donation! You have achieved gold donation status!") elif donation >= 100: print("Thank you for your donation! You have achiev...
def thank_you(donation): if donation >= 1000: print('Thank you for your donation! You have achieved platinum donation status!') elif donation >= 500: print('Thank you for your donation! You have achieved gold donation status!') elif donation >= 100: print('Thank you for your donation...
''' This file holds all the constants that are required for programming the LIS3DH including register addresses and their values ''' ''' The LIS3DH I2C address ''' LIS3DH_I2C_ADDR = 0x18 ''' The LIS3DH Register Map ''' #0x00 - 0x06 - reserved STATUS_REG_AUX = 0x07 OUT_ADC1_L = 0x08...
""" This file holds all the constants that are required for programming the LIS3DH including register addresses and their values """ '\nThe LIS3DH I2C address\n' lis3_dh_i2_c_addr = 24 '\nThe LIS3DH Register Map\n' status_reg_aux = 7 out_adc1_l = 8 out_adc1_h = 9 out_adc2_l = 10 out_adc2_h = 11 out_adc3_l = 12 out_adc3...
def moveDictionary(): electro_shock = {"Name" : "Electro Shock", \ "Kind" : "atk",\ "Pwr" : 25, \ "Acc" : 95, \ "Crit" : 80, \ "Txt" : "releases one thousand volts of static"} #special ...
def move_dictionary(): electro_shock = {'Name': 'Electro Shock', 'Kind': 'atk', 'Pwr': 25, 'Acc': 95, 'Crit': 80, 'Txt': 'releases one thousand volts of static'} heal = {'Name': 'Heal', 'Kind': 'heal', 'Pwr': 28, 'Acc': 36, 'Crit': 5, 'Txt': 'attempts to put itself back together'} robot_punch = {'Name': 'Ro...
class Solution: def rob(self, nums): robbed, notRobbed = 0, 0 for i in nums: robbed, notRobbed = notRobbed + i, max(robbed, notRobbed) return max(robbed, notRobbed)
class Solution: def rob(self, nums): (robbed, not_robbed) = (0, 0) for i in nums: (robbed, not_robbed) = (notRobbed + i, max(robbed, notRobbed)) return max(robbed, notRobbed)
# Common package prefixes, in the order we want to check for them _PREFIXES = (".com.", ".org.", ".net.", ".io.") # By default bazel computes the name of test classes based on the # standard Maven directory structure, which we may not always use, # so try to compute the correct package name. def get_package_name(): ...
_prefixes = ('.com.', '.org.', '.net.', '.io.') def get_package_name(): pkg = native.package_name().replace('/', '.') for prefix in _PREFIXES: idx = pkg.find(prefix) if idx != -1: return pkg[idx + 1:] + '.' return '' def get_class_name(src): idx = src.rindex('.') name =...
numbers = [int(i) for i in input().split(" ")] opposite_numbers = [] for current_num in numbers: if current_num >= 0: opposite_numbers.append(-current_num) elif current_num < 0: opposite_numbers.append(abs(current_num)) print(opposite_numbers)
numbers = [int(i) for i in input().split(' ')] opposite_numbers = [] for current_num in numbers: if current_num >= 0: opposite_numbers.append(-current_num) elif current_num < 0: opposite_numbers.append(abs(current_num)) print(opposite_numbers)
def finder(data, x): if x == 0: return data[x] v1 = data[x] v2 = finder(data, x-1) if v1 > v2: return v1 else: return v2 print(finder([0, -247, 341, 1001, 741, 22]))
def finder(data, x): if x == 0: return data[x] v1 = data[x] v2 = finder(data, x - 1) if v1 > v2: return v1 else: return v2 print(finder([0, -247, 341, 1001, 741, 22]))
def extractStrictlybromanceCom(item): ''' Parser for 'strictlybromance.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('grave robbers\' chronicles', 'grave robbers\' chronicles', ...
def extract_strictlybromance_com(item): """ Parser for 'strictlybromance.com' """ (vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None tagmap = [("grave robbers' chronicles", "grave robbers' chron...
class Solution: def largestTimeFromDigits(self, nums: List[int]) -> str: res=[] def per(depth): if depth==len(nums)-1: res.append(nums[:]) for i in range(depth,len(nums)): nums[i],nums[depth]=nums[depth],nums[i] ...
class Solution: def largest_time_from_digits(self, nums: List[int]) -> str: res = [] def per(depth): if depth == len(nums) - 1: res.append(nums[:]) for i in range(depth, len(nums)): (nums[i], nums[depth]) = (nums[depth], nums[i]) ...
EPS = 1.0e-16 PI = 3.141592653589793
eps = 1e-16 pi = 3.141592653589793
#all binary allSensors = ['D021', 'D022', 'D023', 'D024', 'D025', 'D026', 'D027', 'D028', 'D029', 'D030', 'D031', 'D032', 'M001', 'M002', 'M003', 'M004', 'M005', 'M006', 'M007', 'M008', 'M009', 'M010', 'M011', 'M012', 'M013', 'M014', 'M015', 'M016', 'M017', 'M018', 'M019', 'M020'] doorSens...
all_sensors = ['D021', 'D022', 'D023', 'D024', 'D025', 'D026', 'D027', 'D028', 'D029', 'D030', 'D031', 'D032', 'M001', 'M002', 'M003', 'M004', 'M005', 'M006', 'M007', 'M008', 'M009', 'M010', 'M011', 'M012', 'M013', 'M014', 'M015', 'M016', 'M017', 'M018', 'M019', 'M020'] door_sensors = ['D021', 'D022', 'D023', 'D024', '...
f = [1, 1, 2, 6, 4] for _ in range(int(input())): n = int(input()) if n <= 4: print(f[n]) else: print(0)
f = [1, 1, 2, 6, 4] for _ in range(int(input())): n = int(input()) if n <= 4: print(f[n]) else: print(0)
# 6. Zigzag Conversion # Runtime: 103 ms, faster than 20.89% of Python3 online submissions for Zigzag Conversion. # Memory Usage: 14.7 MB, less than 13.84% of Python3 online submissions for Zigzag Conversion. class Solution: def convert(self, s: str, numRows: int) -> str: if numRows == 1: re...
class Solution: def convert(self, s: str, numRows: int) -> str: if numRows == 1: return s rows = [[] for _ in range(numRows)] largest_interval = numRows * 2 - 2 for r in range(numRows): i = r curr_interval = largest_interval - 2 * r if...
# # PySNMP MIB module AGENTX-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AGENTX-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:15:42 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, value_size_constraint, single_value_constraint, constraints_intersection, constraints_union) ...
class Layer: def __init(self): self.input=None self.output=None def forward(self,input): #to return the output layer pass def backward(self,output_gradient,learning_rate): #change para and return input derivative pass
class Layer: def __init(self): self.input = None self.output = None def forward(self, input): pass def backward(self, output_gradient, learning_rate): pass
class Capture: def capture(self): pass
class Capture: def capture(self): pass
def f(n): if n == 0: return 0 elif n == 1: return 1 else: return f(n-1)+f(n-2) n=int(input()) values = [str(f(x)) for x in range(0, n+1)] print(",".join(values))
def f(n): if n == 0: return 0 elif n == 1: return 1 else: return f(n - 1) + f(n - 2) n = int(input()) values = [str(f(x)) for x in range(0, n + 1)] print(','.join(values))
#TODO Create Functions for PMTA ## TORISPHERICAL TOP HEAD 2:1 - Min thickness allowed and PMTA class TorisphericalCalcs: def __init__(self): self.L_top_head = None self.r_top_head = None self.ratio_L_r_top = None self.M_factor_top_head = None self.t_min_top_head = No...
class Torisphericalcalcs: def __init__(self): self.L_top_head = None self.r_top_head = None self.ratio_L_r_top = None self.M_factor_top_head = None self.t_min_top_head = None self.t_nom_top_head_plate = None self.t_top_head_nom_after_conf = None self....
# Collaborators (including web sites where you got help: (enter none if you didn't need help) # claryse adams def avg_temp(user_list): total = 0 for x in range(1, len(user_list)): total += user_list[x] average = total/(len(user_list)-1) average = round(average, 2) return average if __name...
def avg_temp(user_list): total = 0 for x in range(1, len(user_list)): total += user_list[x] average = total / (len(user_list) - 1) average = round(average, 2) return average if __name__ == '__main__': with open('temps.txt') as file_object: contents = file_object.readlines() i...
def fry(): print('The eggs have been fried')
def fry(): print('The eggs have been fried')
class Data: def __init__(self, dia, mes, ano): self.dia = dia self.mes = mes self.ano = ano print(self) @classmethod def de_string(cls, data_string): dia, mes, ano = map(int, data_string.split("-")) data = cls(dia, mes, ano) return data ...
class Data: def __init__(self, dia, mes, ano): self.dia = dia self.mes = mes self.ano = ano print(self) @classmethod def de_string(cls, data_string): (dia, mes, ano) = map(int, data_string.split('-')) data = cls(dia, mes, ano) return data @stati...
class DummyContext: context = {} dummy_context = DummyContext()
class Dummycontext: context = {} dummy_context = dummy_context()
# Copyright 2020 BBC Research & Development # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
experiment_name = 'exp1_bn' experiment_path = 'experiment/path' output_path = experiment_path + experiment_name core_model = 'bn_model' d_scales = 1 data_path = 'data/path' input_shape = (256, 256) input_color_mode = 'rgb' output_color_mode = 'lab' interpolation = 'nearest' chunk_size = 10000 samples_rate = 1.0 shuffle...
# -*- coding: utf-8 -*- __author__ = 'Wael Ben Zid El Guebsi' __email__ = 'benzid.wael@hotmail.fr' __version__ = '0.0.0'
__author__ = 'Wael Ben Zid El Guebsi' __email__ = 'benzid.wael@hotmail.fr' __version__ = '0.0.0'
# coding: utf-8 n = int(input()) li = [int(i) for i in input().split()] print(sum(li)/n)
n = int(input()) li = [int(i) for i in input().split()] print(sum(li) / n)
class Question: def __init__(self, text, answer): self.text = text self.answer = answer new_q = Question("lkajsdkf", "False")
class Question: def __init__(self, text, answer): self.text = text self.answer = answer new_q = question('lkajsdkf', 'False')
def find_three_values_that_sum(lines, sum=2020): for idx1, line1 in enumerate(lines): for idx2, line2 in enumerate(lines[idx1:]): for idx3, line3 in enumerate(lines[idx1+idx2:]): num1 = int(line1) num2 = int(line2) num3 = int(line3) ...
def find_three_values_that_sum(lines, sum=2020): for (idx1, line1) in enumerate(lines): for (idx2, line2) in enumerate(lines[idx1:]): for (idx3, line3) in enumerate(lines[idx1 + idx2:]): num1 = int(line1) num2 = int(line2) num3 = int(line3) ...
"Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k" class Solution: def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: if not nums or len(nums) == 1: return False ...
"""Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k""" class Solution: def contains_nearby_duplicate(self, nums: List[int], k: int) -> bool: if not nums or len(nums) == 1: return Fa...
class Solution: def generate(self, numRows: int): result = [] if not numRows: return result for i in range(1, numRows + 1): temp = [1] * i lo = 1 hi = i - 2 while lo <= hi: temp[lo] = temp[hi] = result[i - 2...
class Solution: def generate(self, numRows: int): result = [] if not numRows: return result for i in range(1, numRows + 1): temp = [1] * i lo = 1 hi = i - 2 while lo <= hi: temp[lo] = temp[hi] = result[i - 2][lo] + ...
# 1921. Eliminate Maximum Number of Monsters # You are playing a video game where you are defending your city from a group of n monsters. # You are given a 0-indexed integer array dist of size n, where dist[i] is the initial # distance in meters of the ith monster from the city. # The monsters walk toward the city at...
class Solution: def eliminate_maximum(self, dist: List[int], speed: List[int]) -> int: if not dist or not speed or len(dist) == 0 or (len(speed) == 0) or (len(dist) != len(speed)): return 0 l = len(speed) orders = [] for i in range(l): orders.append([dist[i],...
__author__ = 'Chetan' class Wizard(): def __init__(self, src, rootdir): self.choices = [] self.rootdir = rootdir self.src = src def preferences(self, command): self.choices.append(command) def execute(self): for choice in self.choices: ...
__author__ = 'Chetan' class Wizard: def __init__(self, src, rootdir): self.choices = [] self.rootdir = rootdir self.src = src def preferences(self, command): self.choices.append(command) def execute(self): for choice in self.choices: if list(choice.val...
####################################################### # # ManageRacacatPinController.py # Python implementation of the Class ManageRacacatPinController # Generated by Enterprise Architect # Created on: 15-Apr-2020 4:57:23 PM # Original author: Giu Platania # ############################################...
class Manageracacatpincontroller: pass
N = int(input()) ans = 0 if N < 10 ** 3: print(0) elif 10 ** 3 <= N < 10 ** 6: print(N - 10 ** 3 + 1) elif 10 ** 6 <= N < 10 ** 9: print(10 ** 6 - 10 ** 3 + (N - 10 ** 6 + 1)*2) elif 10 ** 9 <= N < 10 ** 12: print(10 ** 6 - 10 ** 3 + (10 ** 9 - 10 ** 6)*2 + (N - 10 ** 9 + 1)*3) elif 10 ** 12 <= N < 10 ...
n = int(input()) ans = 0 if N < 10 ** 3: print(0) elif 10 ** 3 <= N < 10 ** 6: print(N - 10 ** 3 + 1) elif 10 ** 6 <= N < 10 ** 9: print(10 ** 6 - 10 ** 3 + (N - 10 ** 6 + 1) * 2) elif 10 ** 9 <= N < 10 ** 12: print(10 ** 6 - 10 ** 3 + (10 ** 9 - 10 ** 6) * 2 + (N - 10 ** 9 + 1) * 3) elif 10 ** 12 <= N ...
valor = 12 def teste_git(testes): result = testes ** 33 return result print(teste_git(valor))
valor = 12 def teste_git(testes): result = testes ** 33 return result print(teste_git(valor))
def show_first(word): print(word[0]) show_first("abc")
def show_first(word): print(word[0]) show_first('abc')
def count_positives_sum_negatives(arr): if not arr: return [] positive_array_count = 0 negative_array_count = 0 neither_array = 0 for i in arr: if i > 0: positive_array_count = positive_array_count + 1 elif i == 0: neither_array = neither_array + i ...
def count_positives_sum_negatives(arr): if not arr: return [] positive_array_count = 0 negative_array_count = 0 neither_array = 0 for i in arr: if i > 0: positive_array_count = positive_array_count + 1 elif i == 0: neither_array = neither_array + i ...
input_shape = 56, 56, 3 num_class = 80 total_epoches = 50 batch_size = 64 train_num = 11650 val_num = 1254 iterations_per_epoch = train_num // batch_size + 1 test_iterations = val_num // batch_size + 1 weight_decay = 1e-3 label_smoothing = 0.1 ''' numeric characteristics ''' mean = [154.64720717, 163.98750114, 1...
input_shape = (56, 56, 3) num_class = 80 total_epoches = 50 batch_size = 64 train_num = 11650 val_num = 1254 iterations_per_epoch = train_num // batch_size + 1 test_iterations = val_num // batch_size + 1 weight_decay = 0.001 label_smoothing = 0.1 '\nnumeric characteristics\n' mean = [154.64720717, 163.98750114, 175.110...
def sort3(a, b, c): i = [] i.append(a), i.append(b), i.append(c) i = sorted(i) return i a, b, c = input(), input(), input() print(*sort3(a, b, c))
def sort3(a, b, c): i = [] (i.append(a), i.append(b), i.append(c)) i = sorted(i) return i (a, b, c) = (input(), input(), input()) print(*sort3(a, b, c))
''' occurrences_dict loop values: occurrences_dict[value] += 1 ''' # numbers_string = '-2.5 4 3 -2.5 -5.54 4 3 3 -2.5 3' # numbers_string = '2 4 4 5 5 2 3 3 4 4 3 3 4 3 5 3 2 5 4 3' numbers_string = input() occurrence_counts = {} # No such thing as tuple comprehension, this is generator numbers = [float(x) for x...
""" occurrences_dict loop values: occurrences_dict[value] += 1 """ numbers_string = input() occurrence_counts = {} numbers = [float(x) for x in numbers_string.split(' ')] for number in numbers: if number not in occurrence_counts: occurrence_counts[number] = 0 occurrence_counts[number] += 1 for (numb...
count = 0 total = 0 while True: Enter = input('Enter a number:\n') try: if Enter == "Done": break else: inp = int(Enter) total = total + inp count = count + 1 average = total / count except: print('Invalid input') print('Tot...
count = 0 total = 0 while True: enter = input('Enter a number:\n') try: if Enter == 'Done': break else: inp = int(Enter) total = total + inp count = count + 1 average = total / count except: print('Invalid input') print('Tot...
# # PySNMP MIB module BEGEMOT-IP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BEGEMOT-IP-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:37:03 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_constraint, value_range_constraint, single_value_constraint, constraints_union) ...
SECRET_KEY = 'fake-key-here' # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'd...
secret_key = 'fake-key-here' installed_apps = ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'data_ingest'] middleware = ['django.contrib.sessions.middleware....
# RUN: test-parser.sh %s # RUN: test-output.sh %s x = 1 # PARSER-LABEL:x = 1i y = 2 # PARSER-NEXT:y = 2i print("Start") # PARSER-NEXT:print("Start") # OUTPUT-LABEL: Start if x == 1: # PARSER-NEXT:if (x == 1i): if y == 3: # PARSER-NEXT: if ...
x = 1 y = 2 print('Start') if x == 1: if y == 3: print('A') else: print('C') print('D') if x == 1: if y == 3: print('A') else: print('B') else: print('C') print('D') if x == 1: if y == 3: print('A') else: print('B') print('D') if x == 1: if y == 3:...
class CameraNotConnected(Exception): pass class WiredControlAlreadyEstablished(Exception): pass
class Cameranotconnected(Exception): pass class Wiredcontrolalreadyestablished(Exception): pass
# https://codeforces.com/problemset/problem/116/A n = int(input()) stops = [list(map(int, input().split())) for _ in range(n)] p, peak_p = 0, 0 for stop in stops: p -= stop[0] p += stop[1] peak_p = max(p, peak_p) print(peak_p)
n = int(input()) stops = [list(map(int, input().split())) for _ in range(n)] (p, peak_p) = (0, 0) for stop in stops: p -= stop[0] p += stop[1] peak_p = max(p, peak_p) print(peak_p)
def int_to_char(word): arr = list(word) num_str = "" while True: if not arr[0].isdigit(): break num_str += arr[0] arr.pop(0) num = int(num_str) arr.insert(0, chr(num)) return "".join(arr) def switch_letters(word): list_chars = list(word) list_char...
def int_to_char(word): arr = list(word) num_str = '' while True: if not arr[0].isdigit(): break num_str += arr[0] arr.pop(0) num = int(num_str) arr.insert(0, chr(num)) return ''.join(arr) def switch_letters(word): list_chars = list(word) (list_chars[1...
PROJECT_ID = 'dmp-y-tests' DATASET_NAME = 'test_gpl' BUCKET_NAME = 'bucket_gpl' LOCAL_DIR_PATH = '/tmp/gpl_directory'
project_id = 'dmp-y-tests' dataset_name = 'test_gpl' bucket_name = 'bucket_gpl' local_dir_path = '/tmp/gpl_directory'
def commonDiv(num, den, divs = None) : if not divs : divs = divisors(den) for i in divs[1:] : if not num % i : return True return False def validNums(den, minNum, maxNum) : divs = divisors(den) return [i for i in range(minNum,maxNum+1) if not commonDiv(i, den, divs)] def countBetween(lowNum, lowDen, h...
def common_div(num, den, divs=None): if not divs: divs = divisors(den) for i in divs[1:]: if not num % i: return True return False def valid_nums(den, minNum, maxNum): divs = divisors(den) return [i for i in range(minNum, maxNum + 1) if not common_div(i, den, divs)] def...
# Exception Handling function def exception_handling(number1, number2, operator): # Only digit exception try: int(number1) except: return "Error: Numbers must only contain digits." try: int(number2) except: return "Error: Numbers must only contain digits." # More...
def exception_handling(number1, number2, operator): try: int(number1) except: return 'Error: Numbers must only contain digits.' try: int(number2) except: return 'Error: Numbers must only contain digits.' try: if len(number1) > 4 or len(number2) > 4: ...
TWITTER_TAGS = [ "agdq2021", "gamesdonequick.com", "agdq", "sgdq", "gamesdonequick", "awesome games done quick", "games done quick", "summer games done quick", "gdq", ] TWITCH_CHANNEL = "gamesdonequick" TWITCH_HOST = "irc.twitch.tv" TWITCH_PORT = 6667 # Update this value to change t...
twitter_tags = ['agdq2021', 'gamesdonequick.com', 'agdq', 'sgdq', 'gamesdonequick', 'awesome games done quick', 'games done quick', 'summer games done quick', 'gdq'] twitch_channel = 'gamesdonequick' twitch_host = 'irc.twitch.tv' twitch_port = 6667 event_shorthand = 'AGDQ2021' donation_url = 'https://gamesdonequick.com...
''' Problem : Find out duplicate number between 1 to N numbers. - Find array sum - Subtract sum of First (n-1) natural numbers from it to find the result. Author : Alok Tripathi ''' # Method to find duplicate in array def findDuplicate(arr, n): return sum(arr) - (((n - 1) * n) // 2) #it will return int no...
""" Problem : Find out duplicate number between 1 to N numbers. - Find array sum - Subtract sum of First (n-1) natural numbers from it to find the result. Author : Alok Tripathi """ def find_duplicate(arr, n): return sum(arr) - (n - 1) * n // 2 if __name__ == '__main__': arr = [1, 2, 3, 3, 4] n = len...
def get_score(player_deck): score_sum=0 for i in player_deck: try: score_sum+=int(i[1]) except: if i[1] in ['K', 'Q', 'J']: score_sum+=10 if i[1]=='Ace': if (score_sum+11)<=21: score_sum+=11 ...
def get_score(player_deck): score_sum = 0 for i in player_deck: try: score_sum += int(i[1]) except: if i[1] in ['K', 'Q', 'J']: score_sum += 10 if i[1] == 'Ace': if score_sum + 11 <= 21: score_sum += 11 ...
# coding: utf-8 n = int(input()) a = [int(i) for i in input().split()] for i in range(n): if i < n-1 and a[i+1]<a[i]: break if i==n-1: ans = 0 else: ans = n-1-i a = a[i+1:]+a[:i+1] for i in range(n-1): if a[i] > a[i+1]: print(-1) break else: print(ans)
n = int(input()) a = [int(i) for i in input().split()] for i in range(n): if i < n - 1 and a[i + 1] < a[i]: break if i == n - 1: ans = 0 else: ans = n - 1 - i a = a[i + 1:] + a[:i + 1] for i in range(n - 1): if a[i] > a[i + 1]: print(-1) break else: print(ans)
# Scrapy settings for dirbot project SPIDER_MODULES = ['dirbot.spiders'] NEWSPIDER_MODULE = 'dirbot.spiders' DEFAULT_ITEM_CLASS = 'dirbot.items.Website' ITEM_PIPELINES = { 'dirbot.pipelines.RequiredFieldsPipeline': 1, 'dirbot.pipelines.FilterWordsPipeline': 2, 'dirbot.pipelines.DbPipeline': 3, } # Databa...
spider_modules = ['dirbot.spiders'] newspider_module = 'dirbot.spiders' default_item_class = 'dirbot.items.Website' item_pipelines = {'dirbot.pipelines.RequiredFieldsPipeline': 1, 'dirbot.pipelines.FilterWordsPipeline': 2, 'dirbot.pipelines.DbPipeline': 3} db_api_name = 'MySQLdb' db_args = {'host': 'localhost', 'db': '...
class Solution: def getHeight(self, root): if root is None: return 0 lh = self.getHeight(root.left) + 1 rh = self.getHeight(root.right) + 1 return max(lh, rh) def isBalanced(self, root): if root is None: return True leftHeight = self....
class Solution: def get_height(self, root): if root is None: return 0 lh = self.getHeight(root.left) + 1 rh = self.getHeight(root.right) + 1 return max(lh, rh) def is_balanced(self, root): if root is None: return True left_height = self.g...
def get_products_of_all_ints_except_at_index(int_list): if len(int_list) < 2: raise IndexError('Getting the product of numbers at other ' 'indices requires at least 2 numbers') # We make a list with the length of the input list to # hold our products products_of_all_in...
def get_products_of_all_ints_except_at_index(int_list): if len(int_list) < 2: raise index_error('Getting the product of numbers at other indices requires at least 2 numbers') products_of_all_ints_except_at_index = [None] * len(int_list) product_so_far = 1 for i in range(len(int_list)): p...
count = 0 # A global count variable def remember(): global count count += 1 # Count this invocation print(str(count)) remember() remember() remember() remember() remember()
count = 0 def remember(): global count count += 1 print(str(count)) remember() remember() remember() remember() remember()
def find_rc(rc): rc = rc[:: -1] replacements = {"A": "T", "T": "A", "G": "C", "C": "G"} rc = "".join([replacements.get(c, c) for c in rc]) return rc print(find_rc('ATTA'))
def find_rc(rc): rc = rc[::-1] replacements = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'} rc = ''.join([replacements.get(c, c) for c in rc]) return rc print(find_rc('ATTA'))
first_name = input("Please enter your first name: ") print(f"Your first name is: {first_name}") print("a regular string: " + first_name) print('a regular string' + first_name) # string literal with the r prefix print(r'a regular string')
first_name = input('Please enter your first name: ') print(f'Your first name is: {first_name}') print('a regular string: ' + first_name) print('a regular string' + first_name) print('a regular string')
# A variable lets you save some information to use later # You can save numbers! my_var = 1 print(my_var) # Or strings! my_var = "MARIO" print(my_var) # Or anything else you need!
my_var = 1 print(my_var) my_var = 'MARIO' print(my_var)
def code_to_color(code): assert len(code) in (4, 5, 7, 9), f'Bad format color code: {code}' if len(code) == 4 or len(code) == 5: # "#RGB" or "#RGBA" return tuple(map(lambda x: int(x, 16) * 17, code[1:])) elif len(code) == 7 or len(code) == 9: # "#RRGGBB" or "#RRGGBBAA" return tuple(map(la...
def code_to_color(code): assert len(code) in (4, 5, 7, 9), f'Bad format color code: {code}' if len(code) == 4 or len(code) == 5: return tuple(map(lambda x: int(x, 16) * 17, code[1:])) elif len(code) == 7 or len(code) == 9: return tuple(map(lambda x, y: int(x + y, 16), code[::1], code[1::1]))...
class Payload: @staticmethod def login_payload(username, password): return {'UserName': username, 'Password': password, 'ValidateUser': '1', 'dbKeyAuth': 'JusticePA', 'SignOn': 'Sign+On'} @staticmethod def payload(param_parser, last_name, first_name, middle_name, birth_date): ...
class Payload: @staticmethod def login_payload(username, password): return {'UserName': username, 'Password': password, 'ValidateUser': '1', 'dbKeyAuth': 'JusticePA', 'SignOn': 'Sign+On'} @staticmethod def payload(param_parser, last_name, first_name, middle_name, birth_date): payload =...
class Solution: def addBinary(self, a: str, b: str) -> str: max_len = max(len(a), len(b)) a = a.zfill(max_len) b = b.zfill(max_len) result = '' # initialize the carry carry = 0 # Traverse the string for i in range(max_len - 1, -1, -1): r...
class Solution: def add_binary(self, a: str, b: str) -> str: max_len = max(len(a), len(b)) a = a.zfill(max_len) b = b.zfill(max_len) result = '' carry = 0 for i in range(max_len - 1, -1, -1): r = carry r += 1 if a[i] == '1' else 0 ...
''' Locating suspicious data You will now inspect the suspect record by locating the offending row. You will see that, according to the data, Joyce Chepchumba was a man that won a medal in a women's event. That is a data error as you can confirm with a web search. INSTRUCTIONS 70XP Create a Boolean Series with a con...
""" Locating suspicious data You will now inspect the suspect record by locating the offending row. You will see that, according to the data, Joyce Chepchumba was a man that won a medal in a women's event. That is a data error as you can confirm with a web search. INSTRUCTIONS 70XP Create a Boolean Series with a con...
class InvalidSymbolException(Exception): pass class InvalidMoveException(Exception): pass class InvalidCoordinateInputException(Exception): pass
class Invalidsymbolexception(Exception): pass class Invalidmoveexception(Exception): pass class Invalidcoordinateinputexception(Exception): pass
def odd_nums(number: int) -> int: for num in range(1, number + 1, 2): yield num pass n = 15 generator = odd_nums(n) for _ in range(1, n + 1, 2): print(next(generator)) next(generator)
def odd_nums(number: int) -> int: for num in range(1, number + 1, 2): yield num pass n = 15 generator = odd_nums(n) for _ in range(1, n + 1, 2): print(next(generator)) next(generator)
def find_nemo(array): for item in array: if item == 'nemo': print('found NEMO') nemo = ['nemo'] find_nemo(nemo)
def find_nemo(array): for item in array: if item == 'nemo': print('found NEMO') nemo = ['nemo'] find_nemo(nemo)
def loss_function(X_values, X_media, X_org): # X_media = { # "labels": ["facebook", "tiktok"], # "coefs": [6.454, 1.545], # "drs": [0.6, 0.7] # } # X_org = { # "labels": ["const"], # "coefs": [-27.5], # "values": [1] # } y = 0 for i in range(len(X_values)): ...
def loss_function(X_values, X_media, X_org): y = 0 for i in range(len(X_values)): transform = X_values[i] ** X_media['drs'][i] contrib = X_media['coefs'][i] * transform y += contrib for i in range(len(X_org)): contrib = X_org['coefs'][i] * X_org['values'][i] y += cont...
def getcommonletters(strlist): return ''.join([x[0] for x in zip(*strlist) \ if reduce(lambda a,b:(a == b) and a or None,x)]) def findcommonstart(strlist): strlist = strlist[:] prev = None while True: common = getcommonletters(strlist) if common == prev: ...
def getcommonletters(strlist): return ''.join([x[0] for x in zip(*strlist) if reduce(lambda a, b: a == b and a or None, x)]) def findcommonstart(strlist): strlist = strlist[:] prev = None while True: common = getcommonletters(strlist) if common == prev: break strlist...
# DO NOT comment out # (REQ) REQUIRED # ***************************************************************************** # DATA DISCOVERY ENGINE - MAIN (REQ) # ***************************************************************************** # name also used on metadata SITE_NAME = "NIAID Data Portal" SITE_DESC = 'An aggr...
site_name = 'NIAID Data Portal' site_desc = 'An aggregator of open datasets, with a particular focus on allergy and infectious diseases' api_url = 'https://crawler.biothings.io/api/' site_url = 'https://discovery.biothings.io/niaid/' contact_repo = 'https://github.com/SuLab/niaid-data-portal' contact_email = 'cd2h-meta...
# pylint: skip-file POKEAPI_POKEMON_LIST_EXAMPLE = { "count": 949, "previous": None, "results": [ { "url": "https://pokeapi.co/api/v2/pokemon/21/", "name": "spearow" }, { "url": "https://pokeapi.co/api/v2/pokemon/22/", "name": "fearow"...
pokeapi_pokemon_list_example = {'count': 949, 'previous': None, 'results': [{'url': 'https://pokeapi.co/api/v2/pokemon/21/', 'name': 'spearow'}, {'url': 'https://pokeapi.co/api/v2/pokemon/22/', 'name': 'fearow'}]} pokeapi_pokemon_data_example_first = {'forms': [{'url': 'https://pokeapi.co/api/v2/pokemon-form/21/', 'nam...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Mapping: def __init__(self, iterable): self.items_list = [] self.__update(iterable) def __update(self, iterable): for item in iterable: self.items_list.append(item) def test_parent(self): print(self.__update...
class Mapping: def __init__(self, iterable): self.items_list = [] self.__update(iterable) def __update(self, iterable): for item in iterable: self.items_list.append(item) def test_parent(self): print(self.__update) class Mappingsubclass(Mapping): def __up...
class Solution: def removeElement(self, nums: List[int], val: int) -> int: i = 0 length = len(nums) while i < length: if nums[i] == val: nums[i:] = nums[i + 1:] length -= 1 else: i += 1 return length
class Solution: def remove_element(self, nums: List[int], val: int) -> int: i = 0 length = len(nums) while i < length: if nums[i] == val: nums[i:] = nums[i + 1:] length -= 1 else: i += 1 return length
# 7x^1 - 2x^2 + 1x^3 + 2x^4 = 3 # 2x^1 + 8x^2 + 3x^3 + 1x^4 = -2 # -1x^1 + 0x^2 + 5x^3 + 2x^4 = 5 # 0x^1 + 2x^2 - 1x^3 + 4x^4 = 4 def getX1(x2,x3,x4): return (3+2*x2-x3-2*x4)/7 def getX2(x1,x3,x4): return (-2-2*x1-3*x3-x4)/8 def getX3(x1,x2,x4): return (5+x1-2*x4)/5 def getX4(x1,x2,x3): return...
def get_x1(x2, x3, x4): return (3 + 2 * x2 - x3 - 2 * x4) / 7 def get_x2(x1, x3, x4): return (-2 - 2 * x1 - 3 * x3 - x4) / 8 def get_x3(x1, x2, x4): return (5 + x1 - 2 * x4) / 5 def get_x4(x1, x2, x3): return (4 - 2 * x2 + x3) / 4 x1 = 0 x2 = 0 x3 = 0 x4 = 0 x1a = 1e-05 x2a = 1e-05 x3a = 1e-05 x4a = ...
def calc_fact(num): total = 0 final_tot = 1 for x in range(num): total = final_tot * (x+1) final_tot = total print(total) calc_fact(10) # excepted output: 3628800
def calc_fact(num): total = 0 final_tot = 1 for x in range(num): total = final_tot * (x + 1) final_tot = total print(total) calc_fact(10)
z = int(input()) y = int(input()) x = int(input()) space = x * y * z box = int(0) box_space = int(0) while box != "Done": box = input() if box != "Done": box = float(box) box = int(box) box_space += box if box_space > space: print(f"No more free space! You need {box_space - s...
z = int(input()) y = int(input()) x = int(input()) space = x * y * z box = int(0) box_space = int(0) while box != 'Done': box = input() if box != 'Done': box = float(box) box = int(box) box_space += box if box_space > space: print(f'No more free space! You need {box_space - s...
DEBUG_MODE = False #DIR_BASE = '/tmp/sms' DIR_BASE = '/var/spool/sms' DIR_INCOMING = 'incoming' DIR_OUTGOING = 'outgoing' DIR_CHECKED = 'checked' DIR_FAILED = 'failed' DIR_SENT = 'sent' # Default international phone code DEFAULT_CODE = '62' # Unformatted messages will forward to FORWARD_TO ...
debug_mode = False dir_base = '/var/spool/sms' dir_incoming = 'incoming' dir_outgoing = 'outgoing' dir_checked = 'checked' dir_failed = 'failed' dir_sent = 'sent' default_code = '62' forward_to = ('62813123123', '62813123124')
#=============================================================== # DMXIS Macro (c) 2010 db audioware limited #=============================================================== sel = GetAllSelCh(False) if len(sel)>0: for ch in sel: RemoveFixture(ch)
sel = get_all_sel_ch(False) if len(sel) > 0: for ch in sel: remove_fixture(ch)
#!/usr/bin/python3 def echo(input): return input def count_valid(data, anagrams=True): valid = 0 if anagrams: sort = echo else: sort = sorted for line in data: words = [] for word in line.split(): if sort(word) not in words: words.appen...
def echo(input): return input def count_valid(data, anagrams=True): valid = 0 if anagrams: sort = echo else: sort = sorted for line in data: words = [] for word in line.split(): if sort(word) not in words: words.append(sort(word)) ...
def initialize(): global detected, undetected, unsupported, total, report_id detected = {} undetected = {} unsupported = {} total = {} report_id = {} def initialize_colours(): global HEADER, OKBLUE, OKCYAN, OKGREEN, WARNING, FAIL, ENDC, BOLD, UNDERLINE, ALERT, GRAY, WHITE, END global C...
def initialize(): global detected, undetected, unsupported, total, report_id detected = {} undetected = {} unsupported = {} total = {} report_id = {} def initialize_colours(): global HEADER, OKBLUE, OKCYAN, OKGREEN, WARNING, FAIL, ENDC, BOLD, UNDERLINE, ALERT, GRAY, WHITE, END global C ...
##Afficher les communs diverseurs du nombre naturel N n = int(input()) for a in range (1, n + 1) : if n % a == 0 : print(a) else : print(' ')
n = int(input()) for a in range(1, n + 1): if n % a == 0: print(a) else: print(' ')
MAIL_USERNAME = 'buildasaasappwithflask@gmail.com' MAIL_PASSWORD = 'helicopterpantswalrusfoot' STRIPE_SECRET_KEY = 'sk_test_nycOOQdO9C16zxubr2WWtbug' STRIPE_PUBLISHABLE_KEY = 'pk_test_ClU5mzNj1YxRRnrdZB5jEO29'
mail_username = 'buildasaasappwithflask@gmail.com' mail_password = 'helicopterpantswalrusfoot' stripe_secret_key = 'sk_test_nycOOQdO9C16zxubr2WWtbug' stripe_publishable_key = 'pk_test_ClU5mzNj1YxRRnrdZB5jEO29'
#Called when SMU is in List mode class SlaveMaster: SLAVE = 0 MASTER = 1
class Slavemaster: slave = 0 master = 1
def private(): pass class Abra: def other(): private()
def private(): pass class Abra: def other(): private()
class Solution: def majorityElement(self, nums: List[int]) -> int: counter, target = 0, nums[0] for i in nums: if counter == 0: target = i if target != i: counter -= 1 else: counter += 1 return target
class Solution: def majority_element(self, nums: List[int]) -> int: (counter, target) = (0, nums[0]) for i in nums: if counter == 0: target = i if target != i: counter -= 1 else: counter += 1 return target
class QuotaOptions(object): def __init__(self, start_quota: int = 0, refresh_by: str = "month", warning_rate: float = 0.8): self.start_quota = start_quota self.refresh_by = refresh_by self.warning_rate = warning_rate
class Quotaoptions(object): def __init__(self, start_quota: int=0, refresh_by: str='month', warning_rate: float=0.8): self.start_quota = start_quota self.refresh_by = refresh_by self.warning_rate = warning_rate
def FoodStoreLol(Money, time, im): print("What would you like to eat?") time.sleep(2) print("!Heres the menu!") time.sleep(2) im.show() time.sleep(2) eeee = input("Say Any Key to continue.") FoodList = [] cash = 0 time.sleep(5) for Loopies in range(3): ord...
def food_store_lol(Money, time, im): print('What would you like to eat?') time.sleep(2) print('!Heres the menu!') time.sleep(2) im.show() time.sleep(2) eeee = input('Say Any Key to continue.') food_list = [] cash = 0 time.sleep(5) for loopies in range(3): order = int(...
''' An array is monotonic if it is either monotone increasing or monotone decreasing. An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j]. Return true if and only if the given array A is monotonic. Example 1: Input: [1,2,2,3] Outpu...
""" An array is monotonic if it is either monotone increasing or monotone decreasing. An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j]. Return true if and only if the given array A is monotonic. Example 1: Input: [1,2,2,3] Outpu...
#!/usr/local/bin/python3 def imprime(maximo, atual): if atual >= maximo: return print(atual) imprime(maximo, atual + 1) if __name__ == '__main__': imprime(100, 1)
def imprime(maximo, atual): if atual >= maximo: return print(atual) imprime(maximo, atual + 1) if __name__ == '__main__': imprime(100, 1)
project = 'pydatastructs' modules = ['linear_data_structures'] backend = '_backend' cpp = 'cpp' dummy_submodules = ['_arrays.py']
project = 'pydatastructs' modules = ['linear_data_structures'] backend = '_backend' cpp = 'cpp' dummy_submodules = ['_arrays.py']
# Given a list of numbers and a number k. # Return whether any two numbers from the list add up to k. # # For example: # Give [1,2,3,4] and k of 7 # Return true since 3 + 4 is 7 def input_array(): print("Len of array = ", end='') array_len = int(input()) print() array = [] for i in range(array_le...
def input_array(): print('Len of array = ', end='') array_len = int(input()) print() array = [] for i in range(array_len): print('Value of array[{}] = '.format(i), end='') element = int(input()) array.append(element) print('Array is: ', array) return array def input_...
operator = input() num_one = int(input()) num_two = int(input()) def multiply_nums(x, y): result = x * y return result def divide_nums(x, y): if y != 0: result = int(x / y) return result def add_nums(x, y): result = x + y return result def subtract_nums(x, y): result = x ...
operator = input() num_one = int(input()) num_two = int(input()) def multiply_nums(x, y): result = x * y return result def divide_nums(x, y): if y != 0: result = int(x / y) return result def add_nums(x, y): result = x + y return result def subtract_nums(x, y): result = x - y ...
print(" I will now count my chickens:") print("Hens",25+30/6) print("Roosters", 100-25*3%4) print("Now I will continue the eggs:") print(3+2+1-5+4%2-1/4+6) print("Is it true that 3+2<5-7?") print(3+2<5-7) print("What is 3+2?", 3+2) print("What is 5=7?", 5-7) print("Oh, that;s why it;s false.") print("How abao...
print(' I will now count my chickens:') print('Hens', 25 + 30 / 6) print('Roosters', 100 - 25 * 3 % 4) print('Now I will continue the eggs:') print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) print('Is it true that 3+2<5-7?') print(3 + 2 < 5 - 7) print('What is 3+2?', 3 + 2) print('What is 5=7?', 5 - 7) print('Oh, that;s why it...
# Created by MechAviv # Wicked Witch Damage Skin | (2433184) if sm.addDamageSkin(2433184): sm.chat("'Wicked Witch Damage Skin' Damage Skin has been added to your account's damage skin collection.") sm.consumeItem()
if sm.addDamageSkin(2433184): sm.chat("'Wicked Witch Damage Skin' Damage Skin has been added to your account's damage skin collection.") sm.consumeItem()
n = int(input()) votos = [] for i in range(n): x = int(input()) votos.append(x) if votos[0] >= max(votos): print("S") else: print("N")
n = int(input()) votos = [] for i in range(n): x = int(input()) votos.append(x) if votos[0] >= max(votos): print('S') else: print('N')
# Dasean Volk, dvolk@usc.edu # Fall 2021, ITP115 # Section: Boba # Lab 9 # --------------------------------------SHOW RECOMMENDER & FILE CREATOR----------------------------------------------- # def display_menu(): print("TV Shows \nPossible genres are action & adventure, animation, comedy, " "\ndocument...
def display_menu(): print('TV Shows \nPossible genres are action & adventure, animation, comedy, \ndocumentary, drama, mystery & suspense, science fiction & fantasy') def read_file(user_genre, file_name='shows.csv'): show_list = [] open_file = open(file_name, 'r') for line in open_file: line = ...
print('Mind Mapping') print('') q = input('1) ') q1 = input('1.1) ') q2 = input('1.2) ') print('') w = input('2) ') w1 = input('2.1) ') w2 = input('2.2) ') print('') e = input('3) ') e1 = input('3.1) ') e2 = input('3.2) ') print('') r = input('4) ') r1 = input('4.1) ') r2 = input('4.2) ') print('') print('') print('1) ...
print('Mind Mapping') print('') q = input('1) ') q1 = input('1.1) ') q2 = input('1.2) ') print('') w = input('2) ') w1 = input('2.1) ') w2 = input('2.2) ') print('') e = input('3) ') e1 = input('3.1) ') e2 = input('3.2) ') print('') r = input('4) ') r1 = input('4.1) ') r2 = input('4.2) ') print('') print('') print('1) ...