content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
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)
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])
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])
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()
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')
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()
#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)
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)
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)
# 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}')
#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)
pi = { "00": { "value": "00", "description": "Base" }, "02": { "value": "02", "description": "POS" } }
pi = {'00': {'value': '00', 'description': 'Base'}, '02': {'value': '02', 'description': 'POS'}}
#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
# 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()
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.')
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
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))
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)
_first_index_in_every_row_list = list() def _build_first_index_in_every_row_list(): global _first_index_in_every_row_list _first_index_in_every_row_list.clear() _first_index_in_every_row_list.append(0) for delta in range(199, 1, -1): _first_index_in_every_row_list.append(_first_index_in_every_row_list[-1] + delta) _build_first_index_in_every_row_list() def parse_index(index, step=1): if not isinstance(index, int): index = int(index) date_seq_no = (index // 19900) * step correlation_no = index % 19900 # Use binary search to get fund number: # FIXME: Consider to compute fund number directly. low = correlation_no // 199 # include high = min(low * 2 + 1, len(_first_index_in_every_row_list)) # exclude while low < high: middle = (low + high) // 2 if _first_index_in_every_row_list[middle] < correlation_no: low = middle + 1 elif _first_index_in_every_row_list[middle] > correlation_no: high = middle else: low = middle break if _first_index_in_every_row_list[low] > correlation_no: low -= 1 fund1_no = low fund2_no = correlation_no - _first_index_in_every_row_list[fund1_no] + fund1_no + 1 return date_seq_no, fund1_no, fund2_no, correlation_no def calculate_correlation_no(fund1_no, fund2_no): if fund1_no == fund2_no: return None if fund1_no > fund2_no: tmp = fund1_no fund1_no = fund2_no fund2_no = tmp if fund1_no < 0: raise ValueError('fund1_no should >= 0, got %d.' % fund1_no) if fund2_no >= 200: raise ValueError('fund2_no should < 200, got %d.' % fund2_no) ''' input: f1 in [0, 198] f2 in [f1 + 1, 199] output: c = (199 + 198 + ... + (199 - f1 + 1)) + (f2 - (f1 + 1)) |----------- f1 terms -----------| = (199 + (199 - f1 + 1)) * f1 / 2 + (f2 - f1 - 1) = (399 - f1) * f1 / 2 + f2 - f1 - 1 ''' correlation_no = int(((399 - fund1_no) * fund1_no) // 2) + fund2_no - fund1_no - 1 return correlation_no def parse_square_ex_index(index, step=1): if not isinstance(index, int): index = int(index) date_seq_no = (index // 40000) * step index_rem = index % 40000 fund1_no = index_rem // 200 fund2_no = index_rem % 200 correlation_no = calculate_correlation_no(fund1_no, fund2_no) return date_seq_no, fund1_no, fund2_no, correlation_no
_first_index_in_every_row_list = list() def _build_first_index_in_every_row_list(): global _first_index_in_every_row_list _first_index_in_every_row_list.clear() _first_index_in_every_row_list.append(0) for delta in range(199, 1, -1): _first_index_in_every_row_list.append(_first_index_in_every_row_list[-1] + delta) _build_first_index_in_every_row_list() def parse_index(index, step=1): if not isinstance(index, int): index = int(index) date_seq_no = index // 19900 * step correlation_no = index % 19900 low = correlation_no // 199 high = min(low * 2 + 1, len(_first_index_in_every_row_list)) while low < high: middle = (low + high) // 2 if _first_index_in_every_row_list[middle] < correlation_no: low = middle + 1 elif _first_index_in_every_row_list[middle] > correlation_no: high = middle else: low = middle break if _first_index_in_every_row_list[low] > correlation_no: low -= 1 fund1_no = low fund2_no = correlation_no - _first_index_in_every_row_list[fund1_no] + fund1_no + 1 return (date_seq_no, fund1_no, fund2_no, correlation_no) def calculate_correlation_no(fund1_no, fund2_no): if fund1_no == fund2_no: return None if fund1_no > fund2_no: tmp = fund1_no fund1_no = fund2_no fund2_no = tmp if fund1_no < 0: raise value_error('fund1_no should >= 0, got %d.' % fund1_no) if fund2_no >= 200: raise value_error('fund2_no should < 200, got %d.' % fund2_no) '\n input:\n f1 in [0, 198]\n f2 in [f1 + 1, 199]\n\n output:\n c = (199 + 198 + ... + (199 - f1 + 1)) + (f2 - (f1 + 1))\n |----------- f1 terms -----------|\n = (199 + (199 - f1 + 1)) * f1 / 2 + (f2 - f1 - 1)\n = (399 - f1) * f1 / 2 + f2 - f1 - 1\n ' correlation_no = int((399 - fund1_no) * fund1_no // 2) + fund2_no - fund1_no - 1 return correlation_no def parse_square_ex_index(index, step=1): if not isinstance(index, int): index = int(index) date_seq_no = index // 40000 * step index_rem = index % 40000 fund1_no = index_rem // 200 fund2_no = index_rem % 200 correlation_no = calculate_correlation_no(fund1_no, fund2_no) return (date_seq_no, fund1_no, fund2_no, correlation_no)
# Function for finding if it possible # to obtain sorted array or not def fun(arr, n, k): v = [] # Iterate over all elements until K for i in range(k): # Store elements as multiples of K for j in range(i, n, k): v.append(arr[j]); # Sort the elements v.sort(); x = 0 # Put elements in their required position for j in range(i, n, k): arr[j] = v[x]; x += 1 v = [] # Check if the array becomes sorted or not for i in range(n - 1): if (arr[i] > arr[i + 1]): return False return True # Driver code nk= input().split() K = int(nk[1]) n = int(nk[0]) arr= list(map(int,input().split())) if (fun(arr, n, K)): print("True") else: print("False")
def fun(arr, n, k): v = [] for i in range(k): for j in range(i, n, k): v.append(arr[j]) v.sort() x = 0 for j in range(i, n, k): arr[j] = v[x] x += 1 v = [] for i in range(n - 1): if arr[i] > arr[i + 1]: return False return True nk = input().split() k = int(nk[1]) n = int(nk[0]) arr = list(map(int, input().split())) if fun(arr, n, K): print('True') else: print('False')
class Pessoa: menbros_superiores = 2 menbro_inferiores=2 def __init__(self,*familia,name=None,idade=17): self.name= name self.familia= list(familia) self.idade= idade def comprimentar(self): return 'hello my code' def despedisir(self): return 'diz tchau ;3' def contar_1(self): return list(range(10,1,-1)) @staticmethod def estatico (): return 50 @classmethod def atributodeclasse(cls): return f'{cls} - membros superiores {cls.menbros_superiores},membros inferiores {cls.menbro_inferiores}' if __name__ == '__main__': djony = Pessoa(name='djony', idade=17) mother = Pessoa(djony,name='mother',idade=46) type (djony) print(djony.comprimentar()) print(djony.contar_1()) print(djony.name) print(mother.name) for familia in mother.familia: print(familia.name,familia.idade) print(djony.__dict__) print(Pessoa.estatico()) print(Pessoa.atributodeclasse())
class Pessoa: menbros_superiores = 2 menbro_inferiores = 2 def __init__(self, *familia, name=None, idade=17): self.name = name self.familia = list(familia) self.idade = idade def comprimentar(self): return 'hello my code' def despedisir(self): return 'diz tchau ;3' def contar_1(self): return list(range(10, 1, -1)) @staticmethod def estatico(): return 50 @classmethod def atributodeclasse(cls): return f'{cls} - membros superiores {cls.menbros_superiores},membros inferiores {cls.menbro_inferiores}' if __name__ == '__main__': djony = pessoa(name='djony', idade=17) mother = pessoa(djony, name='mother', idade=46) type(djony) print(djony.comprimentar()) print(djony.contar_1()) print(djony.name) print(mother.name) for familia in mother.familia: print(familia.name, familia.idade) print(djony.__dict__) print(Pessoa.estatico()) print(Pessoa.atributodeclasse())
# coding: utf-8 def is_bool(var): return isinstance(var, bool) if __name__ == '__main__': a = False b = 0 print(is_bool(a)) print(is_bool(b))
def is_bool(var): return isinstance(var, bool) if __name__ == '__main__': a = False b = 0 print(is_bool(a)) print(is_bool(b))
class Conta: def __init__(self, numero, nome, saldo=0): self._numero = numero self._nome = nome self._saldo = saldo def atualiza(self, taxa): self._saldo += self._saldo * taxa def deposita(self, valor): self._saldo += valor - 0.10 class ContaCorrente(Conta): def atualiza(self, taxa): self._saldo += self._saldo * taxa * 2 class ContaPoupanca(Conta): def atualiza(self, taxa): self._saldo += self._saldo * taxa * 3 if __name__ == "__main__": c = Conta('123-4', 'joao', 1000) cc = ContaCorrente('123-5', 'pedro', 1000) cp = ContaPoupanca('123-6', 'Maria', 1000) c.atualiza(0.01) cc.atualiza(0.01) cp.atualiza(0.01) print(c._saldo, cc._saldo, cp._saldo)
class Conta: def __init__(self, numero, nome, saldo=0): self._numero = numero self._nome = nome self._saldo = saldo def atualiza(self, taxa): self._saldo += self._saldo * taxa def deposita(self, valor): self._saldo += valor - 0.1 class Contacorrente(Conta): def atualiza(self, taxa): self._saldo += self._saldo * taxa * 2 class Contapoupanca(Conta): def atualiza(self, taxa): self._saldo += self._saldo * taxa * 3 if __name__ == '__main__': c = conta('123-4', 'joao', 1000) cc = conta_corrente('123-5', 'pedro', 1000) cp = conta_poupanca('123-6', 'Maria', 1000) c.atualiza(0.01) cc.atualiza(0.01) cp.atualiza(0.01) print(c._saldo, cc._saldo, cp._saldo)
# -*- coding: utf-8 -*- # Coded by Sungwook Kim # 2020-12-13 # IDE: Jupyter Notebook def Fact(a): res = 1 for i in range(a): res = res * (i + 1) return res T = int(input()) for i in range(T): r, n = map(int, input().split()) a = Fact(n) b = Fact(r) c = Fact(n-r) print(int(a / (c * b)))
def fact(a): res = 1 for i in range(a): res = res * (i + 1) return res t = int(input()) for i in range(T): (r, n) = map(int, input().split()) a = fact(n) b = fact(r) c = fact(n - r) print(int(a / (c * b)))
# The base class for application-specific states. class SarifState(object): def __init__(self): self.parser = None self.ppass = 1 # Taking the easy way out. # We need something in case a descendent wants to trigger # on change to ppass. def set_ppass(self, ppass): self.ppass = ppass def get_ppass(self): return self.ppass def set_parser(self, parser): self.parser = parser def get_parser(self): return self.parser # These functions are named for the handler they reside in # plus the function in that handler. # Only functions that called the state are here. def original_uri_base_id_add(self, uri, uriBaseId, key): raise NotImplementedError("original_uri_base_id_add") def resources_object_member_end(self, parser, key): raise NotImplementedError("resources_object_member_end") def rules_v1_object_member_end(self, parser, key): raise NotImplementedError("rules_v1_object_member_end") def rules_item_array_element_end(self, parser, idx): raise NotImplementedError("rules_item_array_element_end") def run_object_member_end(self, tool_name): raise NotImplementedError("run_object_member_end") def run_object_start(self, parser): raise NotImplementedError("run_object_start") def results_item_array_element_end(self, parser, idx): raise NotImplementedError("results_item_array_element_end") def file_item_add(self, file_item): raise NotImplementedError("file_item_add")
class Sarifstate(object): def __init__(self): self.parser = None self.ppass = 1 def set_ppass(self, ppass): self.ppass = ppass def get_ppass(self): return self.ppass def set_parser(self, parser): self.parser = parser def get_parser(self): return self.parser def original_uri_base_id_add(self, uri, uriBaseId, key): raise not_implemented_error('original_uri_base_id_add') def resources_object_member_end(self, parser, key): raise not_implemented_error('resources_object_member_end') def rules_v1_object_member_end(self, parser, key): raise not_implemented_error('rules_v1_object_member_end') def rules_item_array_element_end(self, parser, idx): raise not_implemented_error('rules_item_array_element_end') def run_object_member_end(self, tool_name): raise not_implemented_error('run_object_member_end') def run_object_start(self, parser): raise not_implemented_error('run_object_start') def results_item_array_element_end(self, parser, idx): raise not_implemented_error('results_item_array_element_end') def file_item_add(self, file_item): raise not_implemented_error('file_item_add')
# store the input from the user into age age = input("How old are you? ") # store the input from the user into height height = input(f"You're {age}? Nice. How tall are you? ") # store the input from the user into weight weight = input("How much do you weigh? ") # print the f-string with the age, height and weight print(f"So you're {age} old. {height} tall and {weight} heavy.")
age = input('How old are you? ') height = input(f"You're {age}? Nice. How tall are you? ") weight = input('How much do you weigh? ') print(f"So you're {age} old. {height} tall and {weight} heavy.")
def loss_layer(self, predicts, labels, scope='loss_layer'): with tf.variable_scope(scope): predict_classes = tf.reshape(predicts[:, :self.boundary1], [self.batch_size, self.cell_size, self.cell_size, self.num_class]) predict_scales = tf.reshape(predicts[:, self.boundary1:self.boundary2], [self.batch_size, self.cell_size, self.cell_size, self.boxes_per_cell]) predict_boxes = tf.reshape(predicts[:, self.boundary2:], [self.batch_size, self.cell_size, self.cell_size, self.boxes_per_cell, 4]) response = tf.reshape(labels[:, :, :, 0], [self.batch_size, self.cell_size, self.cell_size, 1]) boxes = tf.reshape(labels[:, :, :, 1:5], [self.batch_size, self.cell_size, self.cell_size, 1, 4]) boxes = tf.tile(boxes, [1, 1, 1, self.boxes_per_cell, 1]) / self.image_size classes = labels[:, :, :, 5:] offset = tf.constant(self.offset, dtype=tf.float32) offset = tf.reshape(offset, [1, self.cell_size, self.cell_size, self.boxes_per_cell]) offset = tf.tile(offset, [self.batch_size, 1, 1, 1]) predict_boxes_tran = tf.stack([(predict_boxes[:, :, :, :, 0] + offset) / self.cell_size, (predict_boxes[:, :, :, :, 1] + tf.transpose(offset, (0, 2, 1, 3))) / self.cell_size, tf.square(predict_boxes[:, :, :, :, 2]), tf.square(predict_boxes[:, :, :, :, 3])]) predict_boxes_tran = tf.transpose(predict_boxes_tran, [1, 2, 3, 4, 0]) iou_predict_truth = self.calc_iou(predict_boxes_tran, boxes) # calculate I tensor [BATCH_SIZE, CELL_SIZE, CELL_SIZE, BOXES_PER_CELL] object_mask = tf.reduce_max(iou_predict_truth, 3, keep_dims=True) object_mask = tf.cast((iou_predict_truth >= object_mask), tf.float32) * response # calculate no_I tensor [CELL_SIZE, CELL_SIZE, BOXES_PER_CELL] noobject_mask = tf.ones_like(object_mask, dtype=tf.float32) - object_mask boxes_tran = tf.stack([boxes[:, :, :, :, 0] * self.cell_size - offset, boxes[:, :, :, :, 1] * self.cell_size - tf.transpose(offset, (0, 2, 1, 3)), tf.sqrt(boxes[:, :, :, :, 2]), tf.sqrt(boxes[:, :, :, :, 3])]) boxes_tran = tf.transpose(boxes_tran, [1, 2, 3, 4, 0]) # class_loss class_delta = response * (predict_classes - classes) class_loss = tf.reduce_mean(tf.reduce_sum(tf.square(class_delta), axis=[1, 2, 3]), name='class_loss') * self.class_scale # object_loss object_delta = object_mask * (predict_scales - iou_predict_truth) object_loss = tf.reduce_mean(tf.reduce_sum(tf.square(object_delta), axis=[1, 2, 3]), name='object_loss') * self.object_scale # noobject_loss noobject_delta = noobject_mask * predict_scales noobject_loss = tf.reduce_mean(tf.reduce_sum(tf.square(noobject_delta), axis=[1, 2, 3]), name='noobject_loss') * self.noobject_scale # coord_loss coord_mask = tf.expand_dims(object_mask, 4) boxes_delta = coord_mask * (predict_boxes - boxes_tran) coord_loss = tf.reduce_mean(tf.reduce_sum(tf.square(boxes_delta), axis=[1, 2, 3, 4]), name='coord_loss') * self.coord_scale tf.losses.add_loss(class_loss) tf.losses.add_loss(object_loss) tf.losses.add_loss(noobject_loss) tf.losses.add_loss(coord_loss)
def loss_layer(self, predicts, labels, scope='loss_layer'): with tf.variable_scope(scope): predict_classes = tf.reshape(predicts[:, :self.boundary1], [self.batch_size, self.cell_size, self.cell_size, self.num_class]) predict_scales = tf.reshape(predicts[:, self.boundary1:self.boundary2], [self.batch_size, self.cell_size, self.cell_size, self.boxes_per_cell]) predict_boxes = tf.reshape(predicts[:, self.boundary2:], [self.batch_size, self.cell_size, self.cell_size, self.boxes_per_cell, 4]) response = tf.reshape(labels[:, :, :, 0], [self.batch_size, self.cell_size, self.cell_size, 1]) boxes = tf.reshape(labels[:, :, :, 1:5], [self.batch_size, self.cell_size, self.cell_size, 1, 4]) boxes = tf.tile(boxes, [1, 1, 1, self.boxes_per_cell, 1]) / self.image_size classes = labels[:, :, :, 5:] offset = tf.constant(self.offset, dtype=tf.float32) offset = tf.reshape(offset, [1, self.cell_size, self.cell_size, self.boxes_per_cell]) offset = tf.tile(offset, [self.batch_size, 1, 1, 1]) predict_boxes_tran = tf.stack([(predict_boxes[:, :, :, :, 0] + offset) / self.cell_size, (predict_boxes[:, :, :, :, 1] + tf.transpose(offset, (0, 2, 1, 3))) / self.cell_size, tf.square(predict_boxes[:, :, :, :, 2]), tf.square(predict_boxes[:, :, :, :, 3])]) predict_boxes_tran = tf.transpose(predict_boxes_tran, [1, 2, 3, 4, 0]) iou_predict_truth = self.calc_iou(predict_boxes_tran, boxes) object_mask = tf.reduce_max(iou_predict_truth, 3, keep_dims=True) object_mask = tf.cast(iou_predict_truth >= object_mask, tf.float32) * response noobject_mask = tf.ones_like(object_mask, dtype=tf.float32) - object_mask boxes_tran = tf.stack([boxes[:, :, :, :, 0] * self.cell_size - offset, boxes[:, :, :, :, 1] * self.cell_size - tf.transpose(offset, (0, 2, 1, 3)), tf.sqrt(boxes[:, :, :, :, 2]), tf.sqrt(boxes[:, :, :, :, 3])]) boxes_tran = tf.transpose(boxes_tran, [1, 2, 3, 4, 0]) class_delta = response * (predict_classes - classes) class_loss = tf.reduce_mean(tf.reduce_sum(tf.square(class_delta), axis=[1, 2, 3]), name='class_loss') * self.class_scale object_delta = object_mask * (predict_scales - iou_predict_truth) object_loss = tf.reduce_mean(tf.reduce_sum(tf.square(object_delta), axis=[1, 2, 3]), name='object_loss') * self.object_scale noobject_delta = noobject_mask * predict_scales noobject_loss = tf.reduce_mean(tf.reduce_sum(tf.square(noobject_delta), axis=[1, 2, 3]), name='noobject_loss') * self.noobject_scale coord_mask = tf.expand_dims(object_mask, 4) boxes_delta = coord_mask * (predict_boxes - boxes_tran) coord_loss = tf.reduce_mean(tf.reduce_sum(tf.square(boxes_delta), axis=[1, 2, 3, 4]), name='coord_loss') * self.coord_scale tf.losses.add_loss(class_loss) tf.losses.add_loss(object_loss) tf.losses.add_loss(noobject_loss) tf.losses.add_loss(coord_loss)
# AKSHITH K # BUBBLE SORT IMPLEMENTED IN PYTHON RECURSIVELY. def bubblesort(arr, n): # checking if the array does not need to be sorted and has a length of 1. if n <= 1: return # creating a for-loop to iterate for the elements in the array. for i in range(0, n - 1): # creating an if-statement to check for the element not being in the right position. if arr[i] > arr[i + 1]: # code to perform the swapping method. arr[i], arr[i + 1] = arr[i + 1], arr[i] # recursively calling the function for the sorting. return bubblesort(arr, n - 1) # DRIVER CODE FOR TESTING THE ALGORITHM. arr = [4, 9, 1, 3, 0, 2, 6, 8, 5, 7] n = len(arr) bubblesort(arr, n) print(arr)
def bubblesort(arr, n): if n <= 1: return for i in range(0, n - 1): if arr[i] > arr[i + 1]: (arr[i], arr[i + 1]) = (arr[i + 1], arr[i]) return bubblesort(arr, n - 1) arr = [4, 9, 1, 3, 0, 2, 6, 8, 5, 7] n = len(arr) bubblesort(arr, n) print(arr)
## Problem 10.2 # write a program to read through the mbox-short.txt # and figure out the distribution by hour of the day for each of the messages. file_name = input("Enter file:") file_handle = open(file_name) hour_list = list() for line in file_handle: # pull the hour out from the 'From ' line # From [email protected] Sat Jan 5 09:14:16 2008 if line.startswith("From"): line_list = line.split() if len(line_list) > 2: # find the time and then split the string a second time hour = line_list[5][:2] hour_list.append(hour) # accumulate the counts for each hour hour_dict = dict() for key in hour_list: hour_dict[key] = hour_dict.get(key, 0) + 1 # sort by hour srt_list = sorted(hour_dict.items()) # print out the counts, sorted by hour for (k,v) in srt_list: print (k,v)
file_name = input('Enter file:') file_handle = open(file_name) hour_list = list() for line in file_handle: if line.startswith('From'): line_list = line.split() if len(line_list) > 2: hour = line_list[5][:2] hour_list.append(hour) hour_dict = dict() for key in hour_list: hour_dict[key] = hour_dict.get(key, 0) + 1 srt_list = sorted(hour_dict.items()) for (k, v) in srt_list: print(k, v)
# Copyright 2006 James Tauber and contributors # Copyright (C) 2009 Luke Kenneth Casson Leighton <[email protected]> # Copyright (C) 2010 Serge Tarkovski <[email protected]> # Copyright (C) 2010 Rich Newpol (IE override) <[email protected]> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This IE-specific override is required because IE doesn't allow # empty element to generate events. Therefore, when the mouse moves # (or clicks) happen over *only* the GlassWidget (which is empty) # they stop flowing. however, IE does provide setCapture/releaseCapture # methods on elements which can be used to same effect as a regular # GlassWidget. # This file implements the IE version of GlassWidget simply by mapping # the GlassWidget API to the use of setCapture/releaseCapture # we re-use the global 'mousecapturer' to prevent GlassWidget.hide() # from releasing someone else's capture def show(mousetarget, **kwargs): global mousecapturer # get the element that wants events target_element = mousetarget.getElement() # insure element can capture events if hasattr(target_element,"setCapture"): # remember it mousecapturer = target_element # start capturing DOM.setCapture(target_element) def hide(): global mousecapturer if hasattr(mousecapturer,"releaseCapture"): DOM.releaseCapture(mousecapturer) mousecapturer = None
def show(mousetarget, **kwargs): global mousecapturer target_element = mousetarget.getElement() if hasattr(target_element, 'setCapture'): mousecapturer = target_element DOM.setCapture(target_element) def hide(): global mousecapturer if hasattr(mousecapturer, 'releaseCapture'): DOM.releaseCapture(mousecapturer) mousecapturer = None
# WAP to show the use of if..elif..else season= input("Enter season : ") print(season) if season == 'spring': print('plant the garden!') elif season == 'summer': print('water the garden!') elif season == 'fall': print('harvest the garden!') elif season == 'winter': print('stay indoors!') else: print('unrecognized season')
season = input('Enter season : ') print(season) if season == 'spring': print('plant the garden!') elif season == 'summer': print('water the garden!') elif season == 'fall': print('harvest the garden!') elif season == 'winter': print('stay indoors!') else: print('unrecognized season')
# # PySNMP MIB module HH3C-L2TP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-L2TP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:14:47 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint") hh3cCommon, = mibBuilder.importSymbols("HH3C-OID-MIB", "hh3cCommon") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Counter32, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, TimeTicks, Counter64, NotificationType, ObjectIdentity, Gauge32, MibIdentifier, iso, Integer32, ModuleIdentity, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "TimeTicks", "Counter64", "NotificationType", "ObjectIdentity", "Gauge32", "MibIdentifier", "iso", "Integer32", "ModuleIdentity", "IpAddress") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") hh3cL2tp = ModuleIdentity((1, 3, 6, 1, 4, 1, 25506, 2, 139)) hh3cL2tp.setRevisions(('2013-07-05 15:18',)) if mibBuilder.loadTexts: hh3cL2tp.setLastUpdated('201307051518Z') if mibBuilder.loadTexts: hh3cL2tp.setOrganization('Hangzhou H3C Tech. Co., Ltd.') hh3cL2tpObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1)) hh3cL2tpScalar = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1)) hh3cL2tpStats = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1, 1)) hh3cL2tpStatsTotalTunnels = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1, 1, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cL2tpStatsTotalTunnels.setStatus('current') hh3cL2tpStatsTotalSessions = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cL2tpStatsTotalSessions.setStatus('current') hh3cL2tpSessionRate = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cL2tpSessionRate.setStatus('current') mibBuilder.exportSymbols("HH3C-L2TP-MIB", PYSNMP_MODULE_ID=hh3cL2tp, hh3cL2tpObjects=hh3cL2tpObjects, hh3cL2tpStatsTotalTunnels=hh3cL2tpStatsTotalTunnels, hh3cL2tpScalar=hh3cL2tpScalar, hh3cL2tpStatsTotalSessions=hh3cL2tpStatsTotalSessions, hh3cL2tp=hh3cL2tp, hh3cL2tpSessionRate=hh3cL2tpSessionRate, hh3cL2tpStats=hh3cL2tpStats)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_range_constraint, constraints_union, single_value_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueRangeConstraint', 'ConstraintsUnion', 'SingleValueConstraint', 'ValueSizeConstraint') (hh3c_common,) = mibBuilder.importSymbols('HH3C-OID-MIB', 'hh3cCommon') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (counter32, unsigned32, mib_scalar, mib_table, mib_table_row, mib_table_column, bits, time_ticks, counter64, notification_type, object_identity, gauge32, mib_identifier, iso, integer32, module_identity, ip_address) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter32', 'Unsigned32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Bits', 'TimeTicks', 'Counter64', 'NotificationType', 'ObjectIdentity', 'Gauge32', 'MibIdentifier', 'iso', 'Integer32', 'ModuleIdentity', 'IpAddress') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') hh3c_l2tp = module_identity((1, 3, 6, 1, 4, 1, 25506, 2, 139)) hh3cL2tp.setRevisions(('2013-07-05 15:18',)) if mibBuilder.loadTexts: hh3cL2tp.setLastUpdated('201307051518Z') if mibBuilder.loadTexts: hh3cL2tp.setOrganization('Hangzhou H3C Tech. Co., Ltd.') hh3c_l2tp_objects = mib_identifier((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1)) hh3c_l2tp_scalar = mib_identifier((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1)) hh3c_l2tp_stats = mib_identifier((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1, 1)) hh3c_l2tp_stats_total_tunnels = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1, 1, 1), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hh3cL2tpStatsTotalTunnels.setStatus('current') hh3c_l2tp_stats_total_sessions = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1, 1, 2), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hh3cL2tpStatsTotalSessions.setStatus('current') hh3c_l2tp_session_rate = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 139, 1, 1, 1, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hh3cL2tpSessionRate.setStatus('current') mibBuilder.exportSymbols('HH3C-L2TP-MIB', PYSNMP_MODULE_ID=hh3cL2tp, hh3cL2tpObjects=hh3cL2tpObjects, hh3cL2tpStatsTotalTunnels=hh3cL2tpStatsTotalTunnels, hh3cL2tpScalar=hh3cL2tpScalar, hh3cL2tpStatsTotalSessions=hh3cL2tpStatsTotalSessions, hh3cL2tp=hh3cL2tp, hh3cL2tpSessionRate=hh3cL2tpSessionRate, hh3cL2tpStats=hh3cL2tpStats)
kuukiondo = 70 shitsudo = 100 if kuukiondo >= 100: print("A") elif kuukiondo >= 92 and shitsudo > 75: print("B") elif kuukiondo > 88 and shitsudo >= 85: print("C") elif kuukiondo == 75 and shitsudo <= 65: print("D") else: print("E")
kuukiondo = 70 shitsudo = 100 if kuukiondo >= 100: print('A') elif kuukiondo >= 92 and shitsudo > 75: print('B') elif kuukiondo > 88 and shitsudo >= 85: print('C') elif kuukiondo == 75 and shitsudo <= 65: print('D') else: print('E')
class Solution1: def maxSubArray(self, nums: List[int]) -> int: total_max, total = -1e10, 0 for i in range( len(nums) ): if total > 0: total += nums[i] else: total = nums[i] if total > total_max: total_max = total return total_max class Solution2: ## divide and conquer approach def middlemax( self, nums, LL, mid, RR ): totalL, totalR, totalL_max, totalR_max = 0, 0, nums[mid], nums[mid+1] # Left for i in range( mid, LL-1, -1 ): totalL += nums[i] if( totalL_max < totalL ): totalL_max = totalL # Right for i in range( mid+1, RR+1 ): totalR += nums[i] if( totalR_max < totalR ): totalR_max = totalR return totalR_max + totalL_max def findmax( self, nums, LL, RR ): if LL >= RR: return nums[LL] mid = LL + (RR-LL)//2 mmax = self.middlemax( nums, LL, mid, RR ) lmax = self.findmax( nums, LL, mid ) rmax = self.findmax( nums, mid+1, RR ) return max( [mmax, lmax, rmax] ) def maxSubArray(self, nums: List[int]) -> int: Length = len(nums) return self.findmax( nums, 0, Length-1 )
class Solution1: def max_sub_array(self, nums: List[int]) -> int: (total_max, total) = (-10000000000.0, 0) for i in range(len(nums)): if total > 0: total += nums[i] else: total = nums[i] if total > total_max: total_max = total return total_max class Solution2: def middlemax(self, nums, LL, mid, RR): (total_l, total_r, total_l_max, total_r_max) = (0, 0, nums[mid], nums[mid + 1]) for i in range(mid, LL - 1, -1): total_l += nums[i] if totalL_max < totalL: total_l_max = totalL for i in range(mid + 1, RR + 1): total_r += nums[i] if totalR_max < totalR: total_r_max = totalR return totalR_max + totalL_max def findmax(self, nums, LL, RR): if LL >= RR: return nums[LL] mid = LL + (RR - LL) // 2 mmax = self.middlemax(nums, LL, mid, RR) lmax = self.findmax(nums, LL, mid) rmax = self.findmax(nums, mid + 1, RR) return max([mmax, lmax, rmax]) def max_sub_array(self, nums: List[int]) -> int: length = len(nums) return self.findmax(nums, 0, Length - 1)
################################################################################ # # # ____ _ # # | _ \ ___ __| |_ __ _ _ _ __ ___ # # | |_) / _ \ / _` | '__| | | | '_ ` _ \ # # | __/ (_) | (_| | | | |_| | | | | | | # # |_| \___/ \__,_|_| \__,_|_| |_| |_| # # # # Copyright 2021 Podrum Studios # # # # Permission is hereby granted, free of charge, to any person # # obtaining a copy of this software and associated documentation # # files (the "Software"), to deal in the Software without restriction, # # including without limitation the rights to use, copy, modify, merge, # # publish, distribute, sublicense, and/or sell copies of the Software, # # and to permit persons to whom the Software is furnished to do so, # # subject to the following conditions: # # # # The above copyright notice and this permission notice shall be included # # in all copies or substantial portions of the Software. # # # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # # IN THE SOFTWARE. # # # ################################################################################ class metadata_dictionary_type: key_flags: int = 0 key_health: int = 1 key_variant: int = 2 key_color: int = 3 key_nametag: int = 4 key_owner_eid: int = 5 key_target_eid: int = 6 key_air: int = 7 key_potion_color: int = 8 key_potion_ambient: int = 9 key_jump_duration: int = 10 key_hurt_time: int = 11 key_hurt_direction: int = 12 key_paddle_time_left: int = 13 key_paddle_time_right: int = 14 key_experience_value: int = 15 key_minecart_display_block: int = 16 key_minecart_display_offset: int = 17 key_minecart_has_display: int = 18 key_old_swell: int = 20 key_swell_dir: int = 21 key_charge_amount: int = 22 key_enderman_held_runtime_id: int = 23 key_entity_age: int = 24 key_player_flags: int = 26 key_player_index: int = 27 key_player_bed_position: int = 28 key_fireball_power_x: int = 29 key_fireball_power_y: int = 30 key_fireball_power_z: int = 31 key_aux_power: int = 32 key_fish_x: int = 33 key_fish_z: int = 34 key_fish_angle: int = 35 key_potion_aux_value: int = 36 key_lead_holder_eid: int = 37 key_scale: int = 38 key_interactive_tag: int = 39 key_npc_skin_id: int = 40 key_url_tag: int = 41 key_max_airdata_max_air: int = 42 key_mark_variant: int = 43 key_container_type: int = 44 key_container_base_size: int = 45 key_container_extra_slots_per_strength: int = 46 key_block_target: int = 47 key_wither_invulnerable_ticks: int = 48 key_wither_target_1: int = 49 key_wither_target_2: int = 50 key_wither_target_3: int = 51 key_aerial_attack: int = 52 key_boundingbox_width: int = 53 key_boundingbox_height: int = 54 key_fuse_length: int = 55 key_rider_seat_position: int = 57 key_rider_rotation_locked: int = 58 key_rider_max_rotation: int = 58 key_rider_min_rotation: int = 59 key_rider_rotation_offset: int = 60 key_area_effect_clound_radius: int = 61 key_area_effect_clound_waiting: int = 62 key_area_effect_clound_particle_id: int = 63 key_shulker_peak_id: int = 64 key_shulker_attach_face: int = 65 key_shulker_attached: int = 66 key_shulker_attach_pos: int = 67 key_trading_player_eid: int = 68 key_trading_career: int = 69 key_has_command_block: int = 70 key_command_block_command: int = 71 key_command_block_last_output: int = 72 key_command_block_track_output: int = 73 key_controlling_rider_seat_number: int = 74 key_strength: int = 75 key_max_strength: int = 76 key_spell_casting_color: int = 77 key_limited_life: int = 78 key_armor_stand_pose_index: int = 79 key_ender_crystal_time_offset: int = 80 key_always_show_nametag: int = 81 key_color_2: int = 82 key_name_author: int = 83 key_score_tag: int = 84 key_baloon_attached_entity: int = 85 key_pufferfish_size: int = 86 key_bubble_time: int = 87 key_agent: int = 88 key_sitting_amount: int = 89 key_sitting_amount_previous: int = 90 key_eating_counter: int = 91 key_flags_extended: int = 92 key_laying_amount: int = 93 key_laying_amount_previous: int = 94 key_duration: int = 95 key_spawn_time: int = 96 key_change_rate: int = 97 key_change_on_pickup: int = 98 key_pickup_count: int = 99 key_interact_text: int = 100 key_trade_tier: int = 101 key_max_trade_tier: int = 102 key_trade_experience: int = 103 key_skin_id: int = 104 key_spawning_flames: int = 105 key_command_block_tick_delay: int = 106 key_command_block_execute_on_first_tick: int = 107 key_ambient_sound_interval: int = 108 key_ambient_sound_interval_range: int = 109 key_ambient_sound_event_name: int = 110 key_fall_damage_multiplier: int = 111 key_name_raw_text: int = 112 key_can_ride_target: int = 113 key_low_tier_cured_discount: int = 114 key_high_tier_cured_discount: int = 115 key_nearby_cured_discount: int = 116 key_nearby_cured_discount_timestamp: int = 117 key_hitbox: int = 118 key_is_buoyant: int = 119 key_buoyancy_data: int = 120 key_goat_horn_count: int = 121 type_byte: int = 0 type_short: int = 1 type_int: int = 2 type_float: int = 3 type_string: int = 4 type_compound: int = 5 type_vector_3_i: int = 6 type_long: int = 7 type_vector_3_f: int = 8
class Metadata_Dictionary_Type: key_flags: int = 0 key_health: int = 1 key_variant: int = 2 key_color: int = 3 key_nametag: int = 4 key_owner_eid: int = 5 key_target_eid: int = 6 key_air: int = 7 key_potion_color: int = 8 key_potion_ambient: int = 9 key_jump_duration: int = 10 key_hurt_time: int = 11 key_hurt_direction: int = 12 key_paddle_time_left: int = 13 key_paddle_time_right: int = 14 key_experience_value: int = 15 key_minecart_display_block: int = 16 key_minecart_display_offset: int = 17 key_minecart_has_display: int = 18 key_old_swell: int = 20 key_swell_dir: int = 21 key_charge_amount: int = 22 key_enderman_held_runtime_id: int = 23 key_entity_age: int = 24 key_player_flags: int = 26 key_player_index: int = 27 key_player_bed_position: int = 28 key_fireball_power_x: int = 29 key_fireball_power_y: int = 30 key_fireball_power_z: int = 31 key_aux_power: int = 32 key_fish_x: int = 33 key_fish_z: int = 34 key_fish_angle: int = 35 key_potion_aux_value: int = 36 key_lead_holder_eid: int = 37 key_scale: int = 38 key_interactive_tag: int = 39 key_npc_skin_id: int = 40 key_url_tag: int = 41 key_max_airdata_max_air: int = 42 key_mark_variant: int = 43 key_container_type: int = 44 key_container_base_size: int = 45 key_container_extra_slots_per_strength: int = 46 key_block_target: int = 47 key_wither_invulnerable_ticks: int = 48 key_wither_target_1: int = 49 key_wither_target_2: int = 50 key_wither_target_3: int = 51 key_aerial_attack: int = 52 key_boundingbox_width: int = 53 key_boundingbox_height: int = 54 key_fuse_length: int = 55 key_rider_seat_position: int = 57 key_rider_rotation_locked: int = 58 key_rider_max_rotation: int = 58 key_rider_min_rotation: int = 59 key_rider_rotation_offset: int = 60 key_area_effect_clound_radius: int = 61 key_area_effect_clound_waiting: int = 62 key_area_effect_clound_particle_id: int = 63 key_shulker_peak_id: int = 64 key_shulker_attach_face: int = 65 key_shulker_attached: int = 66 key_shulker_attach_pos: int = 67 key_trading_player_eid: int = 68 key_trading_career: int = 69 key_has_command_block: int = 70 key_command_block_command: int = 71 key_command_block_last_output: int = 72 key_command_block_track_output: int = 73 key_controlling_rider_seat_number: int = 74 key_strength: int = 75 key_max_strength: int = 76 key_spell_casting_color: int = 77 key_limited_life: int = 78 key_armor_stand_pose_index: int = 79 key_ender_crystal_time_offset: int = 80 key_always_show_nametag: int = 81 key_color_2: int = 82 key_name_author: int = 83 key_score_tag: int = 84 key_baloon_attached_entity: int = 85 key_pufferfish_size: int = 86 key_bubble_time: int = 87 key_agent: int = 88 key_sitting_amount: int = 89 key_sitting_amount_previous: int = 90 key_eating_counter: int = 91 key_flags_extended: int = 92 key_laying_amount: int = 93 key_laying_amount_previous: int = 94 key_duration: int = 95 key_spawn_time: int = 96 key_change_rate: int = 97 key_change_on_pickup: int = 98 key_pickup_count: int = 99 key_interact_text: int = 100 key_trade_tier: int = 101 key_max_trade_tier: int = 102 key_trade_experience: int = 103 key_skin_id: int = 104 key_spawning_flames: int = 105 key_command_block_tick_delay: int = 106 key_command_block_execute_on_first_tick: int = 107 key_ambient_sound_interval: int = 108 key_ambient_sound_interval_range: int = 109 key_ambient_sound_event_name: int = 110 key_fall_damage_multiplier: int = 111 key_name_raw_text: int = 112 key_can_ride_target: int = 113 key_low_tier_cured_discount: int = 114 key_high_tier_cured_discount: int = 115 key_nearby_cured_discount: int = 116 key_nearby_cured_discount_timestamp: int = 117 key_hitbox: int = 118 key_is_buoyant: int = 119 key_buoyancy_data: int = 120 key_goat_horn_count: int = 121 type_byte: int = 0 type_short: int = 1 type_int: int = 2 type_float: int = 3 type_string: int = 4 type_compound: int = 5 type_vector_3_i: int = 6 type_long: int = 7 type_vector_3_f: int = 8
class Base(object): def __secret(self): print("don't tell") def public(self): self.__secret() class Derived(Base): def __secret(self): print("never ever") if __name__ == "__main__": print("Base class members:", dir(Base)) print("Derived class members:", dir(Derived)) print("Base.public() result:") Base().public() print("Derived.public() result:") Derived().public()
class Base(object): def __secret(self): print("don't tell") def public(self): self.__secret() class Derived(Base): def __secret(self): print('never ever') if __name__ == '__main__': print('Base class members:', dir(Base)) print('Derived class members:', dir(Derived)) print('Base.public() result:') base().public() print('Derived.public() result:') derived().public()
# Basic script to find primer candidates # Hits are 20bp in length, with 50-55% GC content, GC clamps in the 3' end, and no more than 3xGC at the clamp # Paste the target exon sequences from a FASTA sequence with no white spaces # Exon 1 is where forward primer candidates will be identified exon1 = "GCAGTGTCACTAGGCCGGCTGGGGGCCCTGGGTACGCTGTAGACCAGACCGCGACAGGCCAGAACACGGGCGGCGGCTTCGGGCCGGGAGACCCGCGCAGCCCTCGGGGCATCTCAGTGCCTCACTCCCCACCCCCTCCCCCGGGTCGGGGGAGGCGGCGCGTCCGGCGGAGGGTTGAGGGGAGCGGGGCAGGCCTGGAGCGCCATGAGCAGCCCGGATGCGGGATACGCCAGTGACGACCAGAGCCAGACCCAGAGCGCGCTGCCCGCGGTGATGGCCGGGCTGGGCCCCTGCCCCTGGGCCGAGTCGCTGAGCCCCATCGGGGACATGAAGGTGAAGGGCGAGGCGCCGGCGAACAGCGGAGCACCGGCCGGGGCCGCGGGCCGAGCCAAGGGCGAGTCCCGTATCCGGCGGCCGATGAACGCTTTCATGGTGTGGGCTAAGGACGAGCGCAAGCGGCTGGCGCAGCAGAATCCAGACCTGCACAACGCCGAGTTGAGCAAGATGCTGG" # Exon 2 is where reverse primer candidates will be identified exon2 = "GCAAGTCGTGGAAGGCGCTGACGCTGGCGGAGAAGCGGCCCTTCGTGGAGGAGGCAGAGCGGCTGCGCGTGCAGCACATGCAGGACCACCCCAACTACAAGTACCGGCCGCGGCGGCGCAAGCAGGTGAAGCGGCTGAAGCGGGTGGAGGGCGGCTTCCTGCACGGCCTGGCTGAGCCGCAGGCGGCCGCGCTGGGCCCCGAGGGCGGCCGCGTGGCCATGGACGGCCTGGGCCTCCAGTTCCCCGAGCAGGGCTTCCCCGCCGGCCCGCCGCTGCTGCCTCCGCACATGGGCGGCCACTACCGCGACTGCCAGAGTCTGGGCGCGCCTCCGCTCGACGGCTACCCGTTGCCCACGCCCGACACGTCCCCGCTGGACGGCGTGGACCCCGACCCGGCTTTCTTCGCCGCCCCGATGCCCGGGGACTGCCCGGCGGCCGGCACCTACAGCTACGCGCAGGTCTCGGACTACGCTGGCCCCCCGGAGCCTCCCGCCGGTCCCATGCACCCCCGACTCGGCCCAGAGCCCGCGGGTCCCTCGATTCCGGGCCTCCTGGCGCCACCCAGCGCCCTTCACGTGTACTACGGCGCGATGGGCTCGCCCGGGGCGGGCGGCGGGCGCGGCTTCCAGATGCAGCCGCAACACCAGCACCAGCACCAGCACCAGCACCACCCCCCGGGCCCCGGACAGCCGTCGCCCCCTCCGGAGGCACTGCCCTGCCGGGACGGCACGGACCCCAGTCAGCCCGCCGAGCTCCTCGGGGAGGTGGACCGCACGGAATTTGAACAGTATCTGCACTTC" # Function that receives a gene string (only C, G, T or A characters) and outputs an array of primer hits # Looks for a GC clamp reading from start to end of the string def find_hit(gene) -> object: hits = [] for i in range(len(gene) - 20): if gene[i] == 'C' or gene[i] == 'G': if gene[i + 1] == 'C' or gene[i + 1] == 'G': if gene[i + 2] != 'C' and gene[i + 2] != 'G': cg_count = 0 for base in gene[i:i + 20]: if base == 'C' or base == 'G': cg_count += 1 if cg_count == 10 or cg_count == 11: hits.append(gene[i:i + 20]) return hits # Reverse exon 1 as GC clamp should be at the end of the primer exon1 = exon1[::-1] hits_exon1 = find_hit(exon1) hits_rev = [] for elem in hits_exon1: hits_rev.append(elem[::-1]) # Prints out the hits as read in a FASTA sequence (5' to 3') print("Forward primer candidates:") print(hits_rev) print("Reverse primer candidates:") print(find_hit(exon2))
exon1 = 'GCAGTGTCACTAGGCCGGCTGGGGGCCCTGGGTACGCTGTAGACCAGACCGCGACAGGCCAGAACACGGGCGGCGGCTTCGGGCCGGGAGACCCGCGCAGCCCTCGGGGCATCTCAGTGCCTCACTCCCCACCCCCTCCCCCGGGTCGGGGGAGGCGGCGCGTCCGGCGGAGGGTTGAGGGGAGCGGGGCAGGCCTGGAGCGCCATGAGCAGCCCGGATGCGGGATACGCCAGTGACGACCAGAGCCAGACCCAGAGCGCGCTGCCCGCGGTGATGGCCGGGCTGGGCCCCTGCCCCTGGGCCGAGTCGCTGAGCCCCATCGGGGACATGAAGGTGAAGGGCGAGGCGCCGGCGAACAGCGGAGCACCGGCCGGGGCCGCGGGCCGAGCCAAGGGCGAGTCCCGTATCCGGCGGCCGATGAACGCTTTCATGGTGTGGGCTAAGGACGAGCGCAAGCGGCTGGCGCAGCAGAATCCAGACCTGCACAACGCCGAGTTGAGCAAGATGCTGG' exon2 = 'GCAAGTCGTGGAAGGCGCTGACGCTGGCGGAGAAGCGGCCCTTCGTGGAGGAGGCAGAGCGGCTGCGCGTGCAGCACATGCAGGACCACCCCAACTACAAGTACCGGCCGCGGCGGCGCAAGCAGGTGAAGCGGCTGAAGCGGGTGGAGGGCGGCTTCCTGCACGGCCTGGCTGAGCCGCAGGCGGCCGCGCTGGGCCCCGAGGGCGGCCGCGTGGCCATGGACGGCCTGGGCCTCCAGTTCCCCGAGCAGGGCTTCCCCGCCGGCCCGCCGCTGCTGCCTCCGCACATGGGCGGCCACTACCGCGACTGCCAGAGTCTGGGCGCGCCTCCGCTCGACGGCTACCCGTTGCCCACGCCCGACACGTCCCCGCTGGACGGCGTGGACCCCGACCCGGCTTTCTTCGCCGCCCCGATGCCCGGGGACTGCCCGGCGGCCGGCACCTACAGCTACGCGCAGGTCTCGGACTACGCTGGCCCCCCGGAGCCTCCCGCCGGTCCCATGCACCCCCGACTCGGCCCAGAGCCCGCGGGTCCCTCGATTCCGGGCCTCCTGGCGCCACCCAGCGCCCTTCACGTGTACTACGGCGCGATGGGCTCGCCCGGGGCGGGCGGCGGGCGCGGCTTCCAGATGCAGCCGCAACACCAGCACCAGCACCAGCACCAGCACCACCCCCCGGGCCCCGGACAGCCGTCGCCCCCTCCGGAGGCACTGCCCTGCCGGGACGGCACGGACCCCAGTCAGCCCGCCGAGCTCCTCGGGGAGGTGGACCGCACGGAATTTGAACAGTATCTGCACTTC' def find_hit(gene) -> object: hits = [] for i in range(len(gene) - 20): if gene[i] == 'C' or gene[i] == 'G': if gene[i + 1] == 'C' or gene[i + 1] == 'G': if gene[i + 2] != 'C' and gene[i + 2] != 'G': cg_count = 0 for base in gene[i:i + 20]: if base == 'C' or base == 'G': cg_count += 1 if cg_count == 10 or cg_count == 11: hits.append(gene[i:i + 20]) return hits exon1 = exon1[::-1] hits_exon1 = find_hit(exon1) hits_rev = [] for elem in hits_exon1: hits_rev.append(elem[::-1]) print('Forward primer candidates:') print(hits_rev) print('Reverse primer candidates:') print(find_hit(exon2))
# Objective # Today we're discussing scope. Check out the Tutorial tab for learning materials and an instructional video! # The absolute difference between two integers, # and , is written as . The maximum absolute difference between two integers in a set of positive integers, , is the largest absolute difference between any two integers in # . # The Difference class is started for you in the editor. It has a private integer array ( # ) for storing non-negative integers, and a public integer ( # ) for storing the maximum absolute difference. # Task # Complete the Difference class by writing the following: # A class constructor that takes an array of integers as a parameter and saves it to the # instance variable. # A computeDifference method that finds the maximum absolute difference between any # numbers in and stores it in the # instance variable. # Input Format # You are not responsible for reading any input from stdin. The locked Solution class in the editor reads in # lines of input. The first line contains , the size of the elements array. The second line has space-separated integers that describe the # array. # Constraints # , where # Output Format # You are not responsible for printing any output; the Solution class will print the value of the # instance variable. # Sample Input # STDIN Function # ----- -------- # 3 __elements[] size N = 3 # 1 2 5 __elements = [1, 2, 5] # Sample Output # 4 # Explanation # The scope of the # array and integer is the entire class instance. The class constructor saves the argument passed to the constructor as the # instance variable (where the computeDifference method can access it). # To find the maximum difference, computeDifference checks each element in the array and finds the maximum difference between any # elements: # The maximum of these differences is , so it saves the value as the instance variable. The locked stub code in the editor then prints the value stored as , which is . class Difference: def __init__(self, a): self.__elements = a # Add your code here def computeDifference(self): diff_array=[] #loop through the i+1 to the last element and through the first ement to the second last element for i in range(len(self.__elements)-1): for j in range(i+1,len(self.__elements)): diff=abs(self.__elements[j]-self.__elements[i]) diff_array.append(diff) self.maximumDifference=max(diff_array) # End of Difference class _ = input() a = [int(e) for e in input().split(' ')] d = Difference(a) d.computeDifference() print(d.maximumDifference)
class Difference: def __init__(self, a): self.__elements = a def compute_difference(self): diff_array = [] for i in range(len(self.__elements) - 1): for j in range(i + 1, len(self.__elements)): diff = abs(self.__elements[j] - self.__elements[i]) diff_array.append(diff) self.maximumDifference = max(diff_array) _ = input() a = [int(e) for e in input().split(' ')] d = difference(a) d.computeDifference() print(d.maximumDifference)
#another way of doing recursive palindrome def is_palindrome(s): ln = len(s) if s != '': if s[ln-1] == s[0]: return True and is_palindrome(s[1:ln-1]) return False return True assert is_palindrome('abab') == False assert is_palindrome('abba') == True assert is_palindrome('madam') == True assert is_palindrome('madame') == False assert is_palindrome('') == True #non recursive loop method def is_palindrome_loop(s): ln = len(s) for i in xrange(ln/2): if not (s[i] == s[ln-i-1]): return False return True assert is_palindrome_loop('abab') == False assert is_palindrome_loop('abba') == True assert is_palindrome_loop('madam') == True assert is_palindrome_loop('madame') == False assert is_palindrome_loop('') == True #easier pythonic way def is_pal_easy(s): return s == s[::-1] assert is_pal_easy('abab') == False assert is_pal_easy('abba') == True assert is_pal_easy('madam') == True assert is_pal_easy('madame') == False assert is_pal_easy('') == True
def is_palindrome(s): ln = len(s) if s != '': if s[ln - 1] == s[0]: return True and is_palindrome(s[1:ln - 1]) return False return True assert is_palindrome('abab') == False assert is_palindrome('abba') == True assert is_palindrome('madam') == True assert is_palindrome('madame') == False assert is_palindrome('') == True def is_palindrome_loop(s): ln = len(s) for i in xrange(ln / 2): if not s[i] == s[ln - i - 1]: return False return True assert is_palindrome_loop('abab') == False assert is_palindrome_loop('abba') == True assert is_palindrome_loop('madam') == True assert is_palindrome_loop('madame') == False assert is_palindrome_loop('') == True def is_pal_easy(s): return s == s[::-1] assert is_pal_easy('abab') == False assert is_pal_easy('abba') == True assert is_pal_easy('madam') == True assert is_pal_easy('madame') == False assert is_pal_easy('') == True
class Profile(object): @property def name(self): return self.__name @property def trustRoleArn(self): return self.__trustRoleArn @property def sourceProfile(self): return self.__sourceProfile @property def credentials(self): return self.__credentials @name.setter def name(self, value): self.name = value @trustRoleArn.setter def trustRoleArn(self, value): self.__trustRoleArn = value @sourceProfile.setter def sourceProfile(self, value): self.__sourceProfile = value @credentials.setter def credentials(self, value): self.__credentials = value def __init__(self, name = None, trustRoleArn = None, sourceProfile = None, credentials = None): self.__name = name self.__trustRoleArn = trustRoleArn self.__sourceProfile = sourceProfile self.__credentials = credentials
class Profile(object): @property def name(self): return self.__name @property def trust_role_arn(self): return self.__trustRoleArn @property def source_profile(self): return self.__sourceProfile @property def credentials(self): return self.__credentials @name.setter def name(self, value): self.name = value @trustRoleArn.setter def trust_role_arn(self, value): self.__trustRoleArn = value @sourceProfile.setter def source_profile(self, value): self.__sourceProfile = value @credentials.setter def credentials(self, value): self.__credentials = value def __init__(self, name=None, trustRoleArn=None, sourceProfile=None, credentials=None): self.__name = name self.__trustRoleArn = trustRoleArn self.__sourceProfile = sourceProfile self.__credentials = credentials
# f_name = 'ex1.txt' f_name = 'input.txt' all_ingredients = set() possible_allergens = dict() recipes = list() with open(f_name, 'r') as f: for i, line in enumerate(f.readlines()): # get a list of the ingredients and record the food recipe as a set of the # ingredients (recipes = [{'aaa', 'bbb'}, {...}] ingredients = line.split(' (')[0].strip().split() recipes.append(set(ingredients)) all_ingredients |= set(ingredients) # get a list of the allergens and store a dict of allergens with the food it is # contained in (allergens_in_food[dairy] = {1, 2, 3...} allergens = line.split(' (')[1][9:-2].strip().split(', ') for a in allergens: if a not in possible_allergens: possible_allergens[a] = set(ingredients) else: possible_allergens[a] &= set(ingredients) # Part 1: count occurence of each ingredient not a possible allergen in the recipes all_possible_allergens = set((x for ing_set in possible_allergens.values() for x in ing_set)) no_allergens = all_ingredients - all_possible_allergens part1 = 0 for ing in no_allergens: part1 += sum(1 for r in recipes if ing in r) print(f'Part 1: {part1}') # Part 2 final_allergens = dict() queue = [x for x in possible_allergens if len(possible_allergens[x]) == 1] while queue: allg = queue.pop(0) ing = possible_allergens[allg].pop() final_allergens[allg] = ing possible_allergens.pop(allg) for x in possible_allergens: if ing in possible_allergens[x]: possible_allergens[x].remove(ing) queue = [x for x in possible_allergens if len(possible_allergens[x]) == 1] # generate the part2 output, ingredients sorted by allergen name part2 = ','.join([final_allergens[x] for x in sorted(final_allergens)]) print('Part 2:', part2)
f_name = 'input.txt' all_ingredients = set() possible_allergens = dict() recipes = list() with open(f_name, 'r') as f: for (i, line) in enumerate(f.readlines()): ingredients = line.split(' (')[0].strip().split() recipes.append(set(ingredients)) all_ingredients |= set(ingredients) allergens = line.split(' (')[1][9:-2].strip().split(', ') for a in allergens: if a not in possible_allergens: possible_allergens[a] = set(ingredients) else: possible_allergens[a] &= set(ingredients) all_possible_allergens = set((x for ing_set in possible_allergens.values() for x in ing_set)) no_allergens = all_ingredients - all_possible_allergens part1 = 0 for ing in no_allergens: part1 += sum((1 for r in recipes if ing in r)) print(f'Part 1: {part1}') final_allergens = dict() queue = [x for x in possible_allergens if len(possible_allergens[x]) == 1] while queue: allg = queue.pop(0) ing = possible_allergens[allg].pop() final_allergens[allg] = ing possible_allergens.pop(allg) for x in possible_allergens: if ing in possible_allergens[x]: possible_allergens[x].remove(ing) queue = [x for x in possible_allergens if len(possible_allergens[x]) == 1] part2 = ','.join([final_allergens[x] for x in sorted(final_allergens)]) print('Part 2:', part2)
S = 0 T = 0 L = [] for i in range(11): L.append(list(map(int,input().split()))) L.sort(key = lambda t:(t[0],t[1])) for i in L: T+=i[0] S += T + i[1]*20 print(S)
s = 0 t = 0 l = [] for i in range(11): L.append(list(map(int, input().split()))) L.sort(key=lambda t: (t[0], t[1])) for i in L: t += i[0] s += T + i[1] * 20 print(S)
# Evaluacion de expresiones print(3+5) print(3+2*5) print((3+2)*5) print(2**3) print(4**0.5) print(10%3) print('abra' + 'cadabra') print('ja'*3) print(1+2) print(1.0+2.0) print(1.0+2) print(1/2) print(1//2) print(1.0//2.0) print('En el curso hay ' + str(30) + ' alumnos') print('100'+'1') print(int('100') +1) # Variables a = 8 # la variable contiene el valor 8 b = 12 # la variable contiene el valor 12 print(a) print(a+b) c = a + 2 * b #creamos una expresion, se evalua y define c print(c) a = 10 #redefinimos a print(c) # el valor de c no cambia # Usar nombre descriptivos para variables a = 8 b = 12 c = a * b # Mejor: ancho = 8 largo = 12 area = ancho * largo print(area) dia = '12'; mes = 'marzo'; agno = '2018' hoy = dia + ' de ' + mes + ' de '+ agno print(hoy) # Errores ''' No incluidos directamente para que el programa corra # Errores de tipo dia = 13 mes = 'marzo' print('Hoy es ' + dia + ' de ' + mes) # Mes es tipo int # solucion print('Hoy es ' + str(dia) + ' de ' + mes) # Transformamos a string # Errores de identacion x = 3 x #tiene un 'tab' de diferencia' # Errores de sintaxis numero = 15 antecesor = (numero -1)) # Un ) de mas # Errores de nombre lado1 = 15 area = lado1/lado2 # lado2 no definido '''
print(3 + 5) print(3 + 2 * 5) print((3 + 2) * 5) print(2 ** 3) print(4 ** 0.5) print(10 % 3) print('abra' + 'cadabra') print('ja' * 3) print(1 + 2) print(1.0 + 2.0) print(1.0 + 2) print(1 / 2) print(1 // 2) print(1.0 // 2.0) print('En el curso hay ' + str(30) + ' alumnos') print('100' + '1') print(int('100') + 1) a = 8 b = 12 print(a) print(a + b) c = a + 2 * b print(c) a = 10 print(c) a = 8 b = 12 c = a * b ancho = 8 largo = 12 area = ancho * largo print(area) dia = '12' mes = 'marzo' agno = '2018' hoy = dia + ' de ' + mes + ' de ' + agno print(hoy) "\nNo incluidos directamente para que el programa corra\n\n# Errores de tipo\ndia = 13\nmes = 'marzo'\nprint('Hoy es ' + dia + ' de ' + mes) # Mes es tipo int\n# solucion\nprint('Hoy es ' + str(dia) + ' de ' + mes) # Transformamos a string\n\n# Errores de identacion \nx = 3\n x #tiene un 'tab' de diferencia' \n\n# Errores de sintaxis\n\nnumero = 15 \nantecesor = (numero -1)) # Un ) de mas\n\n# Errores de nombre \nlado1 = 15\n\narea = lado1/lado2 # lado2 no definido\n\n"
a, b, c, d = 1, 2, 3, 4 print(a, b, c, d) a, b, c, d = d, c, b, a print(a, b, c, d)
(a, b, c, d) = (1, 2, 3, 4) print(a, b, c, d) (a, b, c, d) = (d, c, b, a) print(a, b, c, d)
def test_metadata(system_config) -> None: assert system_config.provider_code == "system" assert system_config._prefix == "TEST" def test_prefixize(system_config) -> None: assert system_config.prefixize("key1") == "TEST_KEY1" assert system_config.unprefixize("TEST_KEY1") == "key1" def test_get_variable(monkeypatch, system_config) -> None: monkeypatch.setenv("TEST_KEY1", "1") monkeypatch.setenv("TEST_KEY2", "2") assert system_config.get("key1") == "1" assert system_config.get("key2") == "2" monkeypatch.undo() def test_get_variables_list(monkeypatch, system_config) -> None: monkeypatch.setenv("TEST_KEY1", "1") monkeypatch.setenv("TEST_KEY2", "2") monkeypatch.setenv("TEZT_T1", "1") monkeypatch.setenv("TEZT_T2", "2") assert "key1" in system_config.keys() assert "key2" in system_config.keys() assert "t1" not in system_config.keys() assert "t2" not in system_config.keys() monkeypatch.undo()
def test_metadata(system_config) -> None: assert system_config.provider_code == 'system' assert system_config._prefix == 'TEST' def test_prefixize(system_config) -> None: assert system_config.prefixize('key1') == 'TEST_KEY1' assert system_config.unprefixize('TEST_KEY1') == 'key1' def test_get_variable(monkeypatch, system_config) -> None: monkeypatch.setenv('TEST_KEY1', '1') monkeypatch.setenv('TEST_KEY2', '2') assert system_config.get('key1') == '1' assert system_config.get('key2') == '2' monkeypatch.undo() def test_get_variables_list(monkeypatch, system_config) -> None: monkeypatch.setenv('TEST_KEY1', '1') monkeypatch.setenv('TEST_KEY2', '2') monkeypatch.setenv('TEZT_T1', '1') monkeypatch.setenv('TEZT_T2', '2') assert 'key1' in system_config.keys() assert 'key2' in system_config.keys() assert 't1' not in system_config.keys() assert 't2' not in system_config.keys() monkeypatch.undo()
def read_matrix(): rows_count = int(input()) matrix = [] for _ in range(rows_count): row = [int(r) for r in input().split(' ')] matrix.append(row) return matrix def get_primary_diagonal_sum(matrix): p_d_sum = 0 for i in range(len(matrix)): p_d_sum += matrix[i][i] return p_d_sum def get_secondary_diagonal_sum(matrix): s_d_sum = 0 for i in range(len(matrix)): s_d_sum += matrix[i][len(matrix) - i - 1] return s_d_sum matrix = read_matrix() primary_diagonal_sum = get_primary_diagonal_sum(matrix) secondary_diagonal_sum = get_secondary_diagonal_sum(matrix) print(abs(primary_diagonal_sum - secondary_diagonal_sum))
def read_matrix(): rows_count = int(input()) matrix = [] for _ in range(rows_count): row = [int(r) for r in input().split(' ')] matrix.append(row) return matrix def get_primary_diagonal_sum(matrix): p_d_sum = 0 for i in range(len(matrix)): p_d_sum += matrix[i][i] return p_d_sum def get_secondary_diagonal_sum(matrix): s_d_sum = 0 for i in range(len(matrix)): s_d_sum += matrix[i][len(matrix) - i - 1] return s_d_sum matrix = read_matrix() primary_diagonal_sum = get_primary_diagonal_sum(matrix) secondary_diagonal_sum = get_secondary_diagonal_sum(matrix) print(abs(primary_diagonal_sum - secondary_diagonal_sum))
''' 1. The algorithm is a substitution cipher. It shifts each letter by a certain key. 2. Python Library Functions used : a) ord() : Converts a character to its equivalent ASCII value. b) chr() : Converts an ASCII value to its equivalent character. 3. What are 65 and 97? a) 65 is the ASCII value of 'A'. b) 97 is the ASCII value of 'a'. ''' # Get number equivalent of a character def get_num_equivalent(char): return ( ord(char) - 65) if char.isupper() else (ord(char) - 97) # Get character equivalent of a number def get_char_equivalent(char, num): return chr(num + 65) if char.isupper() else chr(num + 97) # Encryption Algorithm def encrypt(plain_text, key): encrypted_text = '' for char in plain_text: num_equivalent = get_num_equivalent(char) # Formula : (num_equivalent + key) mod 26 encrypted_num = (num_equivalent + key) % 26 encrypted_text += get_char_equivalent(char, encrypted_num) return encrypted_text # Decryption Algorithm def decrypt(encrypted_text, key): decrypted_text = '' for char in encrypted_text: num_equivalent = get_num_equivalent(char) # Formula : (num_equivalent - key) mod 26 decrypted_num = (num_equivalent - key) % 26 decrypted_text += get_char_equivalent(char, decrypted_num) return decrypted_text # Driver Code if __name__ == '__main__': plain_text, key = 'TheSkinnyCoder', 3 encrypted_text = encrypt(plain_text, key) decrypted_text = decrypt(encrypted_text, key) print(f'The Original Text is : {plain_text}') print(f'The Encrypted Cipher Text is : {encrypted_text}') print(f'The Decrypted Text is : {decrypted_text}')
""" 1. The algorithm is a substitution cipher. It shifts each letter by a certain key. 2. Python Library Functions used : a) ord() : Converts a character to its equivalent ASCII value. b) chr() : Converts an ASCII value to its equivalent character. 3. What are 65 and 97? a) 65 is the ASCII value of 'A'. b) 97 is the ASCII value of 'a'. """ def get_num_equivalent(char): return ord(char) - 65 if char.isupper() else ord(char) - 97 def get_char_equivalent(char, num): return chr(num + 65) if char.isupper() else chr(num + 97) def encrypt(plain_text, key): encrypted_text = '' for char in plain_text: num_equivalent = get_num_equivalent(char) encrypted_num = (num_equivalent + key) % 26 encrypted_text += get_char_equivalent(char, encrypted_num) return encrypted_text def decrypt(encrypted_text, key): decrypted_text = '' for char in encrypted_text: num_equivalent = get_num_equivalent(char) decrypted_num = (num_equivalent - key) % 26 decrypted_text += get_char_equivalent(char, decrypted_num) return decrypted_text if __name__ == '__main__': (plain_text, key) = ('TheSkinnyCoder', 3) encrypted_text = encrypt(plain_text, key) decrypted_text = decrypt(encrypted_text, key) print(f'The Original Text is : {plain_text}') print(f'The Encrypted Cipher Text is : {encrypted_text}') print(f'The Decrypted Text is : {decrypted_text}')
#!/usr/bin/env python3 #!/usr/bin/python3 dict1 = { 'a': 1, 'b': 2, } dict2 = { 'a': 0, 'b': 2, } if dict1 == dict2: print("FAIL") else: print("PASS") dict1 = { 'a': { 'c': 'bake' }, 'b': 2, } dict2 = { 'a': { 'c': 'shake' }, 'b': 2, } if dict1 == dict2: print("FAIL") else: print("PASS") dict1 = { 'a': { 'c': [0, 1] }, 'b': 2, } dict2 = { 'a': { 'c': [0, 2] }, 'b': 2, } if dict1 == dict2: print("FAIL") else: print("PASS")
dict1 = {'a': 1, 'b': 2} dict2 = {'a': 0, 'b': 2} if dict1 == dict2: print('FAIL') else: print('PASS') dict1 = {'a': {'c': 'bake'}, 'b': 2} dict2 = {'a': {'c': 'shake'}, 'b': 2} if dict1 == dict2: print('FAIL') else: print('PASS') dict1 = {'a': {'c': [0, 1]}, 'b': 2} dict2 = {'a': {'c': [0, 2]}, 'b': 2} if dict1 == dict2: print('FAIL') else: print('PASS')
## Grasshopper - Summation ## 8 kyu ## https://www.codewars.com/kata/55d24f55d7dd296eb9000030 def summation(num): return sum([i for i in range(num+1)])
def summation(num): return sum([i for i in range(num + 1)])
LEFT_ALIGNED = 0 RIGHT_ALIGNED = 1 CENTER_ALIGNED = 2 JUSTIFIED_ALIGNED = 3 NATURAL_ALIGNED = 4
left_aligned = 0 right_aligned = 1 center_aligned = 2 justified_aligned = 3 natural_aligned = 4
score_1 = float(input('Type your 1st score: ')) score_2 = float(input('Type your 2nd score: ')) average = (score_1 + score_2) / 2 print(f'Your average is {average}, therefore you...') print('Pass. Congrats.') if average > 6 \ else print('Fail. Study again, you\'ll get it. :)')
score_1 = float(input('Type your 1st score: ')) score_2 = float(input('Type your 2nd score: ')) average = (score_1 + score_2) / 2 print(f'Your average is {average}, therefore you...') print('Pass. Congrats.') if average > 6 else print("Fail. Study again, you'll get it. :)")
class NoDataError(Exception): def __init__(self, field, obj, module): message = "Missing field '" + field + "' in the object " + str(obj) + " needed in " + module super(NoDataError, self).__init__(message)
class Nodataerror(Exception): def __init__(self, field, obj, module): message = "Missing field '" + field + "' in the object " + str(obj) + ' needed in ' + module super(NoDataError, self).__init__(message)
class Event(): def __init__(self, guild_id, event_type, target_id, target_name, actor, reason, timestamp, role_id=None, role_name=None, count=None, message_id=None): self.guild_id = guild_id self.event_type = event_type self.target_id = target_id self.target_name = target_name self.actor = actor self.reason = reason self.timestamp = timestamp self.role_id = role_id self.role_name = role_name self.count = count self.message_id = message_id @classmethod def from_row(cls, row, actor=None, reason=None): return cls(row.get("guild_id"), row.get("event_type"), row.get("target_id"), row.get("target_name"), row.get("actor") if not actor else actor, row.get("reason") if not reason else reason, row.get("timestamp"), row.get("role_id"), row.get("role_name"), row.get("event_id"), row.get("message_id")) def set_actor(self, actor): self.actor = actor def set_count(self, count): self.count = count def db_insert(self): return (self.guild_id, self.event_type, self.target_id, self.target_name, self.actor if type(self.actor) == int else self.actor.id, self.reason, self.timestamp, self.role_id, self.role_name, self.count)
class Event: def __init__(self, guild_id, event_type, target_id, target_name, actor, reason, timestamp, role_id=None, role_name=None, count=None, message_id=None): self.guild_id = guild_id self.event_type = event_type self.target_id = target_id self.target_name = target_name self.actor = actor self.reason = reason self.timestamp = timestamp self.role_id = role_id self.role_name = role_name self.count = count self.message_id = message_id @classmethod def from_row(cls, row, actor=None, reason=None): return cls(row.get('guild_id'), row.get('event_type'), row.get('target_id'), row.get('target_name'), row.get('actor') if not actor else actor, row.get('reason') if not reason else reason, row.get('timestamp'), row.get('role_id'), row.get('role_name'), row.get('event_id'), row.get('message_id')) def set_actor(self, actor): self.actor = actor def set_count(self, count): self.count = count def db_insert(self): return (self.guild_id, self.event_type, self.target_id, self.target_name, self.actor if type(self.actor) == int else self.actor.id, self.reason, self.timestamp, self.role_id, self.role_name, self.count)
nintendo_games = ['Zelda', 'Mario', 'Donkey Kong', 'Zelda'] nintendo_games.remove('Zelda') print(nintendo_games) if 'Wario' in nintendo_games: nintendo_games.remove('Wario')
nintendo_games = ['Zelda', 'Mario', 'Donkey Kong', 'Zelda'] nintendo_games.remove('Zelda') print(nintendo_games) if 'Wario' in nintendo_games: nintendo_games.remove('Wario')
class Test: def initialize(self): self.x = 42 t = Test() t.initialize() def calc(self, n): return self.x + n Test.calc = calc assert t.calc(4) == 46
class Test: def initialize(self): self.x = 42 t = test() t.initialize() def calc(self, n): return self.x + n Test.calc = calc assert t.calc(4) == 46
# Time: O(n) # Space: O(1) # # 123 # Say you have an array for which the ith element # is the price of a given stock on day i. # # Design an algorithm to find the maximum profit. # You may complete at most two transactions. # # Note: # You may not engage in multiple transactions at the same time # (ie, you must sell the stock before you buy again). # # Input: [3,3,5,0,0,3,1,4] # Output: 6 (= 3-0 + 4-1) # Input: [1,2,3,4,5] # Output: 4 try: xrange # Python 2 except NameError: xrange = range # Python 3 class Solution(object): # USE THIS: CAN EXTEND to k transactions. # @param prices, a list of integer # @return an integer def maxProfit(self, prices): hold1, hold2 = float('-inf'), float('-inf') cash1, cash2 = 0, 0 for p in prices: # to be sequential, hold[j] refers to cash[j-1], and cash[j] refers to hold[j]. # because it is ok to buy then sell in the same day, so the 4 lines # don't need to execute simultaneously (i.e. write in 1 line) hold1 = max(hold1, -p) cash1 = max(cash1, hold1+p) hold2 = max(hold2, cash1-p) cash2 = max(cash2, hold2+p) return cash2 # This solution is AN EXTENSION OF SOLUTION for buy-and-sell-stock-i, and can extend to k. # hold[i] is the balance after ith buy, cash[i] is the balance after ith sell. def maxProfit_extend(self, prices): n, k = len(prices), 2 hold = [float('-inf')] * (k + 1) # entry at index 0 is easy to calculate boundary value cash = [0] * (k + 1) for i in range(n): # because k is constant, won't benefit much by doing the following optimization: # optimization skip unnecessary large k. Need to be i+1, so when i is 0, still set hold[0]. # kamyu solution uses min(k, i//2+1) + 1, but I think for day i, we can do i transactions. #for j in range(1, min(k, i+1)+1): for j in range(1, k + 1): # to be sequential, hold[j] refers to cash[j-1], and cash[j] refers to hold[j] hold[j] = max(hold[j], cash[j-1] - prices[i]) # maximize max_buy means price at buy point needs to be as small as possible cash[j] = max(cash[j], hold[j] + prices[i]) return cash[-1] # Time: O(n) # Space: O(1) class Solution2(object): # similar to Solution 1, but track cost/profit instead of balances. # Maintain the min COST of if we just buy 1, 2, 3... stock, and the max PROFIT (balance) of if we just sell 1,2,3... stock. # In order to get the final max profit, profit1 must be as relatively large as possible to produce a small cost2, # and therefore cost2 can be as small as possible to give the final max profit2. def maxProfit(self, prices): cost1, cost2 = float("inf"), float("inf") profit1, profit2 = 0, 0 for p in prices: cost1 = min(cost1, p) # lowest price profit1 = max(profit1, p - cost1) # global max profit for 1 buy-sell transaction cost2 = min(cost2, p - profit1) # adjust the cost by reducing 1st profit profit2 = max(profit2, p - cost2) # global max profit for 1 to 2 transactions return profit2 # This solution CANNOT extend to k transactions. # Time: O(n) # Space: O(n) class Solution3(object): # @param prices, a list of integer # @return an integer # use any day as divider for 1st and 2nd stock transaction. Compare all possible division # (linear time). Ok to sell then buy at the same day, so divider is on each day (dp array # is length N), not between two days. def maxProfit(self, prices): N = len(prices) _min, maxProfitLeft, maxProfitsLeft = float("inf"), 0, [0]*N _max, maxProfitRight, maxProfitsRight = 0, 0, [0]*N for i in range(N): _min = min(_min, prices[i]) maxProfitLeft = max(maxProfitLeft, prices[i] - _min) maxProfitsLeft[i] = maxProfitLeft _max = max(_max, prices[N-1-i]) maxProfitRight = max(maxProfitRight, _max - prices[N-1-i]) maxProfitsRight[N-1-i] = maxProfitRight return max(maxProfitsLeft[i]+maxProfitsRight[i] for i in range(N)) if N else 0 print(Solution().maxProfit([1,3,2,8,4,9])) # 12 print(Solution().maxProfit([1,2,3,4,5])) # 4 print(Solution().maxProfit([3,3,5,0,0,3,1,4])) # 6
try: xrange except NameError: xrange = range class Solution(object): def max_profit(self, prices): (hold1, hold2) = (float('-inf'), float('-inf')) (cash1, cash2) = (0, 0) for p in prices: hold1 = max(hold1, -p) cash1 = max(cash1, hold1 + p) hold2 = max(hold2, cash1 - p) cash2 = max(cash2, hold2 + p) return cash2 def max_profit_extend(self, prices): (n, k) = (len(prices), 2) hold = [float('-inf')] * (k + 1) cash = [0] * (k + 1) for i in range(n): for j in range(1, k + 1): hold[j] = max(hold[j], cash[j - 1] - prices[i]) cash[j] = max(cash[j], hold[j] + prices[i]) return cash[-1] class Solution2(object): def max_profit(self, prices): (cost1, cost2) = (float('inf'), float('inf')) (profit1, profit2) = (0, 0) for p in prices: cost1 = min(cost1, p) profit1 = max(profit1, p - cost1) cost2 = min(cost2, p - profit1) profit2 = max(profit2, p - cost2) return profit2 class Solution3(object): def max_profit(self, prices): n = len(prices) (_min, max_profit_left, max_profits_left) = (float('inf'), 0, [0] * N) (_max, max_profit_right, max_profits_right) = (0, 0, [0] * N) for i in range(N): _min = min(_min, prices[i]) max_profit_left = max(maxProfitLeft, prices[i] - _min) maxProfitsLeft[i] = maxProfitLeft _max = max(_max, prices[N - 1 - i]) max_profit_right = max(maxProfitRight, _max - prices[N - 1 - i]) maxProfitsRight[N - 1 - i] = maxProfitRight return max((maxProfitsLeft[i] + maxProfitsRight[i] for i in range(N))) if N else 0 print(solution().maxProfit([1, 3, 2, 8, 4, 9])) print(solution().maxProfit([1, 2, 3, 4, 5])) print(solution().maxProfit([3, 3, 5, 0, 0, 3, 1, 4]))
def firstDuplicateValue(array): for n in array: n = abs(n) if array[n - 1] < 0: return n array[n - 1] *= -1 return -1
def first_duplicate_value(array): for n in array: n = abs(n) if array[n - 1] < 0: return n array[n - 1] *= -1 return -1
#!/usr/bin/python # -*- coding: utf-8 -*- def read_gowalla_data(file_path): train_file = open(file_path, 'r') x_data = {} for i in open(file_path): line = train_file.readline() # line = line.strip('\n') if len(line) == 0: continue items = line.split("\t") user_id = items[0] if len(user_id) == 0: continue user_id = int(user_id) if user_id not in x_data.keys(): x_data[user_id] = list() poi_id = items[4] if len(poi_id) == 0: continue else: poi_id = int(poi_id) x_data[user_id].append(poi_id) train_file.close() return x_data def read_foursquare_data(file_path): train_file = open(file_path, 'r') x_data = {} while 1: line = train_file.readline() if not line: break if len(line) == 0: continue items = line.split("\t") user_id = items[0].split("_")[1] if len(user_id) == 0: continue user_id = int(user_id) if user_id not in x_data.keys(): x_data[user_id] = list() poi_id = items[1].split("_")[1] if len(poi_id) == 0: continue else: poi_id = int(poi_id) x_data[user_id].append(poi_id) train_file.close() return x_data def read_gtd_data(file_path): train_file = open(file_path, 'r') x_data = {} while 1: line = train_file.readline() if not line: break if len(line) == 0: continue items = line.split("\t") user_id = items[6] if len(user_id) == 0: continue user_id = int(user_id) if user_id not in x_data.keys(): x_data[user_id] = list() poi_id = items[2] if len(poi_id) == 0: continue else: poi_id = int(poi_id) x_data[user_id].append(poi_id) train_file.close() return x_data def read_foursquare_users(): users = set() t_file = open('../foursquare/foursquare_records.txt', 'r') for i in open('../foursquare/foursquare_records.txt'): line = t_file.readline() items = line.split("\t") user_id = int(items[0].split("_")[1]) users.add(user_id) t_file.close() num_users = len(users) return num_users def read_foursquare_pois(): pois = set() t_file = open('../foursquare/foursquare_records.txt', 'r') for i in open('../foursquare/foursquare_records.txt'): line = t_file.readline() items = line.split("\t") poi_id = int(items[1].split("_")[1]) pois.add(poi_id) t_file.close() num_pois = len(pois) return num_pois def read_gtd_users(): users = set() t_file = open('../GTD/old_GTD-1335/indexed_GTD.txt', 'r') for i in open('../GTD/old_GTD-1335/indexed_GTD.txt'): line = t_file.readline() items = line.split("\t") user_id = int(items[6]) users.add(user_id) t_file.close() num_users = len(users) return num_users def read_gtd_pois(): pois = set() t_file = open('../GTD/old_GTD-1335/indexed_GTD.txt', 'r') for i in open('../GTD/old_GTD-1335/indexed_GTD.txt'): line = t_file.readline() items = line.split("\t") poi_id = int(items[2]) pois.add(poi_id) t_file.close() num_pois = len(pois) return num_pois def read_gowalla_users(): users = set() t_file = open('../gowalla/sorted_indexed_final_gowalla.txt', 'r') for i in open('../gowalla/sorted_indexed_final_gowalla.txt'): line = t_file.readline() items = line.split("\t") user_id = int(items[0]) users.add(user_id) t_file.close() num_users = len(users) return num_users def read_gowalla_pois(): pois = set() t_file = open('../gowalla/sorted_indexed_final_gowalla.txt', 'r') for i in open('../gowalla/sorted_indexed_final_gowalla.txt'): line = t_file.readline() items = line.split("\t") poi_id = int(items[4]) pois.add(poi_id) t_file.close() num_pois = len(pois) return num_pois
def read_gowalla_data(file_path): train_file = open(file_path, 'r') x_data = {} for i in open(file_path): line = train_file.readline() if len(line) == 0: continue items = line.split('\t') user_id = items[0] if len(user_id) == 0: continue user_id = int(user_id) if user_id not in x_data.keys(): x_data[user_id] = list() poi_id = items[4] if len(poi_id) == 0: continue else: poi_id = int(poi_id) x_data[user_id].append(poi_id) train_file.close() return x_data def read_foursquare_data(file_path): train_file = open(file_path, 'r') x_data = {} while 1: line = train_file.readline() if not line: break if len(line) == 0: continue items = line.split('\t') user_id = items[0].split('_')[1] if len(user_id) == 0: continue user_id = int(user_id) if user_id not in x_data.keys(): x_data[user_id] = list() poi_id = items[1].split('_')[1] if len(poi_id) == 0: continue else: poi_id = int(poi_id) x_data[user_id].append(poi_id) train_file.close() return x_data def read_gtd_data(file_path): train_file = open(file_path, 'r') x_data = {} while 1: line = train_file.readline() if not line: break if len(line) == 0: continue items = line.split('\t') user_id = items[6] if len(user_id) == 0: continue user_id = int(user_id) if user_id not in x_data.keys(): x_data[user_id] = list() poi_id = items[2] if len(poi_id) == 0: continue else: poi_id = int(poi_id) x_data[user_id].append(poi_id) train_file.close() return x_data def read_foursquare_users(): users = set() t_file = open('../foursquare/foursquare_records.txt', 'r') for i in open('../foursquare/foursquare_records.txt'): line = t_file.readline() items = line.split('\t') user_id = int(items[0].split('_')[1]) users.add(user_id) t_file.close() num_users = len(users) return num_users def read_foursquare_pois(): pois = set() t_file = open('../foursquare/foursquare_records.txt', 'r') for i in open('../foursquare/foursquare_records.txt'): line = t_file.readline() items = line.split('\t') poi_id = int(items[1].split('_')[1]) pois.add(poi_id) t_file.close() num_pois = len(pois) return num_pois def read_gtd_users(): users = set() t_file = open('../GTD/old_GTD-1335/indexed_GTD.txt', 'r') for i in open('../GTD/old_GTD-1335/indexed_GTD.txt'): line = t_file.readline() items = line.split('\t') user_id = int(items[6]) users.add(user_id) t_file.close() num_users = len(users) return num_users def read_gtd_pois(): pois = set() t_file = open('../GTD/old_GTD-1335/indexed_GTD.txt', 'r') for i in open('../GTD/old_GTD-1335/indexed_GTD.txt'): line = t_file.readline() items = line.split('\t') poi_id = int(items[2]) pois.add(poi_id) t_file.close() num_pois = len(pois) return num_pois def read_gowalla_users(): users = set() t_file = open('../gowalla/sorted_indexed_final_gowalla.txt', 'r') for i in open('../gowalla/sorted_indexed_final_gowalla.txt'): line = t_file.readline() items = line.split('\t') user_id = int(items[0]) users.add(user_id) t_file.close() num_users = len(users) return num_users def read_gowalla_pois(): pois = set() t_file = open('../gowalla/sorted_indexed_final_gowalla.txt', 'r') for i in open('../gowalla/sorted_indexed_final_gowalla.txt'): line = t_file.readline() items = line.split('\t') poi_id = int(items[4]) pois.add(poi_id) t_file.close() num_pois = len(pois) return num_pois
# Which environment frames do we need to keep during evaluation? # There is a set of active environments Values and frames in active environments consume memory # Memory that is used for other values and frames can be recycled # Active environments: # Environments for any functions calls currently being evaluated # Parent environments of functions named in active environments # Functions returned can be reused # max length of active frames at any given time determines how many memory we need def count_frames(f): def counted(*arg): counted.open_count += 1 if counted.max_count < counted.open_count: counted.max_count = counted.open_count result = f(*arg) counted.open_count -= 1 return result counted.open_count = 0 counted.max_count = 0 return counted @count_frames def fib(n): if n ==0 or n ==1: return n else: return fib(n-2) + fib(n-1)
def count_frames(f): def counted(*arg): counted.open_count += 1 if counted.max_count < counted.open_count: counted.max_count = counted.open_count result = f(*arg) counted.open_count -= 1 return result counted.open_count = 0 counted.max_count = 0 return counted @count_frames def fib(n): if n == 0 or n == 1: return n else: return fib(n - 2) + fib(n - 1)
class Solution: def XXX(self, nums: List[int]) -> List[List[int]]: return [[nums[j] for j in range(len(nums)) if i&2**j] for i in range(2**len(nums))]
class Solution: def xxx(self, nums: List[int]) -> List[List[int]]: return [[nums[j] for j in range(len(nums)) if i & 2 ** j] for i in range(2 ** len(nums))]
def viralAdvertising(n): return if __name__ == '__main__': n = int(input()) viralAdvertising(n)
def viral_advertising(n): return if __name__ == '__main__': n = int(input()) viral_advertising(n)
# This is just a demo file print("Hello world") print("this is update to my previous code")
print('Hello world') print('this is update to my previous code')
n = int(input()) # n = 3 sum1 = 0 sum2 = 0 for i in range(1, n + 1): # print("i = ", i) if i % 2 == 0: sum1 += i else: sum2 += i if sum1 == 0: print(sum2) else: print(sum2 - sum1)
n = int(input()) sum1 = 0 sum2 = 0 for i in range(1, n + 1): if i % 2 == 0: sum1 += i else: sum2 += i if sum1 == 0: print(sum2) else: print(sum2 - sum1)
class Solution: # @return a tuple, (index1, index2) def twoSum(self, num, target): length = len(num) # use dict: value: index + 1 # since there is only one solution, the right value must not be duplicated dic = {} for i in xrange(0, length): val = num[i] if (target - val) in dic: return (dic[target - val], i + 1) dic[val] = i + 1 ## test code # num=[2, 7, 11, 15] # t= 26 # s = Solution() # print s.twoSum(num, t)
class Solution: def two_sum(self, num, target): length = len(num) dic = {} for i in xrange(0, length): val = num[i] if target - val in dic: return (dic[target - val], i + 1) dic[val] = i + 1
#Tree Size class Node: def __init__(self, data): self.data = data self.left = None self.right = None def sizeTree(node): if node is None: return 0 else: return (sizeTree(node.left) + 1 + sizeTree(node.right)) # Driver program to test above function root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print("Size of the tree is {}".format(sizeTree(root)))
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def size_tree(node): if node is None: return 0 else: return size_tree(node.left) + 1 + size_tree(node.right) root = node(1) root.left = node(2) root.right = node(3) root.left.left = node(4) root.left.right = node(5) print('Size of the tree is {}'.format(size_tree(root)))
''' One Away: There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away. Example: pale, ple -> true pales, pale -> true pale, bale -> true pale, bake -> false bla, bleble -> false ''' def is_two_chars_away(str1, str2): return (len(str1) - len(str2) >= 2) or (len(str2) - len(str1) >= 2) def number_of_needed_changes(bigger_str, smaller_str): str_counter = {} for char in bigger_str: if char in str_counter: str_counter[char] += 1 else: str_counter[char] = 1 for char in smaller_str: if char in str_counter: str_counter[char] -= 1 needed_changes = 0 for char, counter in str_counter.items(): needed_changes += counter return needed_changes def one_away(str1, str2): if is_two_chars_away(str1, str2): return False needed_changes = 0 if len(str1) >= len(str2): needed_changes = number_of_needed_changes(str1, str2) else: needed_changes = number_of_needed_changes(str2, str1) return needed_changes <= 1 data = [ ('pale', 'ple', True), ('pales', 'pale', True), ('pale', 'bale', True), ('paleabc', 'pleabc', True), ('pale', 'ble', False), ('a', 'b', True), ('', 'd', True), ('d', 'de', True), ('pale', 'pale', True), ('pale', 'ple', True), ('ple', 'pale', True), ('pale', 'bale', True), ('pale', 'bake', False), ('pale', 'pse', False), ('ples', 'pales', True), ('pale', 'pas', False), ('pas', 'pale', False), ('pale', 'pkle', True), ('pkle', 'pable', False), ('pal', 'palks', False), ('palks', 'pal', False), ('bla', 'bleble', False) ] for [test_s1, test_s2, expected] in data: actual = one_away(test_s1, test_s2) print(actual == expected)
""" One Away: There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away. Example: pale, ple -> true pales, pale -> true pale, bale -> true pale, bake -> false bla, bleble -> false """ def is_two_chars_away(str1, str2): return len(str1) - len(str2) >= 2 or len(str2) - len(str1) >= 2 def number_of_needed_changes(bigger_str, smaller_str): str_counter = {} for char in bigger_str: if char in str_counter: str_counter[char] += 1 else: str_counter[char] = 1 for char in smaller_str: if char in str_counter: str_counter[char] -= 1 needed_changes = 0 for (char, counter) in str_counter.items(): needed_changes += counter return needed_changes def one_away(str1, str2): if is_two_chars_away(str1, str2): return False needed_changes = 0 if len(str1) >= len(str2): needed_changes = number_of_needed_changes(str1, str2) else: needed_changes = number_of_needed_changes(str2, str1) return needed_changes <= 1 data = [('pale', 'ple', True), ('pales', 'pale', True), ('pale', 'bale', True), ('paleabc', 'pleabc', True), ('pale', 'ble', False), ('a', 'b', True), ('', 'd', True), ('d', 'de', True), ('pale', 'pale', True), ('pale', 'ple', True), ('ple', 'pale', True), ('pale', 'bale', True), ('pale', 'bake', False), ('pale', 'pse', False), ('ples', 'pales', True), ('pale', 'pas', False), ('pas', 'pale', False), ('pale', 'pkle', True), ('pkle', 'pable', False), ('pal', 'palks', False), ('palks', 'pal', False), ('bla', 'bleble', False)] for [test_s1, test_s2, expected] in data: actual = one_away(test_s1, test_s2) print(actual == expected)
max_n = 10**17 fibs = [ (1, 1), (2, 1), ] while fibs[-1][0] < max_n: fibs.append( (fibs[-1][0] + fibs[-2][0], fibs[-1][1] + fibs[-2][1]) ) print(fibs) counts = [ 1, 1 ] for i in range(2, len(fibs)): fib = fibs[i] counts.append(fib[1] + sum(counts[j] for j in range(i - 1))) print(counts) def count(n): smallest_over_index = 0 smallest_over = fibs[smallest_over_index][0] while smallest_over < n: smallest_over_index += 1 smallest_over = fibs[smallest_over_index][0] if smallest_over == n + 1: return sum(counts[i] for i in range(smallest_over_index)) if smallest_over == n: return 1 + count(n - 1) smallest_under = fibs[smallest_over_index - 1][0] return sum(counts[i] for i in range(smallest_over_index - 1)) + count(n - smallest_under) + n - smallest_under print(count(10**17) - 1)
max_n = 10 ** 17 fibs = [(1, 1), (2, 1)] while fibs[-1][0] < max_n: fibs.append((fibs[-1][0] + fibs[-2][0], fibs[-1][1] + fibs[-2][1])) print(fibs) counts = [1, 1] for i in range(2, len(fibs)): fib = fibs[i] counts.append(fib[1] + sum((counts[j] for j in range(i - 1)))) print(counts) def count(n): smallest_over_index = 0 smallest_over = fibs[smallest_over_index][0] while smallest_over < n: smallest_over_index += 1 smallest_over = fibs[smallest_over_index][0] if smallest_over == n + 1: return sum((counts[i] for i in range(smallest_over_index))) if smallest_over == n: return 1 + count(n - 1) smallest_under = fibs[smallest_over_index - 1][0] return sum((counts[i] for i in range(smallest_over_index - 1))) + count(n - smallest_under) + n - smallest_under print(count(10 ** 17) - 1)
class StateMachine: def __init__(self, initialState): self.currentState = initialState self.currentState.run() # Template method: def runAll(self, inputs): self.currentState = self.currentState.next_state(inputs) self.currentState.run()
class Statemachine: def __init__(self, initialState): self.currentState = initialState self.currentState.run() def run_all(self, inputs): self.currentState = self.currentState.next_state(inputs) self.currentState.run()
numbers = [8, 6, 4, 1, 3, 7, 9, 5, 2] def pancake_sort(array): target_index = len(array)-1 while target_index > 0: max_value = array[target_index] max_index = target_index for number in range(0, target_index): if array[number] > max_value: max_value = array[number] max_index = number array = flip(array, max_index) array = flip(array, target_index) target_index -= 1 return array def flip(array, end_index): unreversed_part = array[end_index+1:] reversed_part = array[end_index::-1] return reversed_part + unreversed_part print(pancake_sort(numbers))
numbers = [8, 6, 4, 1, 3, 7, 9, 5, 2] def pancake_sort(array): target_index = len(array) - 1 while target_index > 0: max_value = array[target_index] max_index = target_index for number in range(0, target_index): if array[number] > max_value: max_value = array[number] max_index = number array = flip(array, max_index) array = flip(array, target_index) target_index -= 1 return array def flip(array, end_index): unreversed_part = array[end_index + 1:] reversed_part = array[end_index::-1] return reversed_part + unreversed_part print(pancake_sort(numbers))