content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# -*- coding: utf-8 -*- def parse_infobox(page): ibox = {} text = ''.join(page) current = '' infobox = [] inside = False for line in page: if line.lower().strip().strip('|') == '}}': break if inside: infobox.append(line) if line.lower().strip().s...
def parse_infobox(page): ibox = {} text = ''.join(page) current = '' infobox = [] inside = False for line in page: if line.lower().strip().strip('|') == '}}': break if inside: infobox.append(line) if line.lower().strip().startswith('{{infobox'): ...
#Exercicio 1 largura = int(input("Digite a largura: ")) altura = int(input("Digite a Altura: ")) #Counters i = 0 j = 0 while i < altura: while j < largura: print("#",end='') j += 1 print() j = 0 i += 1
largura = int(input('Digite a largura: ')) altura = int(input('Digite a Altura: ')) i = 0 j = 0 while i < altura: while j < largura: print('#', end='') j += 1 print() j = 0 i += 1
# This code contains simple examples about the use and manipulation of lists in Python. # What is a list? # Lists are a collection of items (integers, floats, strings...) in a particular order. colors = ["red", "green", "blue", "yellow", "black"] print("This is a list:") print(colors) # Accessing elements in ...
colors = ['red', 'green', 'blue', 'yellow', 'black'] print('This is a list:') print(colors) print('The first element of the list colors is: ' + colors[0]) print('colors[0] = ' + colors[0]) print('colors[1] = ' + colors[1]) print('colors[2] = ' + colors[2]) print('colors[3] = ' + colors[3]) print('colors[4] = ' + colors...
# configuration file for interface "email_1" # this file exists as a reference for configuring e-mail interfaces # # copy this file to your own cage, possibly renaming into # config_interface_YOUR_INTERFACE_NAME.py, then modify the copy config = dict \ ( protocol = "email", # meta server_addres...
config = dict(protocol='email', server_address=('mail.domain.com', 110), connect_timeout=3.0, ssl_key_cert_file=None, ssl_ca_cert_file=None, ssl_ciphers=None, ssl_protocol=None, ssl_server_hostname=None, ssl_ignore_hostname=False, username='user', password='pass', interval=60.0) __all__ = ['get', 'copy'] get = lambda k...
# Maps huegely attribute names to hue API naming scheme HUEGELY_TO_HUE_MAPPING = { # huegely_name: hue_name, 'brightness': 'bri', 'saturation': 'sat', 'temperature': 'ct', 'is_reachable': 'reachable', 'coordinates': 'xy', 'color_mode': 'colormode', 'transition_time': 'transitiontime', ...
huegely_to_hue_mapping = {'brightness': 'bri', 'saturation': 'sat', 'temperature': 'ct', 'is_reachable': 'reachable', 'coordinates': 'xy', 'color_mode': 'colormode', 'transition_time': 'transitiontime', 'last_updated': 'lastupdated'} hue_to_huegely_mapping = {v: k for (k, v) in HUEGELY_TO_HUE_MAPPING.items()}
n = int(input()) A = [[False] * n for _ in range(n) ] for i in range(n): A[0][i] = True A[i][i] = True A[n-1][i] = True A[i][0] = True A[i][n-1] = True A[n-i-1][i] = True for i in range(n): for j in range(n): if A[i][j] : print(".",end='') else : ...
n = int(input()) a = [[False] * n for _ in range(n)] for i in range(n): A[0][i] = True A[i][i] = True A[n - 1][i] = True A[i][0] = True A[i][n - 1] = True A[n - i - 1][i] = True for i in range(n): for j in range(n): if A[i][j]: print('.', end='') else: ...
# To use print function from Python 3 in Python2 # from __future__ import print_function # String word print("hello world") print('this is a string') # this code will get error # print('I'm a string') print("i'm a string") print('"this is a quote"') print('Here is a new line \n and here is the second line') print(...
print('hello world') print('this is a string') print("i'm a string") print('"this is a quote"') print('Here is a new line \n and here is the second line') print('Here is a new tab \t and here is the second line') print(len('Hello World')) s = 'Hello World' print(s) print(s[0]) print(s[1]) print(s[1:]) print(s[:5]) prin...
# -*- coding: utf-8 -*- model = { u'oku': 0, u'la ': 1, u'nga': 2, u' ng': 3, u'a n': 4, u' ku': 5, u'a k': 6, u'thi': 7, u' uk': 8, u'ezi': 9, u'e n': 10, u'uku': 11, u'le ': 12, u'lo ': 13, u'hi ': 14, u'wa ': 15, u' no': 16, u'a u': 17, u'ela': 18, u'we ': 19, u'a i': 20, u'ni ': 21, u'ele': 2...
model = {u'oku': 0, u'la ': 1, u'nga': 2, u' ng': 3, u'a n': 4, u' ku': 5, u'a k': 6, u'thi': 7, u' uk': 8, u'ezi': 9, u'e n': 10, u'uku': 11, u'le ': 12, u'lo ': 13, u'hi ': 14, u'wa ': 15, u' no': 16, u'a u': 17, u'ela': 18, u'we ': 19, u'a i': 20, u'ni ': 21, u'ele': 22, u'zin': 23, u'uth': 24, u'ama': 25, u'elo': 2...
int_max = 0x7FFFFFF json_serialize_method_name = "to_json" class Documents: class Metadata: COLLECTION = "@collection" CONFLICT = "@conflict" PROJECTION = "@projection" METADATA = "@metadata" KEY = "@metadata" ID = "@id" FLAGS = "@flags" ATTACHMENTS ...
int_max = 134217727 json_serialize_method_name = 'to_json' class Documents: class Metadata: collection = '@collection' conflict = '@conflict' projection = '@projection' metadata = '@metadata' key = '@metadata' id = '@id' flags = '@flags' attachments ...
def events(S, S_1): cnt = 0 j = 0 for i in range(len(S)): if S[i] == S_1[j]: j += 1 cnt += 1 return cnt == len(S_1) print(events("ABCBD", "BCBD"))
def events(S, S_1): cnt = 0 j = 0 for i in range(len(S)): if S[i] == S_1[j]: j += 1 cnt += 1 return cnt == len(S_1) print(events('ABCBD', 'BCBD'))
# Code sample from the book 'Data Structures and Algorithms in Python' print('''Welcome to the GPA calculator. Please enter all your letter grades, one per line. Enter a blank line to designate the end.''') def compute_gpa(grades, points = { 'A+' : 4.0, 'A' : 4.0, 'A-' : 3.67, 'B+'...
print('Welcome to the GPA calculator.\nPlease enter all your letter grades, one per line.\nEnter a blank line to designate the end.') def compute_gpa(grades, points={'A+': 4.0, 'A': 4.0, 'A-': 3.67, 'B+': 3.33, 'B': 3.0, 'B-': 2.67, 'C+': 2.33, 'C': 2.0, 'C-': 1.67, 'D+': 1.33, 'D': 1.0, 'F': 0.0}): num_courses = ...
class Cache: def __init__(self): # Name of the file self.__filename = "" # Cache entry location self.__entry_location = "" self.__rankings_location = "" # URL data self.__url = "" self.__url_length = "" self.__url_location = "" self._...
class Cache: def __init__(self): self.__filename = '' self.__entry_location = '' self.__rankings_location = '' self.__url = '' self.__url_length = '' self.__url_location = '' self.__range_url = '' self.__range_url_length = '' self.__range_url_...
class Solution: def fizzBuzz(self, n: int) -> List[str]: answer = [] for i in range(1,n+1): if i % 15 == 0: answer.append('FizzBuzz') elif i % 3 == 0: answer.append('Fizz') elif i % 5 == 0: answer.append('Buzz') else: answer.append(str(i)) retu...
class Solution: def fizz_buzz(self, n: int) -> List[str]: answer = [] for i in range(1, n + 1): if i % 15 == 0: answer.append('FizzBuzz') elif i % 3 == 0: answer.append('Fizz') elif i % 5 == 0: answer.append('Buzz')...
class Solution: def firstUniqChar(self, s: str) -> int: charCount = {} for i in range(len(s)): c = s[i] if c in charCount: charCount[c][1] += 1 else: charCount[c] = [i, 1] ...
class Solution: def first_uniq_char(self, s: str) -> int: char_count = {} for i in range(len(s)): c = s[i] if c in charCount: charCount[c][1] += 1 else: charCount[c] = [i, 1] index = [] for c in charCount: ...
build_config = { "folders": [ u'rm64' ] }
build_config = {'folders': [u'rm64']}
## # Created by sennhviwang # Time: Sun Sep 27 01:12:19 CST 2015. # # Quick Sort # Data Structure: Array # Time Complexity-Best: O(nlogn)(simple partition) or O(n) (three-way partition and equal keys) # Time Complexity-Average: O(nlogn) # Time Complexity-Worst: O(n2) # Space Complexity-Worst: O(...
def quick_sort(lists, left, right): if left >= right: return lists key = lists[left] low = left high = right while left < right: while left < right and lists[right] >= key: right -= 1 lists[left] = lists[right] while left < right and lists[left] <= key: ...
# Resolve the problem!! PALINDROMES = [ 'Acaso hubo buhos aca', 'A la catalana banal atacala', 'Amar da drama', ] NOT_PALINDROMES = [ 'Hola como estas', 'Platzi' 'Oscar', ] def is_palindrome(palindrome): without_blanks = [] cut_word = [] for letter in palindrome: if lette...
palindromes = ['Acaso hubo buhos aca', 'A la catalana banal atacala', 'Amar da drama'] not_palindromes = ['Hola como estas', 'PlatziOscar'] def is_palindrome(palindrome): without_blanks = [] cut_word = [] for letter in palindrome: if letter != ' ': cut_word.insert(0, letter) wit...
class Statistics: def __init__(self, mean, median, std, mode, max, min, count, kurt, sum, unique, var, sem) -> None: self.mean = mean self.median = median self.std = std self.mode = mode self.max = max self.min = min self.count = count self.kurt =...
class Statistics: def __init__(self, mean, median, std, mode, max, min, count, kurt, sum, unique, var, sem) -> None: self.mean = mean self.median = median self.std = std self.mode = mode self.max = max self.min = min self.count = count self.kurt = kur...
class VarAssignmentInterpreter: """ VarAssignmentInterpreter interprets all var assignment expressions """ def __init__(self, identifier, value, env, error): self.identifier = identifier self.value = value self.env = env self.error = error def execute(self): ...
class Varassignmentinterpreter: """ VarAssignmentInterpreter interprets all var assignment expressions """ def __init__(self, identifier, value, env, error): self.identifier = identifier self.value = value self.env = env self.error = error def execute(self): ...
# -*- coding: utf-8 -*- """ Created on Thu Jul 21 17:54:00 2016 @author: schueder """ def isnum(varagin): try: float(varagin) return True except ValueError: return False
""" Created on Thu Jul 21 17:54:00 2016 @author: schueder """ def isnum(varagin): try: float(varagin) return True except ValueError: return False
def slash_to_dash(text): return text.replace("/", "-") def extract_day(date_str): if date_str: return int(date_str.split("-")[2]) return None def extract_month(date_str): if date_str: return date_str.split("-")[1] return None def map_month(num): month_map = { "01":...
def slash_to_dash(text): return text.replace('/', '-') def extract_day(date_str): if date_str: return int(date_str.split('-')[2]) return None def extract_month(date_str): if date_str: return date_str.split('-')[1] return None def map_month(num): month_map = {'01': 'Jan', '02':...
def round_to(value, base): return round(value/base) * base def v_add(p1,p2): return [p1[0]+p2[0],p1[1]+p2[1]] def round_crty_point(point, grid_size): return [round_to(point[0], grid_size),round_to(point[1], grid_size)] def offset_dir(coordinate, offset, center=0): if coordinate > center: retu...
def round_to(value, base): return round(value / base) * base def v_add(p1, p2): return [p1[0] + p2[0], p1[1] + p2[1]] def round_crty_point(point, grid_size): return [round_to(point[0], grid_size), round_to(point[1], grid_size)] def offset_dir(coordinate, offset, center=0): if coordinate > center: ...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ retur...
class Solution(object): def add_two_numbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ return self.getll(self.getnum(l1) + self.getnum(l2)) def getnum(self, l): length = self.getlength(l) num = 0 for i i...
def binary_search(sorted_array, search_key): ''' This function searchs an input array for a key If it is there it returns the index of the key If not it returns -1 ''' for i in range(len(sorted_array)): if sorted_array[i] == search_key: return i return -1 # def binary_s...
def binary_search(sorted_array, search_key): """ This function searchs an input array for a key If it is there it returns the index of the key If not it returns -1 """ for i in range(len(sorted_array)): if sorted_array[i] == search_key: return i return -1
# day7 input = open('input/day7input.txt', 'r').read() # pos = input_example.split(',') pos = input.split(',') crabs = [] for c in pos: crabs.append(int(c)) csum = sum(crabs) destinations = list(range(min(crabs), max(crabs)+1, 1)) complete = max(destinations) fuelc_min = csum**2 efuelc_min = csum**2 for destinatio...
input = open('input/day7input.txt', 'r').read() pos = input.split(',') crabs = [] for c in pos: crabs.append(int(c)) csum = sum(crabs) destinations = list(range(min(crabs), max(crabs) + 1, 1)) complete = max(destinations) fuelc_min = csum ** 2 efuelc_min = csum ** 2 for destination in destinations: dest_min_fue...
description = 'Multiblade detector' sysconfig = dict(datasinks = ['jbi_liveview'],) display_order = 28 devices = dict( det_image = device( 'nicos_ess.devices.datasources.just_bin_it.JustBinItImage', description = 'Detector image channel', hist_topic = 'AMOR_histograms', data_topic...
description = 'Multiblade detector' sysconfig = dict(datasinks=['jbi_liveview']) display_order = 28 devices = dict(det_image=device('nicos_ess.devices.datasources.just_bin_it.JustBinItImage', description='Detector image channel', hist_topic='AMOR_histograms', data_topic='FREIA_detector', brokers=configdata('config.KAFK...
""" Advent of Code 2017 input is: input.txt pbga (66) xhth (57) ebii (61) havc (66) ktlj (57) fwft (72) -> ktlj, cntj, xhth qoyq (66) padx (45) -> pbga, havc, qoyq tknk (41) -> ugml, padx, fwft jptl (61) ugml (68) -> gyxo, ebii, jptl gyxo (61) cntj (57) --- Part Two --- The programs explain the situation: they can'...
""" Advent of Code 2017 input is: input.txt pbga (66) xhth (57) ebii (61) havc (66) ktlj (57) fwft (72) -> ktlj, cntj, xhth qoyq (66) padx (45) -> pbga, havc, qoyq tknk (41) -> ugml, padx, fwft jptl (61) ugml (68) -> gyxo, ebii, jptl gyxo (61) cntj (57) --- Part Two --- The programs explain the situation: they can'...
''' Given a string s, return the longest palindromic substring in s. Example 1: Input: s = "babad" Output: "bab" Note: "aba" is also a valid answer. ''' def longestPalindrome(s: str) -> str: res = '' resLen = 0 for i in range(len(s)): l, r = i, i while l >= 0 and r < len(s) and s[l]...
""" Given a string s, return the longest palindromic substring in s. Example 1: Input: s = "babad" Output: "bab" Note: "aba" is also a valid answer. """ def longest_palindrome(s: str) -> str: res = '' res_len = 0 for i in range(len(s)): (l, r) = (i, i) while l >= 0 and r < len(s) and (...
#FEAT_PATH dir to save files FEAT_PATH = './VGG_face_feat_8class' IMAGE_PATH = '/home/a/Desktop/MSP-Face/jpg_face/*/*' #paths for the VGG_MODEL MEANS_PATH = './affectnet_8class/output/affectnet_emo_mean.json' VGG_MODEL_PATH = './affectnet_8class/output/affectnet_8emo.model' IMAGE_WIDTH = 256 IMAGE_HEIGHT = 256 # us...
feat_path = './VGG_face_feat_8class' image_path = '/home/a/Desktop/MSP-Face/jpg_face/*/*' means_path = './affectnet_8class/output/affectnet_emo_mean.json' vgg_model_path = './affectnet_8class/output/affectnet_8emo.model' image_width = 256 image_height = 256 num_classes = 8 label_path = './Doc/label_consensus.json' name...
def test_shell_task(run_poe_subproc): result = run_poe_subproc("count", project="shells") assert ( result.capture == f"Poe => echo 1 && echo 2 && echo $(python -c 'print(1 + 2)')\n" ) assert result.stdout == "1\n2\n3\n" assert result.stderr == "" def test_shell_task_raises_given_ex...
def test_shell_task(run_poe_subproc): result = run_poe_subproc('count', project='shells') assert result.capture == f"Poe => echo 1 && echo 2 && echo $(python -c 'print(1 + 2)')\n" assert result.stdout == '1\n2\n3\n' assert result.stderr == '' def test_shell_task_raises_given_extra_args(run_poe): re...
class Solution: def checkSubarraySum(self, nums: List[int], k: int) -> bool: runningSum = 0 lookup = {0: -1} for index, number in enumerate(nums): runningSum += number if k: runningSum %= k if runningSum in lookup: ...
class Solution: def check_subarray_sum(self, nums: List[int], k: int) -> bool: running_sum = 0 lookup = {0: -1} for (index, number) in enumerate(nums): running_sum += number if k: running_sum %= k if runningSum in lookup: i...
sum = np.float16(1.0) i = 1. old = np.float16(0.0) while (sum != old): old = sum i += 1. diff = np.float16(1./i) sum += diff print (sum)
sum = np.float16(1.0) i = 1.0 old = np.float16(0.0) while sum != old: old = sum i += 1.0 diff = np.float16(1.0 / i) sum += diff print(sum)
# class Solution: def romanToInt(self, s): roman_dict={'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} result=0 x=0 for i in s[::-1]: if x<=roman_dict[i]: sum+=roman_dict[i] x=roma...
class Solution: def roman_to_int(self, s): roman_dict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} result = 0 x = 0 for i in s[::-1]: if x <= roman_dict[i]: sum += roman_dict[i] x = roman_dict[i] else: ...
# Define a function to return some characteristics of the dataset def data_look(car_list, notcar_list): data_dict = {} # Define a key in data_dict "n_cars" and store the number of car images data_dict["n_cars"] = len(car_list) # Define a key "n_notcars" and store the number of notcar images data_di...
def data_look(car_list, notcar_list): data_dict = {} data_dict['n_cars'] = len(car_list) data_dict['n_notcars'] = len(notcar_list) example_img = mpimg.imread(car_list[0]) data_dict['image_shape'] = example_img.shape data_dict['data_type'] = example_img.dtype return data_dict
int("1") print(type(1)) soma=1+1 print(soma) print("5+2= ",5+2) print("5-2= ",5-2) print("5*2= ",5*2) print("5**2= ",5**2) print("5/2= ",5/2) print("5//2= ",5//2) print("5%2= ",5%2) print("5+2= ",5+2)
int('1') print(type(1)) soma = 1 + 1 print(soma) print('5+2= ', 5 + 2) print('5-2= ', 5 - 2) print('5*2= ', 5 * 2) print('5**2= ', 5 ** 2) print('5/2= ', 5 / 2) print('5//2= ', 5 // 2) print('5%2= ', 5 % 2) print('5+2= ', 5 + 2)
# first day # neo ramotlou # 15 march 2018 Year = int(input('Enter the first year: \n')) Y2 = int(input('Enter the second year: \n')) for Year in range ( Year ,(Y2+1)): day = (Year - 1)%4 day = 1 +5*day day = day +4*((Year-1)%100) day = day +6*((Year-1)%400) day = day%7 ...
year = int(input('Enter the first year: \n')) y2 = int(input('Enter the second year: \n')) for year in range(Year, Y2 + 1): day = (Year - 1) % 4 day = 1 + 5 * day day = day + 4 * ((Year - 1) % 100) day = day + 6 * ((Year - 1) % 400) day = day % 7 if day == 0: day = 'Sunday.' elif day...
# linked list code # creating a node class node: def __init__(self, data): self.data = data self.next = None class linkedlist: def __init__(self): self.head = None #creating a header def search(self,data): #find the node with the given data in the list list...
class Node: def __init__(self, data): self.data = data self.next = None class Linkedlist: def __init__(self): self.head = None def search(self, data): list_cp = self count = 0 while list_cp: if list_cp.head.data == data: return ...
Ohio = "Columbus" Alabama = "Montgomery" Arkansas = "Little Rock" print(Ohio)
ohio = 'Columbus' alabama = 'Montgomery' arkansas = 'Little Rock' print(Ohio)
__author__ = 'sondredyvik' class Variable: def __init__(self, index, x, y): self.index = index self.x = x self.y = y def __repr__(self): return 'n' + str(self.index) def __hash__(self): return hash((self.index, self.x, self.y)) def __eq__(self, other): ...
__author__ = 'sondredyvik' class Variable: def __init__(self, index, x, y): self.index = index self.x = x self.y = y def __repr__(self): return 'n' + str(self.index) def __hash__(self): return hash((self.index, self.x, self.y)) def __eq__(self, other): ...
inputfile = open('day-6/day6_input.txt', 'r') # inputfile = open('day-6/day6_input_ex.txt', 'r') input = [int(val) for val in inputfile.read().split(',')] # At first I did it with a bunch of for loops, goign through everything and adding to the list. # Part 2, with 256 days, was in no way going to work like that. It ...
inputfile = open('day-6/day6_input.txt', 'r') input = [int(val) for val in inputfile.read().split(',')] def get_count_lantern_fish_after_days(fishList, days): fish_list = fishList.copy() count_lantern_fish = len(fishList) cycle_list = [0] * 9 for fish_age in fishList: cycleList[fishAge] += 1 ...
def find_the_ball(start, swaps): for a, b in swaps: if a == start: start = b elif b == start: start = a return start
def find_the_ball(start, swaps): for (a, b) in swaps: if a == start: start = b elif b == start: start = a return start
name = 'hello' def say(): print('hello')
name = 'hello' def say(): print('hello')
def filter(condition, list): for i in list: if condition(i): yield i def sort(lisT, key=lambda x: x, comparator=lambda x, y: x < y, reverse=True): for i in range(len(lisT)): for j in range(i, len(lisT)): if comparator(key(lisT[i]), key(lisT[j])): ...
def filter(condition, list): for i in list: if condition(i): yield i def sort(lisT, key=lambda x: x, comparator=lambda x, y: x < y, reverse=True): for i in range(len(lisT)): for j in range(i, len(lisT)): if comparator(key(lisT[i]), key(lisT[j])): (lisT[i]...
"""Common constants used across different modules. """ CACHEABLE_METHODS = ("HEAD", "GET") # Values below provided in seconds DEFAULT_MAX_AGE = 120 DEFAULT_WAIT_TIMEOUT = 60 * 5 # same value as in aiohttp library DEFAULT_SLEEP_TIME = 0.1 DEFAULT_CACHE_CAPACITY = 100 # max amount of records in cache
"""Common constants used across different modules. """ cacheable_methods = ('HEAD', 'GET') default_max_age = 120 default_wait_timeout = 60 * 5 default_sleep_time = 0.1 default_cache_capacity = 100
arr=[1,2,3,4,5] even=0 odd=0 for i in range(0,5): if arr[i]%2==0: even += 1 else: odd += 1 print("No of even elements in the array : ",even) print("No of odd elements in the array : ",odd)
arr = [1, 2, 3, 4, 5] even = 0 odd = 0 for i in range(0, 5): if arr[i] % 2 == 0: even += 1 else: odd += 1 print('No of even elements in the array : ', even) print('No of odd elements in the array : ', odd)
def get(dataframe, activity, attr_name, parameters=None): if parameters is None: parameters = {} red_df = dataframe[dataframe["event_activity"] == activity] return dict(red_df[attr_name].describe())
def get(dataframe, activity, attr_name, parameters=None): if parameters is None: parameters = {} red_df = dataframe[dataframe['event_activity'] == activity] return dict(red_df[attr_name].describe())
if not session.token: redirect(LOGIN) def index(): return dict()
if not session.token: redirect(LOGIN) def index(): return dict()
class PropertyCache(object): """ a decorator to cache property """ def __init__(self, func): self.func = func def __get__(self, obj, cls): if not obj: return self value = self.func(obj) setattr(obj, self.func.__name__, value) return value c...
class Propertycache(object): """ a decorator to cache property """ def __init__(self, func): self.func = func def __get__(self, obj, cls): if not obj: return self value = self.func(obj) setattr(obj, self.func.__name__, value) return value class Foo:...
def fib(n): if n<2: return 1 else: return fib(n-1)+fib(n-2) print(fib(1)) print(fib(5)) print(fib(10)) print(fib(20)) print(fib(-5)) #1 #8 #89 #10946 #1
def fib(n): if n < 2: return 1 else: return fib(n - 1) + fib(n - 2) print(fib(1)) print(fib(5)) print(fib(10)) print(fib(20)) print(fib(-5))
# Shim to wrap setup.py invocation with setuptools # # We set sys.argv[0] to the path to the underlying setup.py file so # setuptools / distutils don't take the path to the setup.py to be "-c" when # invoking via the shim. This avoids e.g. the following manifest_maker # warning: "warning: manifest_maker: standard file...
setuptools_shim = "import sys, setuptools, tokenize; sys.argv[0] = {0!r}; __file__={0!r};f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\\r\\n', '\\n');f.close();exec(compile(code, __file__, 'exec'))"
class B: def foo(self, arg1): pass class C(B): def foo(self, arg1, arg2=None): #pass pass
class B: def foo(self, arg1): pass class C(B): def foo(self, arg1, arg2=None): pass
#Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. class waterTrap: #[0,1,0,2,1,0,1,3,2,1,2,1] def func(self, list): #left pointer that moves leftidx=0 #right pointer that is fix rightid...
class Watertrap: def func(self, list): leftidx = 0 rightidx = len(list) - 1 leftmax = 0 rightmax = 0 raindrops = 0 while leftidx <= rightidx: leftmax = max(list[0:leftidx]) if leftidx else 0 rightmax = max(list[leftidx:]) temp = mi...
""" Other Operators Documentation - https://www.w3schools.com/python/python_operators.asp """ x = 3 y = 5 # Identity Operators x is y # Returns true if x and y are both the same object x is not y # Returns true if both variables are not the same object # Membership Operators x in y # Returns true if a sequence with...
""" Other Operators Documentation - https://www.w3schools.com/python/python_operators.asp """ x = 3 y = 5 x is y x is not y x in y x not in y x & y x | y x ^ y x << y x >> y
def PE_011(): f = open ('PE_011_input.txt', 'r') length = 20 max = 0 grid = [] # line[:-1] to get rid of \n for line in f: grid.append([int(x) for x in (line[:-1].split(" "))]) for i in xrange(length): # horizontal row = i for index in xrange(length): ...
def pe_011(): f = open('PE_011_input.txt', 'r') length = 20 max = 0 grid = [] for line in f: grid.append([int(x) for x in line[:-1].split(' ')]) for i in xrange(length): row = i for index in xrange(length): if index < length - 3: product = 1 ...
cur.prepareQuery("exec exampleproc") cur.inputBind("in1",1) cur.inputBind("in2",1.1,2,1) cur.inputBind("in3","hello") cur.defineOutputBindInteger("out1") cur.defineOutputBindDouble("out2") cur.defineOutputBindString("out3",20) cur.executeQuery() out1=cur.getOutputBindInteger("out1") out2=cur.getOutputBindDouble("out2")...
cur.prepareQuery('exec exampleproc') cur.inputBind('in1', 1) cur.inputBind('in2', 1.1, 2, 1) cur.inputBind('in3', 'hello') cur.defineOutputBindInteger('out1') cur.defineOutputBindDouble('out2') cur.defineOutputBindString('out3', 20) cur.executeQuery() out1 = cur.getOutputBindInteger('out1') out2 = cur.getOutputBindDoub...
# input # compute # output print(len(set(input())))
print(len(set(input())))
# O(n) time | O(1) space - where n is the number of cities def validStartingCity(distances, fuel, mpg): numberOfCities = len(distances) milesRemaining = 0 indexOfStartingCityCandidate = 0 milesRemainingAtStartingCityCandidate = 0 for cityIdx in range(1, numberOfCities): di...
def valid_starting_city(distances, fuel, mpg): number_of_cities = len(distances) miles_remaining = 0 index_of_starting_city_candidate = 0 miles_remaining_at_starting_city_candidate = 0 for city_idx in range(1, numberOfCities): distance_from_previous_city = distances[cityIdx - 1] fuel...
with open("2.txt") as txt: a, b = (txt.read()).split("\n")[:2] print(a == b) print(len(a)) print(len(b)) for pos, (i, j) in enumerate(zip(a, b)): if i != j: print(pos, repr(i), repr(j)) print(a[pos - 30:pos + 30]) print(b[pos - 30:pos + 30])
with open('2.txt') as txt: (a, b) = txt.read().split('\n')[:2] print(a == b) print(len(a)) print(len(b)) for (pos, (i, j)) in enumerate(zip(a, b)): if i != j: print(pos, repr(i), repr(j)) print(a[pos - 30:pos + 30]) print(b[pos - 30:pos + 30])
COLORS = { "TRANSPARENT": (0, 0, 0), "GREY": (128, 128, 128), "GREEN": (0, 100, 0), "LTGREEN": (0, 255, 0), "DKGREEN": (174, 177, 120), "WHITE": (255, 255, 255), "BLACK": (40, 40, 40), "RED": (201, 0, 22), }
colors = {'TRANSPARENT': (0, 0, 0), 'GREY': (128, 128, 128), 'GREEN': (0, 100, 0), 'LTGREEN': (0, 255, 0), 'DKGREEN': (174, 177, 120), 'WHITE': (255, 255, 255), 'BLACK': (40, 40, 40), 'RED': (201, 0, 22)}
def mtrace(cls): def trace(f): "Decorate a function to print a message before and after execution." def traced(*args, **kw): "Print message before and after a function call." print("Entering", f.__name__) result = f(*args, **kw) print("Leaving", f.__na...
def mtrace(cls): def trace(f): """Decorate a function to print a message before and after execution.""" def traced(*args, **kw): """Print message before and after a function call.""" print('Entering', f.__name__) result = f(*args, **kw) print('Leavin...
""" LeetCode Problem: 896. Monotonic Array Link: https://leetcode.com/problems/monotonic-array/ Language: Python Written by: Mostofa Adib Shakib """ class Solution(object): def isMonotonic(self, A): """ :type A: List[int] :rtype: bool """ if len(A) == 0: return False ...
""" LeetCode Problem: 896. Monotonic Array Link: https://leetcode.com/problems/monotonic-array/ Language: Python Written by: Mostofa Adib Shakib """ class Solution(object): def is_monotonic(self, A): """ :type A: List[int] :rtype: bool """ if len(A) == 0: return...
# One possible solution # hint for other solutions: # - you could use a break in the while loop # - you could avoid accessing res last elements by defining other variables res = [0, 1] next_el = res[0] + res[1] while next_el < 1000: res.append(next_el) next_el = res[-2] + res[-1]
res = [0, 1] next_el = res[0] + res[1] while next_el < 1000: res.append(next_el) next_el = res[-2] + res[-1]
a=[i for i in range(20)] b = [j for j in range(30)] print(a,b) for i,j in enumerate(a,20): print(i,j)
a = [i for i in range(20)] b = [j for j in range(30)] print(a, b) for (i, j) in enumerate(a, 20): print(i, j)
class QemuIsDead(Exception): pass class AngrRefuseToLoadKernel(Exception): pass class KasanReportEntryNotFound(Exception): pass
class Qemuisdead(Exception): pass class Angrrefusetoloadkernel(Exception): pass class Kasanreportentrynotfound(Exception): pass
# Functions def get_ocurrences(elements): ocurrences = {} for idx, element in enumerate(elements): if element not in ocurrences: #print(idx) ocurrences[element] = [1, [idx]] else: ocurrences[element][0] += 1 ocurrences[element][1].append(idx) r...
def get_ocurrences(elements): ocurrences = {} for (idx, element) in enumerate(elements): if element not in ocurrences: ocurrences[element] = [1, [idx]] else: ocurrences[element][0] += 1 ocurrences[element][1].append(idx) return ocurrences def has_equal_el...
# 9. *ForceBook # The force users are struggling to remember which side are the different forceUsers from, because they switch them too often. # So you are tasked to create a web application to manage their profiles. You should store an information # for every unique forceUser, registered in the application. # You will...
data = input() force_book = {'Light': [], 'Lighter': [], 'Dark': [], 'Darker': []} while not data == 'Lumpawaroo': if ' | ' in data: (force_side, force_user) = data.split(' | ') for value_list in force_book.values(): if force_user not in value_list: force_book[force_side]...
def solution(arr, divisor): arr.sort() answer = [i for i in arr if i % divisor == 0] if len(answer) == 0: answer.append(-1) return answer print(solution([3, 2, 6], 10)) print(solution)
def solution(arr, divisor): arr.sort() answer = [i for i in arr if i % divisor == 0] if len(answer) == 0: answer.append(-1) return answer print(solution([3, 2, 6], 10)) print(solution)
#coding:utf-8 def PrimeNum(num): r_value =[] for i in range (2,num+1): for j in range(2,i): if i % j == 0: break else: r_value.append(i) returnr_value def PrimeFactorSolve(num,prime_list): for n in prime_list ...
def prime_num(num): r_value = [] for i in range(2, num + 1): for j in range(2, i): if i % j == 0: break else: r_value.append(i) returnr_value def prime_factor_solve(num, prime_list): for n in prime_list: if num % n == 0: return...
def rectangle_v2(length, width, sign): if int(length) > 0 and int(width) > 0: if int(length) == 1 and int(width) == 1: return sign elif int(length) == 1: return f"{sign}" * int(width) elif int(width) == 1: return f"{sign}\n" * int(length) else: ...
def rectangle_v2(length, width, sign): if int(length) > 0 and int(width) > 0: if int(length) == 1 and int(width) == 1: return sign elif int(length) == 1: return f'{sign}' * int(width) elif int(width) == 1: return f'{sign}\n' * int(length) else: ...
""" " {{file}} " Created on {{date}} " " Copyright (c) {{author}}. Licensed under the {{license}} License. """
""" " {{file}} " Created on {{date}} " " Copyright (c) {{author}}. Licensed under the {{license}} License. """
def radix_sort_LSD(arr): if len(arr) == 0: return arr def get_max(arr): max_elem = arr[0] for elem in arr: if elem > max_elem: max_elem = elem return max_elem round_down = lambda number, exp: number // exp # eg. 802, 10: 80 truncate = lambda n...
def radix_sort_lsd(arr): if len(arr) == 0: return arr def get_max(arr): max_elem = arr[0] for elem in arr: if elem > max_elem: max_elem = elem return max_elem round_down = lambda number, exp: number // exp truncate = lambda number: number % 10...
def try_get_value(obj, key): try: return obj[key] except: return None
def try_get_value(obj, key): try: return obj[key] except: return None
def f8to10(num): print("8- : ", num) l = str(num) length = len(l) sum = 0 for i in range(length): sum += 8**i * int(l[length-1-i]) print("10- :", sum) f8to10(122)
def f8to10(num): print('8- : ', num) l = str(num) length = len(l) sum = 0 for i in range(length): sum += 8 ** i * int(l[length - 1 - i]) print('10- :', sum) f8to10(122)
def test_startpage__documents__2(address_book, browser): """It redirects to the documents if this is set on the address book.""" browser.login('mgr') browser.open(browser.ADDRESS_BOOK_EDIT_URL) browser.getControl('start page after log-in').displayValue = 'Documents' browser.select_favicon() brow...
def test_startpage__documents__2(address_book, browser): """It redirects to the documents if this is set on the address book.""" browser.login('mgr') browser.open(browser.ADDRESS_BOOK_EDIT_URL) browser.getControl('start page after log-in').displayValue = 'Documents' browser.select_favicon() brow...
count = int(input()) bit_count = 0 max_count = 0 for _ in range(count): bit = input() if int(bit) == 0: bit_count=0 continue bit_count += 1 max_count = max(max_count, bit_count) print(max_count)
count = int(input()) bit_count = 0 max_count = 0 for _ in range(count): bit = input() if int(bit) == 0: bit_count = 0 continue bit_count += 1 max_count = max(max_count, bit_count) print(max_count)
result_str=""; for row in range(0,7): for column in range(0,7): if (((column == 1 or column == 5) and (row > 4 or row < 2)) or row == column and column > 0 and column < 6 or (column == 2 and row == 4) or (column == 4 and row == 2)): result_str=result_str+"*" else: ...
result_str = '' for row in range(0, 7): for column in range(0, 7): if (column == 1 or column == 5) and (row > 4 or row < 2) or (row == column and column > 0 and (column < 6)) or (column == 2 and row == 4) or (column == 4 and row == 2): result_str = result_str + '*' else: resu...
def kasir(): print('='*40) print(' Chasier Program With Python') print('='*40) print() print('Choose a Menu: ') print('1. Clothes') print('2. Food') print('3. Item') menu = str(input('What do you select? : ')) if menu == '1': print('You have selected (1)')...
def kasir(): print('=' * 40) print(' Chasier Program With Python') print('=' * 40) print() print('Choose a Menu: ') print('1. Clothes') print('2. Food') print('3. Item') menu = str(input('What do you select? : ')) if menu == '1': print('You have selected (1)') ...
# get an input from user a number, total. # Sum the numbers starting from 1 to n till they are greater than total given number. # For example given total is 20, you stop at 7. and give the total as 24. # 1 + 2 +3 +5 +6 = 17 # 1 + 2 +3 +5 +6 + 7 = 24 # For example given total is 60, you stop at 11. # and give the tota...
str_total = input('give me a number, total, to find 1..n > total') given_total = int(str_total) total = 0 for n in range(1, given_total): total = total + n print(total, n) if total > given_total: break print(f'1..{n}={total}')
"""Settings for Filesystem Adapter repository implementation""" # -*- coding: utf-8 -*- ANCHOR_PATH = 'dlkit.filesystem_adapter' PROVIDER_MANAGER_MODULE_PATH = '..json_.repository.managers'
"""Settings for Filesystem Adapter repository implementation""" anchor_path = 'dlkit.filesystem_adapter' provider_manager_module_path = '..json_.repository.managers'
class HTML: @staticmethod def network_statistic_attachment_template(external_path_to_har_file): style_str = '<style>@keyframes spin{to{ transform: rotate(1turn);}} .progress{position: relative;display: inline-block;width: 5em;height: 5em;margin: 0 .5em;font-size: 12px;text-indent: 999em;overflow: hidde...
class Html: @staticmethod def network_statistic_attachment_template(external_path_to_har_file): style_str = '<style>@keyframes spin{to{ transform: rotate(1turn);}} .progress{position: relative;display: inline-block;width: 5em;height: 5em;margin: 0 .5em;font-size: 12px;text-indent: 999em;overflow: hidde...
class List(list): """ HW2 - EX3 Multidimensional list object, changed core elements to fit the list. Most of the methods used are based on the super class. """ def __init__(self, matrix: list): """ Initializes the objects and check is the input is correct and working properly ...
class List(list): """ HW2 - EX3 Multidimensional list object, changed core elements to fit the list. Most of the methods used are based on the super class. """ def __init__(self, matrix: list): """ Initializes the objects and check is the input is correct and working properly ...
# Copyright 2020 The Bazel Authors. All rights reserved. # # 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 la...
"""toolchain to provide an rpmbuild binary.""" rpmbuild_info = provider(doc='Platform inde artifact.', fields={'name': 'The name of the toolchain', 'valid': 'Is this toolchain valid and usable?', 'label': 'The path to a target I will build', 'path': 'The path to a pre-built rpmbuild'}) def _rpmbuild_toolchain_impl(ctx...
class DatabaseClient: def __init__(self): pass @classmethod def convert_str(cls, val): if isinstance(val, str): return "'" + val + "'" elif isinstance(val, bytes): return "'" + str(val) + "'" elif isinstance(val, int): return str(val) ...
class Databaseclient: def __init__(self): pass @classmethod def convert_str(cls, val): if isinstance(val, str): return "'" + val + "'" elif isinstance(val, bytes): return "'" + str(val) + "'" elif isinstance(val, int): return str(val) ...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def printTree(self, root): """ :type root: TreeNode :rtype: List[List[str]] """ d...
class Solution(object): def print_tree(self, root): """ :type root: TreeNode :rtype: List[List[str]] """ def expand(a, ah, al, sh, sl): if not a: a = [[''] * sl] * sh else: t = sh - ah for level in rang...
""" Mockserver provides a way to check if the protocol between endpoints are complied. Example: Let's say we need to test a project's API, this API depends on some external endpoints which are not under our control and we know the protocol between them. There is one way to check if the talk between dependencies and o...
""" Mockserver provides a way to check if the protocol between endpoints are complied. Example: Let's say we need to test a project's API, this API depends on some external endpoints which are not under our control and we know the protocol between them. There is one way to check if the talk between dependencies and o...
# rectangle.py # # Demonstrates a programmer-defined function with parameters. # Demonstrates the use of a FUNCTION comment block (not the # same thing as this program-level comment block). # Every function should have a comment block right before the # line that begins with 'def' saying 1) what the function does # and...
default_width = 12.34 default_height = 34.56 def show_rectangle_info(width, height): perimeter = 2 * (width + height) area = width * height print('\nA rectangle with a width of ' + format(width, '.2f') + ' and a height of ' + format(height, '.2f') + ' \nhas a perimeter of ' + format(perimeter, '.2f') + ' a...
load("@io_bazel_rules_kotlin//kotlin:kotlin.bzl", "kt_jvm_library") def envoy_mobile_kt_library(name, visibility = None, srcs = [], deps = []): # These source files must be re-exported to the kotlin custom library rule to ensure their # inclusion. This is used to work around testing visibility. native.file...
load('@io_bazel_rules_kotlin//kotlin:kotlin.bzl', 'kt_jvm_library') def envoy_mobile_kt_library(name, visibility=None, srcs=[], deps=[]): native.filegroup(name=name + '_srcs', srcs=srcs, visibility=visibility) kt_jvm_library(name=name, srcs=srcs, deps=deps, visibility=visibility)
# Ethos (1033001) | Frozen Fairy Forest : Elluel | Part of Mercedes Intro Questline sm.sendNext("check")
sm.sendNext('check')
class Slot: 'Time slot making up a part of a Course' def __init__(self, type, days, time): self.type = type self.days = days self.time = time def to_string(self): return self.type + " " + self.days + " " + self.time
class Slot: """Time slot making up a part of a Course""" def __init__(self, type, days, time): self.type = type self.days = days self.time = time def to_string(self): return self.type + ' ' + self.days + ' ' + self.time
#!/usr/bin/env python3 # -*- coding: utf-8 -*- if __name__ == "__main__": u = set("abcdefghijklmnopqrstuvwxyz") a = {"a", "b", "h", "j", "l"} b = {"b", "c", "h", "l", "r", "u"} c = {"j", "k", "n", "t", "z"} d = {"b", "i", "k", "v", "w"} x = (a.union(b)).intersection(c) print(f"x = {x}") ...
if __name__ == '__main__': u = set('abcdefghijklmnopqrstuvwxyz') a = {'a', 'b', 'h', 'j', 'l'} b = {'b', 'c', 'h', 'l', 'r', 'u'} c = {'j', 'k', 'n', 't', 'z'} d = {'b', 'i', 'k', 'v', 'w'} x = a.union(b).intersection(c) print(f'x = {x}') b_a = u.difference(a) b_b = u.difference(b) ...
a,b,c=input().split(),0,0 for i in a: l=[int(x) for x in i.split('@')] b,c=b+l[0],c+l[1] print('%.2f'%(b/c),'kmph')
(a, b, c) = (input().split(), 0, 0) for i in a: l = [int(x) for x in i.split('@')] (b, c) = (b + l[0], c + l[1]) print('%.2f' % (b / c), 'kmph')
"""Code for custom Altair themes. Available themes: - streamlit -- matches theme in Streamlit website - ggplot2 -- hybrid between Streamlit's and ggplot2's themes. """ def streamlit_theme(): font = "IBM Plex Mono" primary_color = "#F63366" font_color = "#262730" grey_color = "#f0f2f6" base_size =...
"""Code for custom Altair themes. Available themes: - streamlit -- matches theme in Streamlit website - ggplot2 -- hybrid between Streamlit's and ggplot2's themes. """ def streamlit_theme(): font = 'IBM Plex Mono' primary_color = '#F63366' font_color = '#262730' grey_color = '#f0f2f6' base_size = ...
#!/usr/bin/python # map_fun.py def to_upper(s): return s.upper() words = ["stone", "cloud", "dream", "sky"] words2 = list(map(to_upper, words)) print (words2)
def to_upper(s): return s.upper() words = ['stone', 'cloud', 'dream', 'sky'] words2 = list(map(to_upper, words)) print(words2)
class DiskType(object): def read_get(self, name, idx_name, unity_client): return unity_client.get_disk_type(idx_name) class DiskTypeColumn(object): def get_idx(self, name, idx, unity_client): return unity_client.get_disks()
class Disktype(object): def read_get(self, name, idx_name, unity_client): return unity_client.get_disk_type(idx_name) class Disktypecolumn(object): def get_idx(self, name, idx, unity_client): return unity_client.get_disks()
"""InterviewBit. Programming > Arrays > MAXSPPROD. """ class Solution: """Solution.""" def produce_specials(self, A): """Return "left-special" values.""" stack = [] specials = [] for i in range(len(A)): while len(stack) > 0 and stack[-1][0] <= A[i]: ...
"""InterviewBit. Programming > Arrays > MAXSPPROD. """ class Solution: """Solution.""" def produce_specials(self, A): """Return "left-special" values.""" stack = [] specials = [] for i in range(len(A)): while len(stack) > 0 and stack[-1][0] <= A[i]: ...
"""Email templates""" RETURN_BORROWED_BOOK_SUBJECT = "Return book to library!" RETURN_BORROWED_BOOK = """ Hi! You have borrowed book. Please return book today to library! """
"""Email templates""" return_borrowed_book_subject = 'Return book to library!' return_borrowed_book = '\nHi!\n\nYou have borrowed book. Please return book today to library!\n'
#Kunal Gautam #Codewars : @Kunalpod #Problem name: Write a number in expanded form #Problem level: 6 kyu def expanded_form(num): return ' + '.join([str(num)[x] + '0'* (len(str(num)) - 1 - x) for x in range(len(str(num))) if str(num)[x] != '0'])
def expanded_form(num): return ' + '.join([str(num)[x] + '0' * (len(str(num)) - 1 - x) for x in range(len(str(num))) if str(num)[x] != '0'])
''' A collection of higher level GCD validation tests. ''' def all_standard_inice_strings_exist(dom_geo_map): ''' Returns True if at least one DOM from the standard IC86 configuration is found. Returns False if whole strings are missing from the geometry. ''' all_strings_exist = True for s...
""" A collection of higher level GCD validation tests. """ def all_standard_inice_strings_exist(dom_geo_map): """ Returns True if at least one DOM from the standard IC86 configuration is found. Returns False if whole strings are missing from the geometry. """ all_strings_exist = True for s...
def lca(root, p, q): if root is p or root is q: return root if not root: return None left = lca(root.left, p, q) right = lca(root.right, p, q) if left and right: return root else: return left or right
def lca(root, p, q): if root is p or root is q: return root if not root: return None left = lca(root.left, p, q) right = lca(root.right, p, q) if left and right: return root else: return left or right
""" If you have not see the [explaination](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/356286/Best-Python-Solution-(How-to-Solve-all-Similar-Problem-Explained)) of the previous [question](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/), please see it first. This probl...
""" If you have not see the [explaination](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/discuss/356286/Best-Python-Solution-(How-to-Solve-all-Similar-Problem-Explained)) of the previous [question](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/), please see it first. This probl...