content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
#!/usr/bin/python3 # code for AdventOfCode day 1 http://adventofcode.com/2017/day/1 # get user input WITHOUT validation # the code will fail when repeating non numeric chars input_seq = input() # append first algarism to the end of a new 'extended' # that way we can use a single 'for' loop for everything input_seq_...
input_seq = input() input_seq_extended = str(input_seq) + str(input_seq[0]) total_output = 0 for i in range(0, len(input_seq)): if input_seq_extended[i] == input_seq_extended[i + 1]: print('Match! ' + str(i) + ' Total output: ' + str(total_output)) total_output += int(input_seq_extended[i]) print('O...
class Player: next_id = 1 def __init__(self, name, corp_id=None, runner_id=None): self.id = Player.next_id Player.next_id += 1 self.name = name self.corp_id = corp_id self.runner_id = runner_id self.score = 0 self.sos = 0 self.esos = 0 se...
class Player: next_id = 1 def __init__(self, name, corp_id=None, runner_id=None): self.id = Player.next_id Player.next_id += 1 self.name = name self.corp_id = corp_id self.runner_id = runner_id self.score = 0 self.sos = 0 self.esos = 0 sel...
word = input('Enter a word') letter = input('Enter a letter') def count(word, letter): counter = 0 for character in word: if character == letter: counter = counter + 1 print(counter) count(word, letter)
word = input('Enter a word') letter = input('Enter a letter') def count(word, letter): counter = 0 for character in word: if character == letter: counter = counter + 1 print(counter) count(word, letter)
''' Implement a function which takes as input a string s and returns true if s is a palindromic string. ''' def is_palindrome(s): # Time: O(n) # i moves forward, and j moves backward. i, j = 0, len(s) - 1 while i < j: # i and j both skip non-alphanumeric characters. while not s[i].isalnum...
""" Implement a function which takes as input a string s and returns true if s is a palindromic string. """ def is_palindrome(s): (i, j) = (0, len(s) - 1) while i < j: while not s[i].isalnum() and i < j: i += 1 while not s[j].isalnum() and i < j: j -= 1 if s[i].l...
def game(player1, player2): history = [] while len(player1) != 0 and len(player2) != 0: state = {'player1': player1.copy(), 'player2': player2.copy()} if state in history: return True, player1 + player2 history.append(state) num1 = player1.pop(0) num2 = player...
def game(player1, player2): history = [] while len(player1) != 0 and len(player2) != 0: state = {'player1': player1.copy(), 'player2': player2.copy()} if state in history: return (True, player1 + player2) history.append(state) num1 = player1.pop(0) num2 = play...
#!/usr/bin/env python3 ###################################################################################### # # # Program purpose: Creates a string made of the first 2 and the last 2 chars # # from a gi...
def get_user_string(mess: str): is_valid = False data = '' while is_valid is False: try: data = input(mess) if len(data) == 0: raise value_error('Please provide a string') is_valid = True except ValueError as ve: print(f'[ERROR]...
# Program to implement Affine Cipher for encryption and decryption #returns gcd of two numbers def gcd(num1, num2): if num2 == 0: return num1 return gcd(num2, num1 % num2) #returns the inverse of a number if it exists, else '-1', under mod def inverse(number, mod): if gcd(number, mod) != 1: ...
def gcd(num1, num2): if num2 == 0: return num1 return gcd(num2, num1 % num2) def inverse(number, mod): if gcd(number, mod) != 1: return None t1 = 0 t2 = 1 while number != 0: quotient = mod // number remainder = mod % number t = t1 - quotient * t2 ...
# coding=utf-8 # autogenerated using ms_props_generator.py PROPS_ID_MAP = { "0x0001": {"data_type": "0x0102", "name": "TemplateData"}, "0x0002": {"data_type": "0x000B", "name": "AlternateRecipientAllowed"}, "0x0004": {"data_type": "0x0102", "name": "ScriptData"}, "0x0005": {"data_type": "0x000B", "name"...
props_id_map = {'0x0001': {'data_type': '0x0102', 'name': 'TemplateData'}, '0x0002': {'data_type': '0x000B', 'name': 'AlternateRecipientAllowed'}, '0x0004': {'data_type': '0x0102', 'name': 'ScriptData'}, '0x0005': {'data_type': '0x000B', 'name': 'AutoForwarded'}, '0x000F': {'data_type': '0x0040', 'name': 'DeferredDeliv...
try: with open("input.txt", "r") as fileContent: segments = [[segment.split(" -> ")] for segment in fileContent.readlines()] segments = [tuple([int(axis) for axis in coordinate.strip().split(",")]) for segment in segments for coordinates in segment for coordin...
try: with open('input.txt', 'r') as file_content: segments = [[segment.split(' -> ')] for segment in fileContent.readlines()] segments = [tuple([int(axis) for axis in coordinate.strip().split(',')]) for segment in segments for coordinates in segment for coordinate in coordinates] segments = ...
def return_rate_limit(github): rate_limit = github.get_rate_limit() rate = rate_limit.rate return rate.remaining
def return_rate_limit(github): rate_limit = github.get_rate_limit() rate = rate_limit.rate return rate.remaining
""" Determine whether an integer is a palindrome. Do this without extra space. A palindrome integer is an integer x for which reverse(x) = x where reverse(x) is x with its digit reversed. Negative numbers are not palindromic. Example : Input : 12121 Output : True Input : 123 Output : False """ class Solution: ...
""" Determine whether an integer is a palindrome. Do this without extra space. A palindrome integer is an integer x for which reverse(x) = x where reverse(x) is x with its digit reversed. Negative numbers are not palindromic. Example : Input : 12121 Output : True Input : 123 Output : False """ class Solution: ...
class Node: def __init__(self, key, left=None, right=None): self.key = key self.left = left self.right = right def __str__(self): return str(self.key) def print_path(path): s = "" for p in path: s += str(p) + " " print(f"{s}\n---") def paths_with_sum(ro...
class Node: def __init__(self, key, left=None, right=None): self.key = key self.left = left self.right = right def __str__(self): return str(self.key) def print_path(path): s = '' for p in path: s += str(p) + ' ' print(f'{s}\n---') def paths_with_sum(root,...
a = 35 b = 7 print("a % b =", a % b)
a = 35 b = 7 print('a % b =', a % b)
# -*- coding: utf-8 -*- """ Created on Thu Jul 9 09:42:41 2020 @author: sv """ #num_obj = 4 #for idx in range(1,num_obj): # print('idx = ', idx) path = 'assets/obj_name.txt' objname_list = [] count = 0 objfile = open(path, 'r') Lines = objfile.readlines() for line in Li...
""" Created on Thu Jul 9 09:42:41 2020 @author: sv """ path = 'assets/obj_name.txt' objname_list = [] count = 0 objfile = open(path, 'r') lines = objfile.readlines() for line in Lines: objname_list.append(line.strip()) count = count + 1 print('line', count, ' : ', line.strip()) print('objname_list : ', ob...
class Car: """ Docstring describing the class """ def __init__(self, car_name) -> None: self.car_name = car_name def __str__(self) -> str: return f"Soh uma string mano {self.car_name}" def anda(self): return f"Anda {self.car_name}" car = Car("ecosport") print(car.and...
class Car: """ Docstring describing the class """ def __init__(self, car_name) -> None: self.car_name = car_name def __str__(self) -> str: return f'Soh uma string mano {self.car_name}' def anda(self): return f'Anda {self.car_name}' car = car('ecosport') print(car.anda(...
def valid_parentheses(s): if not s: return True elif len(s) == 1: return False d = {"(": ")", "{": "}", "[": "]"} stack = [] for bracket in s: if bracket in d: stack.append(bracket) elif d[stack.pop()] != bracket: return False return len...
def valid_parentheses(s): if not s: return True elif len(s) == 1: return False d = {'(': ')', '{': '}', '[': ']'} stack = [] for bracket in s: if bracket in d: stack.append(bracket) elif d[stack.pop()] != bracket: return False return len(st...
#!/usr/bin/env python3 # # Copyright (c) 2018-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. # DOH_URI = '/.well-known/dns-query' DOH_MEDIA_TYPE = 'application/dns-udpwireformat' DOH_CONT...
doh_uri = '/.well-known/dns-query' doh_media_type = 'application/dns-udpwireformat' doh_content_type_param = 'ct' doh_body_param = 'body' doh_h2_npn_protocols = ['h2']
"""" Practice File 3 Created By David Story Description: All about bit operators! """ # Some basic examples of hex, dec, and bin in Python print("Example Using 0xAA:") hexvalue = 0xAA print(hex(hexvalue)) print(int(hexvalue)) print(bin(hexvalue)) print("Example Using decimal 65:") decimal = 65 print(int(decimal)) pr...
"""" Practice File 3 Created By David Story Description: All about bit operators! """ print('Example Using 0xAA:') hexvalue = 170 print(hex(hexvalue)) print(int(hexvalue)) print(bin(hexvalue)) print('Example Using decimal 65:') decimal = 65 print(int(decimal)) print(hex(decimal)) print(bin(decimal)) print('Converting ...
class Complex(object): """Class to save the complex file""" def __init__(self, id, filename): """Creator of Complex class Arguments: - id - string, the id of the complex - filename - string, the file name of the complex """ self.id = id self.chain_dict =...
class Complex(object): """Class to save the complex file""" def __init__(self, id, filename): """Creator of Complex class Arguments: - id - string, the id of the complex - filename - string, the file name of the complex """ self.id = id self.chain_dict ...
load("//ruby/private:constants.bzl", "RULES_RUBY_WORKSPACE_NAME") load("//ruby/private:providers.bzl", "RubyRuntimeContext") DEFAULT_BUNDLER_VERSION = "2.1.2" BUNDLE_BIN_PATH = "bin" BUNDLE_PATH = "lib" SCRIPT_INSTALL_BUNDLER = "download_bundler.rb" SCRIPT_ACTIVATE_GEMS = "activate_gems.rb" SCRIPT_BUILD_FILE_GENERATO...
load('//ruby/private:constants.bzl', 'RULES_RUBY_WORKSPACE_NAME') load('//ruby/private:providers.bzl', 'RubyRuntimeContext') default_bundler_version = '2.1.2' bundle_bin_path = 'bin' bundle_path = 'lib' script_install_bundler = 'download_bundler.rb' script_activate_gems = 'activate_gems.rb' script_build_file_generator ...
# Designing window for login def login(): global login_screen login_screen = Toplevel(main_screen) login_screen.title("Login") login_screen.geometry("300x250") Label(login_screen, text="Please enter details below to login").pack() Label(login_screen, text="").pack() global username_verify...
def login(): global login_screen login_screen = toplevel(main_screen) login_screen.title('Login') login_screen.geometry('300x250') label(login_screen, text='Please enter details below to login').pack() label(login_screen, text='').pack() global username_verify global password_verify ...
def solution(n, times): leftLim = 1; rightLim = max(times) * n; answer = max(times) * n while leftLim <= rightLim: # print(leftLim, rightLim) lim = (leftLim + rightLim)//2; check = sum([lim//time for time in times]) if check >= n: answer = min(answer, lim) rightLim...
def solution(n, times): left_lim = 1 right_lim = max(times) * n answer = max(times) * n while leftLim <= rightLim: lim = (leftLim + rightLim) // 2 check = sum([lim // time for time in times]) if check >= n: answer = min(answer, lim) right_lim = lim - 1 ...
def resta(num_1, num_2): print('Restando:', num_1, '-', num_2) resta_total = num_1 - num_2 print('El resultado es:',resta_total) return resta_total def app_resta(): inp_1 = None # Can be used 'None' instead of 0 too inp_2 = None while inp_1 == None: try: inp_1 = int(inp...
def resta(num_1, num_2): print('Restando:', num_1, '-', num_2) resta_total = num_1 - num_2 print('El resultado es:', resta_total) return resta_total def app_resta(): inp_1 = None inp_2 = None while inp_1 == None: try: inp_1 = int(input('Numero 1?: ')) except Valu...
""" pyifc.compress._exceptions -------------------------- Exceptions used in pyifc.compress module. """ class FileExtensionError(Exception): """ Raised when extension of the file is not correct. """ pass
""" pyifc.compress._exceptions -------------------------- Exceptions used in pyifc.compress module. """ class Fileextensionerror(Exception): """ Raised when extension of the file is not correct. """ pass
class User: """ Class that generates new instances of contacts """ def __init__(self,user_name, password): """ This will construct an object of the instance of the class user """ self.user_name = user_name self.password = password user_list = [] #This is the...
class User: """ Class that generates new instances of contacts """ def __init__(self, user_name, password): """ This will construct an object of the instance of the class user """ self.user_name = user_name self.password = password user_list = [] def sav...
def cycleSort(array, *args): for cycle_start in range(0, len(array) - 1): item = array[cycle_start] pos = cycle_start for i in range(cycle_start + 1, len(array)): if array[i] < item: pos += 1 if pos == cycle_start: continue w...
def cycle_sort(array, *args): for cycle_start in range(0, len(array) - 1): item = array[cycle_start] pos = cycle_start for i in range(cycle_start + 1, len(array)): if array[i] < item: pos += 1 if pos == cycle_start: continue while array...
class FileStream(Stream,IDisposable): """ Exposes a System.IO.Stream around a file,supporting both synchronous and asynchronous read and write operations. FileStream(path: str,mode: FileMode) FileStream(path: str,mode: FileMode,access: FileAccess) FileStream(path: str,mode: FileMode,access: FileAccess,...
class Filestream(Stream, IDisposable): """ Exposes a System.IO.Stream around a file,supporting both synchronous and asynchronous read and write operations. FileStream(path: str,mode: FileMode) FileStream(path: str,mode: FileMode,access: FileAccess) FileStream(path: str,mode: FileMode,access: FileAccess,sh...
aI, aO, aT, aJ, aL, aS, aZ = map(int, input().split()) ans = aO p = [aI, aJ, aL] for i in range(3): if p[i] >= 2: if p[i] % 2 == 0: ans += (p[i] - 2) // 2 * 2 p[i] = 2 else: ans += p[i] // 2 * 2 p[i] = 1 p.sort() if sum(p) >= 5: ans += sum(p) // 2 ...
(a_i, a_o, a_t, a_j, a_l, a_s, a_z) = map(int, input().split()) ans = aO p = [aI, aJ, aL] for i in range(3): if p[i] >= 2: if p[i] % 2 == 0: ans += (p[i] - 2) // 2 * 2 p[i] = 2 else: ans += p[i] // 2 * 2 p[i] = 1 p.sort() if sum(p) >= 5: ans += sum...
class Solution: def twoSum(self, nums , target) : # a python dictionary(hash) # key is number # value is index of list: nums number_dictionary = dict() for index, number in enumerate(nums): # put every number into dictionary...
class Solution: def two_sum(self, nums, target): number_dictionary = dict() for (index, number) in enumerate(nums): number_dictionary[number] = index solution = list() for i in range(len(nums)): value = nums[i] dual = target - value in...
""" 0693. Binary Number with Alternating Bits Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. Example 1: Input: 5 Output: True Explanation: The binary representation of 5 is: 101 Example 2: Input: 7 Output: False Explanation: The binary r...
""" 0693. Binary Number with Alternating Bits Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. Example 1: Input: 5 Output: True Explanation: The binary representation of 5 is: 101 Example 2: Input: 7 Output: False Explanation: The binary r...
n = int(input("Enter the number : ")) fact = 1 for i in range(1,n + 1): fact = fact * i print("Factorial of {} is {}".format(n,fact))
n = int(input('Enter the number : ')) fact = 1 for i in range(1, n + 1): fact = fact * i print('Factorial of {} is {}'.format(n, fact))
""" This module contains all the string constants defined for this repo. """ """ Regex declarations used in Web Info module. """ RE_VISITORS = "^> (.*?) visitors per day <$" RE_IP_V6 = "IPv6.png'><a href='\/info\/whois6\/(.*?)'>" RE_IP_LOCATION = "IP Location: <\/td> <td class='vmiddle'><span class='cflag (.*?)'><\/spa...
""" This module contains all the string constants defined for this repo. """ '\nRegex declarations used in Web Info module.\n' re_visitors = '^> (.*?) visitors per day <$' re_ip_v6 = "IPv6.png'><a href='\\/info\\/whois6\\/(.*?)'>" re_ip_location = "IP Location: <\\/td> <td class='vmiddle'><span class='cflag (.*?)'><\\/...
pkgname = "lua5.4-zlib" pkgver = "1.2" pkgrel = 0 build_style = "makefile" make_build_target = "linux" hostmakedepends = ["pkgconf"] makedepends = ["lua5.4-devel", "zlib-devel"] pkgdesc = "Zlib streaming interface for Lua (5.4)" maintainer = "q66 <q66@chimera-linux.org>" license = "MIT" url = "https://github.com/brimwo...
pkgname = 'lua5.4-zlib' pkgver = '1.2' pkgrel = 0 build_style = 'makefile' make_build_target = 'linux' hostmakedepends = ['pkgconf'] makedepends = ['lua5.4-devel', 'zlib-devel'] pkgdesc = 'Zlib streaming interface for Lua (5.4)' maintainer = 'q66 <q66@chimera-linux.org>' license = 'MIT' url = 'https://github.com/brimwo...
# TempConv.py # Celcius to Fahreinheit def Fahreinheit(temp): temp = float(temp) temp = (temp*9/5)+32 return temp # Fahreinheit to Celcius def Celcius(temp): temp = float(temp) temp = (temp-32)*5/9 return temp
def fahreinheit(temp): temp = float(temp) temp = temp * 9 / 5 + 32 return temp def celcius(temp): temp = float(temp) temp = (temp - 32) * 5 / 9 return temp
friends = ["Sam","Samantha","Saurab"] start_with_s = [x for x in friends if x.startswith("S")] #compare list friends and start_with_s, bot are same value but result should be false. #Because two are different list print(friends is start_with_s) print("friends : ", id(friends)," start_with_s : ",id(start_with_s)) #if...
friends = ['Sam', 'Samantha', 'Saurab'] start_with_s = [x for x in friends if x.startswith('S')] print(friends is start_with_s) print('friends : ', id(friends), ' start_with_s : ', id(start_with_s)) print(friends[0] is start_with_s[0])
#!/usr/bin/python3 # 100-weight_average.py def weight_average(my_list=[]): """Return the weighted average of all integers in a list of tuples.""" if not isinstance(my_list, list) or len(my_list) == 0: return (0) avg = 0 size = 0 for tup in my_list: avg += (tup[0] * tup[1]) ...
def weight_average(my_list=[]): """Return the weighted average of all integers in a list of tuples.""" if not isinstance(my_list, list) or len(my_list) == 0: return 0 avg = 0 size = 0 for tup in my_list: avg += tup[0] * tup[1] size += tup[1] return avg / size
"""" entradas preciocomputador-->P-->float valorcuotas-->T-->float salidas porcentajerecargo-->por-->float """ #entradas P=float(input("Ingrese el precio del computador: ")) T=float(input("Ingrese el valor de las cuotas: ")) #caja negra tc=T*12 r=tc-P por=(r*100)/P #salidas print("El porcentaje de recargo es del ",...
"""" entradas preciocomputador-->P-->float valorcuotas-->T-->float salidas porcentajerecargo-->por-->float """ p = float(input('Ingrese el precio del computador: ')) t = float(input('Ingrese el valor de las cuotas: ')) tc = T * 12 r = tc - P por = r * 100 / P print('El porcentaje de recargo es del ', por, '%')
class MSDocument(object): def setZoomValue(self, zoomLevel): """ Zoom the document. 1.0 represents actual size, 2.0 means 200% etc. """ # Not implemented pass def export(self): """ Takes you to the the export tool. Pass nil as the argument. """ ...
class Msdocument(object): def set_zoom_value(self, zoomLevel): """ Zoom the document. 1.0 represents actual size, 2.0 means 200% etc. """ pass def export(self): """ Takes you to the the export tool. Pass nil as the argument. """ pass def exp...
# -*- coding: utf-8 -*- """ pygments.console ~~~~~~~~~~~~~~~~ Format colored console output. :copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ esc = "\x1b[" codes = {} codes[""] = "" codes["reset"] = esc + "39;49;00m" ...
""" pygments.console ~~~~~~~~~~~~~~~~ Format colored console output. :copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ esc = '\x1b[' codes = {} codes[''] = '' codes['reset'] = esc + '39;49;00m' codes['bold'] = esc + '01m' codes['faint'] ...
## Given a position, write a function to ## find if that position is within 5 points of a monster: a_treasure_map = { "45,46": "sea monster", "55,38": "air monster", "33,78": "lava monster", "22,23": "shining castle", "64,97": "shield of truth", "97,3": "sword of power", } def near_monster(position, a_trea...
a_treasure_map = {'45,46': 'sea monster', '55,38': 'air monster', '33,78': 'lava monster', '22,23': 'shining castle', '64,97': 'shield of truth', '97,3': 'sword of power'} def near_monster(position, a_treasure_map): (x, y) = position.split(',') player_x = int(x) player_y = int(y) for (key, value) in a_...
def batch_iterator(iterable, batch_size): iterator = iter(iterable) iteration_stopped = False while True: batch = [] for _ in range(batch_size): try: batch.append(next(iterator)) except StopIteration: iteration_stopped = True ...
def batch_iterator(iterable, batch_size): iterator = iter(iterable) iteration_stopped = False while True: batch = [] for _ in range(batch_size): try: batch.append(next(iterator)) except StopIteration: iteration_stopped = True ...
""" Constants file for wiating backend """ AUTH0_CLIENT_ID = 'AUTH0_CLIENT_ID' AUTH0_DOMAIN = 'AUTH0_DOMAIN' AUTH0_CLIENT_SECRET = 'AUTH0_CLIENT_SECRET' AUTH0_CALLBACK_URL = 'AUTH0_CALLBACK_URL' AUTH0_AUDIENCE = 'AUTH0_AUDIENCE' SECRET_KEY = 'SECRET_KEY' S3_BUCKET = 'S3_BUCKET' ES_CONNECTION_STRING = 'ES_CONNECTION_STR...
""" Constants file for wiating backend """ auth0_client_id = 'AUTH0_CLIENT_ID' auth0_domain = 'AUTH0_DOMAIN' auth0_client_secret = 'AUTH0_CLIENT_SECRET' auth0_callback_url = 'AUTH0_CALLBACK_URL' auth0_audience = 'AUTH0_AUDIENCE' secret_key = 'SECRET_KEY' s3_bucket = 'S3_BUCKET' es_connection_string = 'ES_CONNECTION_STR...
def cuberoot2(x0): x = x0 i = 0 while True: nextIt = (1/3)*(2*x+2/(x**2)) if (abs(nextIt - x) <= 10**-7): break else: i += 1 x = nextIt print("The sequence starting at", x0, "converges to", x,"in", i, "iterations.") cuberoot2(20) def nesty(x): f = (x - 1) ** 5 g = x ** 5 - 5 ...
def cuberoot2(x0): x = x0 i = 0 while True: next_it = 1 / 3 * (2 * x + 2 / x ** 2) if abs(nextIt - x) <= 10 ** (-7): break else: i += 1 x = nextIt print('The sequence starting at', x0, 'converges to', x, 'in', i, 'iterations.') cuberoot2(20) d...
""" Module: 'machine' on micropython-rp2-1.15 """ # MCU: {'family': 'micropython', 'sysname': 'rp2', 'version': '1.15.0', 'build': '', 'mpy': 5637, 'port': 'rp2', 'platform': 'rp2', 'name': 'micropython', 'arch': 'armv7m', 'machine': 'Raspberry Pi Pico with RP2040', 'nodename': 'rp2', 'ver': '1.15', 'release': '1.15.0'...
""" Module: 'machine' on micropython-rp2-1.15 """ class Adc: """""" core_temp = 4 def read_u16(): pass class I2C: """""" def init(): pass def readfrom(): pass def readfrom_into(): pass def readfrom_mem(): pass def readfrom_mem_into(): ...
# add a key to a dicitonary # Sample dictionary: {0:10,1:20} # Expected Result: {0:10,1:20,2:30} a={0:10,1:20} a[2]=30 print(a)
a = {0: 10, 1: 20} a[2] = 30 print(a)
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Scott Burns <sburns@nmr.mgh.harvard.edu> # # License: BSD (3-clause) def parse_config(fname): """Parse a config file (like .ave and .cov files) Parameters ---------- fname : string config file name Returns...
def parse_config(fname): """Parse a config file (like .ave and .cov files) Parameters ---------- fname : string config file name Returns ------- conditions : list of dict Each condition is indexed by the event type. A condition contains as keys:: tmin, ...
add_user_permissions_response = { 'user': 'enterprise_search', 'permissions': ['permission1'] }
add_user_permissions_response = {'user': 'enterprise_search', 'permissions': ['permission1']}
# # Function for program annotation-to-outline. Responsible for writing the # LaTex structure to file. # def writeToLatex(fileName, outlineContents, defContents, titleContents): # Write contents to .tex file f = open(fileName, 'w') # file object # write LaTex preamble to file f.write("\\documentcla...
def write_to_latex(fileName, outlineContents, defContents, titleContents): f = open(fileName, 'w') f.write('\\documentclass[10pt,a4paper,draft]{report}\n \\usepackage{geometry}\\geometry{a4paper, left=22mm,\n right=22mm,\n top=25mm,\n bottom=30mm,\n ...
dist1={0: 460146, 1: 211769, 2: 89768, 3: 41207, 4: 21465, 5: 10368, 6: 6336, 7: 3640, 8: 2378, 9: 1440, 10: 1068, 11: 694, 12: 483, 13: 336, 14: 237, 15: 155, 16: 153, 17: 128, 18: 94, 19: 81, 20: 123, 21: 71, 22: 89, 23: 40, 24: 44, 25: 43, 26: 25, 27: 15, 28: 19, 29: 19, 30: 23, 31: 19, 32: 6, 33: 13, 34: 8, 35: 3, ...
dist1 = {0: 460146, 1: 211769, 2: 89768, 3: 41207, 4: 21465, 5: 10368, 6: 6336, 7: 3640, 8: 2378, 9: 1440, 10: 1068, 11: 694, 12: 483, 13: 336, 14: 237, 15: 155, 16: 153, 17: 128, 18: 94, 19: 81, 20: 123, 21: 71, 22: 89, 23: 40, 24: 44, 25: 43, 26: 25, 27: 15, 28: 19, 29: 19, 30: 23, 31: 19, 32: 6, 33: 13, 34: 8, 35: 3...
# def get_words(sentence): # return list(filter((lambda x: len(str(x)) > 0), str(sentence).split(sep=' '))) # # # def get_word_count(sentence): # return get_words(sentence).count() def get_word_freq_in_sentences(word, sentences): """ :param word: the word which frequency we calculate :para...
def get_word_freq_in_sentences(word, sentences): """ :param word: the word which frequency we calculate :param sentences: a list of the sentences, representing the document / search space :return: the number of occurrences of the given word in the search space. Letter case is ignored """...
class SpaceAge: def __init__(self, seconds: float): self.seconds = seconds def _space_age(self, ratio: float = 1.0, ndigits: int = 2) -> float: return round(self.seconds / 31557600.0 / ratio, ndigits) def on_mercury(self) -> float: return self._space_age(0.2408467) def on_ven...
class Spaceage: def __init__(self, seconds: float): self.seconds = seconds def _space_age(self, ratio: float=1.0, ndigits: int=2) -> float: return round(self.seconds / 31557600.0 / ratio, ndigits) def on_mercury(self) -> float: return self._space_age(0.2408467) def on_venus(s...
# This program demonstrates the repetition operator. def main(): # Print nine rows increasing in length. for count in range(1, 10): print('Z' * count) # Print nine rows decreasing in length. for count in range(8, 0, -1): print('Z' * count) # Call the main function. main()
def main(): for count in range(1, 10): print('Z' * count) for count in range(8, 0, -1): print('Z' * count) main()
"""Definitions for using tools like saved_model_cli.""" load("//tensorflow:tensorflow.bzl", "clean_dep", "if_xla_available") load("//tensorflow:tensorflow.bzl", "tfcompile_target_cpu") load("//tensorflow/compiler/aot:tfcompile.bzl", "target_llvm_triple") def _maybe_force_compile(args, force_compile): if force_com...
"""Definitions for using tools like saved_model_cli.""" load('//tensorflow:tensorflow.bzl', 'clean_dep', 'if_xla_available') load('//tensorflow:tensorflow.bzl', 'tfcompile_target_cpu') load('//tensorflow/compiler/aot:tfcompile.bzl', 'target_llvm_triple') def _maybe_force_compile(args, force_compile): if force_comp...
#num = 1 # #while num < 10: # print(num) # num = num+1 #nome = 'cecilia' # #for letra in nome: # print(letra) #for num in range(1,6): # print(num) lista = [1,2,3,4,5,6] for num in lista: print(num)
lista = [1, 2, 3, 4, 5, 6] for num in lista: print(num)
s = input('as: ') print(s)
s = input('as: ') print(s)
class Solution: def match(self, pattern, strs): words = strs.split() patterns = list(pattern) patternList = self.getPattern(patterns) wordList = self.getPattern(words) return patternList == wordList def getPattern(self, strList): index = 1 tmpDict = {} ...
class Solution: def match(self, pattern, strs): words = strs.split() patterns = list(pattern) pattern_list = self.getPattern(patterns) word_list = self.getPattern(words) return patternList == wordList def get_pattern(self, strList): index = 1 tmp_dict = ...
def getAverageOverPercentage(n, score): avg = sum(score) / n std = 0 for i in score: if i > avg: std += 1 return round(std / n * 100, 3) for _ in range(int(input())): data = list(map(int, input().split())) result = getAverageOverPercentage(data[0], data[1:]) print("%.3f"%result + '%')
def get_average_over_percentage(n, score): avg = sum(score) / n std = 0 for i in score: if i > avg: std += 1 return round(std / n * 100, 3) for _ in range(int(input())): data = list(map(int, input().split())) result = get_average_over_percentage(data[0], data[1:]) print('...
# We explicitly test here that the constructor is not included in the signatures. @abstract class Abstract: x: int def __init__(self, x: int) -> None: self.x = x __book_url__ = "dummy" __book_version__ = "dummy"
@abstract class Abstract: x: int def __init__(self, x: int) -> None: self.x = x __book_url__ = 'dummy' __book_version__ = 'dummy'
__author__ = 'chira' # for-loop : when number of iterations known # while-loop : when iteration depends on condition for i in range(5,10): print(i) print("------------"); i = 5 while i < 10: print(i) i += 1 print("------------");
__author__ = 'chira' for i in range(5, 10): print(i) print('------------') i = 5 while i < 10: print(i) i += 1 print('------------')
class keyBox: def __init__(self): self.wallet_addresses = [] self.private_keys = [] #for testing self.private_keys.append(b'p.Oids\xedb\xa3\x93\xc5\xad\xb9\x8d\x92\x94\x00\x06\xb9\x82\xde\xb9\xbdBg\\\x82\xd4\x90W\xd0\xd5') self.private_keys.append(b'\x16\xc3\xb37\xb8\x8aG`\xdf\xad\xe3},\x9a\xb4...
class Keybox: def __init__(self): self.wallet_addresses = [] self.private_keys = [] self.private_keys.append(b'p.Oids\xedb\xa3\x93\xc5\xad\xb9\x8d\x92\x94\x00\x06\xb9\x82\xde\xb9\xbdBg\\\x82\xd4\x90W\xd0\xd5') self.private_keys.append(b'\x16\xc3\xb37\xb8\x8aG`\xdf\xad\xe3},\x9a\xb4~...
"""Dude Middleware.""" class ClacksOverhead(object): """Inject HTTP headers into your response.""" def __init__(self, app, *headers, **kwargs): """Initialize the header injector.""" self.app = app self.headers = (headers or ( ('X-Clacks-Overhead', 'GNU'), )) + tupl...
"""Dude Middleware.""" class Clacksoverhead(object): """Inject HTTP headers into your response.""" def __init__(self, app, *headers, **kwargs): """Initialize the header injector.""" self.app = app self.headers = (headers or (('X-Clacks-Overhead', 'GNU'),)) + tuple(kwargs.items()) ...
for i in range(1, 6): for j in range(1, i + 1): print('* ', end='') print() for i in range(4, 0, -1): for j in range(1, i + 1): print('* ', end='') print()
for i in range(1, 6): for j in range(1, i + 1): print('* ', end='') print() for i in range(4, 0, -1): for j in range(1, i + 1): print('* ', end='') print()
class Node: def __init__(self, val): self.val = val self.next = None # Single List, without sentinel node # class MyLinkedList: # # def __init__(self): # """ # Initialize your data structure here. # """ # self.header = None # self.size = 0 # # def ge...
class Node: def __init__(self, val): self.val = val self.next = None class Node: def __init__(self, val): self.val = val self.next = None self.pre = None class Mylinkedlist: def __init__(self): """ Initialize your data structure here. """ ...
class Solution: # @param num, a list of integer # @return an integer def findPeakElement(self, num): l, r = 0, len(num)-1 while l < r: m = (l+r) / 2 if m == 0 or num[m] > num[m-1]: if m == r or num[m] > num[m+1]: return m ...
class Solution: def find_peak_element(self, num): (l, r) = (0, len(num) - 1) while l < r: m = (l + r) / 2 if m == 0 or num[m] > num[m - 1]: if m == r or num[m] > num[m + 1]: return m l = m + 1 else: ...
OPENSEARCH_GIT_RAW = "gits" OPENSEARCH_GIT_GITHUB_CLEAN = "git_github_clean" OPENSEARCH_INDEX_GITHUB_COMMITS = "github_commits" OPENSEARCH_INDEX_GITHUB_ISSUES = "github_issues" OPENSEARCH_INDEX_GITHUB_ISSUES_COMMENTS = "github_issues_comments" OPENSEARCH_INDEX_GITHUB_ISSUES_TIMELINE = "github_issues_timeline" OPENSEAR...
opensearch_git_raw = 'gits' opensearch_git_github_clean = 'git_github_clean' opensearch_index_github_commits = 'github_commits' opensearch_index_github_issues = 'github_issues' opensearch_index_github_issues_comments = 'github_issues_comments' opensearch_index_github_issues_timeline = 'github_issues_timeline' opensearc...
Dataset_Path = dict( CULane = "/workspace/CULANE_DATASET", Tusimple = "/workspace/TUSIMPLE_DATASET", bdd100k = "/workspace/BDD100K_DATASET" )
dataset__path = dict(CULane='/workspace/CULANE_DATASET', Tusimple='/workspace/TUSIMPLE_DATASET', bdd100k='/workspace/BDD100K_DATASET')
"""Routes config.""" def includeme(config): """All routes for the app.""" config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.add_route('results', '/results/{id:\w+}') config.add_route('about', '/about')
"""Routes config.""" def includeme(config): """All routes for the app.""" config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.add_route('results', '/results/{id:\\w+}') config.add_route('about', '/about')
code = [input() for _ in range(610)] for i in range(len(code)-1): if code[i][:3] == 'jmp': code[i] = 'nop' + code[i][3:] elif code[i][:3] == 'nop': code[i] = 'jmp' + code[i][3:] instr_idx = 0 acc_value = 0 executed_ops = set() while instr_idx not in executed_ops and instr_idx ...
code = [input() for _ in range(610)] for i in range(len(code) - 1): if code[i][:3] == 'jmp': code[i] = 'nop' + code[i][3:] elif code[i][:3] == 'nop': code[i] = 'jmp' + code[i][3:] instr_idx = 0 acc_value = 0 executed_ops = set() while instr_idx not in executed_ops and instr_idx <...
class Solution: def maxRotateFunction(self, A): """ :type A: List[int] :rtype: int """ mx, sm = 0, sum(A) for i in range(len(A)): mx += i * A[i] curr = mx for i in range(1, len(A)): curr = curr - sm + A[i - 1] * len(A) ...
class Solution: def max_rotate_function(self, A): """ :type A: List[int] :rtype: int """ (mx, sm) = (0, sum(A)) for i in range(len(A)): mx += i * A[i] curr = mx for i in range(1, len(A)): curr = curr - sm + A[i - 1] * len(A) ...
"""Multiplication Table, by Al Sweigart al@inventwithpython.com Print a multiplication table. This and other games are available at https://nostarch.com/XX Tags: tiny, beginner, math""" __version__ = 0 print('Multiplication Table, by Al Sweigart al@inventwithpython.com') # Print the horizontal number labels: print(' ...
"""Multiplication Table, by Al Sweigart al@inventwithpython.com Print a multiplication table. This and other games are available at https://nostarch.com/XX Tags: tiny, beginner, math""" __version__ = 0 print('Multiplication Table, by Al Sweigart al@inventwithpython.com') print(' | 0 1 2 3 4 5 6 7 8 ...
array = [1,2,3,4,5] result = [5,1,4,2,3] # in-place replacement def rearrange_sorted_max_min_2(arr): max_index = len(arr) - 1 min_index = 0 max_elem = arr[max_index] + 1 # orig element of stored as remainder, max or min element stored # as multiplier, this allows to swap numbers in place, finally...
array = [1, 2, 3, 4, 5] result = [5, 1, 4, 2, 3] def rearrange_sorted_max_min_2(arr): max_index = len(arr) - 1 min_index = 0 max_elem = arr[max_index] + 1 for i in range(len(arr)): if i % 2 is 0: arr[i] += arr[max_index] % max_elem * max_elem max_index -= 1 else:...
n = int(input()) sv = sq = 0 for i in range(n): sv += float(input()) q = len(str(input()).split()) sq += q print('day {}: {} kg'.format(i + 1, q)) print('{:.2f} kg by day'.format(float(sq / n))) print('R$ {:.2f} by day'.format(float(sv / n)))
n = int(input()) sv = sq = 0 for i in range(n): sv += float(input()) q = len(str(input()).split()) sq += q print('day {}: {} kg'.format(i + 1, q)) print('{:.2f} kg by day'.format(float(sq / n))) print('R$ {:.2f} by day'.format(float(sv / n)))
# variables dependent on your setup boardType = "atmega2560" # atmega168 | atmega328p | atmega2560 | atmega1280 | atmega32u4 comPort = "COM3" # com4 for atmega328 com8 for mega2560 SHIFT = 47 LATCH = 48 DATA = 49 # start Arduino service named arduino arduino = Runtime.createAndStart("arduino", "Arduino") arduino.se...
board_type = 'atmega2560' com_port = 'COM3' shift = 47 latch = 48 data = 49 arduino = Runtime.createAndStart('arduino', 'Arduino') arduino.setBoard(boardType) arduino.connect(comPort) arduino.pinMode(SHIFT, Arduino.OUTPUT) arduino.pinMode(LATCH, Arduino.OUTPUT) arduino.pinMode(DATA, Arduino.OUTPUT) def shift_out(value...
airline = pd.read_csv('data/international-airline-passengers.csv', parse_dates=['Month'], sep=';') airline.set_index('Month', inplace=True) ax = airline.plot(legend=False) ax.set_xlabel('Date') ax.set_ylabel('Passengers')
airline = pd.read_csv('data/international-airline-passengers.csv', parse_dates=['Month'], sep=';') airline.set_index('Month', inplace=True) ax = airline.plot(legend=False) ax.set_xlabel('Date') ax.set_ylabel('Passengers')
n=int(input()) if n>=0: sum=int((n*(n+1))/2) print(sum) else: print("Invalid Input")
n = int(input()) if n >= 0: sum = int(n * (n + 1) / 2) print(sum) else: print('Invalid Input')
"""InterviewBit. Programming > Arrays > Min Steps In Infinite Grid. """ class Solution: """Solution.""" # @param A : list of integers # @param B : list of integers # @return an integer def coverPoints(self, A, B): """Cover points.""" x, y = A[0], B[0] steps = 0 fo...
"""InterviewBit. Programming > Arrays > Min Steps In Infinite Grid. """ class Solution: """Solution.""" def cover_points(self, A, B): """Cover points.""" (x, y) = (A[0], B[0]) steps = 0 for (xf, yf) in zip(A, B): (dx, dy) = (abs(x - xf), abs(y - yf)) st...
def moving_average(timeseries, k): result = [] for begin_index in range(0, len(timeseries) - k): end_index = begin_index + k current_sum = 0 for v in timeseries[begin_index:end_index]: current_sum += v current_avg = current_sum / k result.append(curren...
def moving_average(timeseries, k): result = [] for begin_index in range(0, len(timeseries) - k): end_index = begin_index + k current_sum = 0 for v in timeseries[begin_index:end_index]: current_sum += v current_avg = current_sum / k result.append(curren...
# Array # Given an unsorted array of integers, find the length of longest continuous increasing subsequence (subarray). # # Example 1: # Input: [1,3,5,4,7] # Output: 3 # Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3. # Even though [1,3,5,7] is also an increasing subsequence, it...
class Solution: def find_length_of_lcis(self, nums): """ :type nums: List[int] :rtype: int """ (output, temp) = (0, 0) for i in range(len(nums)): if nums[i - 1] >= nums[i]: temp = i output = max(output, i - temp + 1) re...
class Cord: homepage = ( 1, 42, 529,984 ) question = ( 42,317,519,426 ) answer1 = ( 48,487,510,558 ) answer2 = ( 48,573,510,645 ) answer3 = ( 48,660,510,732 ) answer1_clk = ( 94,524 ) answer2_clk = ( 94,609 ) answer3_clk = ( 94,694 )
class Cord: homepage = (1, 42, 529, 984) question = (42, 317, 519, 426) answer1 = (48, 487, 510, 558) answer2 = (48, 573, 510, 645) answer3 = (48, 660, 510, 732) answer1_clk = (94, 524) answer2_clk = (94, 609) answer3_clk = (94, 694)
#Exercise 4-2 - Animals animals = ['lion', 'tiger', 'cat'] for animal in animals: print(animal.title(), "it's a feline.") print('Only one is a great pet.')
animals = ['lion', 'tiger', 'cat'] for animal in animals: print(animal.title(), "it's a feline.") print('Only one is a great pet.')
class ICustomFactory: """ Enables users to write activation code for managed objects that extend System.MarshalByRefObject. """ def CreateInstance(self, serverType): """ CreateInstance(self: ICustomFactory,serverType: Type) -> MarshalByRefObject Creates a new instance of the specifie...
class Icustomfactory: """ Enables users to write activation code for managed objects that extend System.MarshalByRefObject. """ def create_instance(self, serverType): """ CreateInstance(self: ICustomFactory,serverType: Type) -> MarshalByRefObject Creates a new instance of the specified type. ...
PICTURE_DEFAULT = { "image": { "url": str, "name": str }, "thumbnail": { "url": str, "name": str } }
picture_default = {'image': {'url': str, 'name': str}, 'thumbnail': {'url': str, 'name': str}}
__all__ = ( "config_measure_voltage", "config_measure_resistance", "enable_source", "disable_source", "read", "config_voltage_pulse", ) def config_measure_voltage(k2400, nplc=1, voltage=21.0, auto_range=True): """Configures the measurement of voltage. (Courtesy of pymeasure, see link below...
__all__ = ('config_measure_voltage', 'config_measure_resistance', 'enable_source', 'disable_source', 'read', 'config_voltage_pulse') def config_measure_voltage(k2400, nplc=1, voltage=21.0, auto_range=True): """Configures the measurement of voltage. (Courtesy of pymeasure, see link below) args: k240...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # || ____ _ __ # +------+ / __ )(_) /_______________ _____ ___ # | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \ # +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/ # || || /_____/_/\__/\___/_/ \__,_/ /___/\___/ # # Copyright (C) 20...
""" The Crazyflie Micro Quadcopter library API used to communicate with the Crazyflie Micro Quadcopter via a communication link. The API takes care of scanning, opening and closing the communication link as well as sending/receiving data from the Crazyflie. A link is described using an URI of the following format: ...
# Python3 function to calculate number of possible stairs arrangements with given number of boxes/bricks def solution(n): dp=[[0 for x in range(n + 5)] for y in range(n + 5)] for i in range(n+1): for j in range (n+1): dp[i][j]=0 dp[3][2]=1 dp[4][2]=1 for i in range(5...
def solution(n): dp = [[0 for x in range(n + 5)] for y in range(n + 5)] for i in range(n + 1): for j in range(n + 1): dp[i][j] = 0 dp[3][2] = 1 dp[4][2] = 1 for i in range(5, n + 1): for j in range(2, i + 1): if j == 2: dp[i][j] = dp[i - j][j] ...
class PdfDoc(): def __init__(self, filename): self.filename = filename self.pages = [] def page_count(self): return len(self.pages)
class Pdfdoc: def __init__(self, filename): self.filename = filename self.pages = [] def page_count(self): return len(self.pages)
arquivo =open('mobydick.txt', 'r') saida = open('saida.txt', 'w') texto = arquivo.readlines()[:] for linha in texto: if linha == '\n': continue else: linha = linha.split() for palavra in linha: saida.write(f'{palavra} ') saida.write('\n') arquivo.close() saida.close()
arquivo = open('mobydick.txt', 'r') saida = open('saida.txt', 'w') texto = arquivo.readlines()[:] for linha in texto: if linha == '\n': continue else: linha = linha.split() for palavra in linha: saida.write(f'{palavra} ') saida.write('\n') arquivo.close() saida.close()
file = open('signalsAndNoise_input.txt', 'r') lines_read = file.readlines() message_length = len(lines_read[0].strip()) letter_frequencies = [None] * message_length for index in range(message_length): letter_frequencies[index] = dict() for line in lines_read: line = line.strip() for i in range(len(line))...
file = open('signalsAndNoise_input.txt', 'r') lines_read = file.readlines() message_length = len(lines_read[0].strip()) letter_frequencies = [None] * message_length for index in range(message_length): letter_frequencies[index] = dict() for line in lines_read: line = line.strip() for i in range(len(line)): ...
# Python - 3.6.0 def testing(actual, expected): Test.assert_equals(actual, expected) Test.describe('opstrings') Test.it('Basic tests vert_mirror') testing(oper(vert_mirror, 'hSgdHQ\nHnDMao\nClNNxX\niRvxxH\nbqTVvA\nwvSyRu'), 'QHdgSh\noaMDnH\nXxNNlC\nHxxvRi\nAvVTqb\nuRySvw') testing(oper(vert_mirror, 'IzOTWE\nkkbeC...
def testing(actual, expected): Test.assert_equals(actual, expected) Test.describe('opstrings') Test.it('Basic tests vert_mirror') testing(oper(vert_mirror, 'hSgdHQ\nHnDMao\nClNNxX\niRvxxH\nbqTVvA\nwvSyRu'), 'QHdgSh\noaMDnH\nXxNNlC\nHxxvRi\nAvVTqb\nuRySvw') testing(oper(vert_mirror, 'IzOTWE\nkkbeCM\nWuzZxM\nvDddJw\n...
# (C) Datadog, Inc. 2018 # All rights reserved # Licensed under a 3-clause BSD style license (see LICENSE) def headers(agentConfig, **kwargs): # Build the request headers res = { 'User-Agent': 'Datadog Agent/%s' % agentConfig.get('version', '0.0.0'), 'Content-Type': 'application/x-www-form-url...
def headers(agentConfig, **kwargs): res = {'User-Agent': 'Datadog Agent/%s' % agentConfig.get('version', '0.0.0'), 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'text/html, */*'} if 'http_host' in kwargs: res['Host'] = kwargs['http_host'] return res
# from ../../.tcp_chat_server import server.py, client.py # something is wrong with the directory above. # import pytest # Linter said it could not import pytest def test_alive(): """ Does the testing file run? """ pass
def test_alive(): """ Does the testing file run? """ pass
class GlueError(Exception): """Base Exception class for glue Errors.""" error_code = 999 class PILUnavailableError(GlueError): """Raised if some PIL decoder isn't available.""" error_code = 2 class ValidationError(GlueError): """Raised by formats or sprites while .""" error_code = 3 class ...
class Glueerror(Exception): """Base Exception class for glue Errors.""" error_code = 999 class Pilunavailableerror(GlueError): """Raised if some PIL decoder isn't available.""" error_code = 2 class Validationerror(GlueError): """Raised by formats or sprites while .""" error_code = 3 class Sou...
for i in range(101): if i % 3 == 0: print(i)
for i in range(101): if i % 3 == 0: print(i)
""" Otrzymujesz liste par liczb. Liczby w parze reprezentuja poczatek i koniec przedzialu. Niektore przedzialy moga na siebie nachodzic. W takim przypadku polacz je ze soba i zwroc liste niepokrywajacych sie przedzialow. """ # Wersja 1 def polacz_przedzialy_v1(lista): lista = sorted(lista) wynik = [] poc...
""" Otrzymujesz liste par liczb. Liczby w parze reprezentuja poczatek i koniec przedzialu. Niektore przedzialy moga na siebie nachodzic. W takim przypadku polacz je ze soba i zwroc liste niepokrywajacych sie przedzialow. """ def polacz_przedzialy_v1(lista): lista = sorted(lista) wynik = [] (pocz, koniec)...
to_solve = '' with open('input.txt') as f: to_solve = f.readlines() to_solve = list(map(lambda x: x.split(': '), to_solve)) temp = [] for i in to_solve: ttemp = i[0].split(' ') tttemp = ttemp[0].split('-') ttttemp = {'char': ttemp[1], 'passwd': i[1], 'min': int(tttemp[0]), 'max': int(tttemp[1])} temp.append(ttt...
to_solve = '' with open('input.txt') as f: to_solve = f.readlines() to_solve = list(map(lambda x: x.split(': '), to_solve)) temp = [] for i in to_solve: ttemp = i[0].split(' ') tttemp = ttemp[0].split('-') ttttemp = {'char': ttemp[1], 'passwd': i[1], 'min': int(tttemp[0]), 'max': int(tttemp[1])} tem...
""" You have an array of logs. Each log is a space delimited string of words. For each log, the first word in each log is an alphanumeric identifier. Then, either: Each word after the identifier will consist only of lowercase letters, or; Each word after the identifier will consist only of digits. We will ca...
""" You have an array of logs. Each log is a space delimited string of words. For each log, the first word in each log is an alphanumeric identifier. Then, either: Each word after the identifier will consist only of lowercase letters, or; Each word after the identifier will consist only of digits. We will ca...
# http://codingbat.com/prob/p194053 def combo_string(a, b): if len(a) > len(b): return b + a + b else: return a + b + a
def combo_string(a, b): if len(a) > len(b): return b + a + b else: return a + b + a
"""Tests which check the various ways you can set DJANGO_SETTINGS_MODULE If these tests fail you probably forgot to run "python setup.py develop". """ BARE_SETTINGS = ''' # At least one database must be configured DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:...
"""Tests which check the various ways you can set DJANGO_SETTINGS_MODULE If these tests fail you probably forgot to run "python setup.py develop". """ bare_settings = "\n# At least one database must be configured\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': ':memor...
def tree(entity): """tree is a filter to build the file tree Args: entity: the current entity Returns: A file tree, starting with the highest parent """ root = entity # Get the highest available parent while hasattr(root, 'parent') and root.parent and root.parent.type == r...
def tree(entity): """tree is a filter to build the file tree Args: entity: the current entity Returns: A file tree, starting with the highest parent """ root = entity while hasattr(root, 'parent') and root.parent and (root.parent.type == root.type): root = root.parent ...
""" What does the phrase "in-order successor" mean when we are talking about a node in a binary search tree? A - the node that has the next lowest value B - the node that has the maximum value C - the node that has the minimuin value D - the node that has the next highest value answer is : """
""" What does the phrase "in-order successor" mean when we are talking about a node in a binary search tree? A - the node that has the next lowest value B - the node that has the maximum value C - the node that has the minimuin value D - the node that has the next highest value answer is : """