content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def master_plan(): yield from bps.mvr(giantxy.x,x_range/2) yield from bps.mvr(giantxy.y,y_range/2) for _ in range(6): yield from bps.mvr(giantxy.x,-x_range) yield from bps.mvr(giantxy.y,-1) yield from bps.mvr(giantxy.x,+x_range) yield from bps.mvr(giantxy.y,-1) yield from...
def master_plan(): yield from bps.mvr(giantxy.x, x_range / 2) yield from bps.mvr(giantxy.y, y_range / 2) for _ in range(6): yield from bps.mvr(giantxy.x, -x_range) yield from bps.mvr(giantxy.y, -1) yield from bps.mvr(giantxy.x, +x_range) yield from bps.mvr(giantxy.y, -1) ...
number =int(raw_input("enter number:")) word =str(raw_input("enter word:")) if number == 0 or number > 1: print ("%s %ss." % (number,word)) else: print("%s %s." % (number,word)) if word[-3:] == "ife": print( word[:-3] + "ives") elif word[-2:] == "sh": print(word[:-2] + "shes" ) elif word[-2:] == "ch...
number = int(raw_input('enter number:')) word = str(raw_input('enter word:')) if number == 0 or number > 1: print('%s %ss.' % (number, word)) else: print('%s %s.' % (number, word)) if word[-3:] == 'ife': print(word[:-3] + 'ives') elif word[-2:] == 'sh': print(word[:-2] + 'shes') elif word[-2:] == 'ch': ...
FIELDS_EN = { 'title': lambda **kwargs: ' renamed project from "{from}" to "{to}"'.format(**kwargs), 'short': lambda **kwargs: ' changed short name of project from "{from}" to "{to}"'.format(**kwargs), 'description': lambda **kwargs: ' changed description of project from "{from}" to "{to}"'.format(**kwargs)...
fields_en = {'title': lambda **kwargs: ' renamed project from "{from}" to "{to}"'.format(**kwargs), 'short': lambda **kwargs: ' changed short name of project from "{from}" to "{to}"'.format(**kwargs), 'description': lambda **kwargs: ' changed description of project from "{from}" to "{to}"'.format(**kwargs), 'creator': ...
# -*- coding: utf-8 -*- class PeekableGenerator(object): def __init__(self, generator): self.__generator = generator self.__element = None self.__isset = False self.__more = False try: self.__element = generator.next() self.__more = True ...
class Peekablegenerator(object): def __init__(self, generator): self.__generator = generator self.__element = None self.__isset = False self.__more = False try: self.__element = generator.next() self.__more = True self.__isset = True ...
def get_member_guaranteed(ctx, lookup): if len(ctx.message.mentions) > 0: return ctx.message.mentions[0] if lookup.isdigit(): result = ctx.guild.get_member(int(lookup)) if result: return result if "#" in lookup: result = ctx.guild.get_member_named(lookup) ...
def get_member_guaranteed(ctx, lookup): if len(ctx.message.mentions) > 0: return ctx.message.mentions[0] if lookup.isdigit(): result = ctx.guild.get_member(int(lookup)) if result: return result if '#' in lookup: result = ctx.guild.get_member_named(lookup) ...
class Solution: def isIsomorphic(self, s: str, t: str) -> bool: if len(s) != len(t): return False s_t_dic = {} t_s_dic = {} n = len(s) for i in range(n): if (s[i] not in s_t_dic) and (t[i] not in t_s_dic): s_t_dic[s[i]] = t[i] ...
class Solution: def is_isomorphic(self, s: str, t: str) -> bool: if len(s) != len(t): return False s_t_dic = {} t_s_dic = {} n = len(s) for i in range(n): if s[i] not in s_t_dic and t[i] not in t_s_dic: s_t_dic[s[i]] = t[i] ...
class RandomListNode(): def __init__(self, x: int): self.label = x self.next = None self.random = None class Solution(): def copy_random_list(self, root: RandomListNode) -> RandomListNode: head = None if root is not None: pointers = {} new_root =...
class Randomlistnode: def __init__(self, x: int): self.label = x self.next = None self.random = None class Solution: def copy_random_list(self, root: RandomListNode) -> RandomListNode: head = None if root is not None: pointers = {} new_root = ra...
# Copyright 2016 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # These devices are ina3221 (3-channels/i2c address) devices inas = [('0x40:0', 'pp3300_edp_dx', 3.30, 0.020, 'rem', True), #R367 ('0x40:1', '...
inas = [('0x40:0', 'pp3300_edp_dx', 3.3, 0.02, 'rem', True), ('0x40:1', 'pp3300_a', 3.3, 0.002, 'rem', True), ('0x40:2', 'pp1800_a', 1.8, 0.02, 'rem', True), ('0x41:0', 'pp1240_a', 1.24, 0.02, 'rem', True), ('0x41:1', 'pp1800_dram_u', 1.8, 0.02, 'rem', True), ('0x41:2', 'pp1050_s', 1.05, 0.01, 'rem', True), ('0x42:0', ...
n = int(input()) lst = [] for _ in range(n): a, b = [int(i) for i in input().split()] lst.append((a,b)) lst.sort(key = lambda x: x[1]) index = 0 coordinates = [] while index < n: curr = lst[index] while index < n-1 and curr[1]>=lst[index+1][0]: index += 1 coordinates.append(curr[1]) ...
n = int(input()) lst = [] for _ in range(n): (a, b) = [int(i) for i in input().split()] lst.append((a, b)) lst.sort(key=lambda x: x[1]) index = 0 coordinates = [] while index < n: curr = lst[index] while index < n - 1 and curr[1] >= lst[index + 1][0]: index += 1 coordinates.append(curr[1]) ...
# -*- coding: utf-8 -*- class Solution: def numDifferentIntegers(self, word: str) -> int: result = set() number = None for char in word: if char.isdigit() and number is None: number = int(char) elif char.isdigit() and number is not None: ...
class Solution: def num_different_integers(self, word: str) -> int: result = set() number = None for char in word: if char.isdigit() and number is None: number = int(char) elif char.isdigit() and number is not None: number = 10 * numbe...
def fibo(n): return n if n <= 1 else (fibo(n-1) + fibo(n-2)) nums = [1,2,3,4,5,6] [fibo(x) for x in nums] # [1, 1, 2 ,3 ,5, 8] [y for x in nums if (y:= fibo(x)) % 2 == 0] # [2, 8]
def fibo(n): return n if n <= 1 else fibo(n - 1) + fibo(n - 2) nums = [1, 2, 3, 4, 5, 6] [fibo(x) for x in nums] [y for x in nums if (y := fibo(x)) % 2 == 0]
BUTTON_LEFT = 0 BUTTON_MIDDLE = 1 BUTTON_RIGHT = 2
button_left = 0 button_middle = 1 button_right = 2
def main(): file_log = open("hostapd.log",'r').read() address = file_log.find("AP-STA-CONNECTED") mac = set() while address >= 0: mac.add(file_log[address+17:address+34]) address=file_log.find("AP-STA-CONNECTED",address+1) for addr in mac: print(addr) # For ...
def main(): file_log = open('hostapd.log', 'r').read() address = file_log.find('AP-STA-CONNECTED') mac = set() while address >= 0: mac.add(file_log[address + 17:address + 34]) address = file_log.find('AP-STA-CONNECTED', address + 1) for addr in mac: print(addr) if __name__ ==...
COURSE = "Python for Everybody" def which_course_is_this(): print("The course is:", COURSE)
course = 'Python for Everybody' def which_course_is_this(): print('The course is:', COURSE)
DATASOURCE_NAME = "Coderepos" GITHUB_DATASOURCE_NAME = "github"
datasource_name = 'Coderepos' github_datasource_name = 'github'
def readDataIntoMatrix(fileName): f = open(fileName, 'r') i = 0 data = [] for line in f.readlines(): j = 0 row = [] values = line.split() for value in values: row.append(int(value)) j += 1 data.append(row) i += 1 return data
def read_data_into_matrix(fileName): f = open(fileName, 'r') i = 0 data = [] for line in f.readlines(): j = 0 row = [] values = line.split() for value in values: row.append(int(value)) j += 1 data.append(row) i += 1 return data
# -*- coding: UTF-8 -*- logger.info("Loading 2 objects to table invoicing_tariff...") # fields: id, designation, number_of_events, min_asset, max_asset loader.save(create_invoicing_tariff(1,['By presence', 'Pro Anwesenheit', 'By presence'],1,None,None)) loader.save(create_invoicing_tariff(2,['Maximum 10', 'Maximum 10',...
logger.info('Loading 2 objects to table invoicing_tariff...') loader.save(create_invoicing_tariff(1, ['By presence', 'Pro Anwesenheit', 'By presence'], 1, None, None)) loader.save(create_invoicing_tariff(2, ['Maximum 10', 'Maximum 10', 'Maximum 10'], 1, None, 10)) loader.flush_deferred_objects()
#!/usr/bin/env python3 # Write a program that computes the GC% of a DNA sequence # Format the output for 2 decimal places # Use all three formatting methods print('Method 1: printf()') seq = 'ACAGAGCCAGCAGATATACAGCAGATACTAT' # feel free to change gc_count = 0 for i in range(0, len(seq)): if seq[i] == 'G' or seq[i]...
print('Method 1: printf()') seq = 'ACAGAGCCAGCAGATATACAGCAGATACTAT' gc_count = 0 for i in range(0, len(seq)): if seq[i] == 'G' or seq[i] == 'C': gc_count += 1 print('%.2f' % (gc_count / len(seq))) print('-----') print('Method 2: str.format()') gc_count = 0 for i in range(0, len(seq)): if seq[i] == 'G' o...
''' solve amazing problem: Given a 2D array of mines, replace the question mark with the number of mines that immediately surround it. This includes the diagonals, meaning it is possible for it to be surrounded by 8 mines maximum. The key is as follows: An empty space: "-" A mine: "#" Number showing number of mines...
""" solve amazing problem: Given a 2D array of mines, replace the question mark with the number of mines that immediately surround it. This includes the diagonals, meaning it is possible for it to be surrounded by 8 mines maximum. The key is as follows: An empty space: "-" A mine: "#" Number showing number of mines...
#when many condition fullfil use all. subs = 1000 likes = 400 comments = 500 condition = [subs>150,likes>150,comments>50] if all(condition): print('Great Content')
subs = 1000 likes = 400 comments = 500 condition = [subs > 150, likes > 150, comments > 50] if all(condition): print('Great Content')
def write_to(filename:str,text:str): with open(f'{filename}.txt','w') as file1: file1.write(text) write_to('players','zarinaemirbaizak')
def write_to(filename: str, text: str): with open(f'{filename}.txt', 'w') as file1: file1.write(text) write_to('players', 'zarinaemirbaizak')
def main(): # input S = input() N, M = map(int, input().split()) # compute # output print(S[:N-1] + S[M-1] + S[N:M-1] + S[N-1] + S[M:]) if __name__ == '__main__': main()
def main(): s = input() (n, m) = map(int, input().split()) print(S[:N - 1] + S[M - 1] + S[N:M - 1] + S[N - 1] + S[M:]) if __name__ == '__main__': main()
class PropertyMonitor(object): __slots__ = ( '_lock', # concurrency control '_state', # currently active state '_pool', # MsgRecord deque to hold temporary records 'witness', # MsgRecord list of observed events 'on_enter_scope', # callback upo...
class Propertymonitor(object): __slots__ = ('_lock', '_state', '_pool', 'witness', 'on_enter_scope', 'on_exit_scope', 'on_violation', 'on_success', 'time_launch', 'time_shutdown', 'time_state', 'cb_map') prop_id = 'None' prop_title = 'None' prop_desc = 'None' hpl_property = 'globally: /a { True } fo...
le = 0 notas = 0 while le != 2: n = float(input()) if 0 <= n <= 10: notas = notas+n le += 1 else: print('nota invalida') print('media = {:.2f}'.format((notas/2)))
le = 0 notas = 0 while le != 2: n = float(input()) if 0 <= n <= 10: notas = notas + n le += 1 else: print('nota invalida') print('media = {:.2f}'.format(notas / 2))
def ipaddr(interface=None): ''' Returns the IP address for a given interface CLI Example:: salt '*' network.ipaddr eth0 ''' iflist = interfaces() out = None if interface: data = iflist.get(interface) or dict() if data.get('inet'): return data.get('inet'...
def ipaddr(interface=None): """ Returns the IP address for a given interface CLI Example:: salt '*' network.ipaddr eth0 """ iflist = interfaces() out = None if interface: data = iflist.get(interface) or dict() if data.get('inet'): return data.get('inet')...
def generate(env, **kw): if not kw.get('depsOnly',0): env.Tool('addLibrary', library=['astro'], package = 'astro') if env['PLATFORM'] == 'win32'and env.get('CONTAINERNAME','')=='GlastRelease': env.Tool('findPkgPath', package = 'astro') env.Tool('facilitiesLib') env.Tool('tipLib') env.Tool('addLibrary', libr...
def generate(env, **kw): if not kw.get('depsOnly', 0): env.Tool('addLibrary', library=['astro'], package='astro') if env['PLATFORM'] == 'win32' and env.get('CONTAINERNAME', '') == 'GlastRelease': env.Tool('findPkgPath', package='astro') env.Tool('facilitiesLib') env.Tool('tipLib'...
def cvt(s): if isinstance(s, str): return unicode(s) return s class GWTCanvasImplDefault: def createElement(self): e = DOM.createElement("CANVAS") try: # This results occasionally in an error: # AttributeError: XPCOM component '<unknown>' has no attribute 'M...
def cvt(s): if isinstance(s, str): return unicode(s) return s class Gwtcanvasimpldefault: def create_element(self): e = DOM.createElement('CANVAS') try: self.setCanvasContext(e.MozGetIPCContext(u'2d')) except AttributeError: self.setCanvasContext(e.g...
# DSAME prob #40 class Node: def __init__(self, data=None, next=None): self.data = data self.next = next def get_josephus_pos(): q = p = Node() n = int(input("Enter no of players: ")) m = int(input("Enter which player needs to be eliminated each time:")) # create cll containing a...
class Node: def __init__(self, data=None, next=None): self.data = data self.next = next def get_josephus_pos(): q = p = node() n = int(input('Enter no of players: ')) m = int(input('Enter which player needs to be eliminated each time:')) p.data = 1 p.next = node() for i in ...
a=float(input()) b=float(input()) if a<b: print(a) else: print(b)
a = float(input()) b = float(input()) if a < b: print(a) else: print(b)
def grammar(): return [ 'progStructure', 'name', 'body', 'instruction', 'moreInstruction', 'functionCall', 'parameter', 'moreParameter', 'parameterType' ] def progStructure(self): self.name() self.match( ('reserved_word', 'INICIO')...
def grammar(): return ['progStructure', 'name', 'body', 'instruction', 'moreInstruction', 'functionCall', 'parameter', 'moreParameter', 'parameterType'] def prog_structure(self): self.name() self.match(('reserved_word', 'INICIO')) self.body() self.match(('reserved_word', 'FIN')) def name(self): ...
n,m=map(int,input().split()) l1=list(map(int,input().split())) minindex=l1.index(min(l1)) l2=list(map(int,input().split())) maxindex=l2.index(max(l2)) for i in range(0,m): print(minindex,i) for j in range(0,minindex): print(j,maxindex) for j in range(minindex+1,n): print(j,maxindex)
(n, m) = map(int, input().split()) l1 = list(map(int, input().split())) minindex = l1.index(min(l1)) l2 = list(map(int, input().split())) maxindex = l2.index(max(l2)) for i in range(0, m): print(minindex, i) for j in range(0, minindex): print(j, maxindex) for j in range(minindex + 1, n): print(j, maxindex)
class TempSensor: __sensor_path = '/sys/bus/w1/devices/28-00000652b8e4/w1_slave' def __init__(self): self.__recent_values = [] def read(self): data = self.__read_sensor_file() temp_value = self.__parse_sensor_data(data) fahrenheit_value = self.__convert_to_fahrenheit(temp_...
class Tempsensor: __sensor_path = '/sys/bus/w1/devices/28-00000652b8e4/w1_slave' def __init__(self): self.__recent_values = [] def read(self): data = self.__read_sensor_file() temp_value = self.__parse_sensor_data(data) fahrenheit_value = self.__convert_to_fahrenheit(temp_v...
#Question 14 power = int(input('Enter power:')) number = 2**power print('Two last digits:', number%100)
power = int(input('Enter power:')) number = 2 ** power print('Two last digits:', number % 100)
def distance(strand_a, strand_b): if len(strand_a) != len(strand_b): raise ValueError('strands are not of equal length') count = 0 for i in range(len(strand_a)): if strand_a[i] != strand_b[i]: count += 1 return count
def distance(strand_a, strand_b): if len(strand_a) != len(strand_b): raise value_error('strands are not of equal length') count = 0 for i in range(len(strand_a)): if strand_a[i] != strand_b[i]: count += 1 return count
# 367. Valid Perfect Square class Solution: # Binary Search def isPerfectSquare(self, num: int) -> bool: if num < 2: return True left, right = 2, num // 2 while left <= right: mid = left + (right - left) // 2 sqr = mid ** 2 if sqr == num...
class Solution: def is_perfect_square(self, num: int) -> bool: if num < 2: return True (left, right) = (2, num // 2) while left <= right: mid = left + (right - left) // 2 sqr = mid ** 2 if sqr == num: return True el...
class BuySellEnum: BUY_SELL_UNSET = 0 BUY = 1 SELL = 2
class Buysellenum: buy_sell_unset = 0 buy = 1 sell = 2
STATS = [ { "num_node_expansions": 653, "plan_length": 167, "search_time": 0.49, "total_time": 0.49 }, { "num_node_expansions": 978, "plan_length": 167, "search_time": 0.72, "total_time": 0.72 }, { "num_node_expansions": 1087, ...
stats = [{'num_node_expansions': 653, 'plan_length': 167, 'search_time': 0.49, 'total_time': 0.49}, {'num_node_expansions': 978, 'plan_length': 167, 'search_time': 0.72, 'total_time': 0.72}, {'num_node_expansions': 1087, 'plan_length': 194, 'search_time': 17.44, 'total_time': 17.44}, {'num_node_expansions': 923, 'plan_...
# List dog_names = ["tom", "sean", "sally", "mark"] print(type(dog_names)) print(dog_names) # Adding Item On Last Position dog_names.append("sam") print(dog_names) # Adding Item On First Position dog_names.insert(0, "bruz") print(dog_names) # Delete Items del(dog_names[0]) print(dog_names) # Length Of List pr...
dog_names = ['tom', 'sean', 'sally', 'mark'] print(type(dog_names)) print(dog_names) dog_names.append('sam') print(dog_names) dog_names.insert(0, 'bruz') print(dog_names) del dog_names[0] print(dog_names) print('Length Of List: ', len(dog_names))
class BTNode: def __init__(self, data = -1, left = None, right = None): self.data = data self.left = left self.right = right class BTree: def __init__(self): self.root = None self.found = False def is_empty(self): return self.root is None def build(self, ...
class Btnode: def __init__(self, data=-1, left=None, right=None): self.data = data self.left = left self.right = right class Btree: def __init__(self): self.root = None self.found = False def is_empty(self): return self.root is None def build(self, va...
# -- Project information ----------------------------------------------------- project = "Test" copyright = "Test" author = "Test" # -- General configuration --------------------------------------------------- master_doc = "index" # -- Options for HTML output ------------------------------------------------- html_...
project = 'Test' copyright = 'Test' author = 'Test' master_doc = 'index' html_theme = 'pydata_sphinx_theme'
# Reads the UA list from the file "ua_list.txt" # Refer this site for list of UAs: https://developers.whatismybrowser.com/useragents/explore/ ua_file = open("ua_list.txt", "r") lines = ua_file.readlines() ua_list = [] for line in lines: line_cleaned = line.replace("\n","").lower() ua_list.append(line_cleaned)...
ua_file = open('ua_list.txt', 'r') lines = ua_file.readlines() ua_list = [] for line in lines: line_cleaned = line.replace('\n', '').lower() ua_list.append(line_cleaned) ua_list.sort() ua_list = list(dict.fromkeys(ua_list)) ua_list_count = len(ua_list) print(ua_list) print('Identified ', ua_list_count, ' UA...
# greatest of three def greatest(a,b,c): return max(a,b,c) print(greatest(2,4,3))
def greatest(a, b, c): return max(a, b, c) print(greatest(2, 4, 3))
def LCSBackTrack(v, w): v = '-' + v w = '-' + w S = [[0 for i in range(len(w))] for j in range(len(v))] Backtrack = [[0 for i in range(len(w))] for j in range(len(v))] for i in range(1, len(v)): for j in range(1, len(w)): tmp = S[i - 1][j - 1] + (1 if v[i] == w[j] else 0) ...
def lcs_back_track(v, w): v = '-' + v w = '-' + w s = [[0 for i in range(len(w))] for j in range(len(v))] backtrack = [[0 for i in range(len(w))] for j in range(len(v))] for i in range(1, len(v)): for j in range(1, len(w)): tmp = S[i - 1][j - 1] + (1 if v[i] == w[j] else 0) ...
{ "targets": [ { "target_name": "boost-parameter", "type": "none", "include_dirs": [ "1.57.0/parameter-boost-1.57.0/include" ], "all_dependent_settings": { "include_dirs": [ "1.57.0/parameter-boos...
{'targets': [{'target_name': 'boost-parameter', 'type': 'none', 'include_dirs': ['1.57.0/parameter-boost-1.57.0/include'], 'all_dependent_settings': {'include_dirs': ['1.57.0/parameter-boost-1.57.0/include']}, 'dependencies': ['../boost-config/boost-config.gyp:*', '../boost-detail/boost-detail.gyp:*', '../boost-optiona...
class AbstractBatchifier(object): def filter(self, games): return games def apply(self, games): return games
class Abstractbatchifier(object): def filter(self, games): return games def apply(self, games): return games
#coding:utf-8 ''' filename:clsmethod.py learn class method ''' class Message: msg = 'Python is a smart language.' def get_msg(self): print('self :',self) print('attrs of class(Message.msg):',Message.msg) print('use type(self).msg:',type(self).msg) cls = type(self) ...
""" filename:clsmethod.py learn class method """ class Message: msg = 'Python is a smart language.' def get_msg(self): print('self :', self) print('attrs of class(Message.msg):', Message.msg) print('use type(self).msg:', type(self).msg) cls = type(self) print('[...
class Solution: def findNumbers(self, nums: List[int]) -> int: if len(nums) == 0: return 0 return len(list(filter(lambda x:len(str(x))%2==0,nums)))
class Solution: def find_numbers(self, nums: List[int]) -> int: if len(nums) == 0: return 0 return len(list(filter(lambda x: len(str(x)) % 2 == 0, nums)))
# 231 - Power Of Two (Easy) # https://leetcode.com/problems/power-of-two/submissions/ class Solution: def isPowerOfTwo(self, n: int) -> bool: return n and (n & (n-1)) == 0
class Solution: def is_power_of_two(self, n: int) -> bool: return n and n & n - 1 == 0
# Some sites give IR codes in this weird pronto format # Cut off the preamble and footer and find which value represents a 1 in the spacing code = "0000 0016 0000 0016 0000 0016 0000 003F 0000 003F 0000 003F 0000 0016 0000 003F 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0...
code = '0000 0016 0000 0016 0000 0016 0000 003F 0000 003F 0000 003F 0000 0016 0000 003F 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 003F 0000 0016 0000 003F 0000 003F 0000 0016 0000 0016 0000 003F 0000 003F 0000 0016 0000 003F 0000 0016 0000 0016 0000 003F 0000 003F 00...
# ---------------------------------------------------------------------------- # This software is in the public domain, furnished "as is", without technical # support, and with no warranty, express or implied, as to its usefulness for # any purpose. # # iscSendSampleDef # # Author: mathewson # -------------------------...
hr = 3600 sample_def = {} SampleDef['default'] = ([0 * HR], [(-24 * HR, 1 * HR)])
#Write a program (using functions!) that asks the user for a long string containing multiple words. # Print back to the user the same string, except with the words in backwards order. For example, say I type the string: # My name is Michele #Then I would see the string: # Michele is name My #shown back to me. def ...
def reverse(strng: str): list = strng.split(' ') list.reverse() return list print(reverse('My name is Michele'))
def strategy(history, memory): if memory is None or 1 == memory: return 0, 0 else: return 1, 1
def strategy(history, memory): if memory is None or 1 == memory: return (0, 0) else: return (1, 1)
with open("promote.in") as input_file: input_lst = [[*map(int, line.split())] for line in input_file] promotions = [ promotion[1] - promotion[0] for promotion in input_lst ] output = [] for promotion in promotions[::-1]: output.append(sum([])) with open("promote.out", "w") as output_file: for promotio...
with open('promote.in') as input_file: input_lst = [[*map(int, line.split())] for line in input_file] promotions = [promotion[1] - promotion[0] for promotion in input_lst] output = [] for promotion in promotions[::-1]: output.append(sum([])) with open('promote.out', 'w') as output_file: for promotion in pro...
sample_text = ''' The textwrap module can be used to format text for output in situations where pretty-printing is desired. It offers programmatic functionality similar to the paragraph wrapping or filling features found in many text editors. '''
sample_text = '\n The textwrap module can be used to format text for output in\n situations where pretty-printing is desired. It offers\n programmatic functionality similar to the paragraph wrapping\n or filling features found in many text editors.\n '
# Write your solutions for 1.5 here! class Superheros: def __init__(self, name, superpower, strength): self.name = name self.superpower = superpower self.strength = strength def hero (self): print(self.name) print(self.strength) def save_civilian (self, work): if work > self....
class Superheros: def __init__(self, name, superpower, strength): self.name = name self.superpower = superpower self.strength = strength def hero(self): print(self.name) print(self.strength) def save_civilian(self, work): if work > self.strength: print('Superhero is no...
# Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'prefix_header', 'type': 'static_library', 'sources': [ 'file.c', ], 'xcode_settings': { 'GCC_...
{'targets': [{'target_name': 'prefix_header', 'type': 'static_library', 'sources': ['file.c'], 'xcode_settings': {'GCC_PREFIX_HEADER': 'header.h'}}, {'target_name': 'precompiled_prefix_header', 'type': 'shared_library', 'mac_bundle': 1, 'sources': ['file.c'], 'xcode_settings': {'GCC_PREFIX_HEADER': 'header.h', 'GCC_PRE...
#FACTORIAL OF A NUMBER a = input("Enter number1") a=int(a) factorial=1 if a==1: print('Factorial is 1') elif a<1: print('Please enter a valid number') else: for i in range(1, a+1): factorial *= i print(f'The factorial is {factorial}')
a = input('Enter number1') a = int(a) factorial = 1 if a == 1: print('Factorial is 1') elif a < 1: print('Please enter a valid number') else: for i in range(1, a + 1): factorial *= i print(f'The factorial is {factorial}')
# -*- coding: utf-8 -*- class Job: def __init__(self, job_id, name, status, start_date, end_date, source_records, processed_records, price): self.id = job_id self.name = name self.status = status self.start_date = start_date self.end_date = end_date ...
class Job: def __init__(self, job_id, name, status, start_date, end_date, source_records, processed_records, price): self.id = job_id self.name = name self.status = status self.start_date = start_date self.end_date = end_date self.source_records = source_records ...
def median(iterable): items = sorted(iterable) if len(items) == 0: raise ValueError("median() arg is an empty series") median_index = (len(items) - 1) // 2 if len(items) % 2 != 0: return items[median_index] return (items[median_index] + items[median_index + 1]) / 2 print(median([5,...
def median(iterable): items = sorted(iterable) if len(items) == 0: raise value_error('median() arg is an empty series') median_index = (len(items) - 1) // 2 if len(items) % 2 != 0: return items[median_index] return (items[median_index] + items[median_index + 1]) / 2 print(median([5, ...
def get(): return int(input()) def get_num(): return get() def get_line(): return get_num() print(get_line())
def get(): return int(input()) def get_num(): return get() def get_line(): return get_num() print(get_line())
# ### Problem 1 # ``` # # Start with this List # list_of_many_numbers = [12, 24, 1, 34, 10, 2, 7] # ``` # Example Input/Output if the user enters the number 9: # ``` # The User entered 9 # 1 2 7 are smaller than 9 # 12 24 34 10 are larger than 9 # ``` # Ask the user to enter a number. userInput = int(input("Enter...
user_input = int(input('Enter a number ')) list_of_many_numbers = [12, 24, 1, 34, 10, 2, 7] for x in list_of_many_numbers: if userInput > x: print('the value that is smaller than the user input ', x) if userInput < x: print('the value that is greater than the user input ', x)
class Scheduler(object): def __init__(self, env, cpu_list=[], task_list=[]): self.env = env self.cpu_list = cpu_list self.task_list = [] self._lock = False self.overhead = 0 def run(self): pass def on_activate(self, job): pass def on_termin...
class Scheduler(object): def __init__(self, env, cpu_list=[], task_list=[]): self.env = env self.cpu_list = cpu_list self.task_list = [] self._lock = False self.overhead = 0 def run(self): pass def on_activate(self, job): pass def on_terminated...
# test 0 # correct answer # [0] num_topics, num_themes = 1, 1 lst = [0] with open('input.txt', 'w') as f: f.write("{} {}\n".format(num_topics, num_themes)) for l in lst: f.write(str(l) + '\n')
(num_topics, num_themes) = (1, 1) lst = [0] with open('input.txt', 'w') as f: f.write('{} {}\n'.format(num_topics, num_themes)) for l in lst: f.write(str(l) + '\n')
class Stack(): def __init__(self): self.items = [] def push(self, item): return self.items.append(item) def pop(self): return self.items.pop() def IsEmpty(self): return self.items == [] def length(self): return len(self.items) def peek(self): ...
class Stack: def __init__(self): self.items = [] def push(self, item): return self.items.append(item) def pop(self): return self.items.pop() def is_empty(self): return self.items == [] def length(self): return len(self.items) def peek(self): ...
# User input percentage = float(input("Enter your marks: ")) # Program operation & Computer output if (percentage >= 90): print("Your grade is A1 !") elif (percentage >= 80): print("Your grade is A !") elif (percentage >= 70): print("Your grade is B1 !") elif (percentage >= 60): print("Your ...
percentage = float(input('Enter your marks: ')) if percentage >= 90: print('Your grade is A1 !') elif percentage >= 80: print('Your grade is A !') elif percentage >= 70: print('Your grade is B1 !') elif percentage >= 60: print('Your grade is B !') elif percentage >= 50: print('Your grade is C, try b...
#!/usr/bin/env python # -*- coding:utf-8 -*- def q_s(v): if len(v) <=1: return v left, right = 0, len(v) - 1 item = v[int((left+right))/2] left_value = [i for i in v if i < item] right_value = [i for i in v if i > item] return q_s(left_value) + [item] + q_s(right_value) if __name...
def q_s(v): if len(v) <= 1: return v (left, right) = (0, len(v) - 1) item = v[int(left + right) / 2] left_value = [i for i in v if i < item] right_value = [i for i in v if i > item] return q_s(left_value) + [item] + q_s(right_value) if __name__ == '__main__': v = [1, 2, 4, 3, 6, 7, 8...
# # PySNMP MIB module WWP-LEOS-OAM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-LEOS-OAM-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:31:22 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, single_value_constraint, constraints_intersection, value_size_constraint, value_range_constraint) ...
# https://leetcode.com/problems/longest-palindromic-subsequence/ class Solution: def longestPalindromeSubseq(self, s: str) -> int: dp = [[0 for _ in range(len(s))] for _ in range(len(s))] for row in range(len(s)): for col in range(len(s)): # Find len of longest common su...
class Solution: def longest_palindrome_subseq(self, s: str) -> int: dp = [[0 for _ in range(len(s))] for _ in range(len(s))] for row in range(len(s)): for col in range(len(s)): if s[row] == s[-1 - col]: diagonal_top_left = dp[row - 1][col - 1] if row ...
# -- Project information ----------------------------------------------------- project = "PyData Tests" copyright = "2020, Pydata community" author = "Pydata community" master_doc = "index" # -- General configuration --------------------------------------------------- html_theme = "pydata_sphinx_theme" html_copy_s...
project = 'PyData Tests' copyright = '2020, Pydata community' author = 'Pydata community' master_doc = 'index' html_theme = 'pydata_sphinx_theme' html_copy_source = True html_sourcelink_suffix = ''
test = { 'name': 'q5g', 'points': 1, 'suites': [ { 'cases': [ { 'code': ">>> 'result_q5g' in globals()\n" 'True', 'hidden': False, 'locked': False}, ...
test = {'name': 'q5g', 'points': 1, 'suites': [{'cases': [{'code': ">>> 'result_q5g' in globals()\nTrue", 'hidden': False, 'locked': False}, {'code': '>>> result_q5g.to_string(index=False) == df_usa.fillna(value=0).head().to_string(index=False)\nTrue', 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 't...
# ======================== # Information # ======================== # Direct Link: https://www.hackerrank.com/challenges/s10-poisson-distribution-2/problem # Difficulty: Easy # Max Score: 30 # Language: Python # ======================== # Solution # ======================== AVERAGE_X, AVERAGE_Y = [floa...
(average_x, average_y) = [float(num) for num in input().split(' ')] cost_x = 160 + 40 * (AVERAGE_X + AVERAGE_X ** 2) cost_y = 128 + 40 * (AVERAGE_Y + AVERAGE_Y ** 2) print(round(COST_X, 3)) print(round(COST_Y, 3))
def cap_11(packet): # your code here try: if packet["RTMPT"]["string"] == '_result': packet["RTMPT"]["string"] = '_123456' print("cambiado") return packet except: print("fallo") return None
def cap_11(packet): try: if packet['RTMPT']['string'] == '_result': packet['RTMPT']['string'] = '_123456' print('cambiado') return packet except: print('fallo') return None
''' Hardcoded string input no filtering sink: check if a file exists ''' class Class_351: def __init__(self, param): self.var_351 = param def get_var_351(self): return self.var_351
""" Hardcoded string input no filtering sink: check if a file exists """ class Class_351: def __init__(self, param): self.var_351 = param def get_var_351(self): return self.var_351
inv_count = 0 def sorter(l_res , r_res): global inv_count i = 0 r = 0 results = [] while i < len(l_res) and r < len(r_res): if l_res[i] > r_res[r]: results.append(r_res[r]) inv_count += len(l_res) - i r += 1 else: results.append(l_res...
inv_count = 0 def sorter(l_res, r_res): global inv_count i = 0 r = 0 results = [] while i < len(l_res) and r < len(r_res): if l_res[i] > r_res[r]: results.append(r_res[r]) inv_count += len(l_res) - i r += 1 else: results.append(l_res[i...
# # @lc app=leetcode.cn id=133 lang=python3 # # [133] clone-graph # None # @lc code=end
None
def add_node(v): if v in graph: print(v,"already present") else: graph[v]=[] def add_edge(v1,v2): if v1 not in graph: print(v1," not present in graph") elif v2 not in graph: print(v2,"not present in graph") else: graph[v1].append(v2) graph[v2].append(...
def add_node(v): if v in graph: print(v, 'already present') else: graph[v] = [] def add_edge(v1, v2): if v1 not in graph: print(v1, ' not present in graph') elif v2 not in graph: print(v2, 'not present in graph') else: graph[v1].append(v2) graph[v2].a...
# ================================================================ def total_packet_size_bytes (s): return (s ['packet_len'] + s ['num_credits'] + s ['channel_id'] + s ['payload']) def this_packet_size_bytes (s, n): return (s ['packet_len'] + s ['num_credits'] +...
def total_packet_size_bytes(s): return s['packet_len'] + s['num_credits'] + s['channel_id'] + s['payload'] def this_packet_size_bytes(s, n): return s['packet_len'] + s['num_credits'] + s['channel_id'] + n def subst(template, substs): s = '\n'.join(template) for (var, val) in substs: s = s.repl...
class S(str): # Symbol class: the only important difference between S and str is that S has a __substitute__ method # Note that S('a') == 'a' is True. This lets us use strings as shorthand in certain places. def __str__(self): return "S('" + super(S, self).__str__() + "')" def __repr__(self): ...
class S(str): def __str__(self): return "S('" + super(S, self).__str__() + "')" def __repr__(self): return 'S(' + super(S, self).__repr__() + ')' def __substitute__(self, values): return values[self] def identity(x): return x class Transsymbol(object): def __init__(self...
class SwampyException(Exception): pass class ExWelcomeTimeout(SwampyException): pass class ExAbort(SwampyException): pass class ExInvocationError(SwampyException): pass
class Swampyexception(Exception): pass class Exwelcometimeout(SwampyException): pass class Exabort(SwampyException): pass class Exinvocationerror(SwampyException): pass
#!/usr/bin/python3 def new_in_list(my_list, idx, element): new_list = my_list[:] if idx >= 0 and idx < len(my_list): new_list[idx] = element return new_list
def new_in_list(my_list, idx, element): new_list = my_list[:] if idx >= 0 and idx < len(my_list): new_list[idx] = element return new_list
def main(type): x = 0 print(type) if type=="wl": #a while loop while (x <5): print(x) x = x + 1 elif type=="fl": #a for loop for x in range(5,10): print(x) elif type=="cl": #a for loop over a collection days = ["Mon", "Tue", "Wed", "Thurs", "Fri", "Sat", "Sun"] for ...
def main(type): x = 0 print(type) if type == 'wl': while x < 5: print(x) x = x + 1 elif type == 'fl': for x in range(5, 10): print(x) elif type == 'cl': days = ['Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'] for d in days: ...
# Constants in FlexRay spec cdCycleMax = 16000 cCycleCountMax = 63 cStaticSlotIDMax = 1023 cSlotIDMax = 2047 cPayloadLengthMax = 127 cSamplesPerBit = 8 cSyncFrameIDCountMax = 15 cMicroPerMacroNomMin = 40 cdMinMTNom = 1 cdMaxMTNom = 6 cdFES = 2 cdFSS = 1 cChannelIdleDelimiter = 11 cClockDeviationMax = 0.0015 cStrobeOffs...
cd_cycle_max = 16000 c_cycle_count_max = 63 c_static_slot_id_max = 1023 c_slot_id_max = 2047 c_payload_length_max = 127 c_samples_per_bit = 8 c_sync_frame_id_count_max = 15 c_micro_per_macro_nom_min = 40 cd_min_mt_nom = 1 cd_max_mt_nom = 6 cd_fes = 2 cd_fss = 1 c_channel_idle_delimiter = 11 c_clock_deviation_max = 0.00...
class Triple: def __init__(self, subject, predicate, object): self.subject = subject self.predicate = predicate self.object = object
class Triple: def __init__(self, subject, predicate, object): self.subject = subject self.predicate = predicate self.object = object
def main(): return 0 if __name__ == "__main__": for case in range(1, int(input()) + 1): print(f"Case #{case}:", main())
def main(): return 0 if __name__ == '__main__': for case in range(1, int(input()) + 1): print(f'Case #{case}:', main())
file = open('input.txt', 'r') Lines = file.readlines() count = 0 # Strips the newline character for line in Lines: line_parts = line.strip().split(' ') rule_part = line_parts[0].split('-') min_rule = int(rule_part[0]) max_rule = int(rule_part[1]) password = line_parts[2] char = line_parts[1][0] char_count = pa...
file = open('input.txt', 'r') lines = file.readlines() count = 0 for line in Lines: line_parts = line.strip().split(' ') rule_part = line_parts[0].split('-') min_rule = int(rule_part[0]) max_rule = int(rule_part[1]) password = line_parts[2] char = line_parts[1][0] char_count = password.count...
# Roman numeral/Decimal converter # Roman to decimal conversion table RomanValue = { 'I' : 1, 'V' : 5, 'X' : 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000 } def RomanValueList (RomanNumber): number = [] for i in RomanNumber: number.append(RomanValue[i]) return number # Convert Roman number stri...
roman_value = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} def roman_value_list(RomanNumber): number = [] for i in RomanNumber: number.append(RomanValue[i]) return number def to_decimal(number): answer = number[-1] for i in range(len(number) - 1, 0, -1): right ...
# Python Program To Handle Multiple Exceptions def avg(list): tot = 0 for x in list: tot += x avg = tot/len(list) return tot, avg # Call The avg() And Pass A List try: t, a = avg([1,2,3,4,5,'a']) # Here Give Empty List And try print('Total = {}, Average = {}'....
def avg(list): tot = 0 for x in list: tot += x avg = tot / len(list) return (tot, avg) try: (t, a) = avg([1, 2, 3, 4, 5, 'a']) print('Total = {}, Average = {}'.format(t, a)) except TypeError: print('Type Error, Please Provide Numbers.') except ZeroDivisionError: print('Ze...
def dataset(): pass def model(): pass def loss(): pass def opt(): pass
def dataset(): pass def model(): pass def loss(): pass def opt(): pass
class Response: def __init__(self, message=None, data=None): self.message = message self.data = data def build(self): return { "message": self.message, "data": self.data }
class Response: def __init__(self, message=None, data=None): self.message = message self.data = data def build(self): return {'message': self.message, 'data': self.data}
def main(): double_letters = 0 triple_letters = 0 input_file = open('input', 'r') for line in input_file: double_letters_found = False triple_letters_found = False characters = set(line.replace('\n', '')) for character in characters: if not double_letters_foun...
def main(): double_letters = 0 triple_letters = 0 input_file = open('input', 'r') for line in input_file: double_letters_found = False triple_letters_found = False characters = set(line.replace('\n', '')) for character in characters: if not double_letters_foun...
coordinates_E0E1E1 = ((129, 120), (129, 122), (129, 124), (130, 124), (131, 124), (132, 124), (133, 124), (134, 124), (135, 124), (136, 123), (136, 132), (137, 119), (137, 123), (138, 119), (138, 122), (139, 120), (139, 122), (140, 121), (140, 123), (141, 121), (141, 126), (142, 113), (142, 115), (142, 121), (142, 12...
coordinates_e0_e1_e1 = ((129, 120), (129, 122), (129, 124), (130, 124), (131, 124), (132, 124), (133, 124), (134, 124), (135, 124), (136, 123), (136, 132), (137, 119), (137, 123), (138, 119), (138, 122), (139, 120), (139, 122), (140, 121), (140, 123), (141, 121), (141, 126), (142, 113), (142, 115), (142, 121), (142, 12...
num = int(input('digite um numero pra daber sua tabuada: ')) for rep in range(0, 11): print('{} x {:2} = {}'.format(rep, num, num*rep))
num = int(input('digite um numero pra daber sua tabuada: ')) for rep in range(0, 11): print('{} x {:2} = {}'.format(rep, num, num * rep))
class Solution: def bstFromPreorder(self, preorder: List[int]) -> TreeNode: if len(preorder)==0: return None tn=TreeNode(preorder[0]) l=[] r=[] for i in preorder: if i<preorder[0]: l.append(i) elif i>preorder[0]: ...
class Solution: def bst_from_preorder(self, preorder: List[int]) -> TreeNode: if len(preorder) == 0: return None tn = tree_node(preorder[0]) l = [] r = [] for i in preorder: if i < preorder[0]: l.append(i) elif i > preorder...
n = int(input('digite um numero de 1 a 9999: ')) u = n % 10 d = n // 10 % 10 c = n // 100 % 10 m = n // 1000 % 10 print('A unidade', u) print('A dezena', d) print('A centena', c) print('A milhar', m)
n = int(input('digite um numero de 1 a 9999: ')) u = n % 10 d = n // 10 % 10 c = n // 100 % 10 m = n // 1000 % 10 print('A unidade', u) print('A dezena', d) print('A centena', c) print('A milhar', m)
def stair(n): if n == 0 or n == 1: return 1 elif n == 2: return 2 elif n == 3: return 4 else: return stair(n-3) + stair(n-2) + stair(n-1) n = int(input()) print(stair(n))
def stair(n): if n == 0 or n == 1: return 1 elif n == 2: return 2 elif n == 3: return 4 else: return stair(n - 3) + stair(n - 2) + stair(n - 1) n = int(input()) print(stair(n))
# # PySNMP MIB module CADANT-CMTS-EXPORTIMPORT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CADANT-CMTS-EXPORTIMPORT-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:27:10 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python vers...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, single_value_constraint, value_size_constraint, constraints_intersection, constraints_union) ...
#!/home/jepoy/anaconda3/bin/python ## at terminal which python #simple fibonacci series # the sum of two elements defines the next set a, b = 0, 1 while b < 1000: print(b, end = ' ', flush = True) a, b = b, a + b print() # line ending
(a, b) = (0, 1) while b < 1000: print(b, end=' ', flush=True) (a, b) = (b, a + b) print()
def create(type): switcher = { "L": LPiece(), "O": OPiece(), "I": IPiece(), "J": JPiece(), "S": SPiece(), "T": TPiece(), "Z": ZPiece() } return switcher.get(type.upper()) class Piece: def __init__(self): self._rotateIndex...
def create(type): switcher = {'L': l_piece(), 'O': o_piece(), 'I': i_piece(), 'J': j_piece(), 'S': s_piece(), 'T': t_piece(), 'Z': z_piece()} return switcher.get(type.upper()) class Piece: def __init__(self): self._rotateIndex = 0 self._rotations = [] def turn_left(self, times=1): ...
class HelperBase: def __init__(self, app): self.app = app def type(self, locator, text): wd = self.app.wd if text is not None: wd.find_element_by_name(locator).click() wd.find_element_by_name(locator).clear() wd.find_element_by_name(locator).send_k...
class Helperbase: def __init__(self, app): self.app = app def type(self, locator, text): wd = self.app.wd if text is not None: wd.find_element_by_name(locator).click() wd.find_element_by_name(locator).clear() wd.find_element_by_name(locator).send_key...
#!/usr/bin/python3 print("Hello World") x=4 y="ok,google" z=[4,77,x,y] print(y) print(z) print(x,y)
print('Hello World') x = 4 y = 'ok,google' z = [4, 77, x, y] print(y) print(z) print(x, y)