content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
newdata = [] with open("requirements.txt") as f: data = f.read() data = data.split("\n") for i in data: if "@" not in i: newdata.append(i) # print(newdata) file = open("requirements.txt", "w") # print("".join(newdata) + "\n") for i in newdata: print(i) file.write(i + "\n"...
newdata = [] with open('requirements.txt') as f: data = f.read() data = data.split('\n') for i in data: if '@' not in i: newdata.append(i) file = open('requirements.txt', 'w') for i in newdata: print(i) file.write(i + '\n')
source = r'''#include <cstdio> #include "mylib.h" void do_something_else() { printf("something else\n"); }''' print(source)
source = '#include <cstdio>\n#include "mylib.h"\n\nvoid do_something_else()\n{\n printf("something else\\n");\n}' print(source)
print(' ') print('-------Menghitung laba seorang pengusaha-------') a=100000000 sum=0 b=0 laba=[int(0),int(0),int(a)*.1,int(a)*.1,int(a)*.5,int(a)*.5,int(a)*.5,int(a)*.2] print('') print('Modal seorang pengusaha :',a) print(' ') for i in laba: sum=sum+i b+=1 print('Laba Bulan ke -',b,'...
print(' ') print('-------Menghitung laba seorang pengusaha-------') a = 100000000 sum = 0 b = 0 laba = [int(0), int(0), int(a) * 0.1, int(a) * 0.1, int(a) * 0.5, int(a) * 0.5, int(a) * 0.5, int(a) * 0.2] print('') print('Modal seorang pengusaha :', a) print(' ') for i in laba: sum = sum + i b += 1 pri...
#!python3 msn = 0 for x in range(3,1000000) : n = x csn = 0 while n != 1 : if n % 2 == 0 : n = int(n / 2) else : n = n * 3 +1 csn += 1 if csn > msn : msn = csn sn = x print(sn)
msn = 0 for x in range(3, 1000000): n = x csn = 0 while n != 1: if n % 2 == 0: n = int(n / 2) else: n = n * 3 + 1 csn += 1 if csn > msn: msn = csn sn = x print(sn)
def day01_1(input_data): result = 0 for i in range(len(input_data)): if int(input_data[i]) == int(input_data[(i + 1) % len(input_data)]): result += int(input_data[i]) return result def day01_2(input_data): result = 0 for i in range(len(input_data)): if int(input_data[i...
def day01_1(input_data): result = 0 for i in range(len(input_data)): if int(input_data[i]) == int(input_data[(i + 1) % len(input_data)]): result += int(input_data[i]) return result def day01_2(input_data): result = 0 for i in range(len(input_data)): if int(input_data[i])...
class Fuzzy_logical_relationship(object): def __init__(self, lhs, rhs): self.lhs = lhs self.rhs = rhs def __str__(self): return str(self.lhs) + " -> " + str(self.rhs)
class Fuzzy_Logical_Relationship(object): def __init__(self, lhs, rhs): self.lhs = lhs self.rhs = rhs def __str__(self): return str(self.lhs) + ' -> ' + str(self.rhs)
random_list = tuple(range(0, 1000)) def just_mean(x): total = 0 for xi in x: total += xi return total / len(x) mean_output = just_mean(random_list)
random_list = tuple(range(0, 1000)) def just_mean(x): total = 0 for xi in x: total += xi return total / len(x) mean_output = just_mean(random_list)
INVALID_INPUT = 1 DOCKER_ERROR = 2 UNKNOWN_ERROR = 3 class DkrException(Exception): def __init__(self, message, exit_code): self.message = message self.exit_code = exit_code
invalid_input = 1 docker_error = 2 unknown_error = 3 class Dkrexception(Exception): def __init__(self, message, exit_code): self.message = message self.exit_code = exit_code
class Action: def __init__(self, unit, target): self.unit = unit self.target = target def complete(self): self.unit.walked = [] self.unit.action = None self.unit._flee_or_fight_if_enemy() def update(self): pass class MoveAction(Action): def u...
class Action: def __init__(self, unit, target): self.unit = unit self.target = target def complete(self): self.unit.walked = [] self.unit.action = None self.unit._flee_or_fight_if_enemy() def update(self): pass class Moveaction(Action): def update(sel...
a=int(input("enter first number:")) b=int(input("enter second number:")) sum=0 for i in range (a,b+1): sum=sum+i print(sum)
a = int(input('enter first number:')) b = int(input('enter second number:')) sum = 0 for i in range(a, b + 1): sum = sum + i print(sum)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param {integer[]} preorder # @param {integer[]} inorder # @return {TreeNode} def buildTree(self, preorder, inorder): ...
class Solution: def build_tree(self, preorder, inorder): if not preorder or not inorder: return None (n1, n2) = (len(preorder), len(inorder)) if n1 != n2 or n1 == 0: return None root = tree_node(0) st = [root] i = 0 j = 0 last_...
while 1: a = 1 break print(a) # pass
while 1: a = 1 break print(a)
# Migration removed because it depends on models which have been removed def run(): return False
def run(): return False
#-----------------------------------------------------------------# #! Python3 # Author : NK # Month, Year : March, 2019 # Info : Program to get Squares of numbers upto 25, using return # Desc : An example program to show usage of return #--------------------------------------...
def next_square(x): return x * x def main(): for x in range(25): print(next_square(x)) if __name__ == '__main__': main()
def get_planet_name(id): tmp = { 1: "Mercury", 2: "Venus", 3: "Earth", 4: "Mars", 5: "Jupiter", 6: "Saturn", 7: "Uranus", 8: "Neptune" } return tmp[id]
def get_planet_name(id): tmp = {1: 'Mercury', 2: 'Venus', 3: 'Earth', 4: 'Mars', 5: 'Jupiter', 6: 'Saturn', 7: 'Uranus', 8: 'Neptune'} return tmp[id]
class Solution: def successfulPairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: potions = [(val, idx) for idx, val in enumerate(potions)] potions.sort() spells = [(val, idx) for idx, val in enumerate(spells)] spells.sort() left = 0 right =...
class Solution: def successful_pairs(self, spells: List[int], potions: List[int], success: int) -> List[int]: potions = [(val, idx) for (idx, val) in enumerate(potions)] potions.sort() spells = [(val, idx) for (idx, val) in enumerate(spells)] spells.sort() left = 0 r...
# # PySNMP MIB module SONOMASYSTEMS-SONOMA-IPAPPS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SONOMASYSTEMS-SONOMA-IPAPPS-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:09:25 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Pytho...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_union, single_value_constraint, constraints_intersection, value_size_constraint) ...
#!/usr/bin/env python3 '''Iterate over multiple sequences in parallel using zip() function NOET: zip() stops when the shortest sequence is done ''' # Init days = ['Monday', 'Tuesday', 'Wednesday'] fruits = ['banana', 'orange', 'peach'] drinks = ['coffee', 'tea', 'beer'] desserts = ['tiramisu', 'ice cream', 'pie', '...
"""Iterate over multiple sequences in parallel using zip() function NOET: zip() stops when the shortest sequence is done """ days = ['Monday', 'Tuesday', 'Wednesday'] fruits = ['banana', 'orange', 'peach'] drinks = ['coffee', 'tea', 'beer'] desserts = ['tiramisu', 'ice cream', 'pie', 'pudding'] for (day, fruit, dri...
name=input("Please input my daughter's name:") while name!="Nina" and name!="Anime": print("I'm sorry, but the name is not valid.") name=input("Please input my daughter's name:") print("Yes."+name+"is my daughter.")
name = input("Please input my daughter's name:") while name != 'Nina' and name != 'Anime': print("I'm sorry, but the name is not valid.") name = input("Please input my daughter's name:") print('Yes.' + name + 'is my daughter.')
cases = [ ('pmt -s 1 -n 20 populations, use seed so same run each time', 'pmt -s 1 -n 20 populations'), ('pmt -s 2 -n 6 populations, use seed so same run each time', 'pmt -s 2 -n 6 -r 3 populations') ]
cases = [('pmt -s 1 -n 20 populations, use seed so same run each time', 'pmt -s 1 -n 20 populations'), ('pmt -s 2 -n 6 populations, use seed so same run each time', 'pmt -s 2 -n 6 -r 3 populations')]
{ "hawq": { "master": "localhost", "standby": "", "port": 5432, "user": "johnsaxon", "password": "test", "database": "postgres" }, "data_config": { "schema": "public", "table": "elec_tiny", "features": [ { "n...
{'hawq': {'master': 'localhost', 'standby': '', 'port': 5432, 'user': 'johnsaxon', 'password': 'test', 'database': 'postgres'}, 'data_config': {'schema': 'public', 'table': 'elec_tiny', 'features': [{'name': 'id', 'type': 'categorical', 'cates': ['2019-01-20', '2019-03-01', '2019-04-20', '2018-09-10', '2018-12-01', '20...
{ "targets": [{ "target_name": "findGitRepos", "dependencies": [ "vendor/openpa/openpa.gyp:openpa" ], "sources": [ "cpp/src/FindGitRepos.cpp", "cpp/src/Queue.cpp" ], "include_dirs": [ "<!@(node -p \"require('node-addon...
{'targets': [{'target_name': 'findGitRepos', 'dependencies': ['vendor/openpa/openpa.gyp:openpa'], 'sources': ['cpp/src/FindGitRepos.cpp', 'cpp/src/Queue.cpp'], 'include_dirs': ['<!@(node -p "require(\'node-addon-api\').include")', 'cpp/includes'], 'defines': ['NAPI_DISABLE_CPP_EXCEPTIONS'], 'conditions': [["OS=='win'",...
# Using hash table # Time Complexity: O(n) class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: checkDict =dict() final = list() for i in nums1: if i not in checkDict: checkDict[i] = 1 else: checkDict[...
class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: check_dict = dict() final = list() for i in nums1: if i not in checkDict: checkDict[i] = 1 else: checkDict[i] += 1 for i in nums2: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- class Names(): Chemical_Elemnts = ["Yb", "Pb", "Ca", "Ti", "Mo", "Sn", "Cd", "Ag", "La", "Cs", "W", "Sb", "Ta", "V", "Fe", "Bi", "Ce", "Nb", "Cu", "I", "B", "Te", "Al", "Zr", "Gd", "Na", "Ga", "Cl"...
class Names: chemical__elemnts = ['Yb', 'Pb', 'Ca', 'Ti', 'Mo', 'Sn', 'Cd', 'Ag', 'La', 'Cs', 'W', 'Sb', 'Ta', 'V', 'Fe', 'Bi', 'Ce', 'Nb', 'Cu', 'I', 'B', 'Te', 'Al', 'Zr', 'Gd', 'Na', 'Ga', 'Cl', 'S', 'Si', 'O', 'F', 'Mn', 'Ba', 'K', 'Zn', 'N', 'Li', 'Ge', 'Y', 'Sr', 'P', 'Mg', 'Er', 'As'] "\n Chemical_Com...
# Build a Boolean mask to filter out all the 'LAX' departure flights: mask mask = df['Destination Airport'] == 'LAX' # Use the mask to subset the data: la la = df[mask] # Combine two columns of data to create a datetime series: times_tz_none times_tz_none = pd.to_datetime( la['Date (MM/DD/YYYY)'] + ' ' + la['Wheels-...
mask = df['Destination Airport'] == 'LAX' la = df[mask] times_tz_none = pd.to_datetime(la['Date (MM/DD/YYYY)'] + ' ' + la['Wheels-off Time']) times_tz_central = times_tz_none.dt.tz_localize('US/Central') times_tz_pacific = times_tz_central.dt.tz_convert('US/Pacific')
''' Given an unsorted array of integers, find the number of longest increasing subsequence. Example 1: Input: [1,3,5,4,7] Output: 2 Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7]. Example 2: Input: [2,2,2,2,2] Output: 5 Explanation: The length of longest continuous increasing subs...
""" Given an unsorted array of integers, find the number of longest increasing subsequence. Example 1: Input: [1,3,5,4,7] Output: 2 Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7]. Example 2: Input: [2,2,2,2,2] Output: 5 Explanation: The length of longest continuous increasing subs...
# python3 def solve(n, v): #if sum(v) % 3 != 0: # return False res = [] values = [] s = sum(v)//3 for i in range(2**n): bit = [0 for i in range(n)] k = i p = n-1 while k!=0: bit[p] = (k%2) k = k//2 p -= 1 ...
def solve(n, v): res = [] values = [] s = sum(v) // 3 for i in range(2 ** n): bit = [0 for i in range(n)] k = i p = n - 1 while k != 0: bit[p] = k % 2 k = k // 2 p -= 1 val = [a * b for (a, b) in zip(v, bit)] if sum(val)...
# create string and dictionary lines = "" occurrences = {} # prompt for lines line = input("Enter line: ") while line: lines += line + " " line = input("Enter line: ") # iterate through each color and store count for word in set(lines.split()): occurrences[word] = lines.split().count(word) # print result...
lines = '' occurrences = {} line = input('Enter line: ') while line: lines += line + ' ' line = input('Enter line: ') for word in set(lines.split()): occurrences[word] = lines.split().count(word) for word in sorted(occurrences): print(word, occurrences[word])
# python3 n, m = map(int, input().split()) clauses = [ list(map(int, input().split())) for i in range(m) ] # This solution tries all possible 2^n variable assignments. # It is too slow to pass the problem. # Implement a more efficient algorithm here. def isSatisfiable(): for mask in range(1<<n): result = [...
(n, m) = map(int, input().split()) clauses = [list(map(int, input().split())) for i in range(m)] def is_satisfiable(): for mask in range(1 << n): result = [mask >> i & 1 for i in range(n)] formula_is_satisfied = True for clause in clauses: clause_is_satisfied = False ...
class FlPosition: def __init__(self, position_data, column_labels, timestamps, conversion): self.position_data = position_data self.column_labels = column_labels self.timestamps = timestamps self.conversion = conversion
class Flposition: def __init__(self, position_data, column_labels, timestamps, conversion): self.position_data = position_data self.column_labels = column_labels self.timestamps = timestamps self.conversion = conversion
class Recipe: def __init__(self, name, ingredients, yt_link): self.name = name self.ingredients = ingredients self.yt_link = yt_link self.similarity = 0 self.leftChild = None self.rightChild = None class BinarySearchTree: def __init__(self): self.root...
class Recipe: def __init__(self, name, ingredients, yt_link): self.name = name self.ingredients = ingredients self.yt_link = yt_link self.similarity = 0 self.leftChild = None self.rightChild = None class Binarysearchtree: def __init__(self): self.root =...
######################################################################## # Useful classes for implementing quantum heterostructures behavior # # author: Thiago Melo # # creation: 2018-11-09 # # update: 2018-11-09 ...
class Device(object): def __init__(self): pass
def deco(func): def temp(): print("-"*60) func() print("-"*60) return temp @deco def print_h1(): print("body") def main(): print_h1() if __name__ == "__main__": main()
def deco(func): def temp(): print('-' * 60) func() print('-' * 60) return temp @deco def print_h1(): print('body') def main(): print_h1() if __name__ == '__main__': main()
# linear search on sorted list def search(L, e): for i in range(len(L)): if L[i] == e: return True if L[i] > e: # sorted return False return False # O(n) for the loop and O(1) for the lookup to test if e == L[i] # overall complexity is O(n) where n is len(L)
def search(L, e): for i in range(len(L)): if L[i] == e: return True if L[i] > e: return False return False
def CheckPypi(auth, project): projectInfo = auth.GetJson("https://pypi.org/pypi/" + project + "/json") return projectInfo["info"]["version"]
def check_pypi(auth, project): project_info = auth.GetJson('https://pypi.org/pypi/' + project + '/json') return projectInfo['info']['version']
# Exercise 3: # # In this exercise we will create a program that identifies whether someone can # enter a super secret club. # Below are the people that are allowed in the club. # If your name is Bill Gates, Steve Jobs or Jesus, you should be allowed in the # club. # If your name is not one of the above, but your name ...
print("What's your name?") name = raw_input() print("What's your age?") age = input() if name == 'Bill Gates' or name == 'Steve Jobs' or name == 'Jesus': print('You are welcomed in our fancy club!') elif name == 'Maria' and age < 30: print('You are welcomed in our fancy club!') elif age > 100: print('You ar...
N, K = [int(a) for a in input().split()] h = [] for _ in range(N): h.append(int(input())) sortedh = sorted(h) min_ = 1e9 for i in range(N-K+1): diff = sortedh[i+K-1] - sortedh[i] min_ = min(min_, diff) print(min_)
(n, k) = [int(a) for a in input().split()] h = [] for _ in range(N): h.append(int(input())) sortedh = sorted(h) min_ = 1000000000.0 for i in range(N - K + 1): diff = sortedh[i + K - 1] - sortedh[i] min_ = min(min_, diff) print(min_)
#!/usr/bin/env python # -*- coding: utf-8 -*- # Created by AKM_FAN@163.com on 2017/11/6 if __name__ == '__main__': pass
if __name__ == '__main__': pass
# !/usr/bin/python # -*- coding: utf-8 -*- class Friends(object): def __init__(self, connections): super(Friends, self).__init__() self._data = {} self._add_connections(connections) def add(self, connection): is_exists = self.is_exists(connection) self._add_c...
class Friends(object): def __init__(self, connections): super(Friends, self).__init__() self._data = {} self._add_connections(connections) def add(self, connection): is_exists = self.is_exists(connection) self._add_connection(connection) return not is_exists ...
def table_service(*args): text, client, current_channel = args if text.lower().startswith("tables"): number = int(text.split()[-1]) result = "" for i in range(1, 11): result += f"{number} X {i} = {number*i}\n" client.chat_postMessage(channel=current_channel, text=resu...
def table_service(*args): (text, client, current_channel) = args if text.lower().startswith('tables'): number = int(text.split()[-1]) result = '' for i in range(1, 11): result += f'{number} X {i} = {number * i}\n' client.chat_postMessage(channel=current_channel, text=...
class Parameters: def __init__(self, **kwargs): self.__dict__.update(kwargs) def info(self): print("The parameters, and data-type are: ") for key,values in self.__dict__.items(): print("{} = {}, {}\n".format(key, values, type(values)))
class Parameters: def __init__(self, **kwargs): self.__dict__.update(kwargs) def info(self): print('The parameters, and data-type are: ') for (key, values) in self.__dict__.items(): print('{} = {}, {}\n'.format(key, values, type(values)))
if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) max_val = max(arr) while(max_val in arr): arr.remove(max_val) print(max(arr))
if __name__ == '__main__': n = int(input()) arr = list(map(int, input().split())) max_val = max(arr) while max_val in arr: arr.remove(max_val) print(max(arr))
def solution(A): curSlice = float('-inf') maxSlice = float('-inf') for num in A: curSlice = max(num, curSlice+num) maxSlice = max(curSlice, maxSlice) return maxSlice if __name__ == '__main__': print(solution([3,2,-6,4,0])) print(solution([-10]))
def solution(A): cur_slice = float('-inf') max_slice = float('-inf') for num in A: cur_slice = max(num, curSlice + num) max_slice = max(curSlice, maxSlice) return maxSlice if __name__ == '__main__': print(solution([3, 2, -6, 4, 0])) print(solution([-10]))
class Solution: def XXX(self, head: ListNode) -> ListNode: o = head p = None while head is not None: if p is not None and head.val == p.val: p.next = head.next else: p = head head = head.next return o
class Solution: def xxx(self, head: ListNode) -> ListNode: o = head p = None while head is not None: if p is not None and head.val == p.val: p.next = head.next else: p = head head = head.next return o
def start(): return def stop(): return def apply_command(self, c, e, command, arguments): pass def on_welcome(self, c, e): pass def on_invite(self, c, e): pass def on_join(self, c, e): pass def on_namreply(self, c, e): pass def on_pubmsg(self, c, e): pass def on_privmsg(s...
def start(): return def stop(): return def apply_command(self, c, e, command, arguments): pass def on_welcome(self, c, e): pass def on_invite(self, c, e): pass def on_join(self, c, e): pass def on_namreply(self, c, e): pass def on_pubmsg(self, c, e): pass def on_privmsg(self, c, ...
# Code Challenge 13 open_list = ["[", "{", "("] close_list = ["]", "}", ")"] def validate_brackets(str): stack=[] for i in str: if i in open_list: stack.append(i) elif i in close_list: x = close_list.index(i) if ((len(stack) > 0) ...
open_list = ['[', '{', '('] close_list = [']', '}', ')'] def validate_brackets(str): stack = [] for i in str: if i in open_list: stack.append(i) elif i in close_list: x = close_list.index(i) if len(stack) > 0 and open_list[x] == stack[len(stack) - 1]: ...
tail = input() body = input() head = input() meerkat = [tail, body, head] meerkat.reverse() print(meerkat)
tail = input() body = input() head = input() meerkat = [tail, body, head] meerkat.reverse() print(meerkat)
num = int(input()) for i in range(num): s = input() t = input() p = input()
num = int(input()) for i in range(num): s = input() t = input() p = input()
def peopleneeded(Smax, S): needed = 0 for s in range(Smax+1): if sum(S[:s+1])<s+1: needed += s+1-sum(S[:s+1]) S[s] += s+1-sum(S[:s+1]) return needed def get_output(instance): inputdata = open(instance + ".in", 'r') output = open(instance+ ".out", 'w') T = int(inp...
def peopleneeded(Smax, S): needed = 0 for s in range(Smax + 1): if sum(S[:s + 1]) < s + 1: needed += s + 1 - sum(S[:s + 1]) S[s] += s + 1 - sum(S[:s + 1]) return needed def get_output(instance): inputdata = open(instance + '.in', 'r') output = open(instance + '.out',...
class Solution: def isValidSerialization(self, preorder: str) -> bool: degree = 1 # outDegree (children) - inDegree (parent) for node in preorder.split(','): degree -= 1 if degree < 0: return False if node != '#': degree += 2 return degree == 0
class Solution: def is_valid_serialization(self, preorder: str) -> bool: degree = 1 for node in preorder.split(','): degree -= 1 if degree < 0: return False if node != '#': degree += 2 return degree == 0
class ZoneFilter: def __init__(self, rules): self.rules = rules def filter(self, record): # TODO Dummy implementation return [record]
class Zonefilter: def __init__(self, rules): self.rules = rules def filter(self, record): return [record]
class HyperparameterGrid(): def __init__(self): DEFAULT_HYPERPARAMETER_GRID = { 'lr': { 'C': [0.001, 0.01, 0.1, 1], 'penalty': ['l1', 'l2'], 'solver': ['liblinear'], 'intercept_scaling': [1, 1000], 'max_iter': [1000...
class Hyperparametergrid: def __init__(self): default_hyperparameter_grid = {'lr': {'C': [0.001, 0.01, 0.1, 1], 'penalty': ['l1', 'l2'], 'solver': ['liblinear'], 'intercept_scaling': [1, 1000], 'max_iter': [1000]}, 'dt': {'criterion': ['gini', 'entropy'], 'max_depth': [3, 5, 10, None], 'min_samples_leaf': ...
def uniqueElements(myList): uniqList = [] for _var in myList: if _var not in uniqList: uniqList.append(_var) else: return "Not Unique" return "Unique" print(uniqueElements([2,99,99,12,3,11,223]))
def unique_elements(myList): uniq_list = [] for _var in myList: if _var not in uniqList: uniqList.append(_var) else: return 'Not Unique' return 'Unique' print(unique_elements([2, 99, 99, 12, 3, 11, 223]))
def magic_square(square): size_square = len(square) is_magic = True wanted_sum = 0 for index in range(0, size_square): wanted_sum += square[0][index] for row in range(0, size_square): current_sum = 0 for col in range(0, size_square): current_sum += square[row][col] if current_sum != wanted_sum: ...
def magic_square(square): size_square = len(square) is_magic = True wanted_sum = 0 for index in range(0, size_square): wanted_sum += square[0][index] for row in range(0, size_square): current_sum = 0 for col in range(0, size_square): current_sum += square[row][col...
def f(x): y=1 x=x+y return x x=3 y=2 z=f(x) print("x="+str(x)) print("y="+str(y)) print("z="+str(z))
def f(x): y = 1 x = x + y return x x = 3 y = 2 z = f(x) print('x=' + str(x)) print('y=' + str(y)) print('z=' + str(z))
__all__ = [ "mock_generation_data_frame", "test_get_monthly_net_generation", "test_rate_limit", "test_retry", ]
__all__ = ['mock_generation_data_frame', 'test_get_monthly_net_generation', 'test_rate_limit', 'test_retry']
test = { 'name': 'q1_2', 'points': 1, 'suites': [ { 'cases': [ {'code': ">>> assert trending_vids.shape[0] == '40379'\n", 'hidden': False, 'locked': False}, {'code': ">>> assert trending_vids.iloc[0, 0] == '25231'\n", 'hidden': False, 'locked': False}, ...
test = {'name': 'q1_2', 'points': 1, 'suites': [{'cases': [{'code': ">>> assert trending_vids.shape[0] == '40379'\n", 'hidden': False, 'locked': False}, {'code': ">>> assert trending_vids.iloc[0, 0] == '25231'\n", 'hidden': False, 'locked': False}, {'code': ">>> assert trending_vids.iloc[0, 4] == 'Inside Edition'\n", '...
class Income: def __init__(self): self.tranId = "" self.tradeId = "" self.symbol = "" self.incomeType = "" self.income = 0.0 self.asset = "" self.time = 0 @staticmethod def json_parse(json_data): result = Income() re...
class Income: def __init__(self): self.tranId = '' self.tradeId = '' self.symbol = '' self.incomeType = '' self.income = 0.0 self.asset = '' self.time = 0 @staticmethod def json_parse(json_data): result = income() result.tranId = json...
def game(input,max_turns): memory = {} turncounter = 1 most_recent_number = int(input[-1]) for i in range(len(input)): memory[int(input[i])] = [turncounter,-1] turncounter += 1 while turncounter <= max_turns: if memory[most_recent_number][1] == -1: most_r...
def game(input, max_turns): memory = {} turncounter = 1 most_recent_number = int(input[-1]) for i in range(len(input)): memory[int(input[i])] = [turncounter, -1] turncounter += 1 while turncounter <= max_turns: if memory[most_recent_number][1] == -1: most_recent_n...
def is_krampus(n): p = str(n**2) l_p = len(p) for i in range(1, l_p - 1): p_1 = int(p[:i]) p_2 = int(p[i:]) if p_1 and p_2 and p_1 + p_2 == n: return True return False def test_is_krampus(): assert is_krampus(45) assert not is_krampus(100) if __name__ ==...
def is_krampus(n): p = str(n ** 2) l_p = len(p) for i in range(1, l_p - 1): p_1 = int(p[:i]) p_2 = int(p[i:]) if p_1 and p_2 and (p_1 + p_2 == n): return True return False def test_is_krampus(): assert is_krampus(45) assert not is_krampus(100) if __name__ == ...
def adjacentElementsProduct(inputArray): first, second = 0, 1 lp = inputArray[first]*inputArray[second] for index in range(2, len(inputArray)): first = second second = index new_lp = inputArray[first]*inputArray[second] if new_lp > lp: lp = new_lp ...
def adjacent_elements_product(inputArray): (first, second) = (0, 1) lp = inputArray[first] * inputArray[second] for index in range(2, len(inputArray)): first = second second = index new_lp = inputArray[first] * inputArray[second] if new_lp > lp: lp = new_lp re...
def y(): pass def x(): y() for i in range(10): x()
def y(): pass def x(): y() for i in range(10): x()
INSTALLED_APPS = ( 'vkontakte_api', 'vkontakte_places', 'vkontakte_users', 'vkontakte_groups', 'vkontakte_comments', 'm2m_history', ) SOCIAL_API_TOKENS_STORAGES = []
installed_apps = ('vkontakte_api', 'vkontakte_places', 'vkontakte_users', 'vkontakte_groups', 'vkontakte_comments', 'm2m_history') social_api_tokens_storages = []
# # PySNMP MIB module AcAlarm (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AcAlarm # Produced by pysmi-0.3.4 at Wed May 1 11:33: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 2019, 09:23:15)...
(ac_alarm_event_type, ac_alarm_probable_cause, ac_alarm_severity) = mibBuilder.importSymbols('AC-FAULT-TC', 'AcAlarmEventType', 'AcAlarmProbableCause', 'AcAlarmSeverity') (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuil...
''' Processing of data via :py:mod:`.json_io`. Utilities for Excel conversion in :py:mod:`.convert` and :py:mod:`.service_sheet`. Example code in :py:mod:`.cli_examples` and :py:mod:`.plots`. '''
""" Processing of data via :py:mod:`.json_io`. Utilities for Excel conversion in :py:mod:`.convert` and :py:mod:`.service_sheet`. Example code in :py:mod:`.cli_examples` and :py:mod:`.plots`. """
# Create by Packetsss # Personal use is allowed # Commercial use is prohibited name = input("Enter your baphoon:") age = input("Enter your chikka:") print("WTF " + name + "! You are " + age + "??") num1 = input("Number 1:") num2 = input("Number 2:") result = num1 + num2
name = input('Enter your baphoon:') age = input('Enter your chikka:') print('WTF ' + name + '! You are ' + age + '??') num1 = input('Number 1:') num2 = input('Number 2:') result = num1 + num2
class Solution: def twoCitySchedCost(self, costs: List[List[int]]) -> int: for i in range(0,len(costs)): costs[i].append(costs[i][0]-costs[i][1]) costs.sort(key = lambda x:x[2]) result=0 for i in range(0,len(costs)//2): result+=costs[i][0] for ...
class Solution: def two_city_sched_cost(self, costs: List[List[int]]) -> int: for i in range(0, len(costs)): costs[i].append(costs[i][0] - costs[i][1]) costs.sort(key=lambda x: x[2]) result = 0 for i in range(0, len(costs) // 2): result += costs[i][0] ...
print("To print the place values of integer") a=int(input("Enter the integer value:")) n=a%10 print("The unit digit of {} is{}".format(a,n))
print('To print the place values of integer') a = int(input('Enter the integer value:')) n = a % 10 print('The unit digit of {} is{}'.format(a, n))
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def deleteNode(self, root, key): if not root: # if root doesn't exist, just return i...
class Solution(object): def delete_node(self, root, key): if not root: return root if root.val > key: root.left = self.deleteNode(root.left, key) elif root.val < key: root.right = self.deleteNode(root.right, key) else: if not root.righ...
ilksayi=1 ikincisayi=1 fibo=[ilksayi,ikincisayi] for i in range(0,20): ilksayi,ikincisayi=ikincisayi,ilksayi+ikincisayi fibo.append(ikincisayi) print(fibo)
ilksayi = 1 ikincisayi = 1 fibo = [ilksayi, ikincisayi] for i in range(0, 20): (ilksayi, ikincisayi) = (ikincisayi, ilksayi + ikincisayi) fibo.append(ikincisayi) print(fibo)
class BinaryNotFound(Exception): def __init__(self, binary_name): Exception.__init__(self) self.binary_name = binary_name class BinaryCallFailed(Exception): def __init__(self): Exception.__init__(self) class InvalidMedia(Exception): def __init__(self, media_path): Excepti...
class Binarynotfound(Exception): def __init__(self, binary_name): Exception.__init__(self) self.binary_name = binary_name class Binarycallfailed(Exception): def __init__(self): Exception.__init__(self) class Invalidmedia(Exception): def __init__(self, media_path): Except...
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: current = head previous = None while current is not None: ...
class Listnode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def remove_elements(self, head: ListNode, val: int) -> ListNode: current = head previous = None while current is not None: if current.val == val: ...
## ## # File auto-generated against equivalent DynamicSerialize Java class class DeleteFilesRequest(object): def __init__(self): self.datesToDelete = None def getDatesToDelete(self): return self.datesToDelete def setDatesToDelete(self, datesToDelete): self.datesToDelete = datesT...
class Deletefilesrequest(object): def __init__(self): self.datesToDelete = None def get_dates_to_delete(self): return self.datesToDelete def set_dates_to_delete(self, datesToDelete): self.datesToDelete = datesToDelete def get_filename(self): return self.filename ...
# -*- coding: utf-8 -*- ''' In a given list the first element should become the last one. An empty list or list with only one element should stay the same. Input: List. Output: Iterable. ''' def replace_first(items): # your code here return items[1:] + items[:1] if __name__ == "__main__": print("Examp...
""" In a given list the first element should become the last one. An empty list or list with only one element should stay the same. Input: List. Output: Iterable. """ def replace_first(items): return items[1:] + items[:1] if __name__ == '__main__': print('Example:') print(list(replace_first([1, 2, 3, 4]))...
''' FetcherResponse will return a well-formed FetcherResponse object { name: string, payload: {file_name: binary_data} | None, source: string error: Error object } "payload" - string - binary data from a successful url fetch or None on fail "source" - string - the url t...
""" FetcherResponse will return a well-formed FetcherResponse object { name: string, payload: {file_name: binary_data} | None, source: string error: Error object } "payload" - string - binary data from a successful url fetch or None on fail "source" - string - the url t...
load(":character_classes.bzl", "is_alphanumeric", "is_lower_case_letter", "is_numeric", "is_upper_case_letter") def tokenize(s): queue = [] parts = [] part = "" for i in range(len(s)): ch = s[i] if is_alphanumeric(ch): if len(queue) == 2: if is_upper_case_let...
load(':character_classes.bzl', 'is_alphanumeric', 'is_lower_case_letter', 'is_numeric', 'is_upper_case_letter') def tokenize(s): queue = [] parts = [] part = '' for i in range(len(s)): ch = s[i] if is_alphanumeric(ch): if len(queue) == 2: if is_upper_case_let...
# stats.py def init(): global _stats _stats = {} def event_occurred(event): global _stats try: _stats[event] = _stats[event] + 1 except KeyError: _stats[event] = 1 def get_stats(): global _stats return sorted(_stats.items())
def init(): global _stats _stats = {} def event_occurred(event): global _stats try: _stats[event] = _stats[event] + 1 except KeyError: _stats[event] = 1 def get_stats(): global _stats return sorted(_stats.items())
def is_odd(n): return n % 2 == 1 def collatz(n): xs = [] while n != 1: xs.append(n) if is_odd(n): n = 3*n + 1 else: n = n // 2 xs.append(1) return xs def test_collatz(): assert collatz(8) == [8, 4, 2, 1] assert collatz(5) == [5, 16, 8, 4, 2, ...
def is_odd(n): return n % 2 == 1 def collatz(n): xs = [] while n != 1: xs.append(n) if is_odd(n): n = 3 * n + 1 else: n = n // 2 xs.append(1) return xs def test_collatz(): assert collatz(8) == [8, 4, 2, 1] assert collatz(5) == [5, 16, 8, 4, 2...
email = [ "rwandaonline.rw", "rra.gov.rw", "ur.ac.rw", "gmail.com", "yahoo.com", "yahoo.fr" ]
email = ['rwandaonline.rw', 'rra.gov.rw', 'ur.ac.rw', 'gmail.com', 'yahoo.com', 'yahoo.fr']
print('list as x y z ...') a = [] a = input().split(' ') a = list(map(int, a)) for elemt in (map(lambda x: 'par' if x%2 == 0 else 'impar', a)): print (elemt)
print('list as x y z ...') a = [] a = input().split(' ') a = list(map(int, a)) for elemt in map(lambda x: 'par' if x % 2 == 0 else 'impar', a): print(elemt)
while True: try: n = int(input()) except: break data = list() maax = list() miin = list() for x in range(n): data.append(list(map(int, input().split()))) for x in range(n): maax.append(data[x][1]) miin.append(data[x][0]) result = [0]*(...
while True: try: n = int(input()) except: break data = list() maax = list() miin = list() for x in range(n): data.append(list(map(int, input().split()))) for x in range(n): maax.append(data[x][1]) miin.append(data[x][0]) result = [0] * (max(maax) -...
applyPatch('20210630-dldt-disable-unused-targets.patch') applyPatch('20210630-dldt-pdb.patch') applyPatch('20210630-dldt-disable-multidevice-autoplugin.patch') applyPatch('20210630-dldt-vs-version.patch')
apply_patch('20210630-dldt-disable-unused-targets.patch') apply_patch('20210630-dldt-pdb.patch') apply_patch('20210630-dldt-disable-multidevice-autoplugin.patch') apply_patch('20210630-dldt-vs-version.patch')
try: age = int(input("How old are you: ")) #if statement if age < 0: print("You are a time traveller") else: if 0 < age <= 17: print("Too young to vote") else: if age >= 18: print("You can vote") except: print("Please use only numeric...
try: age = int(input('How old are you: ')) if age < 0: print('You are a time traveller') elif 0 < age <= 17: print('Too young to vote') elif age >= 18: print('You can vote') except: print('Please use only numeric values')
# iterating backwards # removing rogue vlues # when an item 's removed from the list, all the later items are shuffled down, to fill in the gap # That messes upu the index numbers, as we work forwards through the list data = [104, 101, 4, 105, 308, 103, 5, 107, 100, 306, 106, 102, 108] min_valid = 100 max_valid...
data = [104, 101, 4, 105, 308, 103, 5, 107, 100, 306, 106, 102, 108] min_valid = 100 max_valid = 200 top_index = len(data) - 1 for (index, value) in enumerate(reversed(data)): if value < min_valid or value > max_valid: print(top_index - index, value) del data[top_index - index] print(data)
# A quick solution for day 12 part 2 in Python # for debugging of the Pascal version x = 0 y = 0 wx = 10 wy = -1 with open('resources/input.txt', 'r') as f: for l in f.readlines(): l = l.strip() i = l[0] n = int(l[1:]) if i == 'N': wy -= n elif i == 'W': ...
x = 0 y = 0 wx = 10 wy = -1 with open('resources/input.txt', 'r') as f: for l in f.readlines(): l = l.strip() i = l[0] n = int(l[1:]) if i == 'N': wy -= n elif i == 'W': wx -= n elif i == 'S': wy += n elif i == 'E': ...
a = get() b = execute(mogrify(get())) print(b) mogrify(a) c = get()
a = get() b = execute(mogrify(get())) print(b) mogrify(a) c = get()
year=int(input('enter a num:')) if year%4==0 or year%400==0: print('leap year') else: print('not')
year = int(input('enter a num:')) if year % 4 == 0 or year % 400 == 0: print('leap year') else: print('not')
# A few global config settings API_KEY='' ORG_ID='' S3_BUCKET_NAME='' S3_ACCESS_KEY='' S3_SECRET_KEY='' MY_ID='' PLAYER_LICENSE=''
api_key = '' org_id = '' s3_bucket_name = '' s3_access_key = '' s3_secret_key = '' my_id = '' player_license = ''
__authors__ = "" __copyright__ = "(c) 2014, pymal" __license__ = "BSD License" __contact__ = "Name Of Current Guardian of this file <email@address>" USER_AGENT = 'api-indiv-0829BA2B33942A4A5E6338FE05EFB8A1' HOST_NAME = "http://myanimelist.net" DEBUG = False RETRY_NUMBER = 4 RETRY_SLEEP = 1 SHORT_SITE_FORMAT_TIME = ...
__authors__ = '' __copyright__ = '(c) 2014, pymal' __license__ = 'BSD License' __contact__ = 'Name Of Current Guardian of this file <email@address>' user_agent = 'api-indiv-0829BA2B33942A4A5E6338FE05EFB8A1' host_name = 'http://myanimelist.net' debug = False retry_number = 4 retry_sleep = 1 short_site_format_time = '%b ...
class Solution: def nextGreaterElements(self, nums: List[int]) -> List[int]: n = len(nums) stack = [] result = [-1] * n for i in range(n * 2): value = nums[i % n] while stack and nums[stack[-1] % n] < value: result[stack.pop() % n] = va...
class Solution: def next_greater_elements(self, nums: List[int]) -> List[int]: n = len(nums) stack = [] result = [-1] * n for i in range(n * 2): value = nums[i % n] while stack and nums[stack[-1] % n] < value: result[stack.pop() % n] = value ...
# Part One matrix = [] with open("input") as f: for row in f: matrix.append(row) gama_rate = "" epsilon_rate = "" element_list = [] def most_frequent(List): return max(set(List), key=List.count) l_row = int(len(matrix[0])) for el in range(1, l_row): for row in matrix: element = row[el...
matrix = [] with open('input') as f: for row in f: matrix.append(row) gama_rate = '' epsilon_rate = '' element_list = [] def most_frequent(List): return max(set(List), key=List.count) l_row = int(len(matrix[0])) for el in range(1, l_row): for row in matrix: element = row[el - 1] ele...
class Address: host = 'localhost' port = '9666' def __init__(self, host=None, port=None): if host is not None: self.host = host if port is not None: self.port = port def is_empty(self) -> bool: return self.host == '' or self.port == '' def string(se...
class Address: host = 'localhost' port = '9666' def __init__(self, host=None, port=None): if host is not None: self.host = host if port is not None: self.port = port def is_empty(self) -> bool: return self.host == '' or self.port == '' def string(se...
f = open("cub_200/val.txt", "r") class_dict = {} rtn = open('val_tmp.txt', 'w') for x in f: class_int = int(x[7:10]) if class_int not in class_dict.keys(): class_dict[class_int] = 1 else: class_dict[class_int] += 1 if class_dict[class_int] > 5: if class_int % 2 == 0: ...
f = open('cub_200/val.txt', 'r') class_dict = {} rtn = open('val_tmp.txt', 'w') for x in f: class_int = int(x[7:10]) if class_int not in class_dict.keys(): class_dict[class_int] = 1 else: class_dict[class_int] += 1 if class_dict[class_int] > 5: if class_int % 2 == 0: ...
# coding: utf-8 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', }, } INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.sessions', 'django.contrib.contenttypes', 'registration', 'test_app', ) SECRET_K...
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}} installed_apps = ('django.contrib.auth', 'django.contrib.sites', 'django.contrib.sessions', 'django.contrib.contenttypes', 'registration', 'test_app') secret_key = '_' site_id = 1 root_urlconf = 'test_app.urls' template_loaders = ('dj...
def show_state(state, player): return { 'hands': state['hands'], 'turn': state['turn'], }
def show_state(state, player): return {'hands': state['hands'], 'turn': state['turn']}
class MultimodalDataset: def __init__(self, samples, modality_factories): super().__init__() self.samples = samples self.modality_factories = modality_factories self._register_modalites_to_samples() def _register_modalites_to_samples(self): for sample in self.samples: ...
class Multimodaldataset: def __init__(self, samples, modality_factories): super().__init__() self.samples = samples self.modality_factories = modality_factories self._register_modalites_to_samples() def _register_modalites_to_samples(self): for sample in self.samples: ...
class Solution: def isValid(self, s: str) -> bool: matched=[0 for i in range(len(s))] open_brace=0 find='' for i in range (len(s)): if(s[i]==')' or s[i]=='}' or s[i]==']'): if(s[i]==')'): find='(' ...
class Solution: def is_valid(self, s: str) -> bool: matched = [0 for i in range(len(s))] open_brace = 0 find = '' for i in range(len(s)): if s[i] == ')' or s[i] == '}' or s[i] == ']': if s[i] == ')': find = '(' elif s[i...
def generate( args ): args = args.split(',') start = int(args[0]) numGroups = int(args[1]) perGroup = int(args[2]) interval = int(args[3]) ret = '' for i in range(numGroups): first = start + i * interval last = first + perGroup - 1 ret = ret + '{0}-{1}'.format...
def generate(args): args = args.split(',') start = int(args[0]) num_groups = int(args[1]) per_group = int(args[2]) interval = int(args[3]) ret = '' for i in range(numGroups): first = start + i * interval last = first + perGroup - 1 ret = ret + '{0}-{1}'.format(first, ...
_base_ = '../retinanet/retinanet_r50_fpn_1x_coco.py' model = dict( neck=[ dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs='on_input', num_outs=5), dict( type='SEPC...
_base_ = '../retinanet/retinanet_r50_fpn_1x_coco.py' model = dict(neck=[dict(type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, start_level=1, add_extra_convs='on_input', num_outs=5), dict(type='SEPC', out_channels=256, Pconv_num=4, pconv_deform=False, lcconv_deform=False, iBN=False)], bbox_head=dict(typ...
def main(): week={'A':'MON','B':'TUE','C':'WED','D':'THU','E':'FRI','F':'SAT','G':'SUN'} strs = [] for i in range(0,4): strs.append(input()) for i in range(0,min(len(strs[0]),len(strs[1]))): if(strs[0][i]==strs[1][i]): if(strs[0][i]>='A' and strs[0][i]<='G'): ...
def main(): week = {'A': 'MON', 'B': 'TUE', 'C': 'WED', 'D': 'THU', 'E': 'FRI', 'F': 'SAT', 'G': 'SUN'} strs = [] for i in range(0, 4): strs.append(input()) for i in range(0, min(len(strs[0]), len(strs[1]))): if strs[0][i] == strs[1][i]: if strs[0][i] >= 'A' and strs[0][i] <=...