content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
''' Write a code which accepts a sequence of words as input and prints the words in a sequence after sorting them alphabetically. Hint: In case of input data being supplied to the question, it should be assumed to be a console input. ''' print('Input number word for : ') n = input() mp = list(map(lambda x: ord(x), n)) mp.sort() mc = list(map(lambda y: chr(y), mp)) dd = '' for z in mc : dd = dd + z print(dd)
""" Write a code which accepts a sequence of words as input and prints the words in a sequence after sorting them alphabetically. Hint: In case of input data being supplied to the question, it should be assumed to be a console input. """ print('Input number word for : ') n = input() mp = list(map(lambda x: ord(x), n)) mp.sort() mc = list(map(lambda y: chr(y), mp)) dd = '' for z in mc: dd = dd + z print(dd)
class subject (): def __init__(self): x=[] self.students=[] def addstudents(self): n=int(input("Enter No. Of Students :- ")) for i in range (n): self.name=input("Enter Name :- ") self.rno=input("Enter Roll No. :- ") self.marks=input("Enter Total Marks :- ") print() self.students+=[[self.name,self.rno,self.marks]] print("ORIGINAL LIST :- ",self.students) def final(self): v=len(self.students) for i in range(v): minpos=i for j in range(i+1,v): if self.students[j][2]>self.students[i][2]: minpos=j temp=self.students[minpos] self.students[minpos]=self.students[i] self.students[i]=temp print() print("SORTED LIST :- ",self.students) a=subject() a.addstudents() a.final()
class Subject: def __init__(self): x = [] self.students = [] def addstudents(self): n = int(input('Enter No. Of Students :- ')) for i in range(n): self.name = input('Enter Name :- ') self.rno = input('Enter Roll No. :- ') self.marks = input('Enter Total Marks :- ') print() self.students += [[self.name, self.rno, self.marks]] print('ORIGINAL LIST :- ', self.students) def final(self): v = len(self.students) for i in range(v): minpos = i for j in range(i + 1, v): if self.students[j][2] > self.students[i][2]: minpos = j temp = self.students[minpos] self.students[minpos] = self.students[i] self.students[i] = temp print() print('SORTED LIST :- ', self.students) a = subject() a.addstudents() a.final()
def make_dot(count, left, right): if left == "" and right == "": return count * "." if right == "": if left == "L": return '.'*count else: return 'R'*count if left == "": if right == "L": return count * "L" else: return count * "." if left == "L" and right == "R": return '.'*count elif right == "L" and left == "R": if count % 2 == 1: return ((count//2) * "R") + "." + ((count//2) * "L") else: return (count//2) * 'R' + 'L' * (count//2) elif left == "L" and right == "L": return count*'L' elif left == "R" and right == "R": return count*'R' class Solution: def pushDominoes(self, dominoes): result_list = [] letter_cache = [] last = '' dot_count = 0 for i in dominoes: if i == ".": if last != '' and last != '.': result_list.append("".join(letter_cache)) letter_cache = [] dot_count += 1 else: if last == ".": result_list.append(dot_count) letter_cache.append(i) dot_count = 0 else: letter_cache.append(i) last = i if dot_count != 0: result_list.append(dot_count) elif letter_cache != []: result_list.append("".join(letter_cache)) print(result_list) for ind in range(len(result_list)): left = '' right = '' if type(result_list[ind]) == int: if ind-1 >= 0: left = result_list[ind-1][-1] if ind+1 < len(result_list): right = result_list[ind+1][0] result_list[ind] = make_dot(result_list[ind], left, right) return "".join(result_list) a = Solution() a.pushDominoes(".L.R...LR..L..") == "LL.RR.LLRRLL.." a.pushDominoes("RR.L") == "RR.L" a.pushDominoes(".") == "." a.pushDominoes("LL") == "LL"
def make_dot(count, left, right): if left == '' and right == '': return count * '.' if right == '': if left == 'L': return '.' * count else: return 'R' * count if left == '': if right == 'L': return count * 'L' else: return count * '.' if left == 'L' and right == 'R': return '.' * count elif right == 'L' and left == 'R': if count % 2 == 1: return count // 2 * 'R' + '.' + count // 2 * 'L' else: return count // 2 * 'R' + 'L' * (count // 2) elif left == 'L' and right == 'L': return count * 'L' elif left == 'R' and right == 'R': return count * 'R' class Solution: def push_dominoes(self, dominoes): result_list = [] letter_cache = [] last = '' dot_count = 0 for i in dominoes: if i == '.': if last != '' and last != '.': result_list.append(''.join(letter_cache)) letter_cache = [] dot_count += 1 elif last == '.': result_list.append(dot_count) letter_cache.append(i) dot_count = 0 else: letter_cache.append(i) last = i if dot_count != 0: result_list.append(dot_count) elif letter_cache != []: result_list.append(''.join(letter_cache)) print(result_list) for ind in range(len(result_list)): left = '' right = '' if type(result_list[ind]) == int: if ind - 1 >= 0: left = result_list[ind - 1][-1] if ind + 1 < len(result_list): right = result_list[ind + 1][0] result_list[ind] = make_dot(result_list[ind], left, right) return ''.join(result_list) a = solution() a.pushDominoes('.L.R...LR..L..') == 'LL.RR.LLRRLL..' a.pushDominoes('RR.L') == 'RR.L' a.pushDominoes('.') == '.' a.pushDominoes('LL') == 'LL'
"""Do a one-time build of default.png""" # Copyright (c) 2001-2009 ElevenCraft Inc. # See LICENSE for details. if __name__ == '__main__': f = file('default.png', 'rb') default_png = f.read() f.close() f = file('_default_png.py', 'wU') f.write('DEFAULT_PNG = %r\n' % default_png) f.close()
"""Do a one-time build of default.png""" if __name__ == '__main__': f = file('default.png', 'rb') default_png = f.read() f.close() f = file('_default_png.py', 'wU') f.write('DEFAULT_PNG = %r\n' % default_png) f.close()
""" docsting of empty_all module. """ __all__ = [] def foo(): """docstring""" def bar(): """docstring""" def baz(): """docstring"""
""" docsting of empty_all module. """ __all__ = [] def foo(): """docstring""" def bar(): """docstring""" def baz(): """docstring"""
load( "@io_bazel_rules_dotnet//dotnet/private:context.bzl", "dotnet_context", ) load( "@io_bazel_rules_dotnet//dotnet/private:providers.bzl", "DotnetLibrary", "DotnetResource", ) load( "@io_bazel_rules_dotnet//dotnet/private:rules/launcher_gen.bzl", "dotnet_launcher_gen", ) def _core_binary_impl(ctx): """dotnet_binary_impl emits actions for compiling dotnet executable assembly.""" dotnet = dotnet_context(ctx) name = ctx.label.name executable = dotnet.binary(dotnet, name = name, srcs = ctx.attr.srcs, deps = ctx.attr.deps, resources = ctx.attr.resources, out = ctx.attr.out, defines = ctx.attr.defines, unsafe = ctx.attr.unsafe, data = ctx.attr.data, ) return [ DefaultInfo( files = depset([executable.result]), runfiles = ctx.runfiles(files = ctx.attr._native_deps.files.to_list() + [dotnet.runner], transitive_files = executable.runfiles), executable = executable.result, ), ] _core_binary = rule( _core_binary_impl, attrs = { "deps": attr.label_list(providers=[DotnetLibrary]), "resources": attr.label_list(providers=[DotnetResource]), "srcs": attr.label_list(allow_files = FileType([".cs"])), "out": attr.string(), "defines": attr.string_list(), "unsafe": attr.bool(default = False), "data": attr.label_list(allow_files = True), "_dotnet_context_data": attr.label(default = Label("@io_bazel_rules_dotnet//:core_context_data")), "_native_deps": attr.label(default = Label("@core_sdk//:native_deps")) }, toolchains = ["@io_bazel_rules_dotnet//dotnet:toolchain_core"], executable = True, ) def core_binary(name, srcs, deps = [], defines = None, out = None, resources = None, data = None): _core_binary(name = "%s_exe" % name, deps = deps, srcs = srcs, out = out, defines = defines, resources = resources, data = data) exe = ":%s_exe" % name dotnet_launcher_gen(name = "%s_launcher" % name, exe = exe) native.cc_binary( name=name, srcs = [":%s_launcher" % name], deps = ["@io_bazel_rules_dotnet//dotnet/tools/runner_core", "@io_bazel_rules_dotnet//dotnet/tools/common"], data = [exe], )
load('@io_bazel_rules_dotnet//dotnet/private:context.bzl', 'dotnet_context') load('@io_bazel_rules_dotnet//dotnet/private:providers.bzl', 'DotnetLibrary', 'DotnetResource') load('@io_bazel_rules_dotnet//dotnet/private:rules/launcher_gen.bzl', 'dotnet_launcher_gen') def _core_binary_impl(ctx): """dotnet_binary_impl emits actions for compiling dotnet executable assembly.""" dotnet = dotnet_context(ctx) name = ctx.label.name executable = dotnet.binary(dotnet, name=name, srcs=ctx.attr.srcs, deps=ctx.attr.deps, resources=ctx.attr.resources, out=ctx.attr.out, defines=ctx.attr.defines, unsafe=ctx.attr.unsafe, data=ctx.attr.data) return [default_info(files=depset([executable.result]), runfiles=ctx.runfiles(files=ctx.attr._native_deps.files.to_list() + [dotnet.runner], transitive_files=executable.runfiles), executable=executable.result)] _core_binary = rule(_core_binary_impl, attrs={'deps': attr.label_list(providers=[DotnetLibrary]), 'resources': attr.label_list(providers=[DotnetResource]), 'srcs': attr.label_list(allow_files=file_type(['.cs'])), 'out': attr.string(), 'defines': attr.string_list(), 'unsafe': attr.bool(default=False), 'data': attr.label_list(allow_files=True), '_dotnet_context_data': attr.label(default=label('@io_bazel_rules_dotnet//:core_context_data')), '_native_deps': attr.label(default=label('@core_sdk//:native_deps'))}, toolchains=['@io_bazel_rules_dotnet//dotnet:toolchain_core'], executable=True) def core_binary(name, srcs, deps=[], defines=None, out=None, resources=None, data=None): _core_binary(name='%s_exe' % name, deps=deps, srcs=srcs, out=out, defines=defines, resources=resources, data=data) exe = ':%s_exe' % name dotnet_launcher_gen(name='%s_launcher' % name, exe=exe) native.cc_binary(name=name, srcs=[':%s_launcher' % name], deps=['@io_bazel_rules_dotnet//dotnet/tools/runner_core', '@io_bazel_rules_dotnet//dotnet/tools/common'], data=[exe])
if sys.version_info.minor > 9: phr = {"user_id": user_id} | content else: z = {"user_id": user_id} phr = {**z, **content}
if sys.version_info.minor > 9: phr = {'user_id': user_id} | content else: z = {'user_id': user_id} phr = {**z, **content}
class Solution: def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: if k <= 1 : return 0 prod =1 res = 0 i,j = 0, 0 while j < len(nums): prod *= nums[j] if prod < k : res += (j-i+1) elif prod >= k : while prod >= k : prod = prod//nums[i] i+=1 res += j-i+1 j+=1 return res
class Solution: def num_subarray_product_less_than_k(self, nums: List[int], k: int) -> int: if k <= 1: return 0 prod = 1 res = 0 (i, j) = (0, 0) while j < len(nums): prod *= nums[j] if prod < k: res += j - i + 1 elif prod >= k: while prod >= k: prod = prod // nums[i] i += 1 res += j - i + 1 j += 1 return res
""" This module defines the learner interface. """ class Learner: """ A learner ingests data, manipulates internal state by learning off this data, supplies agents for taking further actions, and provides an opaque interface to internal evaluation. """ def train(self, data, timesteps): """ Fit the learner using the given dataset of transitions. data is the current ringbuffer and timesteps indicates how many new transitions we have just sampled. """ raise NotImplementedError def agent(self): """ Return an agent.Agent to take some actions. """ raise NotImplementedError def tf_action(self, states_ns): """ Accept a TF state and return a TF tensor for the action this learner would have taken. This is used to evaluate the dynamics quality, so take the action that is used to expand dynamics if the learner uses a dynamics model for planning or learning. """ raise NotImplementedError def evaluate(self, data): """ Report evaluation information. """ raise NotImplementedError
""" This module defines the learner interface. """ class Learner: """ A learner ingests data, manipulates internal state by learning off this data, supplies agents for taking further actions, and provides an opaque interface to internal evaluation. """ def train(self, data, timesteps): """ Fit the learner using the given dataset of transitions. data is the current ringbuffer and timesteps indicates how many new transitions we have just sampled. """ raise NotImplementedError def agent(self): """ Return an agent.Agent to take some actions. """ raise NotImplementedError def tf_action(self, states_ns): """ Accept a TF state and return a TF tensor for the action this learner would have taken. This is used to evaluate the dynamics quality, so take the action that is used to expand dynamics if the learner uses a dynamics model for planning or learning. """ raise NotImplementedError def evaluate(self, data): """ Report evaluation information. """ raise NotImplementedError
# helpers def create_data_list(dic): """ This function creates a list from a data dictionary where all user data is stored """ lst = [] lst.append(dic['cough']) lst.append(dic['fever']) lst.append(dic['sore_throat']) lst.append(dic['shortness_of_breath']) lst.append(dic['head_ache']) lst.append(int(dic['age'])) lst.append(dic['gender']) lst.append(dic['additional_factor']) return lst
def create_data_list(dic): """ This function creates a list from a data dictionary where all user data is stored """ lst = [] lst.append(dic['cough']) lst.append(dic['fever']) lst.append(dic['sore_throat']) lst.append(dic['shortness_of_breath']) lst.append(dic['head_ache']) lst.append(int(dic['age'])) lst.append(dic['gender']) lst.append(dic['additional_factor']) return lst
# -*- coding: utf-8 -*- # ScrollBar part codes # Left arrow of horizontal scroll bar. # @see ScrollBar::scrollStep sbLeftArrow = 0 # Right arrow of horizontal scroll bar. # @see ScrollBar::scrollStep sbRightArrow = 1 # Left paging area of horizontal scroll bar. # @see ScrollBar::scrollStep sbPageLeft = 2 # Right paging area of horizontal scroll bar. # @see ScrollBar::scrollStep sbPageRight = 3 # Top arrow of vertical scroll bar. # @see ScrollBar::scrollStep sbUpArrow = 4 # Bottom arrow of vertical scroll bar. # @see ScrollBar::scrollStep sbDownArrow = 5 # Upper paging area of vertical scroll bar. # @see ScrollBar::scrollStep sbPageUp = 6 # Lower paging area of vertical scroll bar. # @see ScrollBar::scrollStep sbPageDown = 7 # Position indicator on scroll bar. # @see ScrollBar::scrollStep sbIndicator = 8 # ScrollBar options for Window.StandardScrollBar # The scroll bar is horizontal. # @see Window::standardScrollBar sbHorizontal = 0x000 # The scroll bar is vertical. # @see Window::standardScrollBar sbVertical = 0x001 # The scroll bar responds to keyboard commands. # @see Window::standardScrollBar sbHandleKeyboard = 0x002
sb_left_arrow = 0 sb_right_arrow = 1 sb_page_left = 2 sb_page_right = 3 sb_up_arrow = 4 sb_down_arrow = 5 sb_page_up = 6 sb_page_down = 7 sb_indicator = 8 sb_horizontal = 0 sb_vertical = 1 sb_handle_keyboard = 2
BLACK = u"\u001b[30m" RED = u"\u001b[31m" GREEN = u"\u001b[32m" YELLOW = u"\u001b[33m" BLUE = u"\u001b[34m" MAGENTA = u"\u001b[35m" CYAN = u"\u001b[36m" WHITE = u"\u001b[37m" BBLACK = u"\u001b[30;1m" BRED = u"\u001b[31;1m" BGREEN = u"\u001b[32;1m" BYELLOW = u"\u001b[33;1m" BBLUE = u"\u001b[34;1m" BMAGENTA = u"\u001b[35;1m" BCYAN = u"\u001b[36;1m" BWHITE = u"\u001b[37;1m" RESET = u"\u001b[0m"
black = u'\x1b[30m' red = u'\x1b[31m' green = u'\x1b[32m' yellow = u'\x1b[33m' blue = u'\x1b[34m' magenta = u'\x1b[35m' cyan = u'\x1b[36m' white = u'\x1b[37m' bblack = u'\x1b[30;1m' bred = u'\x1b[31;1m' bgreen = u'\x1b[32;1m' byellow = u'\x1b[33;1m' bblue = u'\x1b[34;1m' bmagenta = u'\x1b[35;1m' bcyan = u'\x1b[36;1m' bwhite = u'\x1b[37;1m' reset = u'\x1b[0m'
''' module for implementation of merge sort ''' def merge_sort(arr: list): if len(arr) > 1: mid = len(arr) // 2 L = arr[:mid] R = arr[mid:] merge_sort(L) merge_sort(R) i, j, k = 0, 0, 0 while (i < len(L) and j < len(R)): if (L[i] < R[j]): arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 while (i < len(L)): arr[k] = L[i] i += 1 k += 1 while (j < len(R)): arr[k] = R[j] j += 1 k += 1 return arr ''' PyAlgo Devansh Singh, 2021 '''
""" module for implementation of merge sort """ def merge_sort(arr: list): if len(arr) > 1: mid = len(arr) // 2 l = arr[:mid] r = arr[mid:] merge_sort(L) merge_sort(R) (i, j, k) = (0, 0, 0) while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 while i < len(L): arr[k] = L[i] i += 1 k += 1 while j < len(R): arr[k] = R[j] j += 1 k += 1 return arr '\nPyAlgo\nDevansh Singh, 2021\n'
#!/usr/bin/env python3 class MessageBroadcast: def __init__(self, friend_graph, start_person): self.friend_graph = friend_graph self.start_person = start_person self.people_without_message = list(friend_graph.keys()) self.step_number = 0 self.new_people_with_message_in_last_step = [] def broadcast(self): self.people_without_message.remove(self.start_person) self.new_people_with_message_in_last_step.append(self.start_person) while len(self.people_without_message) > 0 and len(self.new_people_with_message_in_last_step) > 0: self.broadcast_step() self.step_number += 1 def broadcast_step(self): people_who_broadcast_in_this_step = self.new_people_with_message_in_last_step self.new_people_with_message_in_last_step = [] for broadcaster in people_who_broadcast_in_this_step: self.send_message_to_all_friends(broadcaster) def send_message_to_all_friends(self, broadcaster): friends_of_broadcaster = self.friend_graph[broadcaster] for receiver in friends_of_broadcaster: self.receive_message(receiver) def receive_message(self, receiver): if receiver in self.people_without_message: self.people_without_message.remove(receiver) self.new_people_with_message_in_last_step.append(receiver) def has_notified_every_people(self): return len(self.people_without_message) == 0 def get_number_of_steps(self): return self.step_number class Case: def __init__(self): self.friend_graph = {} self.min_steps = -1 self.start_persons_with_min_steps = [] def add_person(self, person_id, their_friends): self.friend_graph[person_id] = their_friends def run_case(self): for person in self.friend_graph: self.try_broadcast_starting_with(person) def try_broadcast_starting_with(self, person): broadcast = MessageBroadcast(self.friend_graph, person) broadcast.broadcast() if broadcast.has_notified_every_people(): steps = broadcast.get_number_of_steps() self.successful_broadcast_for(person, steps) def successful_broadcast_for(self, person, steps): if self.min_steps == -1 or steps < self.min_steps: self.new_broadcast_min_steps(steps, person) elif steps == self.min_steps: self.same_as_current_min_steps(person) def new_broadcast_min_steps(self, steps, person): self.min_steps = steps self.start_persons_with_min_steps = [person] def same_as_current_min_steps(self, person): self.start_persons_with_min_steps.append(person) def get_person_to_notify(self): if self.min_steps == -1: return "0" else: self.start_persons_with_min_steps.sort() return " ".join([str(i) for i in self.start_persons_with_min_steps]) number_of_cases = int(input()) for c in range(number_of_cases): case = Case() number_of_people = int(input()) for p in range(number_of_people): case.add_person(p + 1, [int(i) for i in input().split()]) case.run_case() print(case.get_person_to_notify())
class Messagebroadcast: def __init__(self, friend_graph, start_person): self.friend_graph = friend_graph self.start_person = start_person self.people_without_message = list(friend_graph.keys()) self.step_number = 0 self.new_people_with_message_in_last_step = [] def broadcast(self): self.people_without_message.remove(self.start_person) self.new_people_with_message_in_last_step.append(self.start_person) while len(self.people_without_message) > 0 and len(self.new_people_with_message_in_last_step) > 0: self.broadcast_step() self.step_number += 1 def broadcast_step(self): people_who_broadcast_in_this_step = self.new_people_with_message_in_last_step self.new_people_with_message_in_last_step = [] for broadcaster in people_who_broadcast_in_this_step: self.send_message_to_all_friends(broadcaster) def send_message_to_all_friends(self, broadcaster): friends_of_broadcaster = self.friend_graph[broadcaster] for receiver in friends_of_broadcaster: self.receive_message(receiver) def receive_message(self, receiver): if receiver in self.people_without_message: self.people_without_message.remove(receiver) self.new_people_with_message_in_last_step.append(receiver) def has_notified_every_people(self): return len(self.people_without_message) == 0 def get_number_of_steps(self): return self.step_number class Case: def __init__(self): self.friend_graph = {} self.min_steps = -1 self.start_persons_with_min_steps = [] def add_person(self, person_id, their_friends): self.friend_graph[person_id] = their_friends def run_case(self): for person in self.friend_graph: self.try_broadcast_starting_with(person) def try_broadcast_starting_with(self, person): broadcast = message_broadcast(self.friend_graph, person) broadcast.broadcast() if broadcast.has_notified_every_people(): steps = broadcast.get_number_of_steps() self.successful_broadcast_for(person, steps) def successful_broadcast_for(self, person, steps): if self.min_steps == -1 or steps < self.min_steps: self.new_broadcast_min_steps(steps, person) elif steps == self.min_steps: self.same_as_current_min_steps(person) def new_broadcast_min_steps(self, steps, person): self.min_steps = steps self.start_persons_with_min_steps = [person] def same_as_current_min_steps(self, person): self.start_persons_with_min_steps.append(person) def get_person_to_notify(self): if self.min_steps == -1: return '0' else: self.start_persons_with_min_steps.sort() return ' '.join([str(i) for i in self.start_persons_with_min_steps]) number_of_cases = int(input()) for c in range(number_of_cases): case = case() number_of_people = int(input()) for p in range(number_of_people): case.add_person(p + 1, [int(i) for i in input().split()]) case.run_case() print(case.get_person_to_notify())
''' pythagorean_triples.py: When given the sides of a triangle, tells the user whether the triangle is a right triangle. Based on https://www.redd.it/19jwi6 ''' while True: sides = input('Enter the three sides of a triangle, separated by spaces: ') try: sides = [int(x) for x in sides.split()] except ValueError: print('Error: please enter numbers only!') else: sides.sort() right = 'is' if (sides[0]**2 + sides[1]**2 == sides[2]**2) else 'is not' print('That {0} a right triangle.'.format(right)) if input('Would you like to check another triangle? (Y/n) ').strip()[0].lower() == 'n': break;
""" pythagorean_triples.py: When given the sides of a triangle, tells the user whether the triangle is a right triangle. Based on https://www.redd.it/19jwi6 """ while True: sides = input('Enter the three sides of a triangle, separated by spaces: ') try: sides = [int(x) for x in sides.split()] except ValueError: print('Error: please enter numbers only!') else: sides.sort() right = 'is' if sides[0] ** 2 + sides[1] ** 2 == sides[2] ** 2 else 'is not' print('That {0} a right triangle.'.format(right)) if input('Would you like to check another triangle? (Y/n) ').strip()[0].lower() == 'n': break
# -*- coding: utf-8 -*- # Copyright (c) 2012 Fabian Barkhau <fabian.barkhau@gmail.com> # License: MIT (see LICENSE.TXT file) ID = r"[0-9]+" SLUG = r"[a-z0-9\-]+" USERNAME = r"[\w.@+-]+" # see django.contrib.auth.forms.UserCreationForm def _build_arg(name, pattern): return "(?P<%s>%s)" % (name, pattern) def arg_id(name): return _build_arg(name, ID) def arg_slug(name): return _build_arg(name, SLUG) def arg_username(name): return _build_arg(name, USERNAME)
id = '[0-9]+' slug = '[a-z0-9\\-]+' username = '[\\w.@+-]+' def _build_arg(name, pattern): return '(?P<%s>%s)' % (name, pattern) def arg_id(name): return _build_arg(name, ID) def arg_slug(name): return _build_arg(name, SLUG) def arg_username(name): return _build_arg(name, USERNAME)
""" (C) Copyright 2020 Scott Wiederhold, s.e.wiederhold@gmail.com https://community.openglow.org SPDX-License-Identifier: MIT """ _decode_step_codes = { 'LE': {'mask': 0b00010000, 'test': 0b00010000}, # Laser Enable (ON) 'LP': {'mask': 0b10000000, 'test': 0b01111111}, # Laser Power Setting 'XP': {'mask': 0b00000011, 'test': 0b00000001}, # X+ Step 'XN': {'mask': 0b00000011, 'test': 0b00000011}, # X- Step 'YN': {'mask': 0b00001100, 'test': 0b00000100}, # Y- Step 'YP': {'mask': 0b00001100, 'test': 0b00001100}, # Y+ Step 'ZP': {'mask': 0b01100000, 'test': 0b00100000}, # Z+ Step 'ZN': {'mask': 0b01100000, 'test': 0b01100000}, # Z- Step } _SPEED = 1000 def decode_all_steps(puls: bytes, data: dict = None, mode: tuple = (8, 2)) -> dict: cnt = { 'XP': 0, 'XN': 0, 'XTOT': 0, 'XEND': 0, 'YP': 0, 'YN': 0, 'YTOT': 0, 'YEND': 0, 'ZP': 0, 'ZN': 0, 'ZTOT': 0, 'ZEND': 0, 'LE': 0, 'LP': 0, } for step in puls: if step & _decode_step_codes['LP']['mask']: # Power Setting (LP) cnt['LP'] = cnt['LP'] + 1 else: for action in sorted(_decode_step_codes): if not (step & _decode_step_codes[action]['mask']) ^ _decode_step_codes[action]['test']: cnt[action] = cnt[action] + 1 if action != 'LE': cnt[action[0:1] + 'TOT'] = cnt[action[0:1] + 'TOT'] + 1 cnt[action[0:1] + 'END'] = cnt[action[0:1] + 'END'] + 1 \ if action[1:2] == 'P' else cnt[action[0:1] + 'END'] - 1 for axis in ('X', 'Y'): cnt[axis + 'MM'] = (cnt[axis + 'END'] / mode[0]) * 0.15 cnt['ZMM'] = (cnt['ZEND'] / mode[1]) * 0.70612 for axis in ('X', 'Y', 'Z'): cnt[axis + 'IN'] = cnt[axis + 'MM'] / 25.4 if data is not None: for key, val in cnt.items(): cnt[key] = val + data.get(key, 0) return cnt def generate_linear_puls(x: int, y: int, outfile: str) -> None: expected_count = abs(x) if abs(x) >= abs(y) else abs(y) max_speed = 5 min_speed = 55 acc = 10 acc_dist = int((min_speed - max_speed) / acc) acc_dist = acc_dist if acc_dist < (expected_count / 2) else int(expected_count / 2) steps = 0 d = min_speed with open(outfile, 'bw') as f: for xs, ys in _step_gen(x, y): steps += 1 s = 0 if xs != 0: s |= 0b00000001 if xs > 0 else 0b00000011 if ys != 0: s |= 0b00001100 if ys > 0 else 0b00000100 f.write(bytes([s])) if steps <= acc_dist: # Accelerating d = d - acc if d > max_speed - acc else max_speed elif steps >= (expected_count - acc_dist): # Decelerating d = d + acc if d < min_speed + acc else min_speed f.write('\0'.encode() * d) def _step_gen(x: int, y: int) -> tuple: xd = 1 if x >= 0 else -1 yd = 1 if y >= 0 else -1 xt = abs(x) yt = abs(y) if xt >= yt: maj_target = xt min_target = yt maj_dir = xd min_dir = yd else: maj_target = yt min_target = xt maj_dir = yd min_dir = xd if min_target > 0: maj_per_min = round(maj_target / min_target, 4) else: maj_per_min = maj_target maj_cnt = 0 min_cnt = 0 while maj_cnt < maj_target or min_cnt < min_target: if maj_cnt < maj_target: maj_cnt += 1 if maj_cnt % maj_per_min < 1 and min_cnt < min_target: min_out = min_dir min_cnt += 1 else: min_out = 0 else: maj_dir = 0 min_out = min_dir min_cnt += 1 yield maj_dir if xt >= yt else min_out, min_out if xt >= yt else maj_dir
""" (C) Copyright 2020 Scott Wiederhold, s.e.wiederhold@gmail.com https://community.openglow.org SPDX-License-Identifier: MIT """ _decode_step_codes = {'LE': {'mask': 16, 'test': 16}, 'LP': {'mask': 128, 'test': 127}, 'XP': {'mask': 3, 'test': 1}, 'XN': {'mask': 3, 'test': 3}, 'YN': {'mask': 12, 'test': 4}, 'YP': {'mask': 12, 'test': 12}, 'ZP': {'mask': 96, 'test': 32}, 'ZN': {'mask': 96, 'test': 96}} _speed = 1000 def decode_all_steps(puls: bytes, data: dict=None, mode: tuple=(8, 2)) -> dict: cnt = {'XP': 0, 'XN': 0, 'XTOT': 0, 'XEND': 0, 'YP': 0, 'YN': 0, 'YTOT': 0, 'YEND': 0, 'ZP': 0, 'ZN': 0, 'ZTOT': 0, 'ZEND': 0, 'LE': 0, 'LP': 0} for step in puls: if step & _decode_step_codes['LP']['mask']: cnt['LP'] = cnt['LP'] + 1 else: for action in sorted(_decode_step_codes): if not step & _decode_step_codes[action]['mask'] ^ _decode_step_codes[action]['test']: cnt[action] = cnt[action] + 1 if action != 'LE': cnt[action[0:1] + 'TOT'] = cnt[action[0:1] + 'TOT'] + 1 cnt[action[0:1] + 'END'] = cnt[action[0:1] + 'END'] + 1 if action[1:2] == 'P' else cnt[action[0:1] + 'END'] - 1 for axis in ('X', 'Y'): cnt[axis + 'MM'] = cnt[axis + 'END'] / mode[0] * 0.15 cnt['ZMM'] = cnt['ZEND'] / mode[1] * 0.70612 for axis in ('X', 'Y', 'Z'): cnt[axis + 'IN'] = cnt[axis + 'MM'] / 25.4 if data is not None: for (key, val) in cnt.items(): cnt[key] = val + data.get(key, 0) return cnt def generate_linear_puls(x: int, y: int, outfile: str) -> None: expected_count = abs(x) if abs(x) >= abs(y) else abs(y) max_speed = 5 min_speed = 55 acc = 10 acc_dist = int((min_speed - max_speed) / acc) acc_dist = acc_dist if acc_dist < expected_count / 2 else int(expected_count / 2) steps = 0 d = min_speed with open(outfile, 'bw') as f: for (xs, ys) in _step_gen(x, y): steps += 1 s = 0 if xs != 0: s |= 1 if xs > 0 else 3 if ys != 0: s |= 12 if ys > 0 else 4 f.write(bytes([s])) if steps <= acc_dist: d = d - acc if d > max_speed - acc else max_speed elif steps >= expected_count - acc_dist: d = d + acc if d < min_speed + acc else min_speed f.write('\x00'.encode() * d) def _step_gen(x: int, y: int) -> tuple: xd = 1 if x >= 0 else -1 yd = 1 if y >= 0 else -1 xt = abs(x) yt = abs(y) if xt >= yt: maj_target = xt min_target = yt maj_dir = xd min_dir = yd else: maj_target = yt min_target = xt maj_dir = yd min_dir = xd if min_target > 0: maj_per_min = round(maj_target / min_target, 4) else: maj_per_min = maj_target maj_cnt = 0 min_cnt = 0 while maj_cnt < maj_target or min_cnt < min_target: if maj_cnt < maj_target: maj_cnt += 1 if maj_cnt % maj_per_min < 1 and min_cnt < min_target: min_out = min_dir min_cnt += 1 else: min_out = 0 else: maj_dir = 0 min_out = min_dir min_cnt += 1 yield (maj_dir if xt >= yt else min_out, min_out if xt >= yt else maj_dir)
translations = { "startMessage": "I can help you see all of your EqualHash.pt statistics\n\nYou can control me by " "sending these " "commands:\n\n/newaddr - Add new address\n/myaddrs - View all address\n\n*Edit " "Addresses*\n/setname - Change a address's name\n/setaddress - Change the " "address\n/deleteaddr - Delete a address\n\n*Stats*\n/seestats - View " "Stats\n\n*Notifications*\n/enablenotification - Enable workers status " "notifications\n/disablenotification - Disable workers status notifications", "newAddr": "Alright, a new address. How are we going to call it? Please choose a name for your address.", "newAddr2": "All right!! Now enter the address.", "newAddr3": "Done! Congratulations for your new address:\n\nNow you can start checking your statistics, " "run the /seestats command and choose your address.\n\nName: *<NAMEADDRESS>*\nAddress: *<ADDRESS>*", "delAddrC": "Choose a address to delete.", "setnameAddrC": "Choose the address to which you want to change the name.", "setcodeAddrC": "Choose the address to which you want to change the code.", "stats1": "Where do you want to consult the statistics?", "statsaddr": "My Addresses", "statsp2m": "EqualHash", "statsReturn": "<< Back to Stats", "noneAddr": "You have not added an address yet.\nYou can use the /newaddr command to add a new address.", "selectAddr": "Choose a address from the list below:", "noStats": "I'm sorry but there's still no information for this address. Try it later.", "return": "<< Return", "viewAddr": "Here it is:\n - Name: *<NAMEADDRESS>*\n - Address: *<ADDRESS>*\n\nWhat do you want to do " "with the address?", "viewStats": "See stats", "editAddr": "Edit address", "editNameAddr": "Edit name", "editCodeAddr": "Edit code", "delAddr": "Delete Address", "delAddr2": "Are you sure you want to delete the following address?\n - Name: *<NAMEADDRESS>*\n - " "Address: *<ADDRESS>*", "yesDelAddr": "Yes, delete the address", "addrDelOk": "Address deleted correctly.", "optEdit": "Select an option:", "newNameAddr": "OK. Send me the new name for your address.", "newCodeAddr": "OK. Send me the new code for your address.", "addrUpdate": "Your address information has been updated.\n\nName: *<NAMEADDRESS>*\nAddress: *<ADDRESS>*", "changeWorkers": "Change in workers status:\n", "notifications": "Notifications", "descNotifications": "Activating the notification service will receive a message every time there is a change " "of status in your *Workers*.", "statusNotifications": "Status notifications: *<STATUS>*", "enableNotifications": "Choose the address you want to - *Activate* - notifications:", "disableNotifications": "Choose the address you want to - *Disable* - notifications:" }
translations = {'startMessage': "I can help you see all of your EqualHash.pt statistics\n\nYou can control me by sending these commands:\n\n/newaddr - Add new address\n/myaddrs - View all address\n\n*Edit Addresses*\n/setname - Change a address's name\n/setaddress - Change the address\n/deleteaddr - Delete a address\n\n*Stats*\n/seestats - View Stats\n\n*Notifications*\n/enablenotification - Enable workers status notifications\n/disablenotification - Disable workers status notifications", 'newAddr': 'Alright, a new address. How are we going to call it? Please choose a name for your address.', 'newAddr2': 'All right!! Now enter the address.', 'newAddr3': 'Done! Congratulations for your new address:\n\nNow you can start checking your statistics, run the /seestats command and choose your address.\n\nName: *<NAMEADDRESS>*\nAddress: *<ADDRESS>*', 'delAddrC': 'Choose a address to delete.', 'setnameAddrC': 'Choose the address to which you want to change the name.', 'setcodeAddrC': 'Choose the address to which you want to change the code.', 'stats1': 'Where do you want to consult the statistics?', 'statsaddr': 'My Addresses', 'statsp2m': 'EqualHash', 'statsReturn': '<< Back to Stats', 'noneAddr': 'You have not added an address yet.\nYou can use the /newaddr command to add a new address.', 'selectAddr': 'Choose a address from the list below:', 'noStats': "I'm sorry but there's still no information for this address. Try it later.", 'return': '<< Return', 'viewAddr': 'Here it is:\n - Name: *<NAMEADDRESS>*\n - Address: *<ADDRESS>*\n\nWhat do you want to do with the address?', 'viewStats': 'See stats', 'editAddr': 'Edit address', 'editNameAddr': 'Edit name', 'editCodeAddr': 'Edit code', 'delAddr': 'Delete Address', 'delAddr2': 'Are you sure you want to delete the following address?\n - Name: *<NAMEADDRESS>*\n - Address: *<ADDRESS>*', 'yesDelAddr': 'Yes, delete the address', 'addrDelOk': 'Address deleted correctly.', 'optEdit': 'Select an option:', 'newNameAddr': 'OK. Send me the new name for your address.', 'newCodeAddr': 'OK. Send me the new code for your address.', 'addrUpdate': 'Your address information has been updated.\n\nName: *<NAMEADDRESS>*\nAddress: *<ADDRESS>*', 'changeWorkers': 'Change in workers status:\n', 'notifications': 'Notifications', 'descNotifications': 'Activating the notification service will receive a message every time there is a change of status in your *Workers*.', 'statusNotifications': 'Status notifications: *<STATUS>*', 'enableNotifications': 'Choose the address you want to - *Activate* - notifications:', 'disableNotifications': 'Choose the address you want to - *Disable* - notifications:'}
# A Python program to demonstrate need # of packing and unpacking # A sample function that takes 4 arguments # and prints them. def fun(a, b, c, d): print(a, b, c, d) # Driver Code my_list = [1, 2, 3, 4] # This doesn't work fun(my_list)
def fun(a, b, c, d): print(a, b, c, d) my_list = [1, 2, 3, 4] fun(my_list)
''' 1. Write a Python program for binary search. Binary Search : In computer science, a binary search or half-interval search algorithm finds the position of a target value within a sorted array. The binary search algorithm can be classified as a dichotomies divide-and-conquer search algorithm and executes in logarithmic time. Test Data : binary_search([1,2,3,5,8], 6) -> False binary_search([1,2,3,5,8], 5) -> True 2. Write a Python program for sequential search. Sequential Search : In computer science, linear search or sequential search is a method for finding a particular value in a list that checks each element in sequence until the desired element is found or the list is exhausted. The list need not be ordered. Test Data : Sequential_Search([11,23,58,31,56,77,43,12,65,19],31) -> (True, 3) 3. Write a Python program for binary search for an ordered list. Test Data : Ordered_binary_Search([0, 1, 3, 8, 14, 18, 19, 34, 52], 3) -> True Ordered_binary_Search([0, 1, 3, 8, 14, 18, 19, 34, 52], 17) -> False '''
""" 1. Write a Python program for binary search. Binary Search : In computer science, a binary search or half-interval search algorithm finds the position of a target value within a sorted array. The binary search algorithm can be classified as a dichotomies divide-and-conquer search algorithm and executes in logarithmic time. Test Data : binary_search([1,2,3,5,8], 6) -> False binary_search([1,2,3,5,8], 5) -> True 2. Write a Python program for sequential search. Sequential Search : In computer science, linear search or sequential search is a method for finding a particular value in a list that checks each element in sequence until the desired element is found or the list is exhausted. The list need not be ordered. Test Data : Sequential_Search([11,23,58,31,56,77,43,12,65,19],31) -> (True, 3) 3. Write a Python program for binary search for an ordered list. Test Data : Ordered_binary_Search([0, 1, 3, 8, 14, 18, 19, 34, 52], 3) -> True Ordered_binary_Search([0, 1, 3, 8, 14, 18, 19, 34, 52], 17) -> False """
nums = int(input()) points = [] for i in range(0, nums): read_list = list(map(int, input().split())) # read_list = [int(i) for i in input().split()] points.append((read_list[0], read_list[1])) print(points) """ 3 1 2 23 4 4 5 [(1, 2), (23, 4), (4, 5)] """
nums = int(input()) points = [] for i in range(0, nums): read_list = list(map(int, input().split())) points.append((read_list[0], read_list[1])) print(points) '\n3\n1 2\n23 4\n4 5\n[(1, 2), (23, 4), (4, 5)]\n'
# uncompyle6 version 2.9.10 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) # [GCC 6.2.0 20161005] # Embedded file name: __init__.py MCL_OS_ARCH_I386 = 0 MCL_OS_ARCH_SPARC = 1 MCL_OS_ARCH_ALPHA = 2 MCL_OS_ARCH_ARM = 3 MCL_OS_ARCH_PPC = 4 MCL_OS_ARCH_HPPA1 = 5 MCL_OS_ARCH_HPPA2 = 6 MCL_OS_ARCH_MIPS = 7 MCL_OS_ARCH_X64 = 8 MCL_OS_ARCH_IA64 = 9 MCL_OS_ARCH_SPARC64 = 10 MCL_OS_ARCH_MIPS64 = 11 MCL_OS_ARCH_UNKNOWN = 65535 archNames = {MCL_OS_ARCH_I386: 'i386', MCL_OS_ARCH_SPARC: 'sparc', MCL_OS_ARCH_ALPHA: 'alpha', MCL_OS_ARCH_ARM: 'arm', MCL_OS_ARCH_PPC: 'ppc', MCL_OS_ARCH_HPPA1: 'hppa1', MCL_OS_ARCH_HPPA2: 'hppa2', MCL_OS_ARCH_MIPS: 'mips', MCL_OS_ARCH_X64: 'x64', MCL_OS_ARCH_IA64: 'ia64', MCL_OS_ARCH_SPARC64: 'sparc64', MCL_OS_ARCH_MIPS64: 'mips64', MCL_OS_ARCH_UNKNOWN: 'unknown' } MCL_OS_WIN9X = 0 MCL_OS_WINNT = 1 MCL_OS_LINUX = 2 MCL_OS_SOLARIS = 3 MCL_OS_SUNOS = 4 MCL_OS_AIX = 5 MCL_OS_BSDI = 6 MCL_OS_DEC = 7 MCL_OS_FREEBSD = 8 MCL_OS_IRIX = 9 MCL_OS_HPUX = 10 MCL_OS_MIRAPOINT = 11 MCL_OS_OPENBSD = 12 MCL_OS_SCO = 13 MCL_OS_SELINUX = 14 MCL_OS_DARWIN = 15 MCL_OS_VXWORKS = 16 MCL_OS_PSOS = 17 MCL_OS_WINMOBILE = 18 MCL_OS_IPHONE = 19 MCL_OS_JUNOS = 20 MCL_OS_ANDROID = 21 MCL_OS_UNKNOWN = 65535 osNames = {MCL_OS_WIN9X: 'win9x', MCL_OS_WINNT: 'winnt', MCL_OS_LINUX: 'linux', MCL_OS_SOLARIS: 'solaris', MCL_OS_SUNOS: 'sunos', MCL_OS_AIX: 'aix', MCL_OS_BSDI: 'bsdi', MCL_OS_DEC: 'tru64', MCL_OS_FREEBSD: 'freebsd', MCL_OS_IRIX: 'irix', MCL_OS_HPUX: 'hpux', MCL_OS_MIRAPOINT: 'mirapoint', MCL_OS_OPENBSD: 'openbsd', MCL_OS_SCO: 'sco', MCL_OS_SELINUX: 'linux_se', MCL_OS_DARWIN: 'darwin', MCL_OS_VXWORKS: 'vxworks', MCL_OS_PSOS: 'psos', MCL_OS_WINMOBILE: 'winmobile', MCL_OS_IPHONE: 'iphone', MCL_OS_JUNOS: 'junos', MCL_OS_ANDROID: 'android', MCL_OS_UNKNOWN: 'unknown' }
mcl_os_arch_i386 = 0 mcl_os_arch_sparc = 1 mcl_os_arch_alpha = 2 mcl_os_arch_arm = 3 mcl_os_arch_ppc = 4 mcl_os_arch_hppa1 = 5 mcl_os_arch_hppa2 = 6 mcl_os_arch_mips = 7 mcl_os_arch_x64 = 8 mcl_os_arch_ia64 = 9 mcl_os_arch_sparc64 = 10 mcl_os_arch_mips64 = 11 mcl_os_arch_unknown = 65535 arch_names = {MCL_OS_ARCH_I386: 'i386', MCL_OS_ARCH_SPARC: 'sparc', MCL_OS_ARCH_ALPHA: 'alpha', MCL_OS_ARCH_ARM: 'arm', MCL_OS_ARCH_PPC: 'ppc', MCL_OS_ARCH_HPPA1: 'hppa1', MCL_OS_ARCH_HPPA2: 'hppa2', MCL_OS_ARCH_MIPS: 'mips', MCL_OS_ARCH_X64: 'x64', MCL_OS_ARCH_IA64: 'ia64', MCL_OS_ARCH_SPARC64: 'sparc64', MCL_OS_ARCH_MIPS64: 'mips64', MCL_OS_ARCH_UNKNOWN: 'unknown'} mcl_os_win9_x = 0 mcl_os_winnt = 1 mcl_os_linux = 2 mcl_os_solaris = 3 mcl_os_sunos = 4 mcl_os_aix = 5 mcl_os_bsdi = 6 mcl_os_dec = 7 mcl_os_freebsd = 8 mcl_os_irix = 9 mcl_os_hpux = 10 mcl_os_mirapoint = 11 mcl_os_openbsd = 12 mcl_os_sco = 13 mcl_os_selinux = 14 mcl_os_darwin = 15 mcl_os_vxworks = 16 mcl_os_psos = 17 mcl_os_winmobile = 18 mcl_os_iphone = 19 mcl_os_junos = 20 mcl_os_android = 21 mcl_os_unknown = 65535 os_names = {MCL_OS_WIN9X: 'win9x', MCL_OS_WINNT: 'winnt', MCL_OS_LINUX: 'linux', MCL_OS_SOLARIS: 'solaris', MCL_OS_SUNOS: 'sunos', MCL_OS_AIX: 'aix', MCL_OS_BSDI: 'bsdi', MCL_OS_DEC: 'tru64', MCL_OS_FREEBSD: 'freebsd', MCL_OS_IRIX: 'irix', MCL_OS_HPUX: 'hpux', MCL_OS_MIRAPOINT: 'mirapoint', MCL_OS_OPENBSD: 'openbsd', MCL_OS_SCO: 'sco', MCL_OS_SELINUX: 'linux_se', MCL_OS_DARWIN: 'darwin', MCL_OS_VXWORKS: 'vxworks', MCL_OS_PSOS: 'psos', MCL_OS_WINMOBILE: 'winmobile', MCL_OS_IPHONE: 'iphone', MCL_OS_JUNOS: 'junos', MCL_OS_ANDROID: 'android', MCL_OS_UNKNOWN: 'unknown'}
#!/usr/bin/python ''' --- Part Two --- "Great work; looks like we're on the right track after all. Here's a star for your effort." However, the program seems a little worried. Can programs be worried? "Based on what we're seeing, it looks like all the User wanted is some information about the evenly divisible values in the spreadsheet. Unfortunately, none of us are equipped for that kind of calculation - most of us specialize in bitwise operations." It sounds like the goal is to find the only two numbers in each row where one evenly divides the other - that is, where the result of the division operation is a whole number. They would like you to find those numbers on each line, divide them, and add up each line's result. ''' inFile = open("2.txt",'r') lines = inFile.readlines() #real input #lines = ["5 9 2 8", "9 4 7 3", "3 8 6 5"] #debug only, should yield 9 def check_div(i,j): if j>i: i,j = j,i if i%j == 0: return i//j else: return 0 checksum = 0 for line in lines: line = map(int,line.strip().split()) div = 0 found = False for i in range(len(line)-1): for j in range(i+1,len(line)): div = check_div(line[i],line[j]) if div > 0: checksum += div found = True break if found: break print("Solution: "+str(checksum))
""" --- Part Two --- "Great work; looks like we're on the right track after all. Here's a star for your effort." However, the program seems a little worried. Can programs be worried? "Based on what we're seeing, it looks like all the User wanted is some information about the evenly divisible values in the spreadsheet. Unfortunately, none of us are equipped for that kind of calculation - most of us specialize in bitwise operations." It sounds like the goal is to find the only two numbers in each row where one evenly divides the other - that is, where the result of the division operation is a whole number. They would like you to find those numbers on each line, divide them, and add up each line's result. """ in_file = open('2.txt', 'r') lines = inFile.readlines() def check_div(i, j): if j > i: (i, j) = (j, i) if i % j == 0: return i // j else: return 0 checksum = 0 for line in lines: line = map(int, line.strip().split()) div = 0 found = False for i in range(len(line) - 1): for j in range(i + 1, len(line)): div = check_div(line[i], line[j]) if div > 0: checksum += div found = True break if found: break print('Solution: ' + str(checksum))
File1 = open(input("File path of first list in text file:"), "rt") File2 = open(input("File path of second list in text file:"), "rt") file = open("Compared_List.txt", "a+") suffix_sp = [] #a list of genuses with "sp." suffix to denote the entire genus species = [] #list of species from File1 if __name__ == "__main__": for line in File1: if line[-4:-1] == "sp.": suffix_sp.append(line[:-5]) #extracts the genus identifiers from the list seperates it into the suffix_sp list else: species.append(line.strip()) File1.close() for line in File2: if line[-4:-1] == "sp.": #if theres a genus identifier in the file, this block will find the species in the other list under this genus. for spec in species: if line[:-5] == spec[:len(line[:-5])]: file.write(spec.replace("_", " ")+"\n") species.remove(spec) #checks whether the genus identifier is in the other list and adds to the final text file if line[:-5] in suffix_sp: file.write(line.replace("_", " ")) #finds whether there's a species of same name in other list elif line[:-1] in species: file.write(line.replace("_", " ")) species.remove(line[:-1]) else: #this checks whether a species is in a genus from the list of genuses. for suf_spec in suffix_sp: if suf_spec == line[:len(suf_spec)+1]: file.write(line.replace("_", " ")) File2.close() file.close() #Fin.
file1 = open(input('File path of first list in text file:'), 'rt') file2 = open(input('File path of second list in text file:'), 'rt') file = open('Compared_List.txt', 'a+') suffix_sp = [] species = [] if __name__ == '__main__': for line in File1: if line[-4:-1] == 'sp.': suffix_sp.append(line[:-5]) else: species.append(line.strip()) File1.close() for line in File2: if line[-4:-1] == 'sp.': for spec in species: if line[:-5] == spec[:len(line[:-5])]: file.write(spec.replace('_', ' ') + '\n') species.remove(spec) if line[:-5] in suffix_sp: file.write(line.replace('_', ' ')) elif line[:-1] in species: file.write(line.replace('_', ' ')) species.remove(line[:-1]) else: for suf_spec in suffix_sp: if suf_spec == line[:len(suf_spec) + 1]: file.write(line.replace('_', ' ')) File2.close() file.close()
class Solution: def zigzagLevelOrder(self, root): if root is None: return [] res = [] res.append([root.val]) queue = [] queue.append(root) level_nodes = [] level_node_count = 1 next_level_node_count = 0 left_to_right = True while len(queue) > 0: node = queue.pop(0) level_node_count -= 1 if node.left is not None: level_nodes.append(node.left.val) queue.append(node.left) next_level_node_count += 1 if node.right is not None: queue.append(node.right) level_nodes.append(node.right.val) next_level_node_count += 1 if len(level_nodes) > 0: if level_node_count == 0: left_to_right = not left_to_right if left_to_right: res.append(level_nodes) else: res.append(level_nodes[::-1]) level_nodes = [] level_node_count = next_level_node_count next_level_node_count = 0 return res
class Solution: def zigzag_level_order(self, root): if root is None: return [] res = [] res.append([root.val]) queue = [] queue.append(root) level_nodes = [] level_node_count = 1 next_level_node_count = 0 left_to_right = True while len(queue) > 0: node = queue.pop(0) level_node_count -= 1 if node.left is not None: level_nodes.append(node.left.val) queue.append(node.left) next_level_node_count += 1 if node.right is not None: queue.append(node.right) level_nodes.append(node.right.val) next_level_node_count += 1 if len(level_nodes) > 0: if level_node_count == 0: left_to_right = not left_to_right if left_to_right: res.append(level_nodes) else: res.append(level_nodes[::-1]) level_nodes = [] level_node_count = next_level_node_count next_level_node_count = 0 return res
"""Adding routes for the configuration to find.""" def includeme(config): config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('list', '/') config.add_route('profile', '/profile/{id:\d+}') config.add_route('login', '/login') config.add_route('logout', '/logout') config.add_route('register', '/register')
"""Adding routes for the configuration to find.""" def includeme(config): config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('list', '/') config.add_route('profile', '/profile/{id:\\d+}') config.add_route('login', '/login') config.add_route('logout', '/logout') config.add_route('register', '/register')
# The guess API is already defined for you. # @param num, your guess # @return -1 if my number is lower, 1 if my number is higher, otherwise return 0 # def guess(num): class Solution(object): def guessNumber(self, n, lo=0): """ :type n: int :rtype: int """ if lo >= n: return n if guess(n) == 0: return n x = lo + (n - lo) // 2 compar = guess(x) if compar < 0: return self.guessNumber(x, lo) elif compar > 0: return self.guessNumber(n, x) return x
class Solution(object): def guess_number(self, n, lo=0): """ :type n: int :rtype: int """ if lo >= n: return n if guess(n) == 0: return n x = lo + (n - lo) // 2 compar = guess(x) if compar < 0: return self.guessNumber(x, lo) elif compar > 0: return self.guessNumber(n, x) return x
"""Figure size settings.""" # Some useful constants _GOLDEN_RATIO = (5.0 ** 0.5 - 1.0) / 2.0 _INCHES_PER_POINT = 1.0 * 72.27 # Double-column formats def icml2022_half(**kwargs): """Double-column (half-width) figures for ICML 2022.""" return _icml2022_and_aistats2022_half(**kwargs) def icml2022_full(**kwargs): """Single-column (full-width) figures for ICML 2022.""" return _icml2022_and_aistats2022_full(**kwargs) def aistats2022_half(**kwargs): """Double-column (half-width) figures for AISTATS 2022.""" return _icml2022_and_aistats2022_half(**kwargs) def aistats2022_full(**kwargs): """Single-column (full-width) figures for AISTATS 2022.""" return _icml2022_and_aistats2022_full(**kwargs) def _icml2022_and_aistats2022_half( *, nrows=1, ncols=1, constrained_layout=True, tight_layout=False, height_to_width_ratio=_GOLDEN_RATIO, ): figsize = _from_base_in( width_in=3.25, nrows=nrows, ncols=ncols, height_to_width_ratio=height_to_width_ratio, ) return _figsize_to_output_dict( figsize=figsize, constrained_layout=constrained_layout, tight_layout=tight_layout, ) def _icml2022_and_aistats2022_full( *, nrows=1, ncols=2, constrained_layout=True, tight_layout=False, height_to_width_ratio=_GOLDEN_RATIO, ): figsize = _from_base_in( width_in=6.75, nrows=nrows, ncols=ncols, height_to_width_ratio=height_to_width_ratio, ) return _figsize_to_output_dict( figsize=figsize, constrained_layout=constrained_layout, tight_layout=tight_layout, ) def cvpr2022_half( *, nrows=1, ncols=1, constrained_layout=True, tight_layout=False, height_to_width_ratio=_GOLDEN_RATIO, ): """Double-column (half-width) figures for CVPR 2022.""" figsize = _from_base_pt( width_pt=237.13594, nrows=nrows, ncols=ncols, height_to_width_ratio=height_to_width_ratio, ) return _figsize_to_output_dict( figsize=figsize, constrained_layout=constrained_layout, tight_layout=tight_layout, ) def cvpr2022_full( *, nrows=1, ncols=2, constrained_layout=True, tight_layout=False, height_to_width_ratio=_GOLDEN_RATIO, ): """Single-column (full-width) figures for CVPR 2022.""" figsize = _from_base_pt( width_pt=496.85625, nrows=nrows, ncols=ncols, height_to_width_ratio=height_to_width_ratio, ) return _figsize_to_output_dict( figsize=figsize, constrained_layout=constrained_layout, tight_layout=tight_layout, ) # Single-column formats def jmlr2001( *, nrows=1, ncols=2, constrained_layout=True, tight_layout=False, height_to_width_ratio=_GOLDEN_RATIO, ): """JMLR figure size. Source: https://www.jmlr.org/format/format.html The present format is for US letter format. """ figsize = _from_base_in( width_in=6.0, nrows=nrows, ncols=ncols, height_to_width_ratio=height_to_width_ratio, ) return _figsize_to_output_dict( figsize=figsize, constrained_layout=constrained_layout, tight_layout=tight_layout, ) def neurips2021( *, nrows=1, ncols=2, constrained_layout=True, tight_layout=False, height_to_width_ratio=_GOLDEN_RATIO, ): """Neurips 2021 figure size.""" figsize = _from_base_pt( width_pt=397.48499, nrows=nrows, ncols=ncols, height_to_width_ratio=height_to_width_ratio, ) return _figsize_to_output_dict( figsize=figsize, constrained_layout=constrained_layout, tight_layout=tight_layout, ) def _from_base_pt(*, width_pt, **kwargs): width_in = width_pt / _INCHES_PER_POINT return _from_base_in(width_in=width_in, **kwargs) def _from_base_in(*, width_in, nrows, height_to_width_ratio, ncols): height_in = height_to_width_ratio * width_in * nrows / ncols return width_in, height_in # Other formats def beamer_169( *, rel_width=0.9, rel_height=0.6, constrained_layout=True, tight_layout=False ): """Beamer figure size for `aspectratio=169`.""" textwidth_169_pt = 398.3386 # via '\showthe\textwidth' in latex textwidth_169_in = textwidth_169_pt / _INCHES_PER_POINT textheight_169_in = textwidth_169_in / 16.0 * 9.0 figsize = (textwidth_169_in * rel_width, textheight_169_in * rel_height) return _figsize_to_output_dict( figsize=figsize, constrained_layout=constrained_layout, tight_layout=tight_layout, ) def _figsize_to_output_dict(*, figsize, constrained_layout, tight_layout): return { "figure.figsize": figsize, "figure.constrained_layout.use": constrained_layout, "figure.autolayout": tight_layout, }
"""Figure size settings.""" _golden_ratio = (5.0 ** 0.5 - 1.0) / 2.0 _inches_per_point = 1.0 * 72.27 def icml2022_half(**kwargs): """Double-column (half-width) figures for ICML 2022.""" return _icml2022_and_aistats2022_half(**kwargs) def icml2022_full(**kwargs): """Single-column (full-width) figures for ICML 2022.""" return _icml2022_and_aistats2022_full(**kwargs) def aistats2022_half(**kwargs): """Double-column (half-width) figures for AISTATS 2022.""" return _icml2022_and_aistats2022_half(**kwargs) def aistats2022_full(**kwargs): """Single-column (full-width) figures for AISTATS 2022.""" return _icml2022_and_aistats2022_full(**kwargs) def _icml2022_and_aistats2022_half(*, nrows=1, ncols=1, constrained_layout=True, tight_layout=False, height_to_width_ratio=_GOLDEN_RATIO): figsize = _from_base_in(width_in=3.25, nrows=nrows, ncols=ncols, height_to_width_ratio=height_to_width_ratio) return _figsize_to_output_dict(figsize=figsize, constrained_layout=constrained_layout, tight_layout=tight_layout) def _icml2022_and_aistats2022_full(*, nrows=1, ncols=2, constrained_layout=True, tight_layout=False, height_to_width_ratio=_GOLDEN_RATIO): figsize = _from_base_in(width_in=6.75, nrows=nrows, ncols=ncols, height_to_width_ratio=height_to_width_ratio) return _figsize_to_output_dict(figsize=figsize, constrained_layout=constrained_layout, tight_layout=tight_layout) def cvpr2022_half(*, nrows=1, ncols=1, constrained_layout=True, tight_layout=False, height_to_width_ratio=_GOLDEN_RATIO): """Double-column (half-width) figures for CVPR 2022.""" figsize = _from_base_pt(width_pt=237.13594, nrows=nrows, ncols=ncols, height_to_width_ratio=height_to_width_ratio) return _figsize_to_output_dict(figsize=figsize, constrained_layout=constrained_layout, tight_layout=tight_layout) def cvpr2022_full(*, nrows=1, ncols=2, constrained_layout=True, tight_layout=False, height_to_width_ratio=_GOLDEN_RATIO): """Single-column (full-width) figures for CVPR 2022.""" figsize = _from_base_pt(width_pt=496.85625, nrows=nrows, ncols=ncols, height_to_width_ratio=height_to_width_ratio) return _figsize_to_output_dict(figsize=figsize, constrained_layout=constrained_layout, tight_layout=tight_layout) def jmlr2001(*, nrows=1, ncols=2, constrained_layout=True, tight_layout=False, height_to_width_ratio=_GOLDEN_RATIO): """JMLR figure size. Source: https://www.jmlr.org/format/format.html The present format is for US letter format. """ figsize = _from_base_in(width_in=6.0, nrows=nrows, ncols=ncols, height_to_width_ratio=height_to_width_ratio) return _figsize_to_output_dict(figsize=figsize, constrained_layout=constrained_layout, tight_layout=tight_layout) def neurips2021(*, nrows=1, ncols=2, constrained_layout=True, tight_layout=False, height_to_width_ratio=_GOLDEN_RATIO): """Neurips 2021 figure size.""" figsize = _from_base_pt(width_pt=397.48499, nrows=nrows, ncols=ncols, height_to_width_ratio=height_to_width_ratio) return _figsize_to_output_dict(figsize=figsize, constrained_layout=constrained_layout, tight_layout=tight_layout) def _from_base_pt(*, width_pt, **kwargs): width_in = width_pt / _INCHES_PER_POINT return _from_base_in(width_in=width_in, **kwargs) def _from_base_in(*, width_in, nrows, height_to_width_ratio, ncols): height_in = height_to_width_ratio * width_in * nrows / ncols return (width_in, height_in) def beamer_169(*, rel_width=0.9, rel_height=0.6, constrained_layout=True, tight_layout=False): """Beamer figure size for `aspectratio=169`.""" textwidth_169_pt = 398.3386 textwidth_169_in = textwidth_169_pt / _INCHES_PER_POINT textheight_169_in = textwidth_169_in / 16.0 * 9.0 figsize = (textwidth_169_in * rel_width, textheight_169_in * rel_height) return _figsize_to_output_dict(figsize=figsize, constrained_layout=constrained_layout, tight_layout=tight_layout) def _figsize_to_output_dict(*, figsize, constrained_layout, tight_layout): return {'figure.figsize': figsize, 'figure.constrained_layout.use': constrained_layout, 'figure.autolayout': tight_layout}
""" 1: Client Message 2: Phase1A 3: Phase1B 4: Phase2A 5: Phase2B 6: Decision 7: Leader 8: Catchup 9: Catchup_Answer """ class Message: def __init__(self, msg_type, message=0, instance=0, iid=0, c_rnd=0, c_val=0, rnd=0, v_val=0, v_rnd=0, current_leader=0, prop_id=0, msg_memory=None, print_order=None, total_order=None, total_order_sent=None, total_order_memory=None): # Basic message variables needed for various applications inside Paxos self.message = message self.type = msg_type self.instance = instance self.iid = iid # The values as known from the slides self.c_rnd = c_rnd self.c_val = c_val self.rnd = rnd self.v_val = v_val self.v_rnd = v_rnd # current leader and prop_id needed for leader election self.current_leader = current_leader self.prop_id = prop_id # msg_memory and total order needed for learner catch_up self.msg_memory = msg_memory self.print_order = print_order self.total_order = total_order self.total_order_sent = total_order_sent self.total_order_memory = total_order_memory
""" 1: Client Message 2: Phase1A 3: Phase1B 4: Phase2A 5: Phase2B 6: Decision 7: Leader 8: Catchup 9: Catchup_Answer """ class Message: def __init__(self, msg_type, message=0, instance=0, iid=0, c_rnd=0, c_val=0, rnd=0, v_val=0, v_rnd=0, current_leader=0, prop_id=0, msg_memory=None, print_order=None, total_order=None, total_order_sent=None, total_order_memory=None): self.message = message self.type = msg_type self.instance = instance self.iid = iid self.c_rnd = c_rnd self.c_val = c_val self.rnd = rnd self.v_val = v_val self.v_rnd = v_rnd self.current_leader = current_leader self.prop_id = prop_id self.msg_memory = msg_memory self.print_order = print_order self.total_order = total_order self.total_order_sent = total_order_sent self.total_order_memory = total_order_memory
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Python for AHDA. Part 1, Example 9. """ # Deduplication of a list rhyme = ['Peter', 'Piper', 'picked', 'a', 'piece', 'of', 'pickled', 'pepper', 'A', 'piece', 'of', 'pickled', 'pepper', 'Peter', 'Piper', 'picked'] deduplicated_rhyme = set(rhyme) print(deduplicated_rhyme)
"""Python for AHDA. Part 1, Example 9. """ rhyme = ['Peter', 'Piper', 'picked', 'a', 'piece', 'of', 'pickled', 'pepper', 'A', 'piece', 'of', 'pickled', 'pepper', 'Peter', 'Piper', 'picked'] deduplicated_rhyme = set(rhyme) print(deduplicated_rhyme)
class Solution: # @param {int[]} nums an integer array # @return nothing, do this in-place def moveZeroes(self, nums): # Write your code here i = 0 for j in xrange(len(nums)): if nums[j]: num = nums[j] nums[j] = 0 nums[i] = num i += 1
class Solution: def move_zeroes(self, nums): i = 0 for j in xrange(len(nums)): if nums[j]: num = nums[j] nums[j] = 0 nums[i] = num i += 1
''' key-value methods in dictionary ''' # Keys key_dictionary = { 'sector': 'Keys method', 'variable': 'dictionary' } print(key_dictionary.keys()) # Values value_dictionary = { 'sector': 'Values method', 'variable': 'dictionary' } print(value_dictionary.values()) # Key-value key_value_dictionary = { 'sector': 'key-value method', 'variable': 'dictionary' } print(key_value_dictionary.items())
""" key-value methods in dictionary """ key_dictionary = {'sector': 'Keys method', 'variable': 'dictionary'} print(key_dictionary.keys()) value_dictionary = {'sector': 'Values method', 'variable': 'dictionary'} print(value_dictionary.values()) key_value_dictionary = {'sector': 'key-value method', 'variable': 'dictionary'} print(key_value_dictionary.items())
for _ in range(int(input())): tr = int(input()) ram_task = list(map(int, input().split(' '))) dr = int(input()) ram_dare = list(map(int, input().split(' '))) ts = int(input()) sham_task = list(map(int, input().split(' '))) ds = int(input()) sham_dare = list(map(int, input().split(' '))) lose = False for i in sham_task: if i not in ram_task: lose = True for i in sham_dare: if i not in ram_dare: lose = True if lose: print('no') else: print('yes')
for _ in range(int(input())): tr = int(input()) ram_task = list(map(int, input().split(' '))) dr = int(input()) ram_dare = list(map(int, input().split(' '))) ts = int(input()) sham_task = list(map(int, input().split(' '))) ds = int(input()) sham_dare = list(map(int, input().split(' '))) lose = False for i in sham_task: if i not in ram_task: lose = True for i in sham_dare: if i not in ram_dare: lose = True if lose: print('no') else: print('yes')
q1 = 1 q2 = -2 q3 = 4 state = (q1, q2, q3) state = (-state[0], -state[1], -state[2]) #str(state[0]) = '33' print(state)
q1 = 1 q2 = -2 q3 = 4 state = (q1, q2, q3) state = (-state[0], -state[1], -state[2]) print(state)
def dfs(at, graph, visited): if visited[at]: return visited[at] = True print(at, end=" -> ") neighbours = graph[at] for next in neighbours: dfs(next, graph, visited) if __name__ == "__main__": n = int(input("No. of Nodes : ")) graph = [] for i in range(n): graph.append(list(map(int, input("Nodes linked with {} : ".format(i)).split()))) start_node = int(input("Starting Node : ")) # graph = [[1, 2], [3], [1], [2], [3, 5], [5]] visited = [False] * n print("\nNodes in DFS are : ", end=" ") dfs(start_node, graph, visited) print(" / ") """ Input : No. of Nodes : 6 Nodes linked with 0 : 1 2 Nodes linked with 1 : 3 Nodes linked with 2 : 1 Nodes linked with 3 : 2 Nodes linked with 4 : 3 5 Nodes linked with 5 : 5 Starting Node : 4 Output: Nodes in DFS are : 4 -> 3 -> 2 -> 1 -> 5 -> / """
def dfs(at, graph, visited): if visited[at]: return visited[at] = True print(at, end=' -> ') neighbours = graph[at] for next in neighbours: dfs(next, graph, visited) if __name__ == '__main__': n = int(input('No. of Nodes : ')) graph = [] for i in range(n): graph.append(list(map(int, input('Nodes linked with {} : '.format(i)).split()))) start_node = int(input('Starting Node : ')) visited = [False] * n print('\nNodes in DFS are : ', end=' ') dfs(start_node, graph, visited) print(' / ') '\nInput : \nNo. of Nodes : 6\nNodes linked with 0 : 1 2\nNodes linked with 1 : 3\nNodes linked with 2 : 1\nNodes linked with 3 : 2\nNodes linked with 4 : 3 5\nNodes linked with 5 : 5\nStarting Node : 4\n\nOutput:\nNodes in DFS are : 4 -> 3 -> 2 -> 1 -> 5 -> / \n'
load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES") load( "@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl", "feature", "flag_group", "flag_set", "tool_path", ) all_link_actions = [ ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library, ] all_compile_actions = [ ACTION_NAMES.assemble, ACTION_NAMES.c_compile, ACTION_NAMES.clif_match, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.lto_backend, ACTION_NAMES.preprocess_assemble, ] def _impl(ctx): tool_paths = [ tool_path( name = "ar", path = "wrappers/aarch64-none-linux-gnu-ar", ), tool_path( name = "cpp", path = "wrappers/aarch64-none-linux-gnu-cpp", ), tool_path( name = "gcc", path = "wrappers/aarch64-none-linux-gnu-gcc", ), tool_path( name = "gcov", path = "wrappers/aarch64-none-linux-gnu-gcov", ), tool_path( name = "ld", path = "wrappers/aarch64-none-linux-gnu-ld", ), tool_path( name = "nm", path = "wrappers/aarch64-none-linux-gnu-nm", ), tool_path( name = "objdump", path = "wrappers/aarch64-none-linux-gnu-objdump", ), tool_path( name = "strip", path = "wrappers/aarch64-none-linux-gnu-strip", ), ] default_compiler_flags = feature( name = "default_compiler_flags", enabled = True, flag_sets = [ flag_set( actions = all_compile_actions, flag_groups = [ flag_group( flags = [ "-no-canonical-prefixes", "-fno-canonical-system-headers", "-Wno-builtin-macro-redefined", "-D__DATE__=\"redacted\"", "-D__TIMESTAMP__=\"redacted\"", "-D__TIME__=\"redacted\"", ], ), ], ), ], ) default_linker_flags = feature( name = "default_linker_flags", enabled = True, flag_sets = [ flag_set( actions = all_link_actions, flag_groups = ([ flag_group( flags = [ "-lstdc++", ], ), ]), ), ], ) features = [ default_compiler_flags, default_linker_flags, ] return cc_common.create_cc_toolchain_config_info( ctx = ctx, cxx_builtin_include_directories = [ "/proc/self/cwd/external/aarch64-none-linux-gnu/aarch64-none-linux-gnu/include/c++/10.2.1/", "/proc/self/cwd/external/aarch64-none-linux-gnu/aarch64-none-linux-gnu/libc/usr/include/", "/proc/self/cwd/external/aarch64-none-linux-gnu/lib/gcc/aarch64-none-linux-gnu/10.2.1/include/", "/proc/self/cwd/external/aarch64-none-linux-gnu/aarch64-none-linux-gnu/libc/lib/", ], features = features, toolchain_identifier = "aarch64-toolchain", host_system_name = "local", target_system_name = "unknown", target_cpu = "unknown", target_libc = "unknown", compiler = "unknown", abi_version = "unknown", abi_libc_version = "unknown", tool_paths = tool_paths, ) cc_toolchain_config = rule( implementation = _impl, attrs = {}, provides = [CcToolchainConfigInfo], )
load('@bazel_tools//tools/build_defs/cc:action_names.bzl', 'ACTION_NAMES') load('@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl', 'feature', 'flag_group', 'flag_set', 'tool_path') all_link_actions = [ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library] all_compile_actions = [ACTION_NAMES.assemble, ACTION_NAMES.c_compile, ACTION_NAMES.clif_match, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.lto_backend, ACTION_NAMES.preprocess_assemble] def _impl(ctx): tool_paths = [tool_path(name='ar', path='wrappers/aarch64-none-linux-gnu-ar'), tool_path(name='cpp', path='wrappers/aarch64-none-linux-gnu-cpp'), tool_path(name='gcc', path='wrappers/aarch64-none-linux-gnu-gcc'), tool_path(name='gcov', path='wrappers/aarch64-none-linux-gnu-gcov'), tool_path(name='ld', path='wrappers/aarch64-none-linux-gnu-ld'), tool_path(name='nm', path='wrappers/aarch64-none-linux-gnu-nm'), tool_path(name='objdump', path='wrappers/aarch64-none-linux-gnu-objdump'), tool_path(name='strip', path='wrappers/aarch64-none-linux-gnu-strip')] default_compiler_flags = feature(name='default_compiler_flags', enabled=True, flag_sets=[flag_set(actions=all_compile_actions, flag_groups=[flag_group(flags=['-no-canonical-prefixes', '-fno-canonical-system-headers', '-Wno-builtin-macro-redefined', '-D__DATE__="redacted"', '-D__TIMESTAMP__="redacted"', '-D__TIME__="redacted"'])])]) default_linker_flags = feature(name='default_linker_flags', enabled=True, flag_sets=[flag_set(actions=all_link_actions, flag_groups=[flag_group(flags=['-lstdc++'])])]) features = [default_compiler_flags, default_linker_flags] return cc_common.create_cc_toolchain_config_info(ctx=ctx, cxx_builtin_include_directories=['/proc/self/cwd/external/aarch64-none-linux-gnu/aarch64-none-linux-gnu/include/c++/10.2.1/', '/proc/self/cwd/external/aarch64-none-linux-gnu/aarch64-none-linux-gnu/libc/usr/include/', '/proc/self/cwd/external/aarch64-none-linux-gnu/lib/gcc/aarch64-none-linux-gnu/10.2.1/include/', '/proc/self/cwd/external/aarch64-none-linux-gnu/aarch64-none-linux-gnu/libc/lib/'], features=features, toolchain_identifier='aarch64-toolchain', host_system_name='local', target_system_name='unknown', target_cpu='unknown', target_libc='unknown', compiler='unknown', abi_version='unknown', abi_libc_version='unknown', tool_paths=tool_paths) cc_toolchain_config = rule(implementation=_impl, attrs={}, provides=[CcToolchainConfigInfo])
class Solution: """ @param nums: A list of integers @return: A integer indicate the sum of max subarray """ def maxSubArray(self, nums): n = len(nums) prefixSum = [0 for _ in range(n + 1)] minIdx = 0 largeSum = -sys.maxsize - 1 for i in range(1, n + 1): # update prefixSum prefixSum[i] = prefixSum[i - 1] + nums[i - 1] # compare largeSum = max(largeSum, prefixSum[i] - prefixSum[minIdx]) # update minIdx if prefixSum[i] < prefixSum[minIdx]: minIdx = i return largeSum
class Solution: """ @param nums: A list of integers @return: A integer indicate the sum of max subarray """ def max_sub_array(self, nums): n = len(nums) prefix_sum = [0 for _ in range(n + 1)] min_idx = 0 large_sum = -sys.maxsize - 1 for i in range(1, n + 1): prefixSum[i] = prefixSum[i - 1] + nums[i - 1] large_sum = max(largeSum, prefixSum[i] - prefixSum[minIdx]) if prefixSum[i] < prefixSum[minIdx]: min_idx = i return largeSum
def predicate(h, n): ''' Returns True if we can build a triangle of height h using n coins, else returns False ''' return h*(h+1)//2 <= n t = int(input()) for __ in range(t): n = int(input()) # binary search for the greatest height which can be reached using n coins lo = 0 hi = n while lo<hi: mid = lo + (hi-lo+1)//2 # round UP if predicate(mid, n): lo = mid else: hi = mid-1 print(lo)
def predicate(h, n): """ Returns True if we can build a triangle of height h using n coins, else returns False """ return h * (h + 1) // 2 <= n t = int(input()) for __ in range(t): n = int(input()) lo = 0 hi = n while lo < hi: mid = lo + (hi - lo + 1) // 2 if predicate(mid, n): lo = mid else: hi = mid - 1 print(lo)
class Solution: def hammingDistance(self, x: int, y: int) -> int: count = 0 for i in range(30, -1, -1): mask = 1 << i digitX = x & mask digitY = y & mask if digitX != digitY: count += 1 return count
class Solution: def hamming_distance(self, x: int, y: int) -> int: count = 0 for i in range(30, -1, -1): mask = 1 << i digit_x = x & mask digit_y = y & mask if digitX != digitY: count += 1 return count
# https://javl.github.io/image2cpp/ # 40x40 CALENDAR_40_40 = bytearray([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x00, 0x1c, 0x00, 0x00, 0x38, 0x00, 0x1c, 0x00, 0x00, 0x3c, 0x00, 0x1c, 0x00, 0x01, 0xff, 0xff, 0xff, 0x80, 0x03, 0xff, 0xff, 0xff, 0xc0, 0x07, 0xff, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xff, 0xe0, 0x07, 0x80, 0x00, 0x01, 0xe0, 0x07, 0x00, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x0f, 0xf0, 0xe0, 0x07, 0x00, 0x0f, 0xf0, 0xe0, 0x07, 0x00, 0x0f, 0xf0, 0xe0, 0x07, 0x00, 0x0f, 0xf0, 0xe0, 0x07, 0x00, 0x0f, 0xf0, 0xe0, 0x07, 0x00, 0x0f, 0xf0, 0xe0, 0x07, 0x00, 0x0f, 0xf0, 0xe0, 0x07, 0x00, 0x0f, 0xf0, 0xe0, 0x07, 0x00, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0x00, 0xe0, 0x07, 0x80, 0x00, 0x01, 0xe0, 0x07, 0xff, 0xff, 0xff, 0xe0, 0x03, 0xff, 0xff, 0xff, 0xc0, 0x01, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ])
calendar_40_40 = bytearray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 56, 0, 28, 0, 0, 56, 0, 28, 0, 0, 60, 0, 28, 0, 1, 255, 255, 255, 128, 3, 255, 255, 255, 192, 7, 255, 255, 255, 224, 7, 255, 255, 255, 224, 7, 255, 255, 255, 224, 7, 255, 255, 255, 224, 7, 255, 255, 255, 224, 7, 255, 255, 255, 224, 7, 128, 0, 1, 224, 7, 0, 0, 0, 224, 7, 0, 0, 0, 224, 7, 0, 0, 0, 224, 7, 0, 0, 0, 224, 7, 0, 0, 0, 224, 7, 0, 0, 0, 224, 7, 0, 15, 240, 224, 7, 0, 15, 240, 224, 7, 0, 15, 240, 224, 7, 0, 15, 240, 224, 7, 0, 15, 240, 224, 7, 0, 15, 240, 224, 7, 0, 15, 240, 224, 7, 0, 15, 240, 224, 7, 0, 0, 0, 224, 7, 0, 0, 0, 224, 7, 0, 0, 0, 224, 7, 128, 0, 1, 224, 7, 255, 255, 255, 224, 3, 255, 255, 255, 192, 1, 255, 255, 255, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
class Category: """ Categories of vehicles sold. """ NEW = "new" DEMO = "demo" USED = "preowned" class VehicleType: """ Types of vehicles sold. """ CARGO_VAN = "CARGO VAN" CAR = "Car" SUV = "SUV" TRUCK = "Truck" VAN = "Van"
class Category: """ Categories of vehicles sold. """ new = 'new' demo = 'demo' used = 'preowned' class Vehicletype: """ Types of vehicles sold. """ cargo_van = 'CARGO VAN' car = 'Car' suv = 'SUV' truck = 'Truck' van = 'Van'
class BaseObject(object): """ A base class to provide common features to all models. """
class Baseobject(object): """ A base class to provide common features to all models. """
expected_output = { "interfaces": { "GigabitEthernet1/0/17": { "mac_address": { "0024.9bff.0ac8": { "acct_session_id": "0x0000008d", "common_session_id": "0A8628020000007168945FE6", "current_policy": "Test_DOT1X-DEFAULT_V1", "domain": "DATA", "handle": "0x86000067", "iif_id": "0x1534B4E2", "ipv4_address": "Unknown", "ipv6_address": "Unknown", "user_name": "host/Laptop123.test.com", "status": "Authorized", "oper_host_mode": "multi-auth", "oper_control_dir": "both", "session_timeout": {"type": "N/A"}, "server_policies": { 1: { "name": "ACS ACL", "policies": "xACSACLx-IP-Test_ACL_PERMIT_ALL-565bad69", "security_policy": "None", "security_status": "Link Unsecured", } }, "method_status": { "dot1x": {"method": "dot1x", "state": "Authc Success"}, "mab": {"method": "mab", "state": "Stopped"}, }, } } } } }
expected_output = {'interfaces': {'GigabitEthernet1/0/17': {'mac_address': {'0024.9bff.0ac8': {'acct_session_id': '0x0000008d', 'common_session_id': '0A8628020000007168945FE6', 'current_policy': 'Test_DOT1X-DEFAULT_V1', 'domain': 'DATA', 'handle': '0x86000067', 'iif_id': '0x1534B4E2', 'ipv4_address': 'Unknown', 'ipv6_address': 'Unknown', 'user_name': 'host/Laptop123.test.com', 'status': 'Authorized', 'oper_host_mode': 'multi-auth', 'oper_control_dir': 'both', 'session_timeout': {'type': 'N/A'}, 'server_policies': {1: {'name': 'ACS ACL', 'policies': 'xACSACLx-IP-Test_ACL_PERMIT_ALL-565bad69', 'security_policy': 'None', 'security_status': 'Link Unsecured'}}, 'method_status': {'dot1x': {'method': 'dot1x', 'state': 'Authc Success'}, 'mab': {'method': 'mab', 'state': 'Stopped'}}}}}}}
def my_plot(df, case_type, case_thres=50000): m = Basemap(projection='cyl') m.fillcontinents(color='peru', alpha=0.3) groupby_columns = ['Country/Region', 'Province/State', 'Lat', 'Long'] max_num_cases = df[case_type].max() for k, g in df.groupby(groupby_columns): country_region, province_state, lat, long = k num_cases = g.loc[g['Date'] == g['Date'].max(), case_type].sum() if num_cases > case_thres: x, y = m(long, lat) opacity = np.log(num_cases) / np.log(max_num_cases) size = num_cases / max_num_cases #print(country_region, opacity) #p = m.plot(x, y, marker='o',color='darkblue', alpha=opacity*4) p = m.scatter(long, lat, marker='o',color='darkblue', s=size*500, alpha=opacity) if num_cases > 1000000: plt.text(x, y, province_state or country_region)
def my_plot(df, case_type, case_thres=50000): m = basemap(projection='cyl') m.fillcontinents(color='peru', alpha=0.3) groupby_columns = ['Country/Region', 'Province/State', 'Lat', 'Long'] max_num_cases = df[case_type].max() for (k, g) in df.groupby(groupby_columns): (country_region, province_state, lat, long) = k num_cases = g.loc[g['Date'] == g['Date'].max(), case_type].sum() if num_cases > case_thres: (x, y) = m(long, lat) opacity = np.log(num_cases) / np.log(max_num_cases) size = num_cases / max_num_cases p = m.scatter(long, lat, marker='o', color='darkblue', s=size * 500, alpha=opacity) if num_cases > 1000000: plt.text(x, y, province_state or country_region)
class Review: all_reviews = [] def __init__(self,news_id,title,name,author,description,url, urlToImage,publishedAt,content): self.new_id = new_id self.title = title self.name= name self.author=author self.description=description self.url=link self. urlToImage= imageurl self.publishedAt = date self.content=content def save_review(self): Review.all_reviews.append(self) @classmethod def clear_reviews(cls): Review.all_reviews.clear()
class Review: all_reviews = [] def __init__(self, news_id, title, name, author, description, url, urlToImage, publishedAt, content): self.new_id = new_id self.title = title self.name = name self.author = author self.description = description self.url = link self.urlToImage = imageurl self.publishedAt = date self.content = content def save_review(self): Review.all_reviews.append(self) @classmethod def clear_reviews(cls): Review.all_reviews.clear()
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """HMC5883L: Surface-mount, multi-chip module designed for low-field magnetic sensing with a digital interface for applications such as lowcost compassing and magnetometry""" __author__ = "ChISL" __copyright__ = "TBD" __credits__ = ["Honeywell"] __license__ = "TBD" __version__ = "Version 0.1" __maintainer__ = "https://chisl.io" __email__ = "info@chisl.io" __status__ = "Test" # # THIS FILE IS AUTOMATICALLY CREATED # D O N O T M O D I F Y ! # class REG: ConfigA = 0 ConfigB = 1 Mode = 2 DataOutputX = 3 DataOutputZ = 5 DataOutputY = 7 Status = 9 Identification = 16
"""HMC5883L: Surface-mount, multi-chip module designed for low-field magnetic sensing with a digital interface for applications such as lowcost compassing and magnetometry""" __author__ = 'ChISL' __copyright__ = 'TBD' __credits__ = ['Honeywell'] __license__ = 'TBD' __version__ = 'Version 0.1' __maintainer__ = 'https://chisl.io' __email__ = 'info@chisl.io' __status__ = 'Test' class Reg: config_a = 0 config_b = 1 mode = 2 data_output_x = 3 data_output_z = 5 data_output_y = 7 status = 9 identification = 16
class Solution: def countBits(self, num: int) -> List[int]: ans=[] for i in range(num+1): ans.append(bin(i).count('1')) return ans
class Solution: def count_bits(self, num: int) -> List[int]: ans = [] for i in range(num + 1): ans.append(bin(i).count('1')) return ans
def change(img2_head_mask, img2, cv2, convexhull2, result): (x, y, w, h) = cv2.boundingRect(convexhull2) center_face2 = (int((x + x + w) / 2), int((y + y + h) / 2)) #can change it to Mix_clone seamlessclone = cv2.seamlessClone(result, img2, img2_head_mask, center_face2, cv2.NORMAL_CLONE) return seamlessclone
def change(img2_head_mask, img2, cv2, convexhull2, result): (x, y, w, h) = cv2.boundingRect(convexhull2) center_face2 = (int((x + x + w) / 2), int((y + y + h) / 2)) seamlessclone = cv2.seamlessClone(result, img2, img2_head_mask, center_face2, cv2.NORMAL_CLONE) return seamlessclone
# Created by MechAviv # Map ID :: 100000000 # NPC ID :: 9110000 # Perry maps = [["Showa Town", 100000000], ["Ninja Castle", 100000000], ["Six Path Crossway", 100000000]]# TODO sm.setSpeakerID(9110000) selection = sm.sendNext("Welcome! Where to?\r\n#L0# To Showa Town#l\r\n#L1# To Ninja Castle#l\r\n#L2# To Six Path Crossway#l") sm.setSpeakerID(9110000) if sm.sendAskYesNo(maps[selection][0] + "? Drive safely!"): sm.warp(maps[selection][1]) else: sm.setSpeakerID(9110000) sm.sendNext("I hope the ride wasn't too uncomfortable. I can't upgrade the seating without charging fares.")
maps = [['Showa Town', 100000000], ['Ninja Castle', 100000000], ['Six Path Crossway', 100000000]] sm.setSpeakerID(9110000) selection = sm.sendNext('Welcome! Where to?\r\n#L0# To Showa Town#l\r\n#L1# To Ninja Castle#l\r\n#L2# To Six Path Crossway#l') sm.setSpeakerID(9110000) if sm.sendAskYesNo(maps[selection][0] + '? Drive safely!'): sm.warp(maps[selection][1]) else: sm.setSpeakerID(9110000) sm.sendNext("I hope the ride wasn't too uncomfortable. I can't upgrade the seating without charging fares.")
'''input 98 56 Worse 12 34 Better ''' # -*- coding: utf-8 -*- # AtCoder Beginner Contest # Problem A if __name__ == '__main__': x, y = list(map(int, input().split())) if x < y: print('Better') else: print('Worse')
"""input 98 56 Worse 12 34 Better """ if __name__ == '__main__': (x, y) = list(map(int, input().split())) if x < y: print('Better') else: print('Worse')
INVALID_ARGUMENT = 'invalid argument' PERMISSION_DENIED = 'permission denied' UNKNOWN = 'unknown' NOT_FOUND = 'not found' INTERNAL = 'internal error' TOO_MANY_REQUESTS = 'too many requests' SERVER_UNAVAILABLE = 'service unavailable' BAD_REQUEST = 'bad request' AUTH_ERROR = 'authorization error' class TRError(Exception): def __init__(self, code, message, type_='fatal'): super().__init__() self.code = code or UNKNOWN self.message = message or 'Something went wrong.' self.type_ = type_ @property def json(self): return {'type': self.type_, 'code': self.code, 'message': self.message} class URLScanInternalServerError(TRError): def __init__(self): super().__init__( INTERNAL, 'The URLScan internal error.' ) class URLScanNotFoundError(TRError): def __init__(self): super().__init__( NOT_FOUND, 'The URLScan not found.' ) class URLScanInvalidCredentialsError(TRError): def __init__(self): super().__init__( PERMISSION_DENIED, 'The request is missing a valid API key.' ) class URLScanUnexpectedResponseError(TRError): def __init__(self, payload): error_payload = payload.json() super().__init__( UNKNOWN, str(error_payload) ) class URLScanTooManyRequestsError(TRError): def __init__(self): super().__init__( TOO_MANY_REQUESTS, 'Too many requests have been made to ' 'URLScan. Please, try again later.' ) class URLScanUnavailableError(TRError): def __init__(self): super().__init__( SERVER_UNAVAILABLE, 'The urlscan.io is unavailable. Please, try again later.' ) class URLScanBadRequestError(TRError): def __init__(self): super().__init__( BAD_REQUEST, 'You sent weird url. ' 'Please check the correctness of your url and try again.' ) class URLScanSSLError(TRError): def __init__(self, error): message = getattr( error.args[0].reason.args[0], 'verify_message', '' ) or error.args[0].reason.args[0].args[0] super().__init__( UNKNOWN, f'Unable to verify SSL certificate: {message}' ) class AuthorizationError(TRError): def __init__(self, message): super().__init__( AUTH_ERROR, f"Authorization failed: {message}" ) class BadRequestError(TRError): def __init__(self, error_message): super().__init__( INVALID_ARGUMENT, error_message ) class WatchdogError(TRError): def __init__(self): super().__init__( code='health check failed', message='Invalid Health Check' )
invalid_argument = 'invalid argument' permission_denied = 'permission denied' unknown = 'unknown' not_found = 'not found' internal = 'internal error' too_many_requests = 'too many requests' server_unavailable = 'service unavailable' bad_request = 'bad request' auth_error = 'authorization error' class Trerror(Exception): def __init__(self, code, message, type_='fatal'): super().__init__() self.code = code or UNKNOWN self.message = message or 'Something went wrong.' self.type_ = type_ @property def json(self): return {'type': self.type_, 'code': self.code, 'message': self.message} class Urlscaninternalservererror(TRError): def __init__(self): super().__init__(INTERNAL, 'The URLScan internal error.') class Urlscannotfounderror(TRError): def __init__(self): super().__init__(NOT_FOUND, 'The URLScan not found.') class Urlscaninvalidcredentialserror(TRError): def __init__(self): super().__init__(PERMISSION_DENIED, 'The request is missing a valid API key.') class Urlscanunexpectedresponseerror(TRError): def __init__(self, payload): error_payload = payload.json() super().__init__(UNKNOWN, str(error_payload)) class Urlscantoomanyrequestserror(TRError): def __init__(self): super().__init__(TOO_MANY_REQUESTS, 'Too many requests have been made to URLScan. Please, try again later.') class Urlscanunavailableerror(TRError): def __init__(self): super().__init__(SERVER_UNAVAILABLE, 'The urlscan.io is unavailable. Please, try again later.') class Urlscanbadrequesterror(TRError): def __init__(self): super().__init__(BAD_REQUEST, 'You sent weird url. Please check the correctness of your url and try again.') class Urlscansslerror(TRError): def __init__(self, error): message = getattr(error.args[0].reason.args[0], 'verify_message', '') or error.args[0].reason.args[0].args[0] super().__init__(UNKNOWN, f'Unable to verify SSL certificate: {message}') class Authorizationerror(TRError): def __init__(self, message): super().__init__(AUTH_ERROR, f'Authorization failed: {message}') class Badrequesterror(TRError): def __init__(self, error_message): super().__init__(INVALID_ARGUMENT, error_message) class Watchdogerror(TRError): def __init__(self): super().__init__(code='health check failed', message='Invalid Health Check')
"""This module contains rules for the startup c library.""" load("//lib/bazel:c_rules.bzl", "makani_c_library") def _get_linkopts(ld_files): return (["-Tavionics/firmware/startup/" + f for f in ld_files]) def startup_c_library(name, deps = [], ld_files = [], linkopts = [], **kwargs): makani_c_library( name = name, deps = deps + ld_files, linkopts = linkopts + _get_linkopts(ld_files), **kwargs )
"""This module contains rules for the startup c library.""" load('//lib/bazel:c_rules.bzl', 'makani_c_library') def _get_linkopts(ld_files): return ['-Tavionics/firmware/startup/' + f for f in ld_files] def startup_c_library(name, deps=[], ld_files=[], linkopts=[], **kwargs): makani_c_library(name=name, deps=deps + ld_files, linkopts=linkopts + _get_linkopts(ld_files), **kwargs)
DATA = [ {"gender":"male","name":{"title":"mr","first":"brian","last":"watts"},"location":{"street":"8966 preston rd","city":"des moines","state":"virginia","postcode":15835},"dob":"1977-03-11 11:43:34","id":{"name":"SSN","value":"003-73-8821"},"picture":{"large":"https://randomuser.me/api/portraits/men/68.jpg","medium":"https://randomuser.me/api/portraits/med/men/68.jpg","thumbnail":"https://randomuser.me/api/portraits/thumb/men/68.jpg"}}, {"gender":"female","name":{"title":"miss","first":"terra","last":"jimenez"},"location":{"street":"1989 taylor st","city":"roseburg","state":"illinois","postcode":86261},"dob":"1987-05-08 18:18:06","id":{"name":"SSN","value":"896-95-9224"},"picture":{"large":"https://randomuser.me/api/portraits/women/17.jpg","medium":"https://randomuser.me/api/portraits/med/women/17.jpg","thumbnail":"https://randomuser.me/api/portraits/thumb/women/17.jpg"}}, {"gender":"female","name":{"title":"mrs","first":"jeanette","last":"thomas"},"location":{"street":"7446 hickory creek dr","city":"caldwell","state":"wyoming","postcode":73617},"dob":"1959-03-21 14:19:01","id":{"name":"SSN","value":"578-92-7338"},"picture":{"large":"https://randomuser.me/api/portraits/women/56.jpg","medium":"https://randomuser.me/api/portraits/med/women/56.jpg","thumbnail":"https://randomuser.me/api/portraits/thumb/women/56.jpg"}}, {"gender":"male","name":{"title":"mr","first":"darrell","last":"ramos"},"location":{"street":"4002 green rd","city":"peoria","state":"new york","postcode":62121},"dob":"1960-03-09 16:44:53","id":{"name":"SSN","value":"778-73-1993"},"picture":{"large":"https://randomuser.me/api/portraits/men/54.jpg","medium":"https://randomuser.me/api/portraits/med/men/54.jpg","thumbnail":"https://randomuser.me/api/portraits/thumb/men/54.jpg"}} ] # get data for all students to use in index and write a list def get_all_students(source): # new dictionary students = {} # write id as key and lastname as value into dict for record in source: id = record['id']['value'] # .title() capitalizes the first letter of each word in string lastname = (record['name']['last']).title() students.update({id:lastname}) # return a list of tuples sorted in alpha order by lastname # see https://pybit.es/dict-ordering.html - great resource! return sorted(students.items(), key=lambda x: x[1]) print(get_all_students(DATA))
data = [{'gender': 'male', 'name': {'title': 'mr', 'first': 'brian', 'last': 'watts'}, 'location': {'street': '8966 preston rd', 'city': 'des moines', 'state': 'virginia', 'postcode': 15835}, 'dob': '1977-03-11 11:43:34', 'id': {'name': 'SSN', 'value': '003-73-8821'}, 'picture': {'large': 'https://randomuser.me/api/portraits/men/68.jpg', 'medium': 'https://randomuser.me/api/portraits/med/men/68.jpg', 'thumbnail': 'https://randomuser.me/api/portraits/thumb/men/68.jpg'}}, {'gender': 'female', 'name': {'title': 'miss', 'first': 'terra', 'last': 'jimenez'}, 'location': {'street': '1989 taylor st', 'city': 'roseburg', 'state': 'illinois', 'postcode': 86261}, 'dob': '1987-05-08 18:18:06', 'id': {'name': 'SSN', 'value': '896-95-9224'}, 'picture': {'large': 'https://randomuser.me/api/portraits/women/17.jpg', 'medium': 'https://randomuser.me/api/portraits/med/women/17.jpg', 'thumbnail': 'https://randomuser.me/api/portraits/thumb/women/17.jpg'}}, {'gender': 'female', 'name': {'title': 'mrs', 'first': 'jeanette', 'last': 'thomas'}, 'location': {'street': '7446 hickory creek dr', 'city': 'caldwell', 'state': 'wyoming', 'postcode': 73617}, 'dob': '1959-03-21 14:19:01', 'id': {'name': 'SSN', 'value': '578-92-7338'}, 'picture': {'large': 'https://randomuser.me/api/portraits/women/56.jpg', 'medium': 'https://randomuser.me/api/portraits/med/women/56.jpg', 'thumbnail': 'https://randomuser.me/api/portraits/thumb/women/56.jpg'}}, {'gender': 'male', 'name': {'title': 'mr', 'first': 'darrell', 'last': 'ramos'}, 'location': {'street': '4002 green rd', 'city': 'peoria', 'state': 'new york', 'postcode': 62121}, 'dob': '1960-03-09 16:44:53', 'id': {'name': 'SSN', 'value': '778-73-1993'}, 'picture': {'large': 'https://randomuser.me/api/portraits/men/54.jpg', 'medium': 'https://randomuser.me/api/portraits/med/men/54.jpg', 'thumbnail': 'https://randomuser.me/api/portraits/thumb/men/54.jpg'}}] def get_all_students(source): students = {} for record in source: id = record['id']['value'] lastname = record['name']['last'].title() students.update({id: lastname}) return sorted(students.items(), key=lambda x: x[1]) print(get_all_students(DATA))
def init() -> None: pass def run(raw_data: list) -> list: return [{"result": "Hello World"}]
def init() -> None: pass def run(raw_data: list) -> list: return [{'result': 'Hello World'}]
def can_build(env, platform): return platform=="android" def configure(env): if (env['platform'] == 'android'): env.android_add_java_dir("android") env.android_add_res_dir("res") env.android_add_asset_dir("assets") env.android_add_dependency("implementation files('../../../modules/oppo/android/libs/gamesdk-20190227.jar')") env.android_add_dependency("implementation files('../../../modules/oppo/android/libs/oppo_mobad_api_v301_2018_12_07_release.jar')") env.android_add_default_config("applicationId 'com.opos.mobaddemo'") env.android_add_to_manifest("android/AndroidManifestChunk.xml") env.android_add_to_permissions("android/AndroidPermissionsChunk.xml") env.disable_module()
def can_build(env, platform): return platform == 'android' def configure(env): if env['platform'] == 'android': env.android_add_java_dir('android') env.android_add_res_dir('res') env.android_add_asset_dir('assets') env.android_add_dependency("implementation files('../../../modules/oppo/android/libs/gamesdk-20190227.jar')") env.android_add_dependency("implementation files('../../../modules/oppo/android/libs/oppo_mobad_api_v301_2018_12_07_release.jar')") env.android_add_default_config("applicationId 'com.opos.mobaddemo'") env.android_add_to_manifest('android/AndroidManifestChunk.xml') env.android_add_to_permissions('android/AndroidPermissionsChunk.xml') env.disable_module()
# -*- coding: utf-8 -*- def main(): r, c, d = map(int, input().split()) a = [list(map(int, input().split())) for _ in range(r)] ans = 0 # See: # https://www.slideshare.net/chokudai/arc023 for y in range(r): for x in range(c): if (x + y <= d) and ((x + y) % 2 == d % 2): ans = max(ans, a[y][x]) print(ans) if __name__ == '__main__': main()
def main(): (r, c, d) = map(int, input().split()) a = [list(map(int, input().split())) for _ in range(r)] ans = 0 for y in range(r): for x in range(c): if x + y <= d and (x + y) % 2 == d % 2: ans = max(ans, a[y][x]) print(ans) if __name__ == '__main__': main()
""" LECTURE D'UN FICHIER TEXTE """ """ QUESTION 1 """ with open("texte1", "r+") as f: print(f.read(11), end="\n\n") """ QUESTION 2 """ with open("texte1", "r+") as f: print(f.readline(), end="\n\n") f.readline() print(f.readline(), end="\n\n") """ QUESTION 3 """ with open("texte1", "r+") as f: lines = f.readlines() print(lines[1], lines[3]) """ QUESTION 1 """ with open("texte1", "r+") as f: for i in range(3): print(f.readline()) """ QUESTION 2 """ with open("texte1", "r+") as f: print(f.read(3))
""" LECTURE D'UN FICHIER TEXTE """ '\n QUESTION 1\n' with open('texte1', 'r+') as f: print(f.read(11), end='\n\n') '\n QUESTION 2\n' with open('texte1', 'r+') as f: print(f.readline(), end='\n\n') f.readline() print(f.readline(), end='\n\n') '\n QUESTION 3\n' with open('texte1', 'r+') as f: lines = f.readlines() print(lines[1], lines[3]) '\n QUESTION 1\n' with open('texte1', 'r+') as f: for i in range(3): print(f.readline()) '\n QUESTION 2\n' with open('texte1', 'r+') as f: print(f.read(3))
#https://leetcode.com/problems/largest-rectangle-in-histogram/ #(Asked in Amazon SDE1 interview) class Solution: def largestRectangleArea(self, heights: List[int]) -> int: sta,finalL=[],[] it=0 for i in heights: #code for next smallest left it+=1 if sta: while(sta and i<=sta[-1][1]): sta.pop() if not sta: finalL.append(-1) elif (i>sta[-1][1]): finalL.append(sta[-1][0]-1) else: finalL.append(-1) sta.append([it,i]) print("finalL",finalL) # general len(heights) as for reverse it,sta,finalR=len(heights),[],[] #code of Next smallest right for i in heights[::-1]: #it-=1 for counting index it-=1 #as it process in reverse if sta: while(sta and i<=sta[-1][1]): sta.pop() if not sta: #if array empty 1 index ahead of last index finalR.append(len(heights)) elif (i>sta[-1][1]): finalR.append(sta[-1][0]) else: finalR.append(len(heights)) sta.append([it,i]) finalR=finalR[::-1] print("finalR",finalR) final=[] #calculate width=NSR-NSL-1 and area=width*height[k] ie arr[k] for k in range(len(heights)): final.append( (finalR[k] - finalL[k] -1) *heights[k]) print("area",final) return (max(final))
class Solution: def largest_rectangle_area(self, heights: List[int]) -> int: (sta, final_l) = ([], []) it = 0 for i in heights: it += 1 if sta: while sta and i <= sta[-1][1]: sta.pop() if not sta: finalL.append(-1) elif i > sta[-1][1]: finalL.append(sta[-1][0] - 1) else: finalL.append(-1) sta.append([it, i]) print('finalL', finalL) (it, sta, final_r) = (len(heights), [], []) for i in heights[::-1]: it -= 1 if sta: while sta and i <= sta[-1][1]: sta.pop() if not sta: finalR.append(len(heights)) elif i > sta[-1][1]: finalR.append(sta[-1][0]) else: finalR.append(len(heights)) sta.append([it, i]) final_r = finalR[::-1] print('finalR', finalR) final = [] for k in range(len(heights)): final.append((finalR[k] - finalL[k] - 1) * heights[k]) print('area', final) return max(final)
""" A simple program to calculate a chaotic function. This program will calculate the first ten values of a chaotic function with the form k(x)(1-x) where k=3.9 and x is provided by the user. """ def main(): """ Calculate the values of the chaotic function. """ x = float(input("Enter a number between 1 and 0: ")) # We will avoid using eval() because it is a security concern. # x = eval(input("Enter a number between 1 and 0: ")) for _ in range(10): x = 3.9 * x * (1 - x) print(x) # identifiers that start and end with double underscores (sometimes called # "dunders") are special in Python. if __name__ == "__main__": main()
""" A simple program to calculate a chaotic function. This program will calculate the first ten values of a chaotic function with the form k(x)(1-x) where k=3.9 and x is provided by the user. """ def main(): """ Calculate the values of the chaotic function. """ x = float(input('Enter a number between 1 and 0: ')) for _ in range(10): x = 3.9 * x * (1 - x) print(x) if __name__ == '__main__': main()
class AppSettings: types = { 'url': str, 'requestIntegration': bool, 'authURL': str, 'usernameField': str, 'passwordField': str, 'buttonField': str, 'extraFieldSelector': str, 'extraFieldValue': str, 'optionalField1': str, 'optionalField1Value': str, 'optionalField2': str, 'optionalField2Value': str, 'optionalField3': str, 'optionalField3Value': str } def __init__(self): # The URL of the login page for this app self.url = None # str # Would you like Okta to add an integration for this app? self.requestIntegration = None # bool # The URL of the authenticating site for this app self.authURL = None # str # CSS selector for the username field in the login form self.usernameField = None # str # CSS selector for the password field in the login form self.passwordField = None # str # CSS selector for the login button in the login form self.buttonField = None # str # CSS selector for the extra field in the form self.extraFieldSelector = None # str # Value for extra field form field self.extraFieldValue = None # str # Name of the optional parameter in the login form self.optionalField1 = None # str # Name of the optional value in the login form self.optionalField1Value = None # str # Name of the optional parameter in the login form self.optionalField2 = None # str # Name of the optional value in the login form self.optionalField2Value = None # str # Name of the optional parameter in the login form self.optionalField3 = None # str # Name of the optional value in the login form self.optionalField3Value = None # str
class Appsettings: types = {'url': str, 'requestIntegration': bool, 'authURL': str, 'usernameField': str, 'passwordField': str, 'buttonField': str, 'extraFieldSelector': str, 'extraFieldValue': str, 'optionalField1': str, 'optionalField1Value': str, 'optionalField2': str, 'optionalField2Value': str, 'optionalField3': str, 'optionalField3Value': str} def __init__(self): self.url = None self.requestIntegration = None self.authURL = None self.usernameField = None self.passwordField = None self.buttonField = None self.extraFieldSelector = None self.extraFieldValue = None self.optionalField1 = None self.optionalField1Value = None self.optionalField2 = None self.optionalField2Value = None self.optionalField3 = None self.optionalField3Value = None
class WikiPage: def __init__(self, title, uri=None, text=None, tags=None): self.title = title self.text = text or "" self.tags = tags or {} self.uri = uri or title self.parents = [] self.children = [] def add_child(self, page): self.children.append(page) page.add_parent(self) def add_parent(self, page): self.parents.append(page) if page.uri == "/": self.uri = "/" + self.uri else: self.uri = page.uri + "/" + self.uri
class Wikipage: def __init__(self, title, uri=None, text=None, tags=None): self.title = title self.text = text or '' self.tags = tags or {} self.uri = uri or title self.parents = [] self.children = [] def add_child(self, page): self.children.append(page) page.add_parent(self) def add_parent(self, page): self.parents.append(page) if page.uri == '/': self.uri = '/' + self.uri else: self.uri = page.uri + '/' + self.uri
numbers = [12, 18, 128, 48, 2348, 21, 18, 3, 2, 42, 96, 11, 42, 12, 18] print(numbers) # Insert the number 5 to the beginning of the list. numbers.insert(0, 5) print(numbers) # Remove the number 2348 based on its value (as opposed to a hard-coded index of 4) from the list. numbers.remove(2348) print(numbers) # Create a second list of 5 different numbers and add them to the end of the list in one step. (Make sure it adds the # numbers to the list such as: [1, 2, 3, 4, 5] not as a sub list, such as [1, 2, 3, [4, 5]] ). more_numbers = [1, 2, 3, 4, 5] numbers.extend(more_numbers) print(numbers) # Sort the list using the built in sorting algorithm. numbers.sort() print(numbers) # Sort the list backwards using the built in sorting algorithm. numbers.sort(reverse=True) print(numbers) # Use a built-in function to count the number of 12's in the list. count = numbers.count(12) print(count) # Use a built-in function to find the index of the number 96. index = numbers.index(96) print(index) # Use slicing to get the first half of the list, then get the second half of the list and make sure that nothing was # left out or duplicated in the middle. print(len(numbers)) middle = len(numbers) // 2 first_half = numbers[:middle] # numbers[inclusive:exclusive] print(len(first_half), first_half) second_half = numbers[middle:] print(len(second_half), second_half) # Use slicing to create a new list that has every other item from the original list (i.e., skip elements, # using the step functionality). every_other = numbers[0:len(numbers) - 1:2] print(every_other) # Use slicing to get the last 5 items of the list. For this, please use negative number indexing. print(numbers) last_5 = numbers[:-6:-1] print(last_5)
numbers = [12, 18, 128, 48, 2348, 21, 18, 3, 2, 42, 96, 11, 42, 12, 18] print(numbers) numbers.insert(0, 5) print(numbers) numbers.remove(2348) print(numbers) more_numbers = [1, 2, 3, 4, 5] numbers.extend(more_numbers) print(numbers) numbers.sort() print(numbers) numbers.sort(reverse=True) print(numbers) count = numbers.count(12) print(count) index = numbers.index(96) print(index) print(len(numbers)) middle = len(numbers) // 2 first_half = numbers[:middle] print(len(first_half), first_half) second_half = numbers[middle:] print(len(second_half), second_half) every_other = numbers[0:len(numbers) - 1:2] print(every_other) print(numbers) last_5 = numbers[:-6:-1] print(last_5)
class pbox_description: def __init__(self, pdb_id): self.pdb_id = pdb_id def get_pdb_id(self): return self.pdb_id
class Pbox_Description: def __init__(self, pdb_id): self.pdb_id = pdb_id def get_pdb_id(self): return self.pdb_id
# Getting an input from the user x = int(input("How tall do you want your pyramid to be? ")) while x < 0 or x > 23: x = int(input("Provide a number greater than 0 and smaller than 23: ")) for i in range(x): z = i+1 # counts the number of blocks in the pyramid in each iteration y = x-i # counts the number of spaces in the pyramid in each iteration print(" "*y + "#"*z + " " + "#"*z) # this function builds the pyramid
x = int(input('How tall do you want your pyramid to be? ')) while x < 0 or x > 23: x = int(input('Provide a number greater than 0 and smaller than 23: ')) for i in range(x): z = i + 1 y = x - i print(' ' * y + '#' * z + ' ' + '#' * z)
class Solution: def reverseOnlyLetters(self, s: str) -> str: i = 0 j = len(s)-1 m = list(range(65, 91))+list(range(97, 123)) while i < j: if ord(s[i]) not in m: i += 1 continue if ord(s[j]) not in m: j -= 1 continue s = s[:i]+s[j]+s[i+1:j]+s[i]+s[j+1:] i += 1 j -= 1 return s obj = Solution() res = obj.reverseOnlyLetters(s="a-bC-dEf-ghIj") print(res)
class Solution: def reverse_only_letters(self, s: str) -> str: i = 0 j = len(s) - 1 m = list(range(65, 91)) + list(range(97, 123)) while i < j: if ord(s[i]) not in m: i += 1 continue if ord(s[j]) not in m: j -= 1 continue s = s[:i] + s[j] + s[i + 1:j] + s[i] + s[j + 1:] i += 1 j -= 1 return s obj = solution() res = obj.reverseOnlyLetters(s='a-bC-dEf-ghIj') print(res)
'''Returns unmodifiable sets of "uninteresting" (e.g., not drug like) ligands. References ---------- - `D3R Project <https://github.com/drugdata/D3R/blob/master/d3r/filter/filtering_sets.py`_ ''' METAL_CONTAINING = set(['CP', 'NFU', 'NFR', 'NFE', 'NFV', 'FSO', 'WCC', 'TCN', 'FS2', 'PDV', 'CPT', 'OEC', 'XCC', 'NFS', 'C7P', 'TBR', 'NFC', 'CUB', 'VA3', 'FV1', 'IME', 'FC6', 'RU7', 'TBY', 'REI', 'REJ', 'CNB', 'MM1', 'MM2', 'MM6', 'MM5', 'YBT', 'CN1', 'CLF', 'CLP', 'NC1', 'V4O', 'HC0', 'VO3', 'CFM', 'CZL', 'CON', 'TBR', 'ICS', 'HCN', 'CFN', 'CFC', 'HF3', 'ZRC', 'F3S', 'SRM', 'HDD', 'CUA', 'RU8', 'B22', 'BEF', 'AG1', 'SF4', 'NCO', '0KA', 'FNE', 'QPT']) STABILIZERS = set(['B3P', 'PGE', '6JZ', '15P', 'PE3', 'XPE', '7PE', 'M2M', '13P', '3PP', 'PX4', '3OL', 'OC9', 'AE3', '6JZ', 'XPE', '211', 'ODI', 'DIA', 'PG5', 'CXE', 'ME2', 'P4G', 'TOE', 'PG5', 'PE8', 'ZPG', 'PE3', 'MXE']) BUFFERS = set(['MPO', 'NHE', 'CXS', 'T3A', '3CX', '3FX', 'PIN', 'MES', 'EPE', 'TRS', 'BTB', '144']) COFACTORS = set(['ATP', 'ADP', 'AMP', 'ANP', 'GTP', 'GDP', 'GNP', 'UMP', 'TTP', 'TMP', 'MGD', 'H2U', 'ADN', 'APC', 'M2G', 'OMG', 'OMC', 'UDP', 'UMP', '5GP', '5MU', '5MC', '2MG', '1MA', 'NAD', 'NAP', 'NDP', 'FAD', 'FMN', 'BH4', 'BPH', 'BTN', 'PST', 'SAM', 'SAH', 'COA', 'ACO', 'U10', 'HEM', 'HEC', 'HEA', 'HAS', 'DHE', 'BCL', 'CLA', '6HE', '7HE', 'DCP', '23T', 'H4B', 'WCC', 'CFN', 'AMP', 'BCL', 'BCB', 'CHL', 'NAP', 'CON', 'FAD', 'NAD', 'SXN', 'U', 'G', 'QUY', 'UDG', 'CBY', 'ST9', '25A', ' A', ' C', 'B12', 'HAS', 'BPH', 'BPB', 'IPE', 'PLP', 'H4B', 'PMP', 'PLP', 'TPP', 'TDP', 'COO', 'PQN', 'BCR', 'XAT']) COVALENT_MODS = set(['CS1', 'MSE', 'CME', 'CSO', 'LLP', 'IAS']) FRAGMENTS = set(['ACE', 'ACT', 'DMS', 'EOH', 'FMT', 'IMD', 'DTT', 'BME', 'IPA', 'HED', 'PEP', 'PYR', 'PXY', 'OXE', 'TMT', 'TMZ', 'PLQ', 'TAM', 'HEZ', 'DTV', 'DTU', 'DTD', 'MRD', 'MRY', 'BU1', 'D10', 'OCT', 'ETE', 'TZZ', 'DEP', 'BTB', 'ACY', 'MAE', '144', 'CP', 'UVW', 'BET', 'UAP', 'SER', 'SIN', 'FUM', 'MAK', 'PAE', 'DTL', 'HLT', 'ASC', 'D1D', 'PCT', 'TTN', 'HDA', 'PGA', 'XXD', 'INS', '217', 'BHL', '16D', 'HSE', 'OPE', 'HCS', 'SOR', 'SKM', 'KIV', 'FCN', 'TRA', 'TRC', 'MZP', 'KDG', 'DHK']) EXCIPIENTS = set(['CO2', 'SE', 'GOL', 'PEG', 'EDO', 'PG4', 'C8E', 'CE9', 'BME', '1PE', 'OLC', 'MYR', 'LDA', '2CV', '1PG', '12P', 'XP4', 'PL3', 'PE4', 'PEU', 'MPG', 'B8M', 'BOM', '2PE', 'PG0', 'PE5', 'PG6', 'P33', 'DTV', 'SDS', 'DTU', 'DTD', 'MRD', 'MRY', 'BU1', 'LHG', 'D10', 'OCT', 'LT1', 'ETE', 'BTB', 'PC1', 'ACT', 'ACY', '3GD', 'CDL', 'PLC', 'D1D']) JUNK = set(['AS8', 'PS9', 'CYI', 'NOB', 'DPO', 'MDN', 'APC', 'ACP', 'LPT', 'PBL', 'LFA', 'PGW', 'DD9', 'PGV', 'UPL', 'PEF', 'MC3', 'LAP', 'PEE', 'D12', 'CXE', 'T1A', 'TBA', 'NET', 'NEH', 'P2N', 'PON', 'PIS', 'PPV', 'DPO', 'PSL', 'TLA', 'SRT', '104', 'PTW', 'ACN', 'CHH', 'CCD', 'DAO', 'SBY', 'MYS', 'XPT', 'NM2', 'REE', 'SO4-SO4', 'P4C', 'C10', 'PAW', 'OCM', '9OD', 'Q9C', 'UMQ', 'STP', 'PPK', '3PO', 'BDD', '5HD', 'YES', 'DIO', 'U10', 'C14', 'BTM', 'P03', 'M21', 'PGV', 'LNK', 'EGC', 'BU3', 'R16', '4E6', '1EY', '1EX', 'B9M', 'LPP', 'IHD', 'NKR', 'T8X', 'AE4', 'X13', '16Y', 'B3P', 'RB3', 'OHA', 'DGG', 'HXA', 'D9G', 'HTG', 'B7G', 'FK9', '16P', 'SPM', 'TLA', 'B3P', '15P', 'SPO', 'BCR', 'BCN', 'EPH', 'SPD', 'SPN', 'SPH', 'S9L', 'PTY', 'PE8', 'D12', 'PEK']) DO_NOT_CALL = set(['CP', 'NFU', 'NFR', 'NFE', 'NFV', 'FSO', 'WCC', 'TCN', 'FS2', 'PDV', 'CPT', 'OEC', 'XCC', 'NFS', 'C7P', 'TBR', 'NFC', 'CUB', 'VA3', 'FV1', 'IME', 'FC6', 'RU7', 'TBY', 'REI', 'REJ', 'CNB', 'MM1', 'MM2', 'MM6', 'MM5', 'YBT', 'CN1', 'CLF', 'CLP', 'V4O', 'HC0', 'VO3', 'CFM', 'CZL', 'CON', 'ICS', 'HCN', 'CFN', 'CFC', 'HF3', 'ZRC', 'F3S', 'SRM', 'HDD', 'B3P', 'PGE', '6JZ', '15P', 'PE3', 'XPE', '7PE', 'M2M', '13P', '3PP', 'PX4', '3OL', 'OC9', 'AE3', '211', 'ODI', 'DIA', 'PG5', 'CXE', 'ME2', 'P4G', 'TOE', 'PE8', 'ZPG', 'MXE', 'MPO', 'NHE', 'CXS', 'T3A', '3CX', '3FX', 'PIN', 'MGD', 'NAD', 'NAP', 'NDP', 'FAD', 'FMN', 'BH4', 'BPH', 'BTN', 'COA', 'ACO', 'U10', 'HEM', 'HEC', 'HEA', 'HAS', 'DHE', 'BCL', 'CLA', '6HE', '7HE', 'H4B', 'BCB', 'CHL', 'SXN', 'QUY', 'UDG', 'CBY', 'ST9', '25A', 'B12', 'BPB', 'IPE', 'PLP', 'PMP', 'TPP', 'TDP', 'SO4', 'SUL', 'CL', 'BR', 'CA', 'MG', 'NI', 'MN', 'CU', 'PO4', 'CD', 'NH4', 'CO', 'NA', 'K', 'ZN', 'FE', 'AZI', 'CD2', 'YG', 'CR', 'CR2', 'CR3', 'CAC', 'CO2', 'CO3', 'CYN', 'FS4', 'MO6', 'NCO', 'NO3', 'SCN', 'SF4', 'SE', 'PB', 'AU', 'AU3', 'BR1', 'CA2', 'CL1', 'CS', 'CS1', 'CU1', 'AG', 'AG1', 'AL', 'AL3', 'F', 'FE2', 'FE3', 'IR', 'IR3', 'KR', 'MAL', 'GOL', 'MPD', 'PEG', 'EDO', 'PG4', 'BOG', 'HTO', 'ACX', 'CEG', 'XLS', 'C8E', 'CE9', 'CRY', 'DOX', 'EGL', 'P6G', 'SUC', '1PE', 'OLC', 'POP', 'MES', 'EPE', 'PYR', 'CIT', 'FLC', 'TAR', 'HC4', 'MYR', 'HED', 'DTT', 'BME', 'TRS', 'ABA', 'ACE', 'ACT', 'CME', 'CSD', 'CSO', 'DMS', 'EOH', 'FMT', 'GTT', 'IMD', 'IOH', 'IPA', 'LDA', 'LLP', 'PEP', 'PXY', 'OXE', 'TMT', 'TMZ', '2CV', 'PLQ', 'TAM', '1PG', '12P', 'XP4', 'PL3', 'PE4', 'PEU', 'MPG', 'B8M', 'BOM', 'B7M', '2PE', 'STE', 'DME', 'PLM', 'PG0', 'PE5', 'PG6', 'P33', 'HEZ', 'F23', 'DTV', 'SDS', 'DTU', 'DTD', 'MRD', 'MRY', 'BU1', 'LHG', 'D10', 'OCT', 'LI1', 'ETE', 'TZZ', 'DEP', 'DKA', 'OLA', 'ACD', 'MLR', 'POG', 'BTB', 'PC1', 'ACY', '3GD', 'MAE', 'CA3', '144', '0KA', 'A71', 'UVW', 'BET', 'PBU', 'SER', 'CDL', 'CEY', 'LMN', 'J7Z', 'SIN', 'PLC', 'FNE', 'FUM', 'MAK', 'PAE', 'DTL', 'HLT', 'FPP', 'FII', 'D1D', 'PCT', 'TTN', 'HDA', 'PGA', 'XXD', 'INS', '217', 'BHL', '16D', 'HSE', 'OPE', 'HCS', 'SOR', 'SKM', 'KIV', 'FCN', 'TRA', 'TRC', 'MTL', 'KDG', 'DHK', 'Ar', 'IOD', '35N', 'HGB', '3UQ', 'UNX', 'GSH', 'DGD', 'LMG', 'LMT', 'CAD', 'CUA', 'DMU', 'PEK', 'PGV', 'PSC', 'TGL', 'COO', 'BCR', 'XAT', 'MOE', 'P4C', 'PP9', 'Z0P', 'YZY', 'LMU', 'MLA', 'GAI', 'XE', 'ARS', 'SPM', 'RU8', 'B22', 'BEF', 'DHL', 'HG', 'MBO', 'ARC', 'OH', 'FES', 'RU', 'IAS', 'QPT', 'SR']) all_sets = [METAL_CONTAINING, STABILIZERS, BUFFERS, COFACTORS, COVALENT_MODS, \ FRAGMENTS, EXCIPIENTS, JUNK, DO_NOT_CALL] ALL_GROUPS = {item for subset in all_sets for item in subset}
"""Returns unmodifiable sets of "uninteresting" (e.g., not drug like) ligands. References ---------- - `D3R Project <https://github.com/drugdata/D3R/blob/master/d3r/filter/filtering_sets.py`_ """ metal_containing = set(['CP', 'NFU', 'NFR', 'NFE', 'NFV', 'FSO', 'WCC', 'TCN', 'FS2', 'PDV', 'CPT', 'OEC', 'XCC', 'NFS', 'C7P', 'TBR', 'NFC', 'CUB', 'VA3', 'FV1', 'IME', 'FC6', 'RU7', 'TBY', 'REI', 'REJ', 'CNB', 'MM1', 'MM2', 'MM6', 'MM5', 'YBT', 'CN1', 'CLF', 'CLP', 'NC1', 'V4O', 'HC0', 'VO3', 'CFM', 'CZL', 'CON', 'TBR', 'ICS', 'HCN', 'CFN', 'CFC', 'HF3', 'ZRC', 'F3S', 'SRM', 'HDD', 'CUA', 'RU8', 'B22', 'BEF', 'AG1', 'SF4', 'NCO', '0KA', 'FNE', 'QPT']) stabilizers = set(['B3P', 'PGE', '6JZ', '15P', 'PE3', 'XPE', '7PE', 'M2M', '13P', '3PP', 'PX4', '3OL', 'OC9', 'AE3', '6JZ', 'XPE', '211', 'ODI', 'DIA', 'PG5', 'CXE', 'ME2', 'P4G', 'TOE', 'PG5', 'PE8', 'ZPG', 'PE3', 'MXE']) buffers = set(['MPO', 'NHE', 'CXS', 'T3A', '3CX', '3FX', 'PIN', 'MES', 'EPE', 'TRS', 'BTB', '144']) cofactors = set(['ATP', 'ADP', 'AMP', 'ANP', 'GTP', 'GDP', 'GNP', 'UMP', 'TTP', 'TMP', 'MGD', 'H2U', 'ADN', 'APC', 'M2G', 'OMG', 'OMC', 'UDP', 'UMP', '5GP', '5MU', '5MC', '2MG', '1MA', 'NAD', 'NAP', 'NDP', 'FAD', 'FMN', 'BH4', 'BPH', 'BTN', 'PST', 'SAM', 'SAH', 'COA', 'ACO', 'U10', 'HEM', 'HEC', 'HEA', 'HAS', 'DHE', 'BCL', 'CLA', '6HE', '7HE', 'DCP', '23T', 'H4B', 'WCC', 'CFN', 'AMP', 'BCL', 'BCB', 'CHL', 'NAP', 'CON', 'FAD', 'NAD', 'SXN', 'U', 'G', 'QUY', 'UDG', 'CBY', 'ST9', '25A', ' A', ' C', 'B12', 'HAS', 'BPH', 'BPB', 'IPE', 'PLP', 'H4B', 'PMP', 'PLP', 'TPP', 'TDP', 'COO', 'PQN', 'BCR', 'XAT']) covalent_mods = set(['CS1', 'MSE', 'CME', 'CSO', 'LLP', 'IAS']) fragments = set(['ACE', 'ACT', 'DMS', 'EOH', 'FMT', 'IMD', 'DTT', 'BME', 'IPA', 'HED', 'PEP', 'PYR', 'PXY', 'OXE', 'TMT', 'TMZ', 'PLQ', 'TAM', 'HEZ', 'DTV', 'DTU', 'DTD', 'MRD', 'MRY', 'BU1', 'D10', 'OCT', 'ETE', 'TZZ', 'DEP', 'BTB', 'ACY', 'MAE', '144', 'CP', 'UVW', 'BET', 'UAP', 'SER', 'SIN', 'FUM', 'MAK', 'PAE', 'DTL', 'HLT', 'ASC', 'D1D', 'PCT', 'TTN', 'HDA', 'PGA', 'XXD', 'INS', '217', 'BHL', '16D', 'HSE', 'OPE', 'HCS', 'SOR', 'SKM', 'KIV', 'FCN', 'TRA', 'TRC', 'MZP', 'KDG', 'DHK']) excipients = set(['CO2', 'SE', 'GOL', 'PEG', 'EDO', 'PG4', 'C8E', 'CE9', 'BME', '1PE', 'OLC', 'MYR', 'LDA', '2CV', '1PG', '12P', 'XP4', 'PL3', 'PE4', 'PEU', 'MPG', 'B8M', 'BOM', '2PE', 'PG0', 'PE5', 'PG6', 'P33', 'DTV', 'SDS', 'DTU', 'DTD', 'MRD', 'MRY', 'BU1', 'LHG', 'D10', 'OCT', 'LT1', 'ETE', 'BTB', 'PC1', 'ACT', 'ACY', '3GD', 'CDL', 'PLC', 'D1D']) junk = set(['AS8', 'PS9', 'CYI', 'NOB', 'DPO', 'MDN', 'APC', 'ACP', 'LPT', 'PBL', 'LFA', 'PGW', 'DD9', 'PGV', 'UPL', 'PEF', 'MC3', 'LAP', 'PEE', 'D12', 'CXE', 'T1A', 'TBA', 'NET', 'NEH', 'P2N', 'PON', 'PIS', 'PPV', 'DPO', 'PSL', 'TLA', 'SRT', '104', 'PTW', 'ACN', 'CHH', 'CCD', 'DAO', 'SBY', 'MYS', 'XPT', 'NM2', 'REE', 'SO4-SO4', 'P4C', 'C10', 'PAW', 'OCM', '9OD', 'Q9C', 'UMQ', 'STP', 'PPK', '3PO', 'BDD', '5HD', 'YES', 'DIO', 'U10', 'C14', 'BTM', 'P03', 'M21', 'PGV', 'LNK', 'EGC', 'BU3', 'R16', '4E6', '1EY', '1EX', 'B9M', 'LPP', 'IHD', 'NKR', 'T8X', 'AE4', 'X13', '16Y', 'B3P', 'RB3', 'OHA', 'DGG', 'HXA', 'D9G', 'HTG', 'B7G', 'FK9', '16P', 'SPM', 'TLA', 'B3P', '15P', 'SPO', 'BCR', 'BCN', 'EPH', 'SPD', 'SPN', 'SPH', 'S9L', 'PTY', 'PE8', 'D12', 'PEK']) do_not_call = set(['CP', 'NFU', 'NFR', 'NFE', 'NFV', 'FSO', 'WCC', 'TCN', 'FS2', 'PDV', 'CPT', 'OEC', 'XCC', 'NFS', 'C7P', 'TBR', 'NFC', 'CUB', 'VA3', 'FV1', 'IME', 'FC6', 'RU7', 'TBY', 'REI', 'REJ', 'CNB', 'MM1', 'MM2', 'MM6', 'MM5', 'YBT', 'CN1', 'CLF', 'CLP', 'V4O', 'HC0', 'VO3', 'CFM', 'CZL', 'CON', 'ICS', 'HCN', 'CFN', 'CFC', 'HF3', 'ZRC', 'F3S', 'SRM', 'HDD', 'B3P', 'PGE', '6JZ', '15P', 'PE3', 'XPE', '7PE', 'M2M', '13P', '3PP', 'PX4', '3OL', 'OC9', 'AE3', '211', 'ODI', 'DIA', 'PG5', 'CXE', 'ME2', 'P4G', 'TOE', 'PE8', 'ZPG', 'MXE', 'MPO', 'NHE', 'CXS', 'T3A', '3CX', '3FX', 'PIN', 'MGD', 'NAD', 'NAP', 'NDP', 'FAD', 'FMN', 'BH4', 'BPH', 'BTN', 'COA', 'ACO', 'U10', 'HEM', 'HEC', 'HEA', 'HAS', 'DHE', 'BCL', 'CLA', '6HE', '7HE', 'H4B', 'BCB', 'CHL', 'SXN', 'QUY', 'UDG', 'CBY', 'ST9', '25A', 'B12', 'BPB', 'IPE', 'PLP', 'PMP', 'TPP', 'TDP', 'SO4', 'SUL', 'CL', 'BR', 'CA', 'MG', 'NI', 'MN', 'CU', 'PO4', 'CD', 'NH4', 'CO', 'NA', 'K', 'ZN', 'FE', 'AZI', 'CD2', 'YG', 'CR', 'CR2', 'CR3', 'CAC', 'CO2', 'CO3', 'CYN', 'FS4', 'MO6', 'NCO', 'NO3', 'SCN', 'SF4', 'SE', 'PB', 'AU', 'AU3', 'BR1', 'CA2', 'CL1', 'CS', 'CS1', 'CU1', 'AG', 'AG1', 'AL', 'AL3', 'F', 'FE2', 'FE3', 'IR', 'IR3', 'KR', 'MAL', 'GOL', 'MPD', 'PEG', 'EDO', 'PG4', 'BOG', 'HTO', 'ACX', 'CEG', 'XLS', 'C8E', 'CE9', 'CRY', 'DOX', 'EGL', 'P6G', 'SUC', '1PE', 'OLC', 'POP', 'MES', 'EPE', 'PYR', 'CIT', 'FLC', 'TAR', 'HC4', 'MYR', 'HED', 'DTT', 'BME', 'TRS', 'ABA', 'ACE', 'ACT', 'CME', 'CSD', 'CSO', 'DMS', 'EOH', 'FMT', 'GTT', 'IMD', 'IOH', 'IPA', 'LDA', 'LLP', 'PEP', 'PXY', 'OXE', 'TMT', 'TMZ', '2CV', 'PLQ', 'TAM', '1PG', '12P', 'XP4', 'PL3', 'PE4', 'PEU', 'MPG', 'B8M', 'BOM', 'B7M', '2PE', 'STE', 'DME', 'PLM', 'PG0', 'PE5', 'PG6', 'P33', 'HEZ', 'F23', 'DTV', 'SDS', 'DTU', 'DTD', 'MRD', 'MRY', 'BU1', 'LHG', 'D10', 'OCT', 'LI1', 'ETE', 'TZZ', 'DEP', 'DKA', 'OLA', 'ACD', 'MLR', 'POG', 'BTB', 'PC1', 'ACY', '3GD', 'MAE', 'CA3', '144', '0KA', 'A71', 'UVW', 'BET', 'PBU', 'SER', 'CDL', 'CEY', 'LMN', 'J7Z', 'SIN', 'PLC', 'FNE', 'FUM', 'MAK', 'PAE', 'DTL', 'HLT', 'FPP', 'FII', 'D1D', 'PCT', 'TTN', 'HDA', 'PGA', 'XXD', 'INS', '217', 'BHL', '16D', 'HSE', 'OPE', 'HCS', 'SOR', 'SKM', 'KIV', 'FCN', 'TRA', 'TRC', 'MTL', 'KDG', 'DHK', 'Ar', 'IOD', '35N', 'HGB', '3UQ', 'UNX', 'GSH', 'DGD', 'LMG', 'LMT', 'CAD', 'CUA', 'DMU', 'PEK', 'PGV', 'PSC', 'TGL', 'COO', 'BCR', 'XAT', 'MOE', 'P4C', 'PP9', 'Z0P', 'YZY', 'LMU', 'MLA', 'GAI', 'XE', 'ARS', 'SPM', 'RU8', 'B22', 'BEF', 'DHL', 'HG', 'MBO', 'ARC', 'OH', 'FES', 'RU', 'IAS', 'QPT', 'SR']) all_sets = [METAL_CONTAINING, STABILIZERS, BUFFERS, COFACTORS, COVALENT_MODS, FRAGMENTS, EXCIPIENTS, JUNK, DO_NOT_CALL] all_groups = {item for subset in all_sets for item in subset}
#!/usr/bin/env python # Copyright 2018 National Technology & Engineering Solutions of Sandia, LLC # (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. # Government retains certain rights in this software. class ResultsWriters: def __init__(self): "" self.writers = [] def addWriter(self, writer): "" self.writers.append( writer ) def prerun(self, atestlist, rtinfo, verbosity): "" for wr in self.writers: wr.prerun( atestlist, rtinfo, verbosity ) def midrun(self, atestlist, rtinfo): "" for wr in self.writers: wr.midrun( atestlist, rtinfo ) def postrun(self, atestlist, rtinfo): "" for wr in self.writers: wr.postrun( atestlist, rtinfo ) def info(self, atestlist, rtinfo): "" for wr in self.writers: wr.info( atestlist, rtinfo )
class Resultswriters: def __init__(self): """""" self.writers = [] def add_writer(self, writer): """""" self.writers.append(writer) def prerun(self, atestlist, rtinfo, verbosity): """""" for wr in self.writers: wr.prerun(atestlist, rtinfo, verbosity) def midrun(self, atestlist, rtinfo): """""" for wr in self.writers: wr.midrun(atestlist, rtinfo) def postrun(self, atestlist, rtinfo): """""" for wr in self.writers: wr.postrun(atestlist, rtinfo) def info(self, atestlist, rtinfo): """""" for wr in self.writers: wr.info(atestlist, rtinfo)
# -*- coding: utf-8 -*- """ Created on Tue Oct 30 00:36:25 2018 @author: Ja4rsPC """ x = int(input('Please input integer 1:' )) y = int(input('Please input integer 2: ')) def maxVAlue(m,n): if m>n or m==n: return m else: return n print(maxVAlue(x,y), ' Is greatest') #Scoping def f(x): y = 1 x = x + y print('x = ', x) return x x = 3 y = 2 z = f(x) print('z =', z) print('x =', x) print('y =', y)
""" Created on Tue Oct 30 00:36:25 2018 @author: Ja4rsPC """ x = int(input('Please input integer 1:')) y = int(input('Please input integer 2: ')) def max_v_alue(m, n): if m > n or m == n: return m else: return n print(max_v_alue(x, y), ' Is greatest') def f(x): y = 1 x = x + y print('x = ', x) return x x = 3 y = 2 z = f(x) print('z =', z) print('x =', x) print('y =', y)
n = int(input()) s = [] for i in range(n): s.append(input()) # [d1, d2, d3, ..., dN] m = [] a = [] r = [] c = [] h = [] for i in s: if i[0] == "M": m.append(i) elif i[0] == "A": a.append(i) elif i[0] == "R": r.append(i) elif i[0] == "C": c.append(i) elif i[0] == "H": h.append(i) ml = len(m) al = len(a) rl = len(r) cl = len(c) hl = len(h) count1 = ml*al*rl + ml*al*cl + ml*al*hl + ml*rl*cl + ml*rl*hl + ml*cl*hl + al*rl*cl + al*rl*hl + al*cl*hl + rl*cl*hl print(count1)
n = int(input()) s = [] for i in range(n): s.append(input()) m = [] a = [] r = [] c = [] h = [] for i in s: if i[0] == 'M': m.append(i) elif i[0] == 'A': a.append(i) elif i[0] == 'R': r.append(i) elif i[0] == 'C': c.append(i) elif i[0] == 'H': h.append(i) ml = len(m) al = len(a) rl = len(r) cl = len(c) hl = len(h) count1 = ml * al * rl + ml * al * cl + ml * al * hl + ml * rl * cl + ml * rl * hl + ml * cl * hl + al * rl * cl + al * rl * hl + al * cl * hl + rl * cl * hl print(count1)
""" Problem statement: We are given with N coins having value val_1 ... val_n , where n is even. We are playing a game with an opponent in alternating turns. In each particular turm one player selects one or last coin. We remove the coin from the row and get the value of the coin. Find the max possinle amoint of money one can win """ #Input: value in form of given sequence of coins #Output: Maximum value a player can win from the array of coins #Imp: N must be even def optimal_strategy(coin, N): #table to store sub problems storage = [[0 for i in range(N)] for i in range(N)] #Diagonal traversal for gap in range(N): for j in range(gap, N): i = j - gap x = 0 #option 1 : #choose ith coin with Vi value #now other player can choose between Vi+(F(i+2,j)) #or Vi+(F(i+1,j-1)) #take min of both if((i + 2) <= j): x = storage[i + 2][j] y = 0 #option 2 : #choose jth coin with Vj value #now other player can choose between Vi+(F(i+1,j-1)) #or Vi+(F(i,j-2)) #take min of both if((i + 1) <= (j - 1)): y = storage[i + 1][j - 1] z = 0 if(i <= (j - 2)): z = storage[i][j - 2] #store the maximum of all storage[i][j] = max(coin[i] + min(x, y), coin[j] + min(y, z)) #Output at storage[0][n01] return storage[0][N - 1] #input function def input_user(): arr = list(map(int,input("Enter the numbers:").strip().split(" "))) n = len(arr) print(optimal_strategy(arr, n)) if __name__ == "__main__": input_user()
""" Problem statement: We are given with N coins having value val_1 ... val_n , where n is even. We are playing a game with an opponent in alternating turns. In each particular turm one player selects one or last coin. We remove the coin from the row and get the value of the coin. Find the max possinle amoint of money one can win """ def optimal_strategy(coin, N): storage = [[0 for i in range(N)] for i in range(N)] for gap in range(N): for j in range(gap, N): i = j - gap x = 0 if i + 2 <= j: x = storage[i + 2][j] y = 0 if i + 1 <= j - 1: y = storage[i + 1][j - 1] z = 0 if i <= j - 2: z = storage[i][j - 2] storage[i][j] = max(coin[i] + min(x, y), coin[j] + min(y, z)) return storage[0][N - 1] def input_user(): arr = list(map(int, input('Enter the numbers:').strip().split(' '))) n = len(arr) print(optimal_strategy(arr, n)) if __name__ == '__main__': input_user()
# Section 9.3.2 snippets with open('accounts.txt', mode='r') as accounts: print(f'{"Account":<10}{"Name":<10}{"Balance":>10}') for record in accounts: account, name, balance = record.split() print(f'{account:<10}{name:<10}{balance:>10}') ########################################################################## # (C) Copyright 2019 by Deitel & Associates, Inc. and # # Pearson Education, Inc. All Rights Reserved. # # # # DISCLAIMER: The authors and publisher of this book have used their # # best efforts in preparing the book. These efforts include the # # development, research, and testing of the theories and programs # # to determine their effectiveness. The authors and publisher make # # no warranty of any kind, expressed or implied, with regard to these # # programs or to the documentation contained in these books. The authors # # and publisher shall not be liable in any event for incidental or # # consequential damages in connection with, or arising out of, the # # furnishing, performance, or use of these programs. # ##########################################################################
with open('accounts.txt', mode='r') as accounts: print(f"{'Account':<10}{'Name':<10}{'Balance':>10}") for record in accounts: (account, name, balance) = record.split() print(f'{account:<10}{name:<10}{balance:>10}')
"""Core module of the project.""" def add(x: int, y: int) -> int: """Add two int numbers.""" return x + y
"""Core module of the project.""" def add(x: int, y: int) -> int: """Add two int numbers.""" return x + y
"""misc utils for training neural networks""" class HyperParameterScheduler(object): def __init__(self, initial_val, num_updates, final_val=None, func='linear', gamma=0.999): """ Initialize HyperParameter Scheduler class :param initial_val: initial value of the hyper-parameter :param num_updates: total number of updates for hyper-parameter :param final_val: final value of the hyper-parameter, if None then decay rate is fixed (0.999 for exponential 0 for linear) :param func: decay type ['exponential', linear'] :param gamma: fixed decay rate for exponential decay (if final value is given then this gamma is ignored) """ self.initial_val = initial_val self.total_num_epoch = num_updates self.final_val = final_val self.cur_hp = self.initial_val self.cur_step = 0 if final_val is not None: assert final_val >= 0, 'final value should be positive' if func == "linear": self.hp_lambda = self.linear_scheduler elif func == "exponential": self.hp_lambda = self.exponential_scheduler if initial_val == final_val: self.gamma = 1 else: self.gamma = pow(final_val / initial_val, 1 / self.total_num_epoch) if final_val is not None else gamma else: raise NotImplementedError('scheduler not implemented') def linear_scheduler(self, epoch): if self.final_val is not None: return (self.final_val - self.initial_val)*(epoch/self.total_num_epoch) + self.initial_val else: return self.initial_val - (self.initial_val * (epoch / self.total_num_epoch)) def exponential_scheduler(self, epoch): return self.initial_val * (self.gamma ** epoch) def step(self, epoch=None): assert self.cur_step <= self.total_num_epoch, "scheduler step shouldn't be larger than total steps" if epoch is None: epoch = self.cur_step self.cur_hp = self.hp_lambda(epoch) self.cur_step += 1 return self.cur_hp @property def get_value(self): return self.cur_hp
"""misc utils for training neural networks""" class Hyperparameterscheduler(object): def __init__(self, initial_val, num_updates, final_val=None, func='linear', gamma=0.999): """ Initialize HyperParameter Scheduler class :param initial_val: initial value of the hyper-parameter :param num_updates: total number of updates for hyper-parameter :param final_val: final value of the hyper-parameter, if None then decay rate is fixed (0.999 for exponential 0 for linear) :param func: decay type ['exponential', linear'] :param gamma: fixed decay rate for exponential decay (if final value is given then this gamma is ignored) """ self.initial_val = initial_val self.total_num_epoch = num_updates self.final_val = final_val self.cur_hp = self.initial_val self.cur_step = 0 if final_val is not None: assert final_val >= 0, 'final value should be positive' if func == 'linear': self.hp_lambda = self.linear_scheduler elif func == 'exponential': self.hp_lambda = self.exponential_scheduler if initial_val == final_val: self.gamma = 1 else: self.gamma = pow(final_val / initial_val, 1 / self.total_num_epoch) if final_val is not None else gamma else: raise not_implemented_error('scheduler not implemented') def linear_scheduler(self, epoch): if self.final_val is not None: return (self.final_val - self.initial_val) * (epoch / self.total_num_epoch) + self.initial_val else: return self.initial_val - self.initial_val * (epoch / self.total_num_epoch) def exponential_scheduler(self, epoch): return self.initial_val * self.gamma ** epoch def step(self, epoch=None): assert self.cur_step <= self.total_num_epoch, "scheduler step shouldn't be larger than total steps" if epoch is None: epoch = self.cur_step self.cur_hp = self.hp_lambda(epoch) self.cur_step += 1 return self.cur_hp @property def get_value(self): return self.cur_hp
#Array of numbers numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] #Prints out every number in array for number in numbers: print(number) print('') #Adds 1 to every number in array for number in numbers: number += 20 print(number)
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for number in numbers: print(number) print('') for number in numbers: number += 20 print(number)
# Wrong answer 10% name = input() YESnames = [] NOnames = [] first = "" biggestName = 0 habay = "" while name != "FIM": name, choice = name.split() if choice == "YES": if first == "": first = name l = len(name) if biggestName < l: biggestName = l if name not in YESnames: YESnames.append(name) else: NOnames.append(name)
name = input() ye_snames = [] n_onames = [] first = '' biggest_name = 0 habay = '' while name != 'FIM': (name, choice) = name.split() if choice == 'YES': if first == '': first = name l = len(name) if biggestName < l: biggest_name = l if name not in YESnames: YESnames.append(name) else: NOnames.append(name)
# -*- coding: utf-8 -*- __author__ = 'Huang, Hua' class CSV: def __init__(self, csv_line, sep): self.csv_line = csv_line self.content_list = csv_line.split(sep) if csv_line and isinstance(csv_line, str) else None def get_property(self, ind): if self.content_list and len(self.content_list) > ind: return self.content_list[ind] return None def is_object_valid(self, cls): if hasattr(cls, 'not_null_attrs'): for attr in getattr(cls, 'not_null_attrs'): if not hasattr(self, attr) or not getattr(self, attr): return False return True class FunctionDesc: """ python class mapping to org.apache.kylin.metadata.model.FunctionDesc """ def __init__(self): self.expression = None self.parameter = None self.returntype = None @staticmethod def from_json(json_dict): if not json_dict or type(json_dict) != dict: return None fd = FunctionDesc() fd.expression = json_dict.get('expression') # deserialize json for parameter fd.parameter = ParameterDesc.from_json(json_dict.get('parameter')) fd.returntype = json_dict.get('returntype') return fd class ParameterDesc: """ python class mapping to org.apache.kylin.metadata.model.ParameterDesc """ def __init__(self): self.type = None self.value = None @staticmethod def from_json(json_dict): if not json_dict or type(json_dict) != dict: return None pd = ParameterDesc() pd.type = json_dict.get('type') pd.value = json_dict.get('value') return pd
__author__ = 'Huang, Hua' class Csv: def __init__(self, csv_line, sep): self.csv_line = csv_line self.content_list = csv_line.split(sep) if csv_line and isinstance(csv_line, str) else None def get_property(self, ind): if self.content_list and len(self.content_list) > ind: return self.content_list[ind] return None def is_object_valid(self, cls): if hasattr(cls, 'not_null_attrs'): for attr in getattr(cls, 'not_null_attrs'): if not hasattr(self, attr) or not getattr(self, attr): return False return True class Functiondesc: """ python class mapping to org.apache.kylin.metadata.model.FunctionDesc """ def __init__(self): self.expression = None self.parameter = None self.returntype = None @staticmethod def from_json(json_dict): if not json_dict or type(json_dict) != dict: return None fd = function_desc() fd.expression = json_dict.get('expression') fd.parameter = ParameterDesc.from_json(json_dict.get('parameter')) fd.returntype = json_dict.get('returntype') return fd class Parameterdesc: """ python class mapping to org.apache.kylin.metadata.model.ParameterDesc """ def __init__(self): self.type = None self.value = None @staticmethod def from_json(json_dict): if not json_dict or type(json_dict) != dict: return None pd = parameter_desc() pd.type = json_dict.get('type') pd.value = json_dict.get('value') return pd
pi = { "00": { "value": "00", "description": "Base" }, "02": { "value": "02", "description": "POS" } }
pi = {'00': {'value': '00', 'description': 'Base'}, '02': {'value': '02', 'description': 'POS'}}
class IntervalSchedulingInterval: """interval to schedule in interval scheduling""" def __init__(self, name: str, start_time: int, end_time: int): self.name = name self.start_time = start_time self.end_time = end_time def __repr__(self) -> str: return f"{self.name}({self.start_time}, {self.end_time})" def interval_scheduling(intervals: list[IntervalSchedulingInterval]) -> list[IntervalSchedulingInterval]: """computes biggest set of compatible intervals :param intervals: all available intervals :return: the biggest set of compatible intervals """ sorted_intervals = intervals.copy() sorted_intervals.sort(key=lambda i: i.start_time) selected_intervals = [] while sorted_intervals: new_interval = sorted_intervals.pop(0) selected_intervals.append(new_interval) for interval in sorted_intervals: if new_interval.start_time <= interval.start_time < new_interval.end_time: sorted_intervals.remove(interval) continue if new_interval.start_time < interval.end_time <= new_interval.end_time: sorted_intervals.remove(interval) continue if interval.start_time < new_interval.start_time and new_interval.end_time < interval.end_time: sorted_intervals.remove(interval) return selected_intervals
class Intervalschedulinginterval: """interval to schedule in interval scheduling""" def __init__(self, name: str, start_time: int, end_time: int): self.name = name self.start_time = start_time self.end_time = end_time def __repr__(self) -> str: return f'{self.name}({self.start_time}, {self.end_time})' def interval_scheduling(intervals: list[IntervalSchedulingInterval]) -> list[IntervalSchedulingInterval]: """computes biggest set of compatible intervals :param intervals: all available intervals :return: the biggest set of compatible intervals """ sorted_intervals = intervals.copy() sorted_intervals.sort(key=lambda i: i.start_time) selected_intervals = [] while sorted_intervals: new_interval = sorted_intervals.pop(0) selected_intervals.append(new_interval) for interval in sorted_intervals: if new_interval.start_time <= interval.start_time < new_interval.end_time: sorted_intervals.remove(interval) continue if new_interval.start_time < interval.end_time <= new_interval.end_time: sorted_intervals.remove(interval) continue if interval.start_time < new_interval.start_time and new_interval.end_time < interval.end_time: sorted_intervals.remove(interval) return selected_intervals
#decorators for functions def audio_record_thread(func): def inner(s): print("AudioCapture: Started Recording Audio") func(s) print("AudioCapture: Stopped Recording Audio") return return inner def file_saving(func, filename): def wrap(s, filename): print("Saving file...") func(s, filename) print("File saved") return return wrap
def audio_record_thread(func): def inner(s): print('AudioCapture: Started Recording Audio') func(s) print('AudioCapture: Stopped Recording Audio') return return inner def file_saving(func, filename): def wrap(s, filename): print('Saving file...') func(s, filename) print('File saved') return return wrap
# -*- coding: utf-8 -*- """ ----------Phenix Labs---------- Created on Sat Jan 23 23:47:00 2021 @author: Gyan Krishna Topic: """ n = 6 #pattern 1 for i in range(n): for j in range(n-i): print("", end=" ") for j in range(i): print("*", end=" ") print("") print("\n\n") #pattern 2 curr = [] prev = [1] for i in range(n): print("", end=" ") print(1) for i in range(1,n): curr = [1] for j in range(1,i): curr.append(prev[j]+ prev[j-1]) curr.append(1) prev = curr for i in range(n-i): print("", end=" ") for i in curr: print(i, end=" ") print("") print("\n\n") #pattern 3 text = "ABCD" for i in range(len(text)+1): print(text[0:i]) print("\n\n") #pattern 4 for i in range(n): for j in range(n-i): print("", end=" ") for j in range(i): print("*", end=" ") print("") for i in range(n,0,-1): for j in range(n-i): print("", end=" ") for j in range(i): print("*", end=" ") print("") print("\n\n") #pattern 5: for i in range(n,0,-1): for j in range(n-i): print("", end=" ") for j in range(i): print("*", end=" ") print("") for i in range(n): for j in range(n-i): print("", end=" ") for j in range(i): print("*", end=" ") print("")
""" ----------Phenix Labs---------- Created on Sat Jan 23 23:47:00 2021 @author: Gyan Krishna Topic: """ n = 6 for i in range(n): for j in range(n - i): print('', end=' ') for j in range(i): print('*', end=' ') print('') print('\n\n') curr = [] prev = [1] for i in range(n): print('', end=' ') print(1) for i in range(1, n): curr = [1] for j in range(1, i): curr.append(prev[j] + prev[j - 1]) curr.append(1) prev = curr for i in range(n - i): print('', end=' ') for i in curr: print(i, end=' ') print('') print('\n\n') text = 'ABCD' for i in range(len(text) + 1): print(text[0:i]) print('\n\n') for i in range(n): for j in range(n - i): print('', end=' ') for j in range(i): print('*', end=' ') print('') for i in range(n, 0, -1): for j in range(n - i): print('', end=' ') for j in range(i): print('*', end=' ') print('') print('\n\n') for i in range(n, 0, -1): for j in range(n - i): print('', end=' ') for j in range(i): print('*', end=' ') print('') for i in range(n): for j in range(n - i): print('', end=' ') for j in range(i): print('*', end=' ') print('')
# In case of ASCII horror, # need to get rid of this in the future. def ascii_saver(s): try: s = s.encode('ascii', errors='ignore') except: print('ascii cannot save', s) return s
def ascii_saver(s): try: s = s.encode('ascii', errors='ignore') except: print('ascii cannot save', s) return s
''' Python program to round a fl oating-point number to specifi ednumber decimal places ''' #Sample Solution-1: def setListOfIntegerOptionOne (order_amt): print('\nThe total order amount comes to %f' % float(order_amt)) print('The total order amount comes to %.2f' % float(order_amt)) print() def setListOfIntegerOptionTwo (order_amt): print("\nThe total order amount comes to {:0.6f}".format(float(order_amt))) print("\nThe total order amount comes to {:0.2f}".format(float(order_amt))) def main (): inpOption = int (input ("Select options one of the options : |1|2|\n")) impNumber = float (input ("Input a number")) #Use dictionary instead of switch case selection = { 1 : setListOfIntegerOptionOne, 2 : setListOfIntegerOptionTwo, } for key in selection: if key == inpOption: selection[key](impNumber) break main ()
""" Python program to round a fl oating-point number to specifi ednumber decimal places """ def set_list_of_integer_option_one(order_amt): print('\nThe total order amount comes to %f' % float(order_amt)) print('The total order amount comes to %.2f' % float(order_amt)) print() def set_list_of_integer_option_two(order_amt): print('\nThe total order amount comes to {:0.6f}'.format(float(order_amt))) print('\nThe total order amount comes to {:0.2f}'.format(float(order_amt))) def main(): inp_option = int(input('Select options one of the options : |1|2|\n')) imp_number = float(input('Input a number')) selection = {1: setListOfIntegerOptionOne, 2: setListOfIntegerOptionTwo} for key in selection: if key == inpOption: selection[key](impNumber) break main()
# -*- coding: utf-8 -*- """ Created on Thu Jan 16 11:07:19 2020 @author: 766810 """ x=int(input('Enter number 1: ')) y=int(input('Enter number 2: ')) sum1=0 sum2=0 for i in range(1,x): if x%i==0: sum1+=i for j in range(1,y): if y%j==0: sum2+=j if(sum1==y and sum2==x): print('Amicable!') else: print('Not Amicable!')
""" Created on Thu Jan 16 11:07:19 2020 @author: 766810 """ x = int(input('Enter number 1: ')) y = int(input('Enter number 2: ')) sum1 = 0 sum2 = 0 for i in range(1, x): if x % i == 0: sum1 += i for j in range(1, y): if y % j == 0: sum2 += j if sum1 == y and sum2 == x: print('Amicable!') else: print('Not Amicable!')
class Solution(object): def lengthLongestPath(self, input): """ :type input: str :rtype: int """ maxLen = 0 curLen = 0 stack = [] dfa = {"init": 0, "char": 1, "escapeCMD": 2, "file": 3} state = 0 start = 0 level = 0 for i in xrange(0, len(input)): chr = input[i] if chr == '\n': curLen = 0 if len(stack) == 0 else stack[-1][1] if state == dfa["char"]: curLen += i - start stack.append((input[start:i], curLen + 1, level)) elif state == dfa["file"]: maxLen = max(maxLen, curLen + (i - start)) else: return -1 state = dfa["escapeCMD"] level = 0 elif chr == '\t': if state == dfa["escapeCMD"]: level += 1 else: return "TAB cannot be here" elif chr == '.': if state == dfa["char"] or state == dfa["file"] or state == dfa["escapeCMD"]: state = dfa["file"] else: return "unexpected char before dot", state else: if state == dfa["escapeCMD"]: while stack and stack[-1][2] >= level: stack.pop() start = i state = dfa["char"] elif state == dfa["init"]: state = dfa["char"] elif i == len(input) - 1: curLen = 0 if len(stack) == 0 else stack[-1][1] maxLen = max(maxLen, curLen + (i - start) + 1) # print 'state:', state # print 'stack:', stack # print 'level', level return maxLen
class Solution(object): def length_longest_path(self, input): """ :type input: str :rtype: int """ max_len = 0 cur_len = 0 stack = [] dfa = {'init': 0, 'char': 1, 'escapeCMD': 2, 'file': 3} state = 0 start = 0 level = 0 for i in xrange(0, len(input)): chr = input[i] if chr == '\n': cur_len = 0 if len(stack) == 0 else stack[-1][1] if state == dfa['char']: cur_len += i - start stack.append((input[start:i], curLen + 1, level)) elif state == dfa['file']: max_len = max(maxLen, curLen + (i - start)) else: return -1 state = dfa['escapeCMD'] level = 0 elif chr == '\t': if state == dfa['escapeCMD']: level += 1 else: return 'TAB cannot be here' elif chr == '.': if state == dfa['char'] or state == dfa['file'] or state == dfa['escapeCMD']: state = dfa['file'] else: return ('unexpected char before dot', state) elif state == dfa['escapeCMD']: while stack and stack[-1][2] >= level: stack.pop() start = i state = dfa['char'] elif state == dfa['init']: state = dfa['char'] elif i == len(input) - 1: cur_len = 0 if len(stack) == 0 else stack[-1][1] max_len = max(maxLen, curLen + (i - start) + 1) return maxLen
class PermissionsMixin: @classmethod def get_permissions(cls, info): return [permission(info) for permission in cls._meta.permission_classes] @classmethod def check_permissions(cls, info): for permission in cls.get_permissions(info): if not permission.has_permission(): raise PermissionError('Permission denied.')
class Permissionsmixin: @classmethod def get_permissions(cls, info): return [permission(info) for permission in cls._meta.permission_classes] @classmethod def check_permissions(cls, info): for permission in cls.get_permissions(info): if not permission.has_permission(): raise permission_error('Permission denied.')
""" Project version and meta informations. """ __version__ = "0.3.6dev2" __title__ = "msiempy" __description__ = "msiempy - McAfee SIEM API Python wrapper" __author__ = "andywalden, tristanlatr, mathieubeland, and other contributors. " __author_email__ = "" __license__ = "The MIT License" __url__ = "https://github.com/mfesiem/msiempy" __keywords__ = "mcafee siem api python wrapper"
""" Project version and meta informations. """ __version__ = '0.3.6dev2' __title__ = 'msiempy' __description__ = 'msiempy - McAfee SIEM API Python wrapper' __author__ = 'andywalden, tristanlatr, mathieubeland, and other contributors. ' __author_email__ = '' __license__ = 'The MIT License' __url__ = 'https://github.com/mfesiem/msiempy' __keywords__ = 'mcafee siem api python wrapper'
def bs(arr,target,s,e): if (s>e): return -1 m= int((s+e)/2) if arr[m]==target: return m elif target>arr[m]: return bs(arr,target,m+1,e) else: return bs(arr,target,s,m-1) if __name__ == "__main__": l1=[1, 2, 3, 4, 55, 66, 78] target = 67 print(bs(l1,target,0,len(l1)-1))
def bs(arr, target, s, e): if s > e: return -1 m = int((s + e) / 2) if arr[m] == target: return m elif target > arr[m]: return bs(arr, target, m + 1, e) else: return bs(arr, target, s, m - 1) if __name__ == '__main__': l1 = [1, 2, 3, 4, 55, 66, 78] target = 67 print(bs(l1, target, 0, len(l1) - 1))
#!/usr/bin/env python # Copyright Contributors to the Open Shading Language project. # SPDX-License-Identifier: BSD-3-Clause # https://github.com/AcademySoftwareFoundation/OpenShadingLanguage command += testshade("-g 16 16 -od uint8 -o Cout out0.tif wrcloud") command += testshade("-g 16 16 -od uint8 -o Cout out0_transpose.tif wrcloud_transpose") command += testshade("-g 16 16 -od uint8 -o Cout out0_varying_filename.tif wrcloud_varying_filename") command += testshade("-g 256 256 -param radius 0.01 -od uint8 -o Cout out1.tif rdcloud") command += testshade("-g 256 256 -param radius 0.01 -param filename cloud_masked_1.geo -od uint8 -o Cout out1_masked_1.tif rdcloud") command += testshade("-g 256 256 -param radius 0.01 -param filename cloud_masked_2.geo -od uint8 -o Cout out1_masked_2.tif rdcloud") command += testshade("--vary_pdxdy -g 256 256 -t 1 -param radius 0.01 -od uint8 -o Cout out_zero_derivs.tif rdcloud_zero_derivs") command += testshade("--vary_pdxdy -g 256 256 -t 1 -param radius 0.01 -od uint8 -o Cout out_zero_derivs_search_only.tif rdcloud_zero_derivs_search_only") command += testshade("--vary_pdxdy -g 256 256 -t 1 -param radius 0.01 -od uint8 -o Cout out_search_only.tif rdcloud_search_only") command += testshade("-g 256 256 -param radius 0.1 -od uint8 -o Cout out2.tif rdcloud") command += testshade("--vary_pdxdy -g 256 256 -t 1 -param radius 0.01 -od uint8 -o Cout out_rdcloud_varying_filename.tif rdcloud_varying_filename") command += testshade("--center --vary_pdxdy -g 256 256 -t 1 -param radius 0.1 -od uint8 -o Cout out_rdcloud_varying_maxpoint.tif rdcloud_varying_maxpoint") command += testshade("--center --vary_pdxdy -g 256 256 -t 1 -param radius 0.1 -od uint8 -o Cout out_rdcloud_varying_sort.tif rdcloud_varying_sort") command += testshade("--vary_pdxdy -g 256 256 -t 1 -param radius 0.01 -od uint8 -o Cout out_rdcloud_get_varying_filename.tif rdcloud_get_varying_filename") command += testshade("--center --vary_pdxdy -g 256 256 -t 1 -param radius 0.1 -od uint8 -o Cout out_rdcloud_varying.tif rdcloud_varying") outputs = [ "out0.tif" ] outputs += [ "out0_transpose.tif" ] outputs += [ "out0_varying_filename.tif" ] outputs += [ "out1.tif" ] outputs += [ "out1_masked_1.tif" ] outputs += [ "out1_masked_2.tif" ] outputs += [ "out_zero_derivs.tif" ] outputs += [ "out_search_only.tif" ] outputs += [ "out_zero_derivs_search_only.tif" ] outputs += [ "out2.tif" ] outputs += [ "out_rdcloud_varying_filename.tif" ] outputs += [ "out_rdcloud_varying_maxpoint.tif" ] outputs += [ "out_rdcloud_varying_sort.tif" ] outputs += [ "out_rdcloud_varying.tif" ] outputs += [ "out_rdcloud_get_varying_filename.tif" ] # expect a few LSB failures failthresh = 0.008 failpercent = 3
command += testshade('-g 16 16 -od uint8 -o Cout out0.tif wrcloud') command += testshade('-g 16 16 -od uint8 -o Cout out0_transpose.tif wrcloud_transpose') command += testshade('-g 16 16 -od uint8 -o Cout out0_varying_filename.tif wrcloud_varying_filename') command += testshade('-g 256 256 -param radius 0.01 -od uint8 -o Cout out1.tif rdcloud') command += testshade('-g 256 256 -param radius 0.01 -param filename cloud_masked_1.geo -od uint8 -o Cout out1_masked_1.tif rdcloud') command += testshade('-g 256 256 -param radius 0.01 -param filename cloud_masked_2.geo -od uint8 -o Cout out1_masked_2.tif rdcloud') command += testshade('--vary_pdxdy -g 256 256 -t 1 -param radius 0.01 -od uint8 -o Cout out_zero_derivs.tif rdcloud_zero_derivs') command += testshade('--vary_pdxdy -g 256 256 -t 1 -param radius 0.01 -od uint8 -o Cout out_zero_derivs_search_only.tif rdcloud_zero_derivs_search_only') command += testshade('--vary_pdxdy -g 256 256 -t 1 -param radius 0.01 -od uint8 -o Cout out_search_only.tif rdcloud_search_only') command += testshade('-g 256 256 -param radius 0.1 -od uint8 -o Cout out2.tif rdcloud') command += testshade('--vary_pdxdy -g 256 256 -t 1 -param radius 0.01 -od uint8 -o Cout out_rdcloud_varying_filename.tif rdcloud_varying_filename') command += testshade('--center --vary_pdxdy -g 256 256 -t 1 -param radius 0.1 -od uint8 -o Cout out_rdcloud_varying_maxpoint.tif rdcloud_varying_maxpoint') command += testshade('--center --vary_pdxdy -g 256 256 -t 1 -param radius 0.1 -od uint8 -o Cout out_rdcloud_varying_sort.tif rdcloud_varying_sort') command += testshade('--vary_pdxdy -g 256 256 -t 1 -param radius 0.01 -od uint8 -o Cout out_rdcloud_get_varying_filename.tif rdcloud_get_varying_filename') command += testshade('--center --vary_pdxdy -g 256 256 -t 1 -param radius 0.1 -od uint8 -o Cout out_rdcloud_varying.tif rdcloud_varying') outputs = ['out0.tif'] outputs += ['out0_transpose.tif'] outputs += ['out0_varying_filename.tif'] outputs += ['out1.tif'] outputs += ['out1_masked_1.tif'] outputs += ['out1_masked_2.tif'] outputs += ['out_zero_derivs.tif'] outputs += ['out_search_only.tif'] outputs += ['out_zero_derivs_search_only.tif'] outputs += ['out2.tif'] outputs += ['out_rdcloud_varying_filename.tif'] outputs += ['out_rdcloud_varying_maxpoint.tif'] outputs += ['out_rdcloud_varying_sort.tif'] outputs += ['out_rdcloud_varying.tif'] outputs += ['out_rdcloud_get_varying_filename.tif'] failthresh = 0.008 failpercent = 3
PARAM_DESCR = { 'epochs': 'How many epochs to train.', 'learning rate': 'Optimizer learning rate.', 'batch size': 'The number of samples to use in one training batch.', 'decay': 'Learning rate decay.', 'early stopping': 'Early stopping delta and patience.', 'dropout': 'Dropout rate.', 'layers': 'The number of hidden layers.', 'optimizer': 'Which optimizer to use.' } LONG_DESCR = { 'learning rate': 'A hyperparameter which determines how quickly new learnings override old ones during training. In general, find a learning rate that is low enough that the network will converge to something useful, but high enough that the training does not take too much time.', 'batch size': 'Defines the number of samples to be propagated through the network at once in a batch. The higher the batch size, the more memory you will need.', 'epochs': 'The number of epochs define how often the network will see the complete set of samples during training.', 'decay': 'When using learning rate decay, the learning rate is gradually reduced during training which may result in getting closer to the optimal performance.', 'early stopping': 'Early Stopping is a form of regularization used to avoid overfitting when training. It is controlled via two parameters: Delta defines the minimum change in the monitored quantity to qualify as an improvement. Patience sets the number of epochs with no improvement after which training will be stopped.', 'dropout': 'Dropout is a regularization technique for reducing overfitting in neural networks, The term "dropout" refers to dropping out units (both hidden and visible) in a neural network during training.', 'layers': 'Deep learning models consist of a number of layers which contain one or more neurons. Typically, the neurons in one layer are connected to the next. Models with a higher number of layers can learn more complex representations, but are also more prone to overfitting.', 'optimizer': 'The algorithm which updates model parameters such as the weight and bias values when training the network.', 'sgd': 'Stochastic gradient descent, also known as incremental gradient descent, is a method for optimizing a neural network. It is called stochastic because samples are selected randomly instead of as a single group, as in standard gradient descent.', 'adam': 'The Adam optimization algorithm is an extension to stochastic gradient descent which computes adaptive learning rates for each parameter. Adam is well suited for many practical deep learning problems.', 'environment variables': """\ The following environment variables are available in VergeML: - VERGEML_PERSISTENCE The number of persistent instances - VERGEML_THEME The theme of the command line application - VERGEML_FUNKY_ROBOTS Funky robots""", "overfitting": "When a model performs well on the training samples, but is not able to generalize well to unseen data. During training, a typical sign for overfitting is when your validation loss goes up while your training loss goes down.", "underfitting": "When a model can neither model the training data nor generalize to new data.", "hyperparameters": "Hyperparameters are the parameters of a model that can be set from outside, i.e. are not learned during training. (e.g. learning rate, number of layers, kernel size).", "random seed": "An integer value that seeds the random generator to generate random values. It is used to repeatably reproduce tasks and experiments.", "project": "A VergeML project is just a directory. Typically it contains a vergeml.yaml file, a trainings directory and a samples directory.", 'project file': "A YAML file you can use to configure models, device usage, data processing and taks options.", 'checkpoint': 'A checkpoint is a static image of a trained AI. It can be used to restore the AI after training and make predictions.', 'stats': 'Stats are used to measure the performance of a model (e.g. accuracy).', 'samples': 'Samples are pieces of data (e.g. images, texts) that is being used to train models to create AIs.', 'val split': "Samples different from training samples that are used to evaluate the performance of model hyperparameters. You can set it via the --val-split option. See 'ml help split'.", 'test split': "Samples different from training samples that are used to evaluate the final performance of the model. You can set it via the --test-split option. See 'ml help split'.", 'split': 'split is a part of the sample data reserved for validation and testing (--val-split and --test-split options). It can be configured as either a percentage value (e.g. --val-split=10%) to reserve a fraction of training samples, a number to reserve a fixed number of samples, or a directory where the samples of the split are stored.', 'cache dir': 'A directory which contains the processed data.', } SYNONYMS = { 'stochastic gradient descent': 'sgd', 'hyperparameter': 'hyperparameters', 'project dir': 'project', 'training samples': 'samples', 'overfit': 'overfitting', 'underfit': 'underfitting' } def long_descr(key): key = key.replace("-", " ") key = SYNONYMS.get(key, key) return LONG_DESCR.get(key, "").strip() def short_param_descr(key): key = key.replace("-", " ") key = SYNONYMS.get(key, key) return PARAM_DESCR.get(key, "").strip()
param_descr = {'epochs': 'How many epochs to train.', 'learning rate': 'Optimizer learning rate.', 'batch size': 'The number of samples to use in one training batch.', 'decay': 'Learning rate decay.', 'early stopping': 'Early stopping delta and patience.', 'dropout': 'Dropout rate.', 'layers': 'The number of hidden layers.', 'optimizer': 'Which optimizer to use.'} long_descr = {'learning rate': 'A hyperparameter which determines how quickly new learnings override old ones during training. In general, find a learning rate that is low enough that the network will converge to something useful, but high enough that the training does not take too much time.', 'batch size': 'Defines the number of samples to be propagated through the network at once in a batch. The higher the batch size, the more memory you will need.', 'epochs': 'The number of epochs define how often the network will see the complete set of samples during training.', 'decay': 'When using learning rate decay, the learning rate is gradually reduced during training which may result in getting closer to the optimal performance.', 'early stopping': 'Early Stopping is a form of regularization used to avoid overfitting when training. It is controlled via two parameters: Delta defines the minimum change in the monitored quantity to qualify as an improvement. Patience sets the number of epochs with no improvement after which training will be stopped.', 'dropout': 'Dropout is a regularization technique for reducing overfitting in neural networks, The term "dropout" refers to dropping out units (both hidden and visible) in a neural network during training.', 'layers': 'Deep learning models consist of a number of layers which contain one or more neurons. Typically, the neurons in one layer are connected to the next. Models with a higher number of layers can learn more complex representations, but are also more prone to overfitting.', 'optimizer': 'The algorithm which updates model parameters such as the weight and bias values when training the network.', 'sgd': 'Stochastic gradient descent, also known as incremental gradient descent, is a method for optimizing a neural network. It is called stochastic because samples are selected randomly instead of as a single group, as in standard gradient descent.', 'adam': 'The Adam optimization algorithm is an extension to stochastic gradient descent which computes adaptive learning rates for each parameter. Adam is well suited for many practical deep learning problems.', 'environment variables': 'The following environment variables are available in VergeML:\n- VERGEML_PERSISTENCE The number of persistent instances\n- VERGEML_THEME The theme of the command line application\n- VERGEML_FUNKY_ROBOTS Funky robots', 'overfitting': 'When a model performs well on the training samples, but is not able to generalize well to unseen data. During training, a typical sign for overfitting is when your validation loss goes up while your training loss goes down.', 'underfitting': 'When a model can neither model the training data nor generalize to new data.', 'hyperparameters': 'Hyperparameters are the parameters of a model that can be set from outside, i.e. are not learned during training. (e.g. learning rate, number of layers, kernel size).', 'random seed': 'An integer value that seeds the random generator to generate random values. It is used to repeatably reproduce tasks and experiments.', 'project': 'A VergeML project is just a directory. Typically it contains a vergeml.yaml file, a trainings directory and a samples directory.', 'project file': 'A YAML file you can use to configure models, device usage, data processing and taks options.', 'checkpoint': 'A checkpoint is a static image of a trained AI. It can be used to restore the AI after training and make predictions.', 'stats': 'Stats are used to measure the performance of a model (e.g. accuracy).', 'samples': 'Samples are pieces of data (e.g. images, texts) that is being used to train models to create AIs.', 'val split': "Samples different from training samples that are used to evaluate the performance of model hyperparameters. You can set it via the --val-split option. See 'ml help split'.", 'test split': "Samples different from training samples that are used to evaluate the final performance of the model. You can set it via the --test-split option. See 'ml help split'.", 'split': 'split is a part of the sample data reserved for validation and testing (--val-split and --test-split options). It can be configured as either a percentage value (e.g. --val-split=10%) to reserve a fraction of training samples, a number to reserve a fixed number of samples, or a directory where the samples of the split are stored.', 'cache dir': 'A directory which contains the processed data.'} synonyms = {'stochastic gradient descent': 'sgd', 'hyperparameter': 'hyperparameters', 'project dir': 'project', 'training samples': 'samples', 'overfit': 'overfitting', 'underfit': 'underfitting'} def long_descr(key): key = key.replace('-', ' ') key = SYNONYMS.get(key, key) return LONG_DESCR.get(key, '').strip() def short_param_descr(key): key = key.replace('-', ' ') key = SYNONYMS.get(key, key) return PARAM_DESCR.get(key, '').strip()
"""Problem 2 - Paying Debt Off in a Year Now write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. By a fixed monthly payment, we mean a single number which does not change each month, but instead is a constant amount that will be paid each month. In this problem, we will not be dealing with a minimum monthly payment rate. The following variables contain values as described below: balance - the outstanding balance on the credit card annualInterestRate - annual interest rate as a decimal The program should print out one line: the lowest monthly payment that will pay off all debt in under 1 year, for example: Lowest Payment: 180 Assume that the interest is compounded monthly according to the balance at the end of the month (after the payment for that month is made). The monthly payment must be a multiple of $10 and is the same for all months. Notice that it is possible for the balance to become negative using this payment scheme, which is okay. A summary of the required math is found below: Monthly interest rate = (Annual interest rate) / 12.0 Monthly unpaid balance = (Previous balance) - (Minimum fixed monthly payment) Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance) """ def estimateRemainingBalance(balance, annualInterestRate, monthlyPaymentRate): monthlyUnpaidBalance = balance interest = 0 for i in range(13): if i > 0: balance = monthlyUnpaidBalance + interest pass monthlyUnpaidBalance = balance - monthlyPaymentRate interest = annualInterestRate/12 * monthlyUnpaidBalance return round(balance, 2) def estimateLowestPayment(balance, annualInterestRate, monthlyPaymentRate): monthlyPayment = monthlyPaymentRate while estimateRemainingBalance(balance, annualInterestRate, monthlyPayment) > 0: monthlyPayment += 10 print('Lowest Payment: ', monthlyPayment) return monthlyPayment
"""Problem 2 - Paying Debt Off in a Year Now write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. By a fixed monthly payment, we mean a single number which does not change each month, but instead is a constant amount that will be paid each month. In this problem, we will not be dealing with a minimum monthly payment rate. The following variables contain values as described below: balance - the outstanding balance on the credit card annualInterestRate - annual interest rate as a decimal The program should print out one line: the lowest monthly payment that will pay off all debt in under 1 year, for example: Lowest Payment: 180 Assume that the interest is compounded monthly according to the balance at the end of the month (after the payment for that month is made). The monthly payment must be a multiple of $10 and is the same for all months. Notice that it is possible for the balance to become negative using this payment scheme, which is okay. A summary of the required math is found below: Monthly interest rate = (Annual interest rate) / 12.0 Monthly unpaid balance = (Previous balance) - (Minimum fixed monthly payment) Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance) """ def estimate_remaining_balance(balance, annualInterestRate, monthlyPaymentRate): monthly_unpaid_balance = balance interest = 0 for i in range(13): if i > 0: balance = monthlyUnpaidBalance + interest pass monthly_unpaid_balance = balance - monthlyPaymentRate interest = annualInterestRate / 12 * monthlyUnpaidBalance return round(balance, 2) def estimate_lowest_payment(balance, annualInterestRate, monthlyPaymentRate): monthly_payment = monthlyPaymentRate while estimate_remaining_balance(balance, annualInterestRate, monthlyPayment) > 0: monthly_payment += 10 print('Lowest Payment: ', monthlyPayment) return monthlyPayment
def username_generator(first,last): counter = 0 username = "" for i in first: if counter <= 2: counter += 1 username += i counter = 0 for j in last: if counter <= 3: counter += 1 username += j return username def password_generator(username="testin"): password = "" counter = 0 for i in username: password += username[counter -1] counter += 1 return password print(password_generator())
def username_generator(first, last): counter = 0 username = '' for i in first: if counter <= 2: counter += 1 username += i counter = 0 for j in last: if counter <= 3: counter += 1 username += j return username def password_generator(username='testin'): password = '' counter = 0 for i in username: password += username[counter - 1] counter += 1 return password print(password_generator())
# -*- coding: utf-8 -*- class Controller(object): def __init__(self, router, view): self.router = router self.view = view def show(self): if self.view: self.view.show() else: raise Exception("None view") def hide(self): if self.view: self.view.hide() else: raise Exception("None view") def go(self, ctrl_name, hide_self=True): self.router.go(ctrl_name) if hide_self: self.hide()
class Controller(object): def __init__(self, router, view): self.router = router self.view = view def show(self): if self.view: self.view.show() else: raise exception('None view') def hide(self): if self.view: self.view.hide() else: raise exception('None view') def go(self, ctrl_name, hide_self=True): self.router.go(ctrl_name) if hide_self: self.hide()
def geometric_eq(p,k): return (1-p)**k*p class GeometricDist: def __init__(self,p): self.p = p self.mean = (1-p)/p self.var = (1-p)/p**2 def __getitem__(self,k): return geometric_eq(self.p,k)
def geometric_eq(p, k): return (1 - p) ** k * p class Geometricdist: def __init__(self, p): self.p = p self.mean = (1 - p) / p self.var = (1 - p) / p ** 2 def __getitem__(self, k): return geometric_eq(self.p, k)
class letterCombinations: def letterCombinationsFn(self, digits: str) -> List[str]: # If the input is empty, immediately return an empty answer array if len(digits) == 0: return [] # Map all the digits to their corresponding letters letters = {"2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"} def backtrack(index, path): # If the path is the same length as digits, we have a complete combination if len(path) == len(digits): combinations.append("".join(path)) return # Backtrack # Get the letters that the current digit maps to, and loop through them possible_letters = letters[digits[index]] for letter in possible_letters: # Add the letter to our current path path.append(letter) # Move on to the next digit backtrack(index + 1, path) # Backtrack by removing the letter before moving onto the next path.pop() # Initiate backtracking with an empty path and starting index of 0 combinations = [] backtrack(0, []) return combinations
class Lettercombinations: def letter_combinations_fn(self, digits: str) -> List[str]: if len(digits) == 0: return [] letters = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'} def backtrack(index, path): if len(path) == len(digits): combinations.append(''.join(path)) return possible_letters = letters[digits[index]] for letter in possible_letters: path.append(letter) backtrack(index + 1, path) path.pop() combinations = [] backtrack(0, []) return combinations
class Solution: def uniquePaths(self, m: int, n: int) -> int: dp = [[0]*n for i in range(m)] for i in range(m): dp[i][n-1] = 1 for i in range(n): dp[m-1][i] = 1 for i in range(m-2,-1,-1): for j in range(n-2,-1,-1): dp[i][j] = dp[i+1][j] + dp[i][j+1] return dp[0][0]
class Solution: def unique_paths(self, m: int, n: int) -> int: dp = [[0] * n for i in range(m)] for i in range(m): dp[i][n - 1] = 1 for i in range(n): dp[m - 1][i] = 1 for i in range(m - 2, -1, -1): for j in range(n - 2, -1, -1): dp[i][j] = dp[i + 1][j] + dp[i][j + 1] return dp[0][0]
n,m = list(map(int,input().split(' '))) coins = list(map(int,input().split(' '))) dp =[ [-1 for x in range(m+1)] for y in range(n+1) ] def getCount(amount,index): if amount == 0: return 1 if index == 1: coin = coins[0] if amount%coin == 0: return 1 else: return 0 if dp[amount][index] != -1: return dp[amount][index] ans = 0 parts = int(amount/(coins[index-1])) for i in range(parts+1): got = int(getCount(amount - i*coins[index-1],index-1)) ans = ans+got dp[amount][index] = ans return ans print(getCount(n,m))
(n, m) = list(map(int, input().split(' '))) coins = list(map(int, input().split(' '))) dp = [[-1 for x in range(m + 1)] for y in range(n + 1)] def get_count(amount, index): if amount == 0: return 1 if index == 1: coin = coins[0] if amount % coin == 0: return 1 else: return 0 if dp[amount][index] != -1: return dp[amount][index] ans = 0 parts = int(amount / coins[index - 1]) for i in range(parts + 1): got = int(get_count(amount - i * coins[index - 1], index - 1)) ans = ans + got dp[amount][index] = ans return ans print(get_count(n, m))
class TableNotFound: def title(self): return "Table Not Found" def description(self): return "You are trying to make a query on a table that cannot be found. Check that :table migration exists and that migrations have been ran with 'python craft migrate' command." def regex(self): return r"no such table: (?P<table>(\w+))" class MissingCSRFToken: def title(self): return "Missing CSRF Token" def description(self): return "You are trying to make a sensitive request without providing a CSRF token. Your request might be vulnerable to Cross Site Request Forgery. To resolve this issue you should use {{ csrf_field }} in HTML forms or add X-CSRF-TOKEN header in AJAX requests." def regex(self): return r"Missing CSRF Token" class InvalidCSRFToken: def title(self): return "The session does not match the CSRF token" def description(self): return "Try clearing your cookies for the localhost domain in your browsers developer tools." def regex(self): return r"Invalid CSRF Token" class TemplateNotFound: def title(self): return "Template Not Found" def description(self): return """':template.html' view file has not been found in registered view locations. Please verify the spelling of the template and that it exists in locations declared in Kernel file. You can check available view locations with app.make('view.locations').""" def regex(self): return r"Template '(?P<template>(\w+))' not found" class NoneResponse: def title(self): return "Response cannot be None" def description(self): return """Ensure that the controller method used in this request returned something. A controller method cannot return None or nothing. If you don't want to return a value you can return an empty string ''.""" def regex(self): return r"Responses cannot be of type: None." class RouteMiddlewareNotFound: def title(self): return "Did you register the middleware key in your Kernel.py file?" def description(self): return "Check your Kernel.py file inside your 'route_middleware' attribute and look for a :middleware key" def regex(self): return r"Could not find the \'(?P<middleware>(\w+))\' middleware key"
class Tablenotfound: def title(self): return 'Table Not Found' def description(self): return "You are trying to make a query on a table that cannot be found. Check that :table migration exists and that migrations have been ran with 'python craft migrate' command." def regex(self): return 'no such table: (?P<table>(\\w+))' class Missingcsrftoken: def title(self): return 'Missing CSRF Token' def description(self): return 'You are trying to make a sensitive request without providing a CSRF token. Your request might be vulnerable to Cross Site Request Forgery. To resolve this issue you should use {{ csrf_field }} in HTML forms or add X-CSRF-TOKEN header in AJAX requests.' def regex(self): return 'Missing CSRF Token' class Invalidcsrftoken: def title(self): return 'The session does not match the CSRF token' def description(self): return 'Try clearing your cookies for the localhost domain in your browsers developer tools.' def regex(self): return 'Invalid CSRF Token' class Templatenotfound: def title(self): return 'Template Not Found' def description(self): return "':template.html' view file has not been found in registered view locations. Please verify the spelling of the template and that it exists in locations declared in Kernel file. You can check\n available view locations with app.make('view.locations')." def regex(self): return "Template '(?P<template>(\\w+))' not found" class Noneresponse: def title(self): return 'Response cannot be None' def description(self): return "Ensure that the controller method used in this request returned something. A controller method cannot return None or nothing.\n If you don't want to return a value you can return an empty string ''." def regex(self): return 'Responses cannot be of type: None.' class Routemiddlewarenotfound: def title(self): return 'Did you register the middleware key in your Kernel.py file?' def description(self): return "Check your Kernel.py file inside your 'route_middleware' attribute and look for a :middleware key" def regex(self): return "Could not find the \\'(?P<middleware>(\\w+))\\' middleware key"
c.NotebookApp.ip = '*' c.NotebookApp.token = '' c.NotebookApp.password = '' c.NotebookApp.open_browser = False c.NotebookApp.port = 8081 c.NotebookApp.allow_remote_access = True c.NotebookApp.allow_origin_pat = '(^https://8081-dot-[0-9]+-dot-devshell\.appspot\.com$)|(^https://colab\.research\.google\.com$)'
c.NotebookApp.ip = '*' c.NotebookApp.token = '' c.NotebookApp.password = '' c.NotebookApp.open_browser = False c.NotebookApp.port = 8081 c.NotebookApp.allow_remote_access = True c.NotebookApp.allow_origin_pat = '(^https://8081-dot-[0-9]+-dot-devshell\\.appspot\\.com$)|(^https://colab\\.research\\.google\\.com$)'
prova1 = float ( input()) prova2 = float ( input ()) prova3 = float (input ()) media = (((prova1 * 2.0) + (prova2 * 3.0) + (prova3 * 5.0)) / 10 ) print("MEDIA = %0.1F" % media )
prova1 = float(input()) prova2 = float(input()) prova3 = float(input()) media = (prova1 * 2.0 + prova2 * 3.0 + prova3 * 5.0) / 10 print('MEDIA = %0.1F' % media)
# https://www.codechef.com/problems/DEVUGRAP for T in range(int(input())): N,K=map(int,input().split()) n,ans=list(map(int,input().split())),0 for i in range(N): if(n[i]>=K): ans+=min(n[i]%K,K-n[i]%K) else: ans+=K-n[i]%K print(ans)
for t in range(int(input())): (n, k) = map(int, input().split()) (n, ans) = (list(map(int, input().split())), 0) for i in range(N): if n[i] >= K: ans += min(n[i] % K, K - n[i] % K) else: ans += K - n[i] % K print(ans)