content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE # Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt __version__ = "2.11.2" version = __version__
__version__ = '2.11.2' version = __version__
def method1(X, Y): m = len(X) n = len(Y) L = [[None] * (n + 1) for i in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: L[i][j] = 0 elif X[i - 1] == Y[j - 1]: L[i][j] = L[i - 1][j - 1] + 1 else: L[i][j] = max(L[i - 1][j], L[i][j - 1]) return L[m][n] def method2(X, Y, m, n): if m == 0 or n == 0: return 0 elif X[m - 1] == Y[n - 1]: return 1 + method2(X, Y, m - 1, n - 1) else: return max(method2(X, Y, m, n - 1), method2(X, Y, m - 1, n)) if __name__ == "__main__": """ from timeit import timeit X = "AGGTAB" Y = "GXTXAYB" print(timeit(lambda: method1(X, Y), number=10000)) # 0.14817858800233807 print( timeit(lambda: method2(X, Y, len(X), len(Y)), number=10000) ) # 0.5299446069984697 """
def method1(X, Y): m = len(X) n = len(Y) l = [[None] * (n + 1) for i in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: L[i][j] = 0 elif X[i - 1] == Y[j - 1]: L[i][j] = L[i - 1][j - 1] + 1 else: L[i][j] = max(L[i - 1][j], L[i][j - 1]) return L[m][n] def method2(X, Y, m, n): if m == 0 or n == 0: return 0 elif X[m - 1] == Y[n - 1]: return 1 + method2(X, Y, m - 1, n - 1) else: return max(method2(X, Y, m, n - 1), method2(X, Y, m - 1, n)) if __name__ == '__main__': '\n from timeit import timeit\n\n X = "AGGTAB"\n Y = "GXTXAYB"\n print(timeit(lambda: method1(X, Y), number=10000)) # 0.14817858800233807\n print(\n timeit(lambda: method2(X, Y, len(X), len(Y)), number=10000)\n ) # 0.5299446069984697\n '
def combination(n, r): r = min(n - r, r) result = 1 for i in range(n, n - r, -1): result *= i for i in range(1, r + 1): result //= i return result N, A, B = map(int, input().split()) v_list = list(map(int, input().split())) v_list.sort(reverse=True) mean_max = sum(v_list[:A]) / A comb = 0 if v_list[0] != v_list[A - 1]: x = v_list.count(v_list[A - 1]) y = v_list[:A].count(v_list[A - 1]) comb = combination(x, y) else: x = v_list.count(v_list[A - 1]) for i in range(A, B + 1): if v_list[i - 1] == v_list[0]: comb += combination(x, i) print("{:.10f}".format(mean_max)) print(comb)
def combination(n, r): r = min(n - r, r) result = 1 for i in range(n, n - r, -1): result *= i for i in range(1, r + 1): result //= i return result (n, a, b) = map(int, input().split()) v_list = list(map(int, input().split())) v_list.sort(reverse=True) mean_max = sum(v_list[:A]) / A comb = 0 if v_list[0] != v_list[A - 1]: x = v_list.count(v_list[A - 1]) y = v_list[:A].count(v_list[A - 1]) comb = combination(x, y) else: x = v_list.count(v_list[A - 1]) for i in range(A, B + 1): if v_list[i - 1] == v_list[0]: comb += combination(x, i) print('{:.10f}'.format(mean_max)) print(comb)
variable1 = input('Variable 1:') variable2 = input('Variable 2:') variable1, variable2 = variable2, variable1 print(f"Variable 1: {variable1}") print(f"Variable 2: {variable2}")
variable1 = input('Variable 1:') variable2 = input('Variable 2:') (variable1, variable2) = (variable2, variable1) print(f'Variable 1: {variable1}') print(f'Variable 2: {variable2}')
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable 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. # # Build configuration for ctmalloc. This is not a part of the original # library. { 'targets': [ { 'target_name': 'ctmalloc_lib', 'type': 'static_library', 'sources': [ 'wtf/AsanHooks.cpp', 'wtf/AsanHooks.h', 'wtf/Assertions.h', 'wtf/Atomics.h', 'wtf/BitwiseOperations.h', 'wtf/ByteSwap.h', 'wtf/Compiler.h', 'wtf/config.h', 'wtf/CPU.h', 'wtf/malloc.cpp', 'wtf/PageAllocator.cpp', 'wtf/PageAllocator.h', 'wtf/PartitionAlloc.cpp', 'wtf/PartitionAlloc.h', 'wtf/ProcessID.h', 'wtf/SpinLock.h', 'wtf/WTFExport.h', ], 'defines': [ 'CTMALLOC_NDEBUG', ], 'include_dirs': [ '<(src)/third_party/ctmalloc', ], 'all_dependent_settings': { 'defines': [ # We disable debug features of the CtMalloc heap as they are redundant # given SyzyASan's extensive debug features. 'CTMALLOC_NDEBUG', ], 'include_dirs': [ '<(src)/third_party/ctmalloc', ], }, }, ], }
{'targets': [{'target_name': 'ctmalloc_lib', 'type': 'static_library', 'sources': ['wtf/AsanHooks.cpp', 'wtf/AsanHooks.h', 'wtf/Assertions.h', 'wtf/Atomics.h', 'wtf/BitwiseOperations.h', 'wtf/ByteSwap.h', 'wtf/Compiler.h', 'wtf/config.h', 'wtf/CPU.h', 'wtf/malloc.cpp', 'wtf/PageAllocator.cpp', 'wtf/PageAllocator.h', 'wtf/PartitionAlloc.cpp', 'wtf/PartitionAlloc.h', 'wtf/ProcessID.h', 'wtf/SpinLock.h', 'wtf/WTFExport.h'], 'defines': ['CTMALLOC_NDEBUG'], 'include_dirs': ['<(src)/third_party/ctmalloc'], 'all_dependent_settings': {'defines': ['CTMALLOC_NDEBUG'], 'include_dirs': ['<(src)/third_party/ctmalloc']}}]}
def main(): # Manage input file input = open(r"C:\Users\lawht\Desktop\Github\ROSALIND\Bioinformatics Stronghold\Complementing a Stand of DNA\Complementing a Stand of DNA\rosalind_revc.txt","r") DNA_string = input.readline(); # take first line of input file for counting # Take in input file of DNA string and print out its reverse complement print(reverse_complement(DNA_string)) input.close() # Given: A DNA string s of length at most 1000 bp. # Return: The reverse complement sc of s. def reverse_complement(s): sc = ""; for n in reversed(s): if n == "A": sc = sc + "T" elif n == "T": sc = sc + "A" elif n == "C": sc = sc + "G" elif n == "G": sc = sc + "C" else: continue return sc # Manually call main() on the file load if __name__ == "__main__": main()
def main(): input = open('C:\\Users\\lawht\\Desktop\\Github\\ROSALIND\\Bioinformatics Stronghold\\Complementing a Stand of DNA\\Complementing a Stand of DNA\\rosalind_revc.txt', 'r') dna_string = input.readline() print(reverse_complement(DNA_string)) input.close() def reverse_complement(s): sc = '' for n in reversed(s): if n == 'A': sc = sc + 'T' elif n == 'T': sc = sc + 'A' elif n == 'C': sc = sc + 'G' elif n == 'G': sc = sc + 'C' else: continue return sc if __name__ == '__main__': main()
""" Given a binary tree, return the postorder traversal of its nodes' values. For example: Given binary tree {1,#,2,3}, 1 \ 2 / 3 return [3,2,1]. """ # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def postorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ path = [] if root is None: return path stack1 = [] stack2 = [] stack1.append(root) while stack1: root = stack1.pop() stack2.append(root.val) if root.left is not None: stack1.append(root.left) if root.right is not None: stack1.append(root.right) while stack2: path.append(stack2.pop()) return path
""" Given a binary tree, return the postorder traversal of its nodes' values. For example: Given binary tree {1,#,2,3}, 1 2 / 3 return [3,2,1]. """ class Solution(object): def postorder_traversal(self, root): """ :type root: TreeNode :rtype: List[int] """ path = [] if root is None: return path stack1 = [] stack2 = [] stack1.append(root) while stack1: root = stack1.pop() stack2.append(root.val) if root.left is not None: stack1.append(root.left) if root.right is not None: stack1.append(root.right) while stack2: path.append(stack2.pop()) return path
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def part_1(program): i = 0 while i < len(program): opcode, a, b, dest = program[i:i+4] i += 4 assert opcode in {1, 2, 99}, f'Unexpected opcode: {opcode}' if opcode == 1: val = program[a] + program[b] elif opcode == 2: val = program[a] * program[b] elif opcode == 99: return program program[dest] = val def part_2(program, goal): for noun in range(99): for verb in range(99): p = program[:] p[1] = noun p[2] = verb p = part_1(p) if p[0] == goal: return noun, verb if __name__ == '__main__': with open('input.txt') as f: program = f.readline() program = [int(i) for i in program.split(',')] p_1 = program[:] p_1[1] = 12 p_1[2] = 2 p = part_1(p_1) print(f'part 1: {p[0]}') noun, verb = part_2(program, 19690720) print(f'part 2: noun={noun}\n\tverb={verb}')
def part_1(program): i = 0 while i < len(program): (opcode, a, b, dest) = program[i:i + 4] i += 4 assert opcode in {1, 2, 99}, f'Unexpected opcode: {opcode}' if opcode == 1: val = program[a] + program[b] elif opcode == 2: val = program[a] * program[b] elif opcode == 99: return program program[dest] = val def part_2(program, goal): for noun in range(99): for verb in range(99): p = program[:] p[1] = noun p[2] = verb p = part_1(p) if p[0] == goal: return (noun, verb) if __name__ == '__main__': with open('input.txt') as f: program = f.readline() program = [int(i) for i in program.split(',')] p_1 = program[:] p_1[1] = 12 p_1[2] = 2 p = part_1(p_1) print(f'part 1: {p[0]}') (noun, verb) = part_2(program, 19690720) print(f'part 2: noun={noun}\n\tverb={verb}')
# Copyright 2021 Duan-JM, Sun Aries # 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. # Note: passing both BUILD_SHARED_LIBS=ON and BUILD_STATIC_LIBS=ON to cmake # still only builds the shared libraries, so we have to choose one or the # other. We build shared libraries by default, but this variable can be used # to switch to static libraries. OPENCV_SHARED_LIBS = False OPENCV_TAG = "4.5.0" OPENCV_SO_VERSION = "4.5" # OPENCV_SO_VERSION need to match OPENCV_TAG # Note: this determines the order in which the libraries are passed to the # linker, so if library A depends on library B, library B must come _after_. # Hence core is at the bottom. OPENCV_MODULES = [ "calib3d", "features2d", "flann", "highgui", "video", "videoio", "imgcodecs", "imgproc", "core", ] OPENCV_THIRD_PARTY_DEPS = [ "liblibjpeg-turbo.a", "liblibpng.a", "liblibprotobuf.a", "libquirc.a", "libtegra_hal.a", "libzlib.a", "libade.a", "liblibopenjp2.a" ]
opencv_shared_libs = False opencv_tag = '4.5.0' opencv_so_version = '4.5' opencv_modules = ['calib3d', 'features2d', 'flann', 'highgui', 'video', 'videoio', 'imgcodecs', 'imgproc', 'core'] opencv_third_party_deps = ['liblibjpeg-turbo.a', 'liblibpng.a', 'liblibprotobuf.a', 'libquirc.a', 'libtegra_hal.a', 'libzlib.a', 'libade.a', 'liblibopenjp2.a']
# Copyright (C) 2007-2012 Red Hat # see file 'COPYING' for use and warranty information # # policygentool is a tool for the initial generation of SELinux policy # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA # 02111-1307 USA # # ########################### tmp Template File ############################# te_types=""" type TEMPLATETYPE_rw_t; files_type(TEMPLATETYPE_rw_t) """ te_rules=""" manage_dirs_pattern(TEMPLATETYPE_t, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t) manage_files_pattern(TEMPLATETYPE_t, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t) manage_lnk_files_pattern(TEMPLATETYPE_t, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t) """ ########################### Interface File ############################# if_rules=""" ######################################## ## <summary> ## Search TEMPLATETYPE rw directories. ## </summary> ## <param name="domain"> ## <summary> ## Domain allowed access. ## </summary> ## </param> # interface(`TEMPLATETYPE_search_rw_dir',` gen_require(` type TEMPLATETYPE_rw_t; ') allow $1 TEMPLATETYPE_rw_t:dir search_dir_perms; files_search_rw($1) ') ######################################## ## <summary> ## Read TEMPLATETYPE rw files. ## </summary> ## <param name="domain"> ## <summary> ## Domain allowed access. ## </summary> ## </param> # interface(`TEMPLATETYPE_read_rw_files',` gen_require(` type TEMPLATETYPE_rw_t; ') read_files_pattern($1, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t) allow $1 TEMPLATETYPE_rw_t:dir list_dir_perms; files_search_rw($1) ') ######################################## ## <summary> ## Manage TEMPLATETYPE rw files. ## </summary> ## <param name="domain"> ## <summary> ## Domain allowed access. ## </summary> ## </param> # interface(`TEMPLATETYPE_manage_rw_files',` gen_require(` type TEMPLATETYPE_rw_t; ') manage_files_pattern($1, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t) ') ######################################## ## <summary> ## Create, read, write, and delete ## TEMPLATETYPE rw dirs. ## </summary> ## <param name="domain"> ## <summary> ## Domain allowed access. ## </summary> ## </param> # interface(`TEMPLATETYPE_manage_rw_dirs',` gen_require(` type TEMPLATETYPE_rw_t; ') manage_dirs_pattern($1, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t) ') """ te_stream_rules=""" manage_sock_files_pattern(TEMPLATETYPE_t, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t) """ if_stream_rules="""\ ######################################## ## <summary> ## Connect to TEMPLATETYPE over a unix stream socket. ## </summary> ## <param name="domain"> ## <summary> ## Domain allowed access. ## </summary> ## </param> # interface(`TEMPLATETYPE_stream_connect',` gen_require(` type TEMPLATETYPE_t, TEMPLATETYPE_rw_t; ') stream_connect_pattern($1, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t, TEMPLATETYPE_t) ') """ if_admin_types=""" type TEMPLATETYPE_rw_t;""" if_admin_rules=""" files_search_etc($1) admin_pattern($1, TEMPLATETYPE_rw_t) """ ########################### File Context ################################## fc_file=""" FILENAME -- gen_context(system_u:object_r:TEMPLATETYPE_rw_t,s0) """ fc_sock_file="""\ FILENAME -s gen_context(system_u:object_r:TEMPLATETYPE_etc_rw_t,s0) """ fc_dir=""" FILENAME(/.*)? gen_context(system_u:object_r:TEMPLATETYPE_rw_t,s0) """
te_types = '\ntype TEMPLATETYPE_rw_t;\nfiles_type(TEMPLATETYPE_rw_t)\n' te_rules = '\nmanage_dirs_pattern(TEMPLATETYPE_t, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t)\nmanage_files_pattern(TEMPLATETYPE_t, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t)\nmanage_lnk_files_pattern(TEMPLATETYPE_t, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t)\n' if_rules = '\n########################################\n## <summary>\n##\tSearch TEMPLATETYPE rw directories.\n## </summary>\n## <param name="domain">\n##\t<summary>\n##\tDomain allowed access.\n##\t</summary>\n## </param>\n#\ninterface(`TEMPLATETYPE_search_rw_dir\',`\n\tgen_require(`\n\t\ttype TEMPLATETYPE_rw_t;\n\t\')\n\n\tallow $1 TEMPLATETYPE_rw_t:dir search_dir_perms;\n\tfiles_search_rw($1)\n\')\n\n########################################\n## <summary>\n##\tRead TEMPLATETYPE rw files.\n## </summary>\n## <param name="domain">\n##\t<summary>\n##\tDomain allowed access.\n##\t</summary>\n## </param>\n#\ninterface(`TEMPLATETYPE_read_rw_files\',`\n\tgen_require(`\n\t\ttype TEMPLATETYPE_rw_t;\n\t\')\n\n\tread_files_pattern($1, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t)\n\tallow $1 TEMPLATETYPE_rw_t:dir list_dir_perms;\n\tfiles_search_rw($1)\n\')\n\n########################################\n## <summary>\n##\tManage TEMPLATETYPE rw files.\n## </summary>\n## <param name="domain">\n##\t<summary>\n##\tDomain allowed access.\n##\t</summary>\n## </param>\n#\ninterface(`TEMPLATETYPE_manage_rw_files\',`\n\tgen_require(`\n\t\ttype TEMPLATETYPE_rw_t;\n\t\')\n\n\tmanage_files_pattern($1, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t)\n\')\n\n########################################\n## <summary>\n##\tCreate, read, write, and delete\n##\tTEMPLATETYPE rw dirs.\n## </summary>\n## <param name="domain">\n##\t<summary>\n##\tDomain allowed access.\n##\t</summary>\n## </param>\n#\ninterface(`TEMPLATETYPE_manage_rw_dirs\',`\n\tgen_require(`\n\t\ttype TEMPLATETYPE_rw_t;\n\t\')\n\n\tmanage_dirs_pattern($1, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t)\n\')\n\n' te_stream_rules = '\nmanage_sock_files_pattern(TEMPLATETYPE_t, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t)\n' if_stream_rules = '########################################\n## <summary>\n##\tConnect to TEMPLATETYPE over a unix stream socket.\n## </summary>\n## <param name="domain">\n##\t<summary>\n##\tDomain allowed access.\n##\t</summary>\n## </param>\n#\ninterface(`TEMPLATETYPE_stream_connect\',`\n\tgen_require(`\n\t\ttype TEMPLATETYPE_t, TEMPLATETYPE_rw_t;\n\t\')\n\n\tstream_connect_pattern($1, TEMPLATETYPE_rw_t, TEMPLATETYPE_rw_t, TEMPLATETYPE_t)\n\')\n' if_admin_types = '\n\t\ttype TEMPLATETYPE_rw_t;' if_admin_rules = '\n\tfiles_search_etc($1)\n\tadmin_pattern($1, TEMPLATETYPE_rw_t)\n' fc_file = '\nFILENAME\t\t--\tgen_context(system_u:object_r:TEMPLATETYPE_rw_t,s0)\n' fc_sock_file = 'FILENAME -s gen_context(system_u:object_r:TEMPLATETYPE_etc_rw_t,s0)\n' fc_dir = '\nFILENAME(/.*)?\t\tgen_context(system_u:object_r:TEMPLATETYPE_rw_t,s0)\n'
""" Compartmentalize: [ ascii art input ] --------------- | maybe some | | sort of auxillary | | drawing program | | | \ / v [ lex/parser ] --> [ translater ] --------- ---------- | grammar | | notes literals| | to numerical | | patterns with | | timestamps | | and midi meta | | data | | ,------------------------' | `--> [ sequencer ] ----------- | do the | | sequencing | | duh | | | \ / v [ midi sender ] ---------- | communicate to | | midi external | """
""" Compartmentalize: [ ascii art input ] --------------- | maybe some | | sort of auxillary | | drawing program | | | \\ / v [ lex/parser ] --> [ translater ] --------- ---------- | grammar | | notes literals| | to numerical | | patterns with | | timestamps | | and midi meta | | data | | ,------------------------' | `--> [ sequencer ] ----------- | do the | | sequencing | | duh | | | \\ / v [ midi sender ] ---------- | communicate to | | midi external | """
if __name__ == "__main__": """ Pobierz podstawe i wysokosc trojkata i wypisz pole. """ print("podaj podstawe i wysokosc trojkata:") a = int(input()) h = int(input()) print( "pole trojkata o podstawie ", a, " i wysokosci ", h, " jest rowne ", a * h / 2 ) """ Pobierz dlugosci bokow prostokata i wypisz pole. """ print("podaj dlogosci bokow prostokata:") a = int(input()) b = int(input()) print("pole prostokata o bokach ", a, " i ", b, " jest rowne ", a * b)
if __name__ == '__main__': '\n Pobierz podstawe i wysokosc trojkata i wypisz pole.\n ' print('podaj podstawe i wysokosc trojkata:') a = int(input()) h = int(input()) print('pole trojkata o podstawie ', a, ' i wysokosci ', h, ' jest rowne ', a * h / 2) ' \n\tPobierz dlugosci bokow prostokata i wypisz pole.\n\t' print('podaj dlogosci bokow prostokata:') a = int(input()) b = int(input()) print('pole prostokata o bokach ', a, ' i ', b, ' jest rowne ', a * b)
# # 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. """Gabbi specific exceptions.""" class GabbiDataLoadError(ValueError): """An exception to alert when data streams cannot be loaded.""" pass class GabbiFormatError(ValueError): """An exception to encapsulate poorly formed test data.""" pass class GabbiSyntaxWarning(SyntaxWarning): """A warning about syntax that is not desirable.""" pass
"""Gabbi specific exceptions.""" class Gabbidataloaderror(ValueError): """An exception to alert when data streams cannot be loaded.""" pass class Gabbiformaterror(ValueError): """An exception to encapsulate poorly formed test data.""" pass class Gabbisyntaxwarning(SyntaxWarning): """A warning about syntax that is not desirable.""" pass
logo = """ _____________________ | _________________ | | | Pythonista 0. | | .----------------. .----------------. .----------------. .----------------. | |_________________| | | .--------------. || .--------------. || .--------------. || .--------------. | | ___ ___ ___ ___ | | | ______ | || | __ | || | _____ | || | ______ | | | | 7 | 8 | 9 | | + | | | | .' ___ | | || | / \ | || | |_ _| | || | .' ___ | | | | |___|___|___| |___| | | | / .' \_| | || | / /\ \ | || | | | | || | / .' \_| | | | | 4 | 5 | 6 | | - | | | | | | | || | / ____ \ | || | | | _ | || | | | | | | |___|___|___| |___| | | | \ `.___.'\ | || | _/ / \ \_ | || | _| |__/ | | || | \ `.___.'\ | | | | 1 | 2 | 3 | | x | | | | `._____.' | || ||____| |____|| || | |________| | || | `._____.' | | | |___|___|___| |___| | | | | || | | || | | || | | | | | . | 0 | = | | / | | | '--------------' || '--------------' || '--------------' || '--------------' | | |___|___|___| |___| | '----------------' '----------------' '----------------' '----------------' |_____________________| """ print(logo) def add(x, y): return x+y def subtract(x, y): return x-y def division(x, y): if(y == 0): print("It can't divide per 0'") else: return x/y def multiply(x, y): return x*y operators = { "+": add, "-": subtract, "/": division, "*": multiply } def calculator(): x = float(input("Please enter a number: ")) keep_going = "y" while(keep_going == "y"): operator_chosen = input("Please enter the desired operation: ") y = float(input("Please enter a number: ")) calculation = operators[operator_chosen] answer = calculation(x, y) print(f"{x} {operator_chosen} {y} = {answer}") keep_going = input( f"Type 'y' to continue calculating with {answer} or type 'n' to exit: ").lower() if(keep_going == "y"): x = answer """Here we have a recursion when the user does not want to use the same answer before and it want to start a new iteration""" else: calculator() calculator()
logo = "\n _____________________\n| _________________ |\n| | Pythonista 0. | | .----------------. .----------------. .----------------. .----------------. \n| |_________________| | | .--------------. || .--------------. || .--------------. || .--------------. |\n| ___ ___ ___ ___ | | | ______ | || | __ | || | _____ | || | ______ | |\n| | 7 | 8 | 9 | | + | | | | .' ___ | | || | / \\ | || | |_ _| | || | .' ___ | | |\n| |___|___|___| |___| | | | / .' \\_| | || | / /\\ \\ | || | | | | || | / .' \\_| | |\n| | 4 | 5 | 6 | | - | | | | | | | || | / ____ \\ | || | | | _ | || | | | | |\n| |___|___|___| |___| | | | \\ `.___.'\\ | || | _/ / \\ \\_ | || | _| |__/ | | || | \\ `.___.'\\ | |\n| | 1 | 2 | 3 | | x | | | | `._____.' | || ||____| |____|| || | |________| | || | `._____.' | |\n| |___|___|___| |___| | | | | || | | || | | || | | |\n| | . | 0 | = | | / | | | '--------------' || '--------------' || '--------------' || '--------------' |\n| |___|___|___| |___| | '----------------' '----------------' '----------------' '----------------' \n|_____________________|\n" print(logo) def add(x, y): return x + y def subtract(x, y): return x - y def division(x, y): if y == 0: print("It can't divide per 0'") else: return x / y def multiply(x, y): return x * y operators = {'+': add, '-': subtract, '/': division, '*': multiply} def calculator(): x = float(input('Please enter a number: ')) keep_going = 'y' while keep_going == 'y': operator_chosen = input('Please enter the desired operation: ') y = float(input('Please enter a number: ')) calculation = operators[operator_chosen] answer = calculation(x, y) print(f'{x} {operator_chosen} {y} = {answer}') keep_going = input(f"Type 'y' to continue calculating with {answer} or type 'n' to exit: ").lower() if keep_going == 'y': x = answer 'Here we have a recursion when the user does not want to use the same answer before and it want to start a new iteration' else: calculator() calculator()
fd = open('f',"r") buffer = fd.read(2) print("first 2 chars in f:",buffer) fd.close()
fd = open('f', 'r') buffer = fd.read(2) print('first 2 chars in f:', buffer) fd.close()
# from http://www.voidspace.org.uk/python/weblog/arch_d7_2007_03_17.shtml#e664 def ReadOnlyProxy(obj): class _ReadOnlyProxy(object): def __getattr__(self, name): return getattr(obj, name) def __setattr__(self, name, value): raise AttributeError("Attributes can't be set on this object") for name in dir(obj): if not (name[:2] == '__' == name[-2:]): continue if name in ('__new__', '__init__', '__class__', '__bases__'): continue if not callable(getattr(obj, name)): continue def get_proxy_method(name): def proxy_method(self, *args, **keywargs): return getattr(obj, name)(*args, **keywargs) return proxy_method setattr(_ReadOnlyProxy, name, get_proxy_method(name)) return _ReadOnlyProxy()
def read_only_proxy(obj): class _Readonlyproxy(object): def __getattr__(self, name): return getattr(obj, name) def __setattr__(self, name, value): raise attribute_error("Attributes can't be set on this object") for name in dir(obj): if not name[:2] == '__' == name[-2:]: continue if name in ('__new__', '__init__', '__class__', '__bases__'): continue if not callable(getattr(obj, name)): continue def get_proxy_method(name): def proxy_method(self, *args, **keywargs): return getattr(obj, name)(*args, **keywargs) return proxy_method setattr(_ReadOnlyProxy, name, get_proxy_method(name)) return __read_only_proxy()
settings = {"velocity_min": 1, "velocity_max": 3, "x_boundary": 800, "y_boundary": 800, "small_particle_radius": 5, "big_particle_radius": 10, "number_of_particles": 500, "density_min": 2, "density_max": 20 }
settings = {'velocity_min': 1, 'velocity_max': 3, 'x_boundary': 800, 'y_boundary': 800, 'small_particle_radius': 5, 'big_particle_radius': 10, 'number_of_particles': 500, 'density_min': 2, 'density_max': 20}
'''8. Write a Python program to count occurrences of a substring in a string.''' def count_word_in_string(string1, substring2): return string1.count(substring2) print(count_word_in_string('The quick brown fox jumps over the lazy dog that is chasing the fox.', "fox"))
"""8. Write a Python program to count occurrences of a substring in a string.""" def count_word_in_string(string1, substring2): return string1.count(substring2) print(count_word_in_string('The quick brown fox jumps over the lazy dog that is chasing the fox.', 'fox'))
test = { "name": "q2", "points": 1, "hidden": True, "suites": [ { "cases": [ { "code": r""" >>> sample_population(test_results).num_rows 3000 """, "hidden": False, "locked": False, }, { "code": r""" >>> "Test Result" in sample_population(test_results).labels True """, "hidden": False, "locked": False, }, { "code": r""" >>> round(apply_statistic(test_results, "Village Number", np.average), 4) 8.1307 """, "hidden": False, "locked": False, }, ], "scored": False, "setup": "", "teardown": "", "type": "doctest" }, ] }
test = {'name': 'q2', 'points': 1, 'hidden': True, 'suites': [{'cases': [{'code': '\n\t\t\t\t\t>>> sample_population(test_results).num_rows\n\t\t\t\t\t3000\n\t\t\t\t\t', 'hidden': False, 'locked': False}, {'code': '\n\t\t\t\t\t>>> "Test Result" in sample_population(test_results).labels\n\t\t\t\t\tTrue\n\t\t\t\t\t', 'hidden': False, 'locked': False}, {'code': '\n\t\t\t\t\t>>> round(apply_statistic(test_results, "Village Number", np.average), 4)\n\t\t\t\t\t8.1307\n\t\t\t\t\t', 'hidden': False, 'locked': False}], 'scored': False, 'setup': '', 'teardown': '', 'type': 'doctest'}]}
class Solution: def isValid(self, s): """ :type s: str :rtype: bool """ if not s: return True stack = [] for char in s: if char == '{' or char == '[' or char == '(': stack.append(char) else: try: c = stack.pop() if char == '}': if c != '{': return False elif char == ']': if c != '[': return False elif char == ')': if c != '(': return False except IndexError: return False if len(stack) > 0: return False else: return True print(Solution().isValid('()'))
class Solution: def is_valid(self, s): """ :type s: str :rtype: bool """ if not s: return True stack = [] for char in s: if char == '{' or char == '[' or char == '(': stack.append(char) else: try: c = stack.pop() if char == '}': if c != '{': return False elif char == ']': if c != '[': return False elif char == ')': if c != '(': return False except IndexError: return False if len(stack) > 0: return False else: return True print(solution().isValid('()'))
def read_data(): rules = dict() your_ticket = None nearby_tickets = [] state = 0 with open('in') as f: for line in map(lambda x: x.strip(), f.readlines()): if line == '': state += 1 continue if line == 'your ticket:': continue if line == 'nearby tickets:': continue if state == 0: parts = line.split(':') ranges = parts[1].split('or') rules[parts[0]] = [] for r in ranges: nums = r.split('-') rules[parts[0]].append((int(nums[0]), int(nums[1]))) if state == 1: your_ticket = list(map(int, line.split(','))) if state == 2: nearby_tickets.append(list(map(int, line.split(',')))) return rules, your_ticket, nearby_tickets def part_one(rules, tickets): error_rate = 0 invalid_tickets = [] for i, ticket in enumerate(tickets): for val in ticket: valid_val = False for rule in rules.keys(): valid = False for m, M in rules[rule]: if val >= m and val <= M: valid = True break if valid: valid_val = True break if not valid_val: error_rate += val invalid_tickets.append(i) return invalid_tickets, error_rate def part_two(rules, your_ticket, tickets): possible_values = [set(rules.keys()) for i in range(len(rules.keys()))] for ticket in tickets: for i, val in enumerate(ticket): for rule in rules.keys(): valid = False for m, M in rules[rule]: if val >= m and val <= M: valid = True break if not valid and rule in possible_values[i]: possible_values[i].remove(rule) while True: to_filter = False for v in map(len, possible_values): if v > 1: to_filter = True if not to_filter: break for i in range(len(possible_values)): if len(possible_values[i]) == 1: for j in range(len(possible_values)): if i != j: possible_values[j] -= possible_values[i] res = 1 for i in range(len(possible_values)): if 'departure' in list(possible_values[i])[0]: res *= your_ticket[i] return res def main(): rules, your_ticket, nearby_tickets = read_data() invalid_tickets, error_rate = part_one(rules, nearby_tickets) p_two = part_two(rules, your_ticket, [t for i, t in enumerate(nearby_tickets) if i not in invalid_tickets]) print(f'Part One: {error_rate}') print(f'Part Two: {p_two}') if __name__ == '__main__': main()
def read_data(): rules = dict() your_ticket = None nearby_tickets = [] state = 0 with open('in') as f: for line in map(lambda x: x.strip(), f.readlines()): if line == '': state += 1 continue if line == 'your ticket:': continue if line == 'nearby tickets:': continue if state == 0: parts = line.split(':') ranges = parts[1].split('or') rules[parts[0]] = [] for r in ranges: nums = r.split('-') rules[parts[0]].append((int(nums[0]), int(nums[1]))) if state == 1: your_ticket = list(map(int, line.split(','))) if state == 2: nearby_tickets.append(list(map(int, line.split(',')))) return (rules, your_ticket, nearby_tickets) def part_one(rules, tickets): error_rate = 0 invalid_tickets = [] for (i, ticket) in enumerate(tickets): for val in ticket: valid_val = False for rule in rules.keys(): valid = False for (m, m) in rules[rule]: if val >= m and val <= M: valid = True break if valid: valid_val = True break if not valid_val: error_rate += val invalid_tickets.append(i) return (invalid_tickets, error_rate) def part_two(rules, your_ticket, tickets): possible_values = [set(rules.keys()) for i in range(len(rules.keys()))] for ticket in tickets: for (i, val) in enumerate(ticket): for rule in rules.keys(): valid = False for (m, m) in rules[rule]: if val >= m and val <= M: valid = True break if not valid and rule in possible_values[i]: possible_values[i].remove(rule) while True: to_filter = False for v in map(len, possible_values): if v > 1: to_filter = True if not to_filter: break for i in range(len(possible_values)): if len(possible_values[i]) == 1: for j in range(len(possible_values)): if i != j: possible_values[j] -= possible_values[i] res = 1 for i in range(len(possible_values)): if 'departure' in list(possible_values[i])[0]: res *= your_ticket[i] return res def main(): (rules, your_ticket, nearby_tickets) = read_data() (invalid_tickets, error_rate) = part_one(rules, nearby_tickets) p_two = part_two(rules, your_ticket, [t for (i, t) in enumerate(nearby_tickets) if i not in invalid_tickets]) print(f'Part One: {error_rate}') print(f'Part Two: {p_two}') if __name__ == '__main__': main()
mapping = { "settings": { "index": { "max_result_window": 15000, "analysis": { "analyzer": { "default": { "type": "custom", "tokenizer": "whitespace", "filter": ["english_stemmer", "lowercase"] }, "autocomplete": { "type": "custom", "tokenizer": "whitespace", "filter": ["lowercase", "autocomplete_filter"] }, "symbols": { "type": "custom", "tokenizer": "whitespace", "filter": ["lowercase"] } }, "filter": { "english_stemmer": { "type": "stemmer", "language": "english" }, "autocomplete_filter": { "type": "edge_ngram", "min_gram": "1", "max_gram": "20" } } }, "number_of_replicas": "1", #temporarily "number_of_shards": "5" } }, "mappings": { # having a raw field means it can be a facet or sorted by "searchable_item": { "properties": { "name": { "type": "string", "fields": { "symbol": { "type": "string", "analyzer": "symbols" }, "raw": { "type": "string", "index": "not_analyzed" }, "autocomplete": { "type": "string", "analyzer": "autocomplete" } } }, "category": { "type": "string", "analyzer": "symbols" }, "href": { "type": "string", "analyzer": "symbols" }, "description": { "type": "string" }, "first_name": { "type": "string", "fields": { "raw": { "type": "string", "index": "not_analyzed" } } }, "last_name": { "type": "string", "fields": { "raw": { "type": "string", "index": "not_analyzed" } } }, "institution": { "type": "string", "fields": { "raw": { "type": "string", "index": "not_analyzed" } } }, "position": { "type": "string", "fields": { "raw": { "type": "string", "index": "not_analyzed" } } }, "country": { "type": "string", "fields": { "raw": { "type": "string", "index": "not_analyzed" } } }, "state": { "type": "string", "fields": { "raw": { "type": "string", "index": "not_analyzed" } } }, "colleague_loci": { "type": "string", "fields": { "raw": { "type": "string", "index": "not_analyzed" }, "symbol": { "type": "string", "analyzer": "symbols" } } }, "number_annotations": { "type": "integer" }, "feature_type": { "type": "string", "fields": { "symbol": { "type": "string", "analyzer": "symbols" }, "raw": { "type": "string", "index": "not_analyzed" } } }, "name_description": { "type": "string" }, "summary": { "type": "string" }, "phenotypes": { "type": "string", "fields": { "symbol": { "type": "string", "analyzer": "symbols" } } }, "cellular_component": { "type": "string", "fields": { "symbol": { "type": "string", "analyzer": "symbols" }, "raw": { "type": "string", "index": "not_analyzed" } } }, "biological_process": { "type": "string", "fields": { "symbol": { "type": "string", "analyzer": "symbols" }, "raw": { "type": "string", "index": "not_analyzed" } } }, "molecular_function": { "type": "string", "fields": { "symbol": { "type": "string", "analyzer": "symbols" }, "raw": { "type": "string", "index": "not_analyzed" } } }, "ec_number": { "type": "string", "analyzer": "symbols" }, "protein": { "type": "string", "fields": { "symbol": { "type": "string", "analyzer": "symbols" } } }, "tc_number": { "type": "string", "analyzer": "symbols" }, "secondary_sgdid": { "type": "string", "analyzer": "symbols" }, "sequence_history": { "type": "string", "analyzer": "symbols" }, "gene_history": { "type": "string", "analyzer": "symbols" }, "bioentity_id": { "type": "string", "analyzer": "symbols" }, "keys": { "type": "string", "analyzer": "symbols" }, "status": { "type": "string", "analyzer": "symbols", "fields": { "raw": { "type": "string", "index": "not_analyzed" } } }, "observable": { "type": "string", "fields": { "symbol": { "type": "string", "analyzer": "symbols" }, "raw": { "type": "string", "index": "not_analyzed" } } }, "qualifier": { "type": "string", "fields": { "symbol": { "type": "string", "analyzer": "symbols" }, "raw": { "type": "string", "index": "not_analyzed" } } }, "references": { "type": "string", "analyzer": "symbols", "fields": { "raw": { "type": "string", "index": "not_analyzed" } } }, "phenotype_loci": { "type": "string", "fields": { "raw": { "type": "string", "index": "not_analyzed" }, "symbol": { "type": "string", "analyzer": "symbols" } } }, "chemical": { "type": "string", "fields": { "symbol": { "type": "string", "analyzer": "symbols" }, "raw": { "type": "string", "index": "not_analyzed" } } }, "mutant_type": { "type": "string", "fields": { "symbol": { "type": "string", "analyzer": "symbols" }, "raw": { "type": "string", "index": "not_analyzed" } } }, "synonyms": { "type": "string" }, "go_id": { "type": "string", "analyzer": "symbols" }, "go_loci": { "type": "string", "fields": { "raw": { "type": "string", "index": "not_analyzed" }, "symbol": { "type": "string", "analyzer": "symbols" } } }, "author": { "type": "string", "analyzer": "symbols", "fields": { "raw": { "type": "string", "index": "not_analyzed" } } }, "journal": { "type": "string", "analyzer": "symbols", "fields": { "raw": { "type": "string", "index": "not_analyzed" } } }, "year": { "type": "string", "analyzer": "symbols", "fields": { "raw": { "type": "string", "index": "not_analyzed" } } }, "reference_loci": { "type": "string", "analyzer": "symbols", "fields": { "raw": { "type": "string", "index": "not_analyzed" } } }, "aliases": { "type": "string", "fields": { "raw": { "type": "string", "index": "not_analyzed" }, "symbol": { "type": "string", "analyzer": "symbols" } } }, "format": { "type": "string", "fields": { "raw": { "type": "string", "index": "not_analyzed" }, "symbol": { "type": "string", "analyzer": "symbols" } } }, "keyword": { "type": "string", "fields": { "raw": { "type": "string", "index": "not_analyzed" }, "symbol": { "type": "string", "analyzer": "symbols" } } }, "file_size": { "type": "string", "fields": { "raw": { "type": "string", "index": "not_analyzed" }, "symbol": { "type": "string", "analyzer": "symbols" } } }, "readme_url": { "type": "string", "fields": { "raw": { "type": "string", "index": "not_analyzed" }, "symbol": { "type": "string", "analyzer": "symbols" } } }, "topic": { "type": "string", "fields": { "raw": { "type": "string", "index": "not_analyzed" }, "symbol": { "type": "string", "analyzer": "symbols" } } }, "data": { "type": "string", "fields": { "raw": { "type": "string", "index": "not_analyzed" }, "symbol": { "type": "string", "analyzer": "symbols" } } }, "is_quick_flag": { "type": "string", "fields": { "raw": { "type": "string", "index": "not_analyzed" }, "symbol": { "type": "string", "analyzer": "symbols" } } } } } } }
mapping = {'settings': {'index': {'max_result_window': 15000, 'analysis': {'analyzer': {'default': {'type': 'custom', 'tokenizer': 'whitespace', 'filter': ['english_stemmer', 'lowercase']}, 'autocomplete': {'type': 'custom', 'tokenizer': 'whitespace', 'filter': ['lowercase', 'autocomplete_filter']}, 'symbols': {'type': 'custom', 'tokenizer': 'whitespace', 'filter': ['lowercase']}}, 'filter': {'english_stemmer': {'type': 'stemmer', 'language': 'english'}, 'autocomplete_filter': {'type': 'edge_ngram', 'min_gram': '1', 'max_gram': '20'}}}, 'number_of_replicas': '1', 'number_of_shards': '5'}}, 'mappings': {'searchable_item': {'properties': {'name': {'type': 'string', 'fields': {'symbol': {'type': 'string', 'analyzer': 'symbols'}, 'raw': {'type': 'string', 'index': 'not_analyzed'}, 'autocomplete': {'type': 'string', 'analyzer': 'autocomplete'}}}, 'category': {'type': 'string', 'analyzer': 'symbols'}, 'href': {'type': 'string', 'analyzer': 'symbols'}, 'description': {'type': 'string'}, 'first_name': {'type': 'string', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}}}, 'last_name': {'type': 'string', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}}}, 'institution': {'type': 'string', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}}}, 'position': {'type': 'string', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}}}, 'country': {'type': 'string', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}}}, 'state': {'type': 'string', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}}}, 'colleague_loci': {'type': 'string', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}, 'symbol': {'type': 'string', 'analyzer': 'symbols'}}}, 'number_annotations': {'type': 'integer'}, 'feature_type': {'type': 'string', 'fields': {'symbol': {'type': 'string', 'analyzer': 'symbols'}, 'raw': {'type': 'string', 'index': 'not_analyzed'}}}, 'name_description': {'type': 'string'}, 'summary': {'type': 'string'}, 'phenotypes': {'type': 'string', 'fields': {'symbol': {'type': 'string', 'analyzer': 'symbols'}}}, 'cellular_component': {'type': 'string', 'fields': {'symbol': {'type': 'string', 'analyzer': 'symbols'}, 'raw': {'type': 'string', 'index': 'not_analyzed'}}}, 'biological_process': {'type': 'string', 'fields': {'symbol': {'type': 'string', 'analyzer': 'symbols'}, 'raw': {'type': 'string', 'index': 'not_analyzed'}}}, 'molecular_function': {'type': 'string', 'fields': {'symbol': {'type': 'string', 'analyzer': 'symbols'}, 'raw': {'type': 'string', 'index': 'not_analyzed'}}}, 'ec_number': {'type': 'string', 'analyzer': 'symbols'}, 'protein': {'type': 'string', 'fields': {'symbol': {'type': 'string', 'analyzer': 'symbols'}}}, 'tc_number': {'type': 'string', 'analyzer': 'symbols'}, 'secondary_sgdid': {'type': 'string', 'analyzer': 'symbols'}, 'sequence_history': {'type': 'string', 'analyzer': 'symbols'}, 'gene_history': {'type': 'string', 'analyzer': 'symbols'}, 'bioentity_id': {'type': 'string', 'analyzer': 'symbols'}, 'keys': {'type': 'string', 'analyzer': 'symbols'}, 'status': {'type': 'string', 'analyzer': 'symbols', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}}}, 'observable': {'type': 'string', 'fields': {'symbol': {'type': 'string', 'analyzer': 'symbols'}, 'raw': {'type': 'string', 'index': 'not_analyzed'}}}, 'qualifier': {'type': 'string', 'fields': {'symbol': {'type': 'string', 'analyzer': 'symbols'}, 'raw': {'type': 'string', 'index': 'not_analyzed'}}}, 'references': {'type': 'string', 'analyzer': 'symbols', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}}}, 'phenotype_loci': {'type': 'string', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}, 'symbol': {'type': 'string', 'analyzer': 'symbols'}}}, 'chemical': {'type': 'string', 'fields': {'symbol': {'type': 'string', 'analyzer': 'symbols'}, 'raw': {'type': 'string', 'index': 'not_analyzed'}}}, 'mutant_type': {'type': 'string', 'fields': {'symbol': {'type': 'string', 'analyzer': 'symbols'}, 'raw': {'type': 'string', 'index': 'not_analyzed'}}}, 'synonyms': {'type': 'string'}, 'go_id': {'type': 'string', 'analyzer': 'symbols'}, 'go_loci': {'type': 'string', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}, 'symbol': {'type': 'string', 'analyzer': 'symbols'}}}, 'author': {'type': 'string', 'analyzer': 'symbols', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}}}, 'journal': {'type': 'string', 'analyzer': 'symbols', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}}}, 'year': {'type': 'string', 'analyzer': 'symbols', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}}}, 'reference_loci': {'type': 'string', 'analyzer': 'symbols', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}}}, 'aliases': {'type': 'string', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}, 'symbol': {'type': 'string', 'analyzer': 'symbols'}}}, 'format': {'type': 'string', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}, 'symbol': {'type': 'string', 'analyzer': 'symbols'}}}, 'keyword': {'type': 'string', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}, 'symbol': {'type': 'string', 'analyzer': 'symbols'}}}, 'file_size': {'type': 'string', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}, 'symbol': {'type': 'string', 'analyzer': 'symbols'}}}, 'readme_url': {'type': 'string', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}, 'symbol': {'type': 'string', 'analyzer': 'symbols'}}}, 'topic': {'type': 'string', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}, 'symbol': {'type': 'string', 'analyzer': 'symbols'}}}, 'data': {'type': 'string', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}, 'symbol': {'type': 'string', 'analyzer': 'symbols'}}}, 'is_quick_flag': {'type': 'string', 'fields': {'raw': {'type': 'string', 'index': 'not_analyzed'}, 'symbol': {'type': 'string', 'analyzer': 'symbols'}}}}}}}
# -*- coding: utf-8 -*- """ Created on Mon Jul 26 15:06:57 2021 @author: user24 """ file = "./data/tsuretsuregusa.txt" with open(file, "r", encoding="utf_8") as fileobj: while True: # set line as value of the file line line = fileobj.readline() # removes any white space at the end of string aline = line.rstrip() # if line exists, print line if aline: print(aline) # if don't exist, break from loop else: break
""" Created on Mon Jul 26 15:06:57 2021 @author: user24 """ file = './data/tsuretsuregusa.txt' with open(file, 'r', encoding='utf_8') as fileobj: while True: line = fileobj.readline() aline = line.rstrip() if aline: print(aline) else: break
''' https://www.hackerrank.com/challenges/strings-xor/submissions/code/102872134 Given two strings consisting of digits 0 and 1 only, find the XOR of the two strings. ''' def strings_xor(s, t): res = "" for i in range(len(s)): if s[i] != t[i]: res += '1' else: res += '0' return res s = input() t = input() print(strings_xor(s, t))
""" https://www.hackerrank.com/challenges/strings-xor/submissions/code/102872134 Given two strings consisting of digits 0 and 1 only, find the XOR of the two strings. """ def strings_xor(s, t): res = '' for i in range(len(s)): if s[i] != t[i]: res += '1' else: res += '0' return res s = input() t = input() print(strings_xor(s, t))
__description__ = "Gearman RPC broker" __config__ = { "gearmand.listen_address": dict( description = "IP address to bind to", default = "127.0.0.1", ), "gearmand.user": dict( display_name = "Gearmand user", description = "User to run the gearmand procses as", default = "nobody", ), "gearmand.pidfile": dict( display_name = "Gearmand pid file", description = "Path to the PID file for gearmand", default = "/var/run/gearmand/gearmand.pid", ), }
__description__ = 'Gearman RPC broker' __config__ = {'gearmand.listen_address': dict(description='IP address to bind to', default='127.0.0.1'), 'gearmand.user': dict(display_name='Gearmand user', description='User to run the gearmand procses as', default='nobody'), 'gearmand.pidfile': dict(display_name='Gearmand pid file', description='Path to the PID file for gearmand', default='/var/run/gearmand/gearmand.pid')}
bot_token = '' waiting_timeout = 5 # Seconds admin_id = "" channel_id = "" bitly_access_token = "" vars_file = ""
bot_token = '' waiting_timeout = 5 admin_id = '' channel_id = '' bitly_access_token = '' vars_file = ''
# parsetab.py # This file is automatically generated. Do not edit. _tabversion = '3.5' _lr_method = 'LALR' _lr_signature = '5E2BB3531AA676A6BB1D06733251B2F3' _lr_action_items = {'COS':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[1,1,1,1,1,1,1,1,1,1,-26,1,-32,1,1,1,1,1,-18,-19,1,-52,1,1,-27,-35,-24,1,-28,-37,1,-25,-34,-36,1,-30,-31,-39,1,1,1,-23,-38,-21,1,-29,1,1,-22,1,1,1,1,-47,-40,1,1,1,-7,-42,-49,1,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'COT':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[5,5,5,5,5,5,5,5,5,5,-26,5,-32,5,5,5,5,5,-18,-19,5,-52,5,5,-27,-35,-24,5,-28,-37,5,-25,-34,-36,5,-30,-31,-39,5,5,5,-23,-38,-21,5,-29,5,5,-22,5,5,5,5,-47,-40,5,5,5,-7,-42,-49,5,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'DEGREE':([12,14,22,23,27,32,33,34,36,37,39,40,42,44,45,46,50,51,52,54,57,62,63,67,68,69,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[-26,-32,-18,-19,-52,-27,62,-24,-28,69,-25,72,75,-30,-31,78,-23,83,-21,-29,-22,-47,-40,-7,-42,-49,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-28,-33,]),'SUM':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[3,3,3,3,3,3,3,3,3,3,-26,3,-32,3,3,3,3,3,-18,-19,3,-52,3,3,-27,-35,-24,3,-28,-37,3,-25,-34,-36,3,-30,-31,-39,3,3,3,-23,-38,-21,3,-29,3,3,-22,3,3,3,3,-47,-40,3,3,3,-7,-42,-49,3,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'MINUS':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,21,22,23,26,27,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,],[4,4,4,4,4,4,4,4,4,4,-26,4,-32,4,4,4,4,4,-27,-18,-19,4,-52,4,4,61,-27,61,61,64,-28,61,4,61,61,61,61,64,61,61,61,64,64,4,61,61,61,4,-29,4,4,-22,4,4,4,4,-47,-40,4,4,4,61,-42,-49,64,-45,-46,-20,-41,-48,61,-44,-51,61,61,61,-43,-50,61,61,-14,61,-11,-13,-12,-12,61,-33,]),'LOG':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[2,2,2,2,2,2,2,2,2,2,-26,2,-32,2,2,2,2,2,-18,-19,2,-52,2,2,-27,-35,-24,2,-28,-37,2,-25,-34,-36,2,-30,-31,-39,2,2,2,-23,-38,-21,2,-29,2,2,-22,2,2,2,2,-47,-40,2,2,2,-7,-42,-49,2,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'RAD':([12,14,22,23,27,32,33,34,36,37,39,40,42,44,45,46,50,51,52,54,57,62,63,67,68,69,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[-26,-32,-18,-19,-52,-27,63,-24,-28,68,-25,71,74,-30,-31,77,-23,82,-21,-29,-22,-47,-40,-7,-42,-49,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-28,-33,]),'POWER':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[6,6,6,6,6,6,6,6,6,6,-26,6,-32,6,6,6,6,6,-18,-19,6,-52,6,6,-27,-35,-24,6,-28,-37,6,-25,-34,-36,6,-30,-31,-39,6,6,6,-23,-38,-21,6,-29,6,6,-22,6,6,6,6,-47,-40,6,6,6,-7,-42,-49,6,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'LN':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[7,7,7,7,7,7,7,7,7,7,-26,7,-32,7,7,7,7,7,-18,-19,7,-52,7,7,-27,-35,-24,7,-28,-37,7,-25,-34,-36,7,-30,-31,-39,7,7,7,-23,-38,-21,7,-29,7,7,-22,7,7,7,7,-47,-40,7,7,7,-7,-42,-49,7,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'SIN':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[8,8,8,8,8,8,8,8,8,8,-26,8,-32,8,8,8,8,8,-18,-19,8,-52,8,8,-27,-35,-24,8,-28,-37,8,-25,-34,-36,8,-30,-31,-39,8,8,8,-23,-38,-21,8,-29,8,8,-22,8,8,8,8,-47,-40,8,8,8,-7,-42,-49,8,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'OPAR':([0,1,2,3,4,5,6,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[9,9,9,9,9,9,38,9,9,9,9,-26,9,-32,9,9,9,9,9,-18,-19,9,-52,9,9,-27,-35,-24,9,-28,-37,9,-25,-34,-36,9,-30,-31,-39,9,9,9,-23,-38,-21,9,-29,9,9,-22,9,9,9,9,-47,-40,9,9,9,-7,-42,-49,9,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'SEC':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[29,29,29,29,29,29,29,29,29,29,-26,29,-32,29,29,29,29,29,-18,-19,29,-52,29,29,-27,-35,-24,29,-28,-37,29,-25,-34,-36,29,-30,-31,-39,29,29,29,-23,-38,-21,29,-29,29,29,-22,29,29,29,29,-47,-40,29,29,29,-7,-42,-49,29,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'TAN':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[11,11,11,11,11,11,11,11,11,11,-26,11,-32,11,11,11,11,11,-18,-19,11,-52,11,11,-27,-35,-24,11,-28,-37,11,-25,-34,-36,11,-30,-31,-39,11,11,11,-23,-38,-21,11,-29,11,11,-22,11,11,11,11,-47,-40,11,11,11,-7,-42,-49,11,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'PI':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[12,12,12,12,12,12,12,12,12,12,-26,12,-32,12,12,12,12,12,-18,-19,12,-52,12,12,-27,-35,-24,12,-28,-37,12,-25,-34,-36,12,-30,-31,-39,12,12,12,-23,-38,-21,12,-29,12,12,-22,12,12,12,12,-47,-40,12,12,12,-7,-42,-49,12,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'QUOTIENT':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[13,13,13,13,13,13,13,13,13,13,-26,13,-32,13,13,13,13,13,-18,-19,13,-52,13,13,-27,-35,-24,13,-28,-37,13,-25,-34,-36,13,-30,-31,-39,13,13,13,-23,-38,-21,13,-29,13,13,-22,13,13,13,13,-47,-40,13,13,13,-7,-42,-49,13,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'PLUS':([12,14,21,22,23,27,31,32,33,34,35,36,37,39,40,41,42,43,44,45,46,47,48,50,51,52,54,57,62,63,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,],[-26,-32,-27,-18,-19,-52,59,-27,59,59,59,-28,59,59,59,59,59,59,59,59,59,59,59,59,59,59,-29,-22,-47,-40,-29,-22,59,-42,-49,59,-45,-46,-20,-41,-48,59,-44,-51,59,59,59,-43,-50,59,59,-14,59,-11,-13,-12,-12,59,-33,]),'SQUARE':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,21,22,23,26,27,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,],[15,15,15,15,15,15,15,15,15,15,-26,15,-32,15,15,15,15,15,-27,-18,-19,15,-52,15,15,54,-27,54,54,65,-28,54,15,54,54,54,54,65,54,54,54,65,65,15,54,54,54,15,-29,15,15,-22,15,15,15,15,-47,-40,15,15,15,54,-42,-49,65,-45,-46,-20,-41,-48,54,-44,-51,54,54,54,-43,-50,54,54,-14,54,-11,-13,-12,-12,54,-33,]),'XOR':([12,14,21,22,23,27,31,32,33,34,35,36,37,39,40,41,42,43,44,45,46,47,48,50,51,52,54,57,62,63,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,],[-26,-32,-27,-18,-19,-52,55,-27,55,55,55,-28,55,55,55,55,55,55,55,55,55,55,55,55,55,55,-29,-22,-47,-40,-29,-22,55,-42,-49,55,-45,-46,-20,-41,-48,55,-44,-51,55,55,55,-43,-50,55,55,-14,55,-11,-13,-12,-12,55,-33,]),'DIVIDE':([12,14,21,22,23,27,31,32,33,34,35,36,37,39,40,41,42,43,44,45,46,47,48,50,51,52,54,57,62,63,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,],[-26,-32,-27,-18,-19,-52,56,-27,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,56,-29,-22,-47,-40,-29,-22,56,-42,-49,56,-45,-46,-20,-41,-48,56,-44,-51,56,56,56,-43,-50,56,56,-14,56,56,-13,56,56,56,-33,]),'SQROOT':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[16,16,16,16,16,16,16,16,16,16,-26,16,-32,16,16,16,16,16,-18,-19,16,-52,16,16,-27,-35,-24,16,-28,-37,16,-25,-34,-36,16,-30,-31,-39,16,16,16,-23,-38,-21,16,-29,16,16,-22,16,16,16,16,-47,-40,16,16,16,-7,-42,-49,16,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'CPAR':([12,14,22,23,27,32,33,34,36,37,39,40,41,42,44,45,46,50,51,52,54,57,62,63,67,68,69,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,92,93,],[-26,-32,-18,-19,-52,-27,-35,-24,-28,-37,-25,-34,73,-36,-30,-31,-39,-23,-38,-21,-29,-22,-47,-40,-7,-42,-49,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-28,93,-33,]),'EQUALS':([21,],[49,]),'TIMES':([12,14,21,22,23,27,31,32,33,34,35,36,37,39,40,41,42,43,44,45,46,47,48,50,51,52,54,57,62,63,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,],[-26,-32,-27,-18,-19,-52,60,-27,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,60,-29,-22,-47,-40,-29,-22,60,-42,-49,60,-45,-46,-20,-41,-48,60,-44,-51,60,60,60,-43,-50,60,60,-14,60,60,-13,60,60,60,-33,]),'COSEC':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[17,17,17,17,17,17,17,17,17,17,-26,17,-32,17,17,17,17,17,-18,-19,17,-52,17,17,-27,-35,-24,17,-28,-37,17,-25,-34,-36,17,-30,-31,-39,17,17,17,-23,-38,-21,17,-29,17,17,-22,17,17,17,17,-47,-40,17,17,17,-7,-42,-49,17,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'DIFFERENCE':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[18,18,18,18,18,18,18,18,18,18,-26,18,-32,18,18,18,18,18,-18,-19,18,-52,18,18,-27,-35,-24,18,-28,-37,18,-25,-34,-36,18,-30,-31,-39,18,18,18,-23,-38,-21,18,-29,18,18,-22,18,18,18,18,-47,-40,18,18,18,-7,-42,-49,18,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'AND':([12,14,21,22,23,27,31,32,33,34,35,36,37,39,40,41,42,43,44,45,46,47,48,50,51,52,54,57,62,63,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,],[-26,-32,-27,-18,-19,-52,53,-27,53,53,53,-28,53,53,53,53,53,53,53,53,53,53,53,53,53,53,-29,-22,-47,-40,-29,-22,53,-42,-49,53,-45,-46,-20,-41,-48,53,-44,-51,53,53,53,-43,-50,53,53,-14,53,-11,-13,-12,-12,53,-33,]),'QUIT':([0,],[19,]),'PRODUCT':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[20,20,20,20,20,20,20,20,20,20,-26,20,-32,20,20,20,20,20,-18,-19,20,-52,20,20,-27,-35,-24,20,-28,-37,20,-25,-34,-36,20,-30,-31,-39,20,20,20,-23,-38,-21,20,-29,20,20,-22,20,20,20,20,-47,-40,20,20,20,-7,-42,-49,20,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'NAME':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[21,32,32,32,32,32,32,32,32,32,-26,32,-32,32,32,32,32,32,-18,-19,32,-52,32,32,-27,-35,-24,32,-28,-37,32,-25,-34,-36,32,-30,-31,-39,32,32,32,-23,-38,-21,32,-29,32,32,-22,32,32,32,32,-47,-40,32,32,32,-7,-42,-49,32,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'INT':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[22,22,22,22,22,22,22,22,22,22,-26,22,-32,22,22,22,22,22,-18,-19,22,-52,22,22,-27,-35,-24,22,-28,-37,22,-25,-34,-36,22,-30,-31,-39,22,22,22,-23,-38,-21,22,-29,22,22,-22,22,22,22,22,-47,-40,22,22,22,-7,-42,-49,22,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'FLOAT':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[23,23,23,23,23,23,23,23,23,23,-26,23,-32,23,23,23,23,23,-18,-19,23,-52,23,23,-27,-35,-24,23,-28,-37,23,-25,-34,-36,23,-30,-31,-39,23,23,23,-23,-38,-21,23,-29,23,23,-22,23,23,23,23,-47,-40,23,23,23,-7,-42,-49,23,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'BREAK':([0,],[25,]),'FACTORIAL':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,21,22,23,26,27,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,],[26,26,26,26,26,26,26,26,26,26,-26,26,-32,26,26,26,26,26,-27,-18,-19,26,-52,26,26,57,-27,57,57,66,-28,57,26,57,57,57,57,66,57,57,57,66,66,26,57,57,57,26,-29,26,26,-22,26,26,26,26,-47,-40,26,26,26,57,-42,-49,66,-45,-46,-20,-41,-48,57,-44,-51,57,57,57,-43,-50,57,57,-14,57,-11,-13,-12,-12,57,-33,]),'REGISTERS':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[27,27,27,27,27,27,27,27,27,27,-26,27,-32,27,27,27,27,27,-18,-19,27,-52,27,27,-27,-35,-24,27,-28,-37,27,-25,-34,-36,27,-30,-31,-39,27,27,27,-23,-38,-21,27,-29,27,27,-22,27,27,27,27,-47,-40,27,27,27,-7,-42,-49,27,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'EXIT':([0,],[28,]),'NOT':([0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,20,22,23,26,27,29,30,32,33,34,35,36,37,38,39,40,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,82,83,84,85,86,87,88,89,90,91,93,],[30,30,30,30,30,30,30,30,30,30,-26,30,-32,30,30,30,30,30,-18,-19,30,-52,30,30,-27,-35,-24,30,-28,-37,30,-25,-34,-36,30,-30,-31,-39,30,30,30,-23,-38,-21,30,-29,30,30,-22,30,30,30,30,-47,-40,30,30,30,-7,-42,-49,30,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-43,-50,-16,-17,-14,-15,-11,-13,-12,-12,-33,]),'$end':([10,12,14,19,21,22,23,24,25,27,28,31,32,33,34,36,37,39,40,42,44,45,46,50,51,52,54,57,62,63,67,68,69,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,93,],[-2,-26,-32,-6,-27,-18,-19,0,-4,-52,-5,-3,-27,-35,-24,-28,-37,-25,-34,-36,-30,-31,-39,-23,-38,-21,-29,-22,-47,-40,-7,-42,-49,-45,-46,-20,-41,-48,-10,-44,-51,-8,-9,-1,-43,-50,-16,-17,-14,-15,-11,-13,-12,-28,-33,]),'OR':([12,14,21,22,23,27,31,32,33,34,35,36,37,39,40,41,42,43,44,45,46,47,48,50,51,52,54,57,62,63,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,],[-26,-32,-27,-18,-19,-52,58,-27,58,58,58,-28,58,58,58,58,58,58,58,58,58,58,58,58,58,58,-29,-22,-47,-40,-29,-22,58,-42,-49,58,-45,-46,-20,-41,-48,58,-44,-51,58,58,58,-43,-50,58,58,-14,58,-11,-13,-12,-12,58,-33,]),} _lr_action = {} for _k, _v in _lr_action_items.items(): for _x,_y in zip(_v[0],_v[1]): if not _x in _lr_action: _lr_action[_x] = {} _lr_action[_x][_k] = _y del _lr_action_items _lr_goto_items = {'function1':([0,1,2,3,4,5,7,8,9,11,13,15,16,17,18,20,26,29,30,35,38,43,47,48,49,53,55,56,58,59,60,61,64,65,66,70,],[14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,]),'expression':([0,1,2,3,4,5,7,8,9,11,13,15,16,17,18,20,26,29,30,35,38,43,47,48,49,53,55,56,58,59,60,61,64,65,66,70,],[31,33,34,35,36,37,39,40,41,42,43,44,45,46,47,48,50,51,52,67,70,76,79,80,81,84,85,86,87,88,89,90,91,44,50,92,]),'assign':([0,],[24,]),'statement':([0,],[10,]),} _lr_goto = {} for _k, _v in _lr_goto_items.items(): for _x, _y in zip(_v[0], _v[1]): if not _x in _lr_goto: _lr_goto[_x] = {} _lr_goto[_x][_k] = _y del _lr_goto_items _lr_productions = [ ("S' -> assign","S'",1,None,None,None), ('assign -> NAME EQUALS expression','assign',3,'p_statement_assign','calc1.py',13), ('assign -> statement','assign',1,'p_statement_assign','calc1.py',14), ('statement -> expression','statement',1,'p_statement_expr','calc1.py',22), ('statement -> BREAK','statement',1,'p_statement_expr','calc1.py',23), ('statement -> EXIT','statement',1,'p_statement_expr','calc1.py',24), ('statement -> QUIT','statement',1,'p_statement_expr','calc1.py',25), ('expression -> SUM expression expression','expression',3,'p_exprr','calc1.py',34), ('expression -> DIFFERENCE expression expression','expression',3,'p_exprr','calc1.py',35), ('expression -> PRODUCT expression expression','expression',3,'p_exprr','calc1.py',36), ('expression -> QUOTIENT expression expression','expression',3,'p_exprr','calc1.py',37), ('expression -> expression PLUS expression','expression',3,'p_expression_binop','calc1.py',50), ('expression -> expression MINUS expression','expression',3,'p_expression_binop','calc1.py',51), ('expression -> expression TIMES expression','expression',3,'p_expression_binop','calc1.py',52), ('expression -> expression DIVIDE expression','expression',3,'p_expression_binop','calc1.py',53), ('expression -> expression OR expression','expression',3,'p_expression_binop','calc1.py',54), ('expression -> expression AND expression','expression',3,'p_expression_binop','calc1.py',55), ('expression -> expression XOR expression','expression',3,'p_expression_binop','calc1.py',56), ('expression -> INT','expression',1,'p_factor','calc1.py',80), ('expression -> FLOAT','expression',1,'p_factor','calc1.py',81), ('expression -> OPAR expression CPAR','expression',3,'p_paran','calc1.py',85), ('expression -> NOT expression','expression',2,'p_logical_not','calc1.py',89), ('expression -> expression FACTORIAL','expression',2,'p_factorial_exp','calc1.py',93), ('expression -> FACTORIAL expression','expression',2,'p_factorial_exp','calc1.py',94), ('expression -> LOG expression','expression',2,'p_logarithms','calc1.py',108), ('expression -> LN expression','expression',2,'p_logarithms','calc1.py',109), ('expression -> PI','expression',1,'p_pival','calc1.py',126), ('expression -> NAME','expression',1,'p_pival','calc1.py',127), ('expression -> MINUS expression','expression',2,'p_uniminus','calc1.py',134), ('expression -> expression SQUARE','expression',2,'p_square_fun','calc1.py',138), ('expression -> SQUARE expression','expression',2,'p_square_fun','calc1.py',139), ('expression -> SQROOT expression','expression',2,'p_square_root','calc1.py',147), ('expression -> function1','expression',1,'p_math_fun','calc1.py',151), ('expression -> POWER OPAR expression expression CPAR','expression',5,'p_math_pow','calc1.py',155), ('function1 -> SIN expression','function1',2,'p_trig_func1','calc1.py',161), ('function1 -> COS expression','function1',2,'p_trig_func1','calc1.py',162), ('function1 -> TAN expression','function1',2,'p_trig_func1','calc1.py',163), ('function1 -> COT expression','function1',2,'p_trig_func1','calc1.py',164), ('function1 -> SEC expression','function1',2,'p_trig_func1','calc1.py',165), ('function1 -> COSEC expression','function1',2,'p_trig_func1','calc1.py',166), ('function1 -> COS expression RAD','function1',3,'p_trig_func1','calc1.py',167), ('function1 -> TAN expression RAD','function1',3,'p_trig_func1','calc1.py',168), ('function1 -> COT expression RAD','function1',3,'p_trig_func1','calc1.py',169), ('function1 -> SEC expression RAD','function1',3,'p_trig_func1','calc1.py',170), ('function1 -> COSEC expression RAD','function1',3,'p_trig_func1','calc1.py',171), ('function1 -> SIN expression RAD','function1',3,'p_trig_func1','calc1.py',172), ('function1 -> SIN expression DEGREE','function1',3,'p_func1','calc1.py',190), ('function1 -> COS expression DEGREE','function1',3,'p_func1','calc1.py',191), ('function1 -> TAN expression DEGREE','function1',3,'p_func1','calc1.py',192), ('function1 -> COT expression DEGREE','function1',3,'p_func1','calc1.py',193), ('function1 -> SEC expression DEGREE','function1',3,'p_func1','calc1.py',194), ('function1 -> COSEC expression DEGREE','function1',3,'p_func1','calc1.py',195), ('expression -> REGISTERS','expression',1,'p_registers','calc1.py',211), ]
_tabversion = '3.5' _lr_method = 'LALR' _lr_signature = '5E2BB3531AA676A6BB1D06733251B2F3' _lr_action_items = {'COS': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -26, 1, -32, 1, 1, 1, 1, 1, -18, -19, 1, -52, 1, 1, -27, -35, -24, 1, -28, -37, 1, -25, -34, -36, 1, -30, -31, -39, 1, 1, 1, -23, -38, -21, 1, -29, 1, 1, -22, 1, 1, 1, 1, -47, -40, 1, 1, 1, -7, -42, -49, 1, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -12, -33]), 'COT': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, -26, 5, -32, 5, 5, 5, 5, 5, -18, -19, 5, -52, 5, 5, -27, -35, -24, 5, -28, -37, 5, -25, -34, -36, 5, -30, -31, -39, 5, 5, 5, -23, -38, -21, 5, -29, 5, 5, -22, 5, 5, 5, 5, -47, -40, 5, 5, 5, -7, -42, -49, 5, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -12, -33]), 'DEGREE': ([12, 14, 22, 23, 27, 32, 33, 34, 36, 37, 39, 40, 42, 44, 45, 46, 50, 51, 52, 54, 57, 62, 63, 67, 68, 69, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [-26, -32, -18, -19, -52, -27, 62, -24, -28, 69, -25, 72, 75, -30, -31, 78, -23, 83, -21, -29, -22, -47, -40, -7, -42, -49, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -28, -33]), 'SUM': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, -26, 3, -32, 3, 3, 3, 3, 3, -18, -19, 3, -52, 3, 3, -27, -35, -24, 3, -28, -37, 3, -25, -34, -36, 3, -30, -31, -39, 3, 3, 3, -23, -38, -21, 3, -29, 3, 3, -22, 3, 3, 3, 3, -47, -40, 3, 3, 3, -7, -42, -49, 3, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -12, -33]), 'MINUS': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 26, 27, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93], [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, -26, 4, -32, 4, 4, 4, 4, 4, -27, -18, -19, 4, -52, 4, 4, 61, -27, 61, 61, 64, -28, 61, 4, 61, 61, 61, 61, 64, 61, 61, 61, 64, 64, 4, 61, 61, 61, 4, -29, 4, 4, -22, 4, 4, 4, 4, -47, -40, 4, 4, 4, 61, -42, -49, 64, -45, -46, -20, -41, -48, 61, -44, -51, 61, 61, 61, -43, -50, 61, 61, -14, 61, -11, -13, -12, -12, 61, -33]), 'LOG': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, -26, 2, -32, 2, 2, 2, 2, 2, -18, -19, 2, -52, 2, 2, -27, -35, -24, 2, -28, -37, 2, -25, -34, -36, 2, -30, -31, -39, 2, 2, 2, -23, -38, -21, 2, -29, 2, 2, -22, 2, 2, 2, 2, -47, -40, 2, 2, 2, -7, -42, -49, 2, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -12, -33]), 'RAD': ([12, 14, 22, 23, 27, 32, 33, 34, 36, 37, 39, 40, 42, 44, 45, 46, 50, 51, 52, 54, 57, 62, 63, 67, 68, 69, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [-26, -32, -18, -19, -52, -27, 63, -24, -28, 68, -25, 71, 74, -30, -31, 77, -23, 82, -21, -29, -22, -47, -40, -7, -42, -49, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -28, -33]), 'POWER': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, -26, 6, -32, 6, 6, 6, 6, 6, -18, -19, 6, -52, 6, 6, -27, -35, -24, 6, -28, -37, 6, -25, -34, -36, 6, -30, -31, -39, 6, 6, 6, -23, -38, -21, 6, -29, 6, 6, -22, 6, 6, 6, 6, -47, -40, 6, 6, 6, -7, -42, -49, 6, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -12, -33]), 'LN': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [7, 7, 7, 7, 7, 7, 7, 7, 7, 7, -26, 7, -32, 7, 7, 7, 7, 7, -18, -19, 7, -52, 7, 7, -27, -35, -24, 7, -28, -37, 7, -25, -34, -36, 7, -30, -31, -39, 7, 7, 7, -23, -38, -21, 7, -29, 7, 7, -22, 7, 7, 7, 7, -47, -40, 7, 7, 7, -7, -42, -49, 7, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -12, -33]), 'SIN': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [8, 8, 8, 8, 8, 8, 8, 8, 8, 8, -26, 8, -32, 8, 8, 8, 8, 8, -18, -19, 8, -52, 8, 8, -27, -35, -24, 8, -28, -37, 8, -25, -34, -36, 8, -30, -31, -39, 8, 8, 8, -23, -38, -21, 8, -29, 8, 8, -22, 8, 8, 8, 8, -47, -40, 8, 8, 8, -7, -42, -49, 8, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -12, -33]), 'OPAR': ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [9, 9, 9, 9, 9, 9, 38, 9, 9, 9, 9, -26, 9, -32, 9, 9, 9, 9, 9, -18, -19, 9, -52, 9, 9, -27, -35, -24, 9, -28, -37, 9, -25, -34, -36, 9, -30, -31, -39, 9, 9, 9, -23, -38, -21, 9, -29, 9, 9, -22, 9, 9, 9, 9, -47, -40, 9, 9, 9, -7, -42, -49, 9, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -12, -33]), 'SEC': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [29, 29, 29, 29, 29, 29, 29, 29, 29, 29, -26, 29, -32, 29, 29, 29, 29, 29, -18, -19, 29, -52, 29, 29, -27, -35, -24, 29, -28, -37, 29, -25, -34, -36, 29, -30, -31, -39, 29, 29, 29, -23, -38, -21, 29, -29, 29, 29, -22, 29, 29, 29, 29, -47, -40, 29, 29, 29, -7, -42, -49, 29, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -12, -33]), 'TAN': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [11, 11, 11, 11, 11, 11, 11, 11, 11, 11, -26, 11, -32, 11, 11, 11, 11, 11, -18, -19, 11, -52, 11, 11, -27, -35, -24, 11, -28, -37, 11, -25, -34, -36, 11, -30, -31, -39, 11, 11, 11, -23, -38, -21, 11, -29, 11, 11, -22, 11, 11, 11, 11, -47, -40, 11, 11, 11, -7, -42, -49, 11, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -12, -33]), 'PI': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [12, 12, 12, 12, 12, 12, 12, 12, 12, 12, -26, 12, -32, 12, 12, 12, 12, 12, -18, -19, 12, -52, 12, 12, -27, -35, -24, 12, -28, -37, 12, -25, -34, -36, 12, -30, -31, -39, 12, 12, 12, -23, -38, -21, 12, -29, 12, 12, -22, 12, 12, 12, 12, -47, -40, 12, 12, 12, -7, -42, -49, 12, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -12, -33]), 'QUOTIENT': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [13, 13, 13, 13, 13, 13, 13, 13, 13, 13, -26, 13, -32, 13, 13, 13, 13, 13, -18, -19, 13, -52, 13, 13, -27, -35, -24, 13, -28, -37, 13, -25, -34, -36, 13, -30, -31, -39, 13, 13, 13, -23, -38, -21, 13, -29, 13, 13, -22, 13, 13, 13, 13, -47, -40, 13, 13, 13, -7, -42, -49, 13, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -12, -33]), 'PLUS': ([12, 14, 21, 22, 23, 27, 31, 32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 50, 51, 52, 54, 57, 62, 63, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93], [-26, -32, -27, -18, -19, -52, 59, -27, 59, 59, 59, -28, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, -29, -22, -47, -40, -29, -22, 59, -42, -49, 59, -45, -46, -20, -41, -48, 59, -44, -51, 59, 59, 59, -43, -50, 59, 59, -14, 59, -11, -13, -12, -12, 59, -33]), 'SQUARE': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 26, 27, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93], [15, 15, 15, 15, 15, 15, 15, 15, 15, 15, -26, 15, -32, 15, 15, 15, 15, 15, -27, -18, -19, 15, -52, 15, 15, 54, -27, 54, 54, 65, -28, 54, 15, 54, 54, 54, 54, 65, 54, 54, 54, 65, 65, 15, 54, 54, 54, 15, -29, 15, 15, -22, 15, 15, 15, 15, -47, -40, 15, 15, 15, 54, -42, -49, 65, -45, -46, -20, -41, -48, 54, -44, -51, 54, 54, 54, -43, -50, 54, 54, -14, 54, -11, -13, -12, -12, 54, -33]), 'XOR': ([12, 14, 21, 22, 23, 27, 31, 32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 50, 51, 52, 54, 57, 62, 63, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93], [-26, -32, -27, -18, -19, -52, 55, -27, 55, 55, 55, -28, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, -29, -22, -47, -40, -29, -22, 55, -42, -49, 55, -45, -46, -20, -41, -48, 55, -44, -51, 55, 55, 55, -43, -50, 55, 55, -14, 55, -11, -13, -12, -12, 55, -33]), 'DIVIDE': ([12, 14, 21, 22, 23, 27, 31, 32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 50, 51, 52, 54, 57, 62, 63, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93], [-26, -32, -27, -18, -19, -52, 56, -27, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, -29, -22, -47, -40, -29, -22, 56, -42, -49, 56, -45, -46, -20, -41, -48, 56, -44, -51, 56, 56, 56, -43, -50, 56, 56, -14, 56, 56, -13, 56, 56, 56, -33]), 'SQROOT': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [16, 16, 16, 16, 16, 16, 16, 16, 16, 16, -26, 16, -32, 16, 16, 16, 16, 16, -18, -19, 16, -52, 16, 16, -27, -35, -24, 16, -28, -37, 16, -25, -34, -36, 16, -30, -31, -39, 16, 16, 16, -23, -38, -21, 16, -29, 16, 16, -22, 16, 16, 16, 16, -47, -40, 16, 16, 16, -7, -42, -49, 16, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -12, -33]), 'CPAR': ([12, 14, 22, 23, 27, 32, 33, 34, 36, 37, 39, 40, 41, 42, 44, 45, 46, 50, 51, 52, 54, 57, 62, 63, 67, 68, 69, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93], [-26, -32, -18, -19, -52, -27, -35, -24, -28, -37, -25, -34, 73, -36, -30, -31, -39, -23, -38, -21, -29, -22, -47, -40, -7, -42, -49, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -28, 93, -33]), 'EQUALS': ([21], [49]), 'TIMES': ([12, 14, 21, 22, 23, 27, 31, 32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 50, 51, 52, 54, 57, 62, 63, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93], [-26, -32, -27, -18, -19, -52, 60, -27, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, -29, -22, -47, -40, -29, -22, 60, -42, -49, 60, -45, -46, -20, -41, -48, 60, -44, -51, 60, 60, 60, -43, -50, 60, 60, -14, 60, 60, -13, 60, 60, 60, -33]), 'COSEC': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [17, 17, 17, 17, 17, 17, 17, 17, 17, 17, -26, 17, -32, 17, 17, 17, 17, 17, -18, -19, 17, -52, 17, 17, -27, -35, -24, 17, -28, -37, 17, -25, -34, -36, 17, -30, -31, -39, 17, 17, 17, -23, -38, -21, 17, -29, 17, 17, -22, 17, 17, 17, 17, -47, -40, 17, 17, 17, -7, -42, -49, 17, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -12, -33]), 'DIFFERENCE': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [18, 18, 18, 18, 18, 18, 18, 18, 18, 18, -26, 18, -32, 18, 18, 18, 18, 18, -18, -19, 18, -52, 18, 18, -27, -35, -24, 18, -28, -37, 18, -25, -34, -36, 18, -30, -31, -39, 18, 18, 18, -23, -38, -21, 18, -29, 18, 18, -22, 18, 18, 18, 18, -47, -40, 18, 18, 18, -7, -42, -49, 18, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -12, -33]), 'AND': ([12, 14, 21, 22, 23, 27, 31, 32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 50, 51, 52, 54, 57, 62, 63, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93], [-26, -32, -27, -18, -19, -52, 53, -27, 53, 53, 53, -28, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, -29, -22, -47, -40, -29, -22, 53, -42, -49, 53, -45, -46, -20, -41, -48, 53, -44, -51, 53, 53, 53, -43, -50, 53, 53, -14, 53, -11, -13, -12, -12, 53, -33]), 'QUIT': ([0], [19]), 'PRODUCT': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [20, 20, 20, 20, 20, 20, 20, 20, 20, 20, -26, 20, -32, 20, 20, 20, 20, 20, -18, -19, 20, -52, 20, 20, -27, -35, -24, 20, -28, -37, 20, -25, -34, -36, 20, -30, -31, -39, 20, 20, 20, -23, -38, -21, 20, -29, 20, 20, -22, 20, 20, 20, 20, -47, -40, 20, 20, 20, -7, -42, -49, 20, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -12, -33]), 'NAME': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [21, 32, 32, 32, 32, 32, 32, 32, 32, 32, -26, 32, -32, 32, 32, 32, 32, 32, -18, -19, 32, -52, 32, 32, -27, -35, -24, 32, -28, -37, 32, -25, -34, -36, 32, -30, -31, -39, 32, 32, 32, -23, -38, -21, 32, -29, 32, 32, -22, 32, 32, 32, 32, -47, -40, 32, 32, 32, -7, -42, -49, 32, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -12, -33]), 'INT': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [22, 22, 22, 22, 22, 22, 22, 22, 22, 22, -26, 22, -32, 22, 22, 22, 22, 22, -18, -19, 22, -52, 22, 22, -27, -35, -24, 22, -28, -37, 22, -25, -34, -36, 22, -30, -31, -39, 22, 22, 22, -23, -38, -21, 22, -29, 22, 22, -22, 22, 22, 22, 22, -47, -40, 22, 22, 22, -7, -42, -49, 22, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -12, -33]), 'FLOAT': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [23, 23, 23, 23, 23, 23, 23, 23, 23, 23, -26, 23, -32, 23, 23, 23, 23, 23, -18, -19, 23, -52, 23, 23, -27, -35, -24, 23, -28, -37, 23, -25, -34, -36, 23, -30, -31, -39, 23, 23, 23, -23, -38, -21, 23, -29, 23, 23, -22, 23, 23, 23, 23, -47, -40, 23, 23, 23, -7, -42, -49, 23, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -12, -33]), 'BREAK': ([0], [25]), 'FACTORIAL': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23, 26, 27, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93], [26, 26, 26, 26, 26, 26, 26, 26, 26, 26, -26, 26, -32, 26, 26, 26, 26, 26, -27, -18, -19, 26, -52, 26, 26, 57, -27, 57, 57, 66, -28, 57, 26, 57, 57, 57, 57, 66, 57, 57, 57, 66, 66, 26, 57, 57, 57, 26, -29, 26, 26, -22, 26, 26, 26, 26, -47, -40, 26, 26, 26, 57, -42, -49, 66, -45, -46, -20, -41, -48, 57, -44, -51, 57, 57, 57, -43, -50, 57, 57, -14, 57, -11, -13, -12, -12, 57, -33]), 'REGISTERS': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [27, 27, 27, 27, 27, 27, 27, 27, 27, 27, -26, 27, -32, 27, 27, 27, 27, 27, -18, -19, 27, -52, 27, 27, -27, -35, -24, 27, -28, -37, 27, -25, -34, -36, 27, -30, -31, -39, 27, 27, 27, -23, -38, -21, 27, -29, 27, 27, -22, 27, 27, 27, 27, -47, -40, 27, 27, 27, -7, -42, -49, 27, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -12, -33]), 'EXIT': ([0], [28]), 'NOT': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 23, 26, 27, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [30, 30, 30, 30, 30, 30, 30, 30, 30, 30, -26, 30, -32, 30, 30, 30, 30, 30, -18, -19, 30, -52, 30, 30, -27, -35, -24, 30, -28, -37, 30, -25, -34, -36, 30, -30, -31, -39, 30, 30, 30, -23, -38, -21, 30, -29, 30, 30, -22, 30, 30, 30, 30, -47, -40, 30, 30, 30, -7, -42, -49, 30, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -43, -50, -16, -17, -14, -15, -11, -13, -12, -12, -33]), '$end': ([10, 12, 14, 19, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34, 36, 37, 39, 40, 42, 44, 45, 46, 50, 51, 52, 54, 57, 62, 63, 67, 68, 69, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 93], [-2, -26, -32, -6, -27, -18, -19, 0, -4, -52, -5, -3, -27, -35, -24, -28, -37, -25, -34, -36, -30, -31, -39, -23, -38, -21, -29, -22, -47, -40, -7, -42, -49, -45, -46, -20, -41, -48, -10, -44, -51, -8, -9, -1, -43, -50, -16, -17, -14, -15, -11, -13, -12, -28, -33]), 'OR': ([12, 14, 21, 22, 23, 27, 31, 32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 50, 51, 52, 54, 57, 62, 63, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93], [-26, -32, -27, -18, -19, -52, 58, -27, 58, 58, 58, -28, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, -29, -22, -47, -40, -29, -22, 58, -42, -49, 58, -45, -46, -20, -41, -48, 58, -44, -51, 58, 58, 58, -43, -50, 58, 58, -14, 58, -11, -13, -12, -12, 58, -33])} _lr_action = {} for (_k, _v) in _lr_action_items.items(): for (_x, _y) in zip(_v[0], _v[1]): if not _x in _lr_action: _lr_action[_x] = {} _lr_action[_x][_k] = _y del _lr_action_items _lr_goto_items = {'function1': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 13, 15, 16, 17, 18, 20, 26, 29, 30, 35, 38, 43, 47, 48, 49, 53, 55, 56, 58, 59, 60, 61, 64, 65, 66, 70], [14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14]), 'expression': ([0, 1, 2, 3, 4, 5, 7, 8, 9, 11, 13, 15, 16, 17, 18, 20, 26, 29, 30, 35, 38, 43, 47, 48, 49, 53, 55, 56, 58, 59, 60, 61, 64, 65, 66, 70], [31, 33, 34, 35, 36, 37, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 50, 51, 52, 67, 70, 76, 79, 80, 81, 84, 85, 86, 87, 88, 89, 90, 91, 44, 50, 92]), 'assign': ([0], [24]), 'statement': ([0], [10])} _lr_goto = {} for (_k, _v) in _lr_goto_items.items(): for (_x, _y) in zip(_v[0], _v[1]): if not _x in _lr_goto: _lr_goto[_x] = {} _lr_goto[_x][_k] = _y del _lr_goto_items _lr_productions = [("S' -> assign", "S'", 1, None, None, None), ('assign -> NAME EQUALS expression', 'assign', 3, 'p_statement_assign', 'calc1.py', 13), ('assign -> statement', 'assign', 1, 'p_statement_assign', 'calc1.py', 14), ('statement -> expression', 'statement', 1, 'p_statement_expr', 'calc1.py', 22), ('statement -> BREAK', 'statement', 1, 'p_statement_expr', 'calc1.py', 23), ('statement -> EXIT', 'statement', 1, 'p_statement_expr', 'calc1.py', 24), ('statement -> QUIT', 'statement', 1, 'p_statement_expr', 'calc1.py', 25), ('expression -> SUM expression expression', 'expression', 3, 'p_exprr', 'calc1.py', 34), ('expression -> DIFFERENCE expression expression', 'expression', 3, 'p_exprr', 'calc1.py', 35), ('expression -> PRODUCT expression expression', 'expression', 3, 'p_exprr', 'calc1.py', 36), ('expression -> QUOTIENT expression expression', 'expression', 3, 'p_exprr', 'calc1.py', 37), ('expression -> expression PLUS expression', 'expression', 3, 'p_expression_binop', 'calc1.py', 50), ('expression -> expression MINUS expression', 'expression', 3, 'p_expression_binop', 'calc1.py', 51), ('expression -> expression TIMES expression', 'expression', 3, 'p_expression_binop', 'calc1.py', 52), ('expression -> expression DIVIDE expression', 'expression', 3, 'p_expression_binop', 'calc1.py', 53), ('expression -> expression OR expression', 'expression', 3, 'p_expression_binop', 'calc1.py', 54), ('expression -> expression AND expression', 'expression', 3, 'p_expression_binop', 'calc1.py', 55), ('expression -> expression XOR expression', 'expression', 3, 'p_expression_binop', 'calc1.py', 56), ('expression -> INT', 'expression', 1, 'p_factor', 'calc1.py', 80), ('expression -> FLOAT', 'expression', 1, 'p_factor', 'calc1.py', 81), ('expression -> OPAR expression CPAR', 'expression', 3, 'p_paran', 'calc1.py', 85), ('expression -> NOT expression', 'expression', 2, 'p_logical_not', 'calc1.py', 89), ('expression -> expression FACTORIAL', 'expression', 2, 'p_factorial_exp', 'calc1.py', 93), ('expression -> FACTORIAL expression', 'expression', 2, 'p_factorial_exp', 'calc1.py', 94), ('expression -> LOG expression', 'expression', 2, 'p_logarithms', 'calc1.py', 108), ('expression -> LN expression', 'expression', 2, 'p_logarithms', 'calc1.py', 109), ('expression -> PI', 'expression', 1, 'p_pival', 'calc1.py', 126), ('expression -> NAME', 'expression', 1, 'p_pival', 'calc1.py', 127), ('expression -> MINUS expression', 'expression', 2, 'p_uniminus', 'calc1.py', 134), ('expression -> expression SQUARE', 'expression', 2, 'p_square_fun', 'calc1.py', 138), ('expression -> SQUARE expression', 'expression', 2, 'p_square_fun', 'calc1.py', 139), ('expression -> SQROOT expression', 'expression', 2, 'p_square_root', 'calc1.py', 147), ('expression -> function1', 'expression', 1, 'p_math_fun', 'calc1.py', 151), ('expression -> POWER OPAR expression expression CPAR', 'expression', 5, 'p_math_pow', 'calc1.py', 155), ('function1 -> SIN expression', 'function1', 2, 'p_trig_func1', 'calc1.py', 161), ('function1 -> COS expression', 'function1', 2, 'p_trig_func1', 'calc1.py', 162), ('function1 -> TAN expression', 'function1', 2, 'p_trig_func1', 'calc1.py', 163), ('function1 -> COT expression', 'function1', 2, 'p_trig_func1', 'calc1.py', 164), ('function1 -> SEC expression', 'function1', 2, 'p_trig_func1', 'calc1.py', 165), ('function1 -> COSEC expression', 'function1', 2, 'p_trig_func1', 'calc1.py', 166), ('function1 -> COS expression RAD', 'function1', 3, 'p_trig_func1', 'calc1.py', 167), ('function1 -> TAN expression RAD', 'function1', 3, 'p_trig_func1', 'calc1.py', 168), ('function1 -> COT expression RAD', 'function1', 3, 'p_trig_func1', 'calc1.py', 169), ('function1 -> SEC expression RAD', 'function1', 3, 'p_trig_func1', 'calc1.py', 170), ('function1 -> COSEC expression RAD', 'function1', 3, 'p_trig_func1', 'calc1.py', 171), ('function1 -> SIN expression RAD', 'function1', 3, 'p_trig_func1', 'calc1.py', 172), ('function1 -> SIN expression DEGREE', 'function1', 3, 'p_func1', 'calc1.py', 190), ('function1 -> COS expression DEGREE', 'function1', 3, 'p_func1', 'calc1.py', 191), ('function1 -> TAN expression DEGREE', 'function1', 3, 'p_func1', 'calc1.py', 192), ('function1 -> COT expression DEGREE', 'function1', 3, 'p_func1', 'calc1.py', 193), ('function1 -> SEC expression DEGREE', 'function1', 3, 'p_func1', 'calc1.py', 194), ('function1 -> COSEC expression DEGREE', 'function1', 3, 'p_func1', 'calc1.py', 195), ('expression -> REGISTERS', 'expression', 1, 'p_registers', 'calc1.py', 211)]
# The following is a list of gene-plan combinations which should # not be run BLACKLIST = [ ('8C58', 'performance'), # performance.xml make specific references to 52DC ('7DDA', 'performance') # performance.xml make specific references to 52DC ] IGNORE = { 'history' : ['uuid', 'creationTool', 'creationDate'], 'genome' : ['uuid', 'creationTool', 'creationDate'], # the following two ignored because they contain line numbers 'attempt' : ['description'], 'compared' : ['description'] }
blacklist = [('8C58', 'performance'), ('7DDA', 'performance')] ignore = {'history': ['uuid', 'creationTool', 'creationDate'], 'genome': ['uuid', 'creationTool', 'creationDate'], 'attempt': ['description'], 'compared': ['description']}
track = dict( author_username='alexisbcook', course_name='Data Cleaning', course_url='https://www.kaggle.com/learn/data-cleaning', course_forum_url='https://www.kaggle.com/learn-forum/172650' ) lessons = [ {'topic': topic_name} for topic_name in ['Handling missing values', #1 'Scaling and normalization', #2 'Parsing dates', #3 'Character encodings', #4 'Inconsistent data entry'] #5 ] notebooks = [ dict( filename='tut1.ipynb', lesson_idx=0, type='tutorial', dataset_sources=['maxhorowitz/nflplaybyplay2009to2016'], ), dict( filename='ex1.ipynb', lesson_idx=0, type='exercise', dataset_sources=['aparnashastry/building-permit-applications-data'], scriptid=10824396 ), dict( filename='tut2.ipynb', lesson_idx=1, type='tutorial', ), dict( filename='ex2.ipynb', lesson_idx=1, type='exercise', dataset_sources=['kemical/kickstarter-projects'], scriptid=10824404 ), dict( filename='tut3.ipynb', lesson_idx=2, type='tutorial', dataset_sources=['nasa/landslide-events'] ), dict( filename='ex3.ipynb', lesson_idx=2, type='exercise', dataset_sources=['usgs/earthquake-database', 'smithsonian/volcanic-eruptions'], scriptid=10824403 ), dict( filename='tut4.ipynb', lesson_idx=3, type='tutorial', dataset_sources=['kemical/kickstarter-projects'] ), dict( filename='ex4.ipynb', lesson_idx=3, type='exercise', dataset_sources=['kwullum/fatal-police-shootings-in-the-us'], scriptid=10824401 ), dict( filename='tut5.ipynb', lesson_idx=4, type='tutorial', dataset_sources=['alexisbcook/pakistan-intellectual-capital'] ), dict( filename='ex5.ipynb', lesson_idx=4, type='exercise', dataset_sources=['alexisbcook/pakistan-intellectual-capital'], scriptid=10824407 ), ]
track = dict(author_username='alexisbcook', course_name='Data Cleaning', course_url='https://www.kaggle.com/learn/data-cleaning', course_forum_url='https://www.kaggle.com/learn-forum/172650') lessons = [{'topic': topic_name} for topic_name in ['Handling missing values', 'Scaling and normalization', 'Parsing dates', 'Character encodings', 'Inconsistent data entry']] notebooks = [dict(filename='tut1.ipynb', lesson_idx=0, type='tutorial', dataset_sources=['maxhorowitz/nflplaybyplay2009to2016']), dict(filename='ex1.ipynb', lesson_idx=0, type='exercise', dataset_sources=['aparnashastry/building-permit-applications-data'], scriptid=10824396), dict(filename='tut2.ipynb', lesson_idx=1, type='tutorial'), dict(filename='ex2.ipynb', lesson_idx=1, type='exercise', dataset_sources=['kemical/kickstarter-projects'], scriptid=10824404), dict(filename='tut3.ipynb', lesson_idx=2, type='tutorial', dataset_sources=['nasa/landslide-events']), dict(filename='ex3.ipynb', lesson_idx=2, type='exercise', dataset_sources=['usgs/earthquake-database', 'smithsonian/volcanic-eruptions'], scriptid=10824403), dict(filename='tut4.ipynb', lesson_idx=3, type='tutorial', dataset_sources=['kemical/kickstarter-projects']), dict(filename='ex4.ipynb', lesson_idx=3, type='exercise', dataset_sources=['kwullum/fatal-police-shootings-in-the-us'], scriptid=10824401), dict(filename='tut5.ipynb', lesson_idx=4, type='tutorial', dataset_sources=['alexisbcook/pakistan-intellectual-capital']), dict(filename='ex5.ipynb', lesson_idx=4, type='exercise', dataset_sources=['alexisbcook/pakistan-intellectual-capital'], scriptid=10824407)]
""" https://leetcode.com/problems/3sum/ Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. Example: Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ] """ class Solution(object): def threeSum(self, nums): """ Strategy is to use sort first and then use three pointers: 1. One pointer is current value 2. One pointer is "left" index that starts from index after current value 3. One pointer is "right" index that starts from last index Calculate sum of all three pointers. If sum is greater than 0, need to make sum smaller, so decrease right index until next distinct integer If sum is less than 0, need to make bigger, so increase left index until next distinct integer If sum is 0, we found combination that works - when combination is found, need to increment left and right indices until next distinct integers for both. When left index surpasses right index, stop iterating and move on to next value. Can only calculate sums when current value is not positive. This is because three positive values can't sum to 0. :type nums: List[int] :rtype: List[List[int]] """ triplets = [] nums.sort() for index, target in enumerate(nums[:-2]): if target <= 0 and (index == 0 or (index > 0 and nums[index] != nums[index - 1])): left_index = index + 1 right_index = len(nums) - 1 while left_index < right_index: triplet_sum = target + nums[left_index] + nums[right_index] if triplet_sum > 0: right_value = nums[right_index] while left_index < right_index and right_value == nums[right_index]: right_index -= 1 elif triplet_sum < 0: left_value = nums[left_index] while left_index < right_index and left_value == nums[left_index]: left_index += 1 else: triplets.append([ target, nums[left_index], nums[right_index], ]) right_value = nums[right_index] while left_index < right_index and right_value == nums[right_index]: right_index -= 1 left_value = nums[left_index] while left_index < right_index and left_value == nums[left_index]: left_index += 1 return triplets
""" https://leetcode.com/problems/3sum/ Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. Example: Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ] """ class Solution(object): def three_sum(self, nums): """ Strategy is to use sort first and then use three pointers: 1. One pointer is current value 2. One pointer is "left" index that starts from index after current value 3. One pointer is "right" index that starts from last index Calculate sum of all three pointers. If sum is greater than 0, need to make sum smaller, so decrease right index until next distinct integer If sum is less than 0, need to make bigger, so increase left index until next distinct integer If sum is 0, we found combination that works - when combination is found, need to increment left and right indices until next distinct integers for both. When left index surpasses right index, stop iterating and move on to next value. Can only calculate sums when current value is not positive. This is because three positive values can't sum to 0. :type nums: List[int] :rtype: List[List[int]] """ triplets = [] nums.sort() for (index, target) in enumerate(nums[:-2]): if target <= 0 and (index == 0 or (index > 0 and nums[index] != nums[index - 1])): left_index = index + 1 right_index = len(nums) - 1 while left_index < right_index: triplet_sum = target + nums[left_index] + nums[right_index] if triplet_sum > 0: right_value = nums[right_index] while left_index < right_index and right_value == nums[right_index]: right_index -= 1 elif triplet_sum < 0: left_value = nums[left_index] while left_index < right_index and left_value == nums[left_index]: left_index += 1 else: triplets.append([target, nums[left_index], nums[right_index]]) right_value = nums[right_index] while left_index < right_index and right_value == nums[right_index]: right_index -= 1 left_value = nums[left_index] while left_index < right_index and left_value == nums[left_index]: left_index += 1 return triplets
# !usr/bin/python # -*- coding: UTF-8 -*- class Image: def __init__(self, name, path, url): self.name = name self.path = path self.url = url @property def full_path(self): return self.path + self.name def __str__(self): return self.name def __repr__(self): return f' {{ Name: {self.name}, \nPath: {self.path}, \nURL:{self.url} }}'
class Image: def __init__(self, name, path, url): self.name = name self.path = path self.url = url @property def full_path(self): return self.path + self.name def __str__(self): return self.name def __repr__(self): return f' {{ Name: {self.name}, \nPath: {self.path}, \nURL:{self.url} }}'
def metade(preco,sit): if sit==True: return (f'R${preco/2}') else: return preco/2 def dobro(preco,sit): if sit==True: return (f'R${preco * 2}') else: return preco * 2 def aumentar(preco,r,sit): if sit==True: return (f'R${preco * (100 + r)/100}') else: return preco * (100 + r) / 100 def diminuir(preco,r,sit): if sit==True: return(f'R${preco * (100 - r)/100}') else: return preco * (100-r)/100 def moeda(preco): return (f'R${preco}') def resumo(p=0, r=10, q=5): print('-'*30) print('RESUMO DO VALOR'.center(30)) print('-' * 30) print(f'Preco analisado: \t{moeda(p):>10}') print(f'Dobro do preco: \t{dobro(p, True):>10}') print(f'Metade do preco: \t{metade(p, True):>10}') print(f'{r}% de aumento: \t{aumentar(p, r, True):>10}') print(f'{q}% de reducao: \t{diminuir(p, q, True):>10}')
def metade(preco, sit): if sit == True: return f'R${preco / 2}' else: return preco / 2 def dobro(preco, sit): if sit == True: return f'R${preco * 2}' else: return preco * 2 def aumentar(preco, r, sit): if sit == True: return f'R${preco * (100 + r) / 100}' else: return preco * (100 + r) / 100 def diminuir(preco, r, sit): if sit == True: return f'R${preco * (100 - r) / 100}' else: return preco * (100 - r) / 100 def moeda(preco): return f'R${preco}' def resumo(p=0, r=10, q=5): print('-' * 30) print('RESUMO DO VALOR'.center(30)) print('-' * 30) print(f'Preco analisado: \t{moeda(p):>10}') print(f'Dobro do preco: \t{dobro(p, True):>10}') print(f'Metade do preco: \t{metade(p, True):>10}') print(f'{r}% de aumento: \t{aumentar(p, r, True):>10}') print(f'{q}% de reducao: \t{diminuir(p, q, True):>10}')
""" Test filters used by test_toolbox_filters.py. """ def filter_tool( context, tool ): """Test Filter Tool""" return False def filter_section( context, section ): """Test Filter Section""" return False def filter_label_1( context, label ): """Test Filter Label 1""" return False def filter_label_2( context, label ): """Test Filter Label 2""" return False
""" Test filters used by test_toolbox_filters.py. """ def filter_tool(context, tool): """Test Filter Tool""" return False def filter_section(context, section): """Test Filter Section""" return False def filter_label_1(context, label): """Test Filter Label 1""" return False def filter_label_2(context, label): """Test Filter Label 2""" return False
word=input("enter any word:") d={} for x in word: d[x]=d.get(x,0)+1 for k,v in d.items(): print(k,"occured",v,"times")
word = input('enter any word:') d = {} for x in word: d[x] = d.get(x, 0) + 1 for (k, v) in d.items(): print(k, 'occured', v, 'times')
#!/usr/bin/env python3 average = 0 score = int(input('Enter first score: ')) score += int(input('Enter second score: ')) score += int(input('Enter third score: ')) average = score / 3.0 average = round(average, 2) print(f'Total Score: {score}') print(f'Average Score: {average}')
average = 0 score = int(input('Enter first score: ')) score += int(input('Enter second score: ')) score += int(input('Enter third score: ')) average = score / 3.0 average = round(average, 2) print(f'Total Score: {score}') print(f'Average Score: {average}')
"""restrictive_growth_strings.py: Constructs the lexicographic restrictive growth string representation of all the way to partition a set, given the length of the set.""" __author__ = "Justin Overstreet" __copyright__ = "oversj96.github.io" def set_to_zero(working_set, index): """Given a set and an index, set all elements to 0 after the index.""" if index == len(working_set) - 1: return working_set else: for i in range(index + 1, len(working_set)): working_set[i] = 0 return working_set def update_b_row(a_row, b_row): """Update b row to reflect the max value of a sequence range in row a""" for i in range(1, len(a_row)): b_row[i - 1] = max(a_row[:i]) + 1 return b_row def restrictive_growth_strings(length): """Returns the set of all partitions of a set in a lexicographic integer format. The algorithm is based on Donald Knuth's volume 4A on combinatoric algorithms. Algorithm H.""" n = length - 1 a_string = [0 for i in range(0, length)] b_string = [1 for i in range(0, n)] lexico_string = [a_string.copy()] incrementable = True while incrementable: incrementable = False for index in range(n, 0, -1): if a_string[index] < n and a_string[index] < b_string[index - 1]: incrementable = True a_string[index] += 1 a_string = set_to_zero(a_string, index) b_string = update_b_row(a_string, b_string) lexico_string.append(a_string.copy()) break return lexico_string if __name__ == "__main__": """A quick way to check if the module works correctly is to compare the partition count to the bell number of the correct 'n' size. For a set of 7 elements, the partition count should be 877 by Bell's numbers.""" strings = restrictive_growth_strings(7) for string in strings: print(string) print(len(strings))
"""restrictive_growth_strings.py: Constructs the lexicographic restrictive growth string representation of all the way to partition a set, given the length of the set.""" __author__ = 'Justin Overstreet' __copyright__ = 'oversj96.github.io' def set_to_zero(working_set, index): """Given a set and an index, set all elements to 0 after the index.""" if index == len(working_set) - 1: return working_set else: for i in range(index + 1, len(working_set)): working_set[i] = 0 return working_set def update_b_row(a_row, b_row): """Update b row to reflect the max value of a sequence range in row a""" for i in range(1, len(a_row)): b_row[i - 1] = max(a_row[:i]) + 1 return b_row def restrictive_growth_strings(length): """Returns the set of all partitions of a set in a lexicographic integer format. The algorithm is based on Donald Knuth's volume 4A on combinatoric algorithms. Algorithm H.""" n = length - 1 a_string = [0 for i in range(0, length)] b_string = [1 for i in range(0, n)] lexico_string = [a_string.copy()] incrementable = True while incrementable: incrementable = False for index in range(n, 0, -1): if a_string[index] < n and a_string[index] < b_string[index - 1]: incrementable = True a_string[index] += 1 a_string = set_to_zero(a_string, index) b_string = update_b_row(a_string, b_string) lexico_string.append(a_string.copy()) break return lexico_string if __name__ == '__main__': "A quick way to check if the module works correctly is to compare\n the partition count to the bell number of the correct 'n' size.\n For a set of 7 elements, the partition count should be 877 by Bell's numbers." strings = restrictive_growth_strings(7) for string in strings: print(string) print(len(strings))
""" Author: Sean Toll Test simulation functionality """ print("Test")
""" Author: Sean Toll Test simulation functionality """ print('Test')
def binary_tree(r): """ :param r: This is root node :return: returns tree """ return [r, [], []] def insert_left(root, new_branch): """ :param root: current root of the tree :param new_branch: new branch for a tree :return: updated root of the tree """ t = root.pop(1) if len(t) > 1: root.insert(1, [new_branch, t, []]) else: root.insert(1, [new_branch, [], []]) return root def insert_right(root, new_branch): """ :param root: current root of the tree :param new_branch: new branch for a tree :return: updated root of the tree """ t = root.pop(2) if len(t) > 1: root.insert(2, [new_branch, [], t]) else: root.insert(2, [new_branch, [], []]) return root def get_root_val(root): """ :param root: current tree root :return: current tree root value """ return root[0] def set_root_val(root, new_val): """ :param root: current tree root :param new_val: new value for root to update it :return: updated tree root """ root[0] = new_val def get_left_child(root): """ :param root: current root :return: Left child of selected root """ return root[1] def get_right_child(root): """ :param root: current root :return: Right child of selected root """ return root[2] if __name__ == '__main__': r = binary_tree(3) print(insert_left(r, 5)) print(insert_left(r, 6)) print(insert_right(r, 7)) print(insert_right(r, 8)) l = get_left_child(r) print(l) rg = get_right_child(r) print(rg)
def binary_tree(r): """ :param r: This is root node :return: returns tree """ return [r, [], []] def insert_left(root, new_branch): """ :param root: current root of the tree :param new_branch: new branch for a tree :return: updated root of the tree """ t = root.pop(1) if len(t) > 1: root.insert(1, [new_branch, t, []]) else: root.insert(1, [new_branch, [], []]) return root def insert_right(root, new_branch): """ :param root: current root of the tree :param new_branch: new branch for a tree :return: updated root of the tree """ t = root.pop(2) if len(t) > 1: root.insert(2, [new_branch, [], t]) else: root.insert(2, [new_branch, [], []]) return root def get_root_val(root): """ :param root: current tree root :return: current tree root value """ return root[0] def set_root_val(root, new_val): """ :param root: current tree root :param new_val: new value for root to update it :return: updated tree root """ root[0] = new_val def get_left_child(root): """ :param root: current root :return: Left child of selected root """ return root[1] def get_right_child(root): """ :param root: current root :return: Right child of selected root """ return root[2] if __name__ == '__main__': r = binary_tree(3) print(insert_left(r, 5)) print(insert_left(r, 6)) print(insert_right(r, 7)) print(insert_right(r, 8)) l = get_left_child(r) print(l) rg = get_right_child(r) print(rg)
# Copyright 2022 Huawei Technologies Co., Ltd # # 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. # ============================================================================ ''' calculate AUC ''' def calc_auc(raw_arr): ''' calculate AUC :param raw_arr: :return: ''' arr = sorted(raw_arr, key=lambda d: d[0], reverse=True) pos, neg = 0., 0. for record in arr: if abs(record[1] - 1.) < 0.000001: pos += 1 else: neg += 1 fp, tp = 0., 0. xy_arr = [] for record in arr: if abs(record[1] - 1.) < 0.000001: tp += 1 else: fp += 1 xy_arr.append([fp / neg, tp / pos]) auc = 0. prev_x = 0. prev_y = 0. for x, y in xy_arr: if x != prev_x: auc += ((x - prev_x) * (y + prev_y) / 2.) prev_x = x prev_y = y return auc
""" calculate AUC """ def calc_auc(raw_arr): """ calculate AUC :param raw_arr: :return: """ arr = sorted(raw_arr, key=lambda d: d[0], reverse=True) (pos, neg) = (0.0, 0.0) for record in arr: if abs(record[1] - 1.0) < 1e-06: pos += 1 else: neg += 1 (fp, tp) = (0.0, 0.0) xy_arr = [] for record in arr: if abs(record[1] - 1.0) < 1e-06: tp += 1 else: fp += 1 xy_arr.append([fp / neg, tp / pos]) auc = 0.0 prev_x = 0.0 prev_y = 0.0 for (x, y) in xy_arr: if x != prev_x: auc += (x - prev_x) * (y + prev_y) / 2.0 prev_x = x prev_y = y return auc
def is_valid(r, c, size): if 0 <= r < size and 0 <= c < size: return True return False count_presents = int(input()) n = int(input()) matrix = [] nice_kids_count = 0 given_to_nice = 0 for _ in range(n): data = input().split() matrix.append(data) nice_kids_count += data.count("V") santa_row = int santa_col = int for row in range(n): for col in range(n): if matrix[row][col] == "S": santa_row = row santa_col = col all_directions = { "up": (-1, 0), "down": (1, 0), "left": (0, -1), "right": (0, 1) } while True: command = input() if command == "Christmas morning": break next_row = santa_row + all_directions[command][0] next_col = santa_col + all_directions[command][1] if is_valid(next_row, next_col, n): if matrix[next_row][next_col] == "V": given_to_nice += 1 count_presents -= 1 elif matrix[next_row][next_col] == "C": for direction in all_directions: next_step_row = next_row + all_directions[direction][0] next_step_col = next_col + all_directions[direction][1] if is_valid(next_step_row, next_step_col, n): if matrix[next_step_row][next_step_col] == "V": given_to_nice += 1 count_presents -= 1 elif matrix[next_step_row][next_step_col] == "X": count_presents -= 1 matrix[next_step_row][next_step_col] = "-" if count_presents == 0: break matrix[santa_row][santa_col] = "-" matrix[next_row][next_col] = "S" santa_row = next_row santa_col = next_col if count_presents == 0: break if count_presents == 0 and nice_kids_count != given_to_nice: print("Santa ran out of presents!") for sublist in matrix: print(" ".join(sublist)) if nice_kids_count == given_to_nice: print(f"Good job, Santa! {given_to_nice} happy nice kid/s.") else: print(f"No presents for {nice_kids_count - given_to_nice} nice kid/s.")
def is_valid(r, c, size): if 0 <= r < size and 0 <= c < size: return True return False count_presents = int(input()) n = int(input()) matrix = [] nice_kids_count = 0 given_to_nice = 0 for _ in range(n): data = input().split() matrix.append(data) nice_kids_count += data.count('V') santa_row = int santa_col = int for row in range(n): for col in range(n): if matrix[row][col] == 'S': santa_row = row santa_col = col all_directions = {'up': (-1, 0), 'down': (1, 0), 'left': (0, -1), 'right': (0, 1)} while True: command = input() if command == 'Christmas morning': break next_row = santa_row + all_directions[command][0] next_col = santa_col + all_directions[command][1] if is_valid(next_row, next_col, n): if matrix[next_row][next_col] == 'V': given_to_nice += 1 count_presents -= 1 elif matrix[next_row][next_col] == 'C': for direction in all_directions: next_step_row = next_row + all_directions[direction][0] next_step_col = next_col + all_directions[direction][1] if is_valid(next_step_row, next_step_col, n): if matrix[next_step_row][next_step_col] == 'V': given_to_nice += 1 count_presents -= 1 elif matrix[next_step_row][next_step_col] == 'X': count_presents -= 1 matrix[next_step_row][next_step_col] = '-' if count_presents == 0: break matrix[santa_row][santa_col] = '-' matrix[next_row][next_col] = 'S' santa_row = next_row santa_col = next_col if count_presents == 0: break if count_presents == 0 and nice_kids_count != given_to_nice: print('Santa ran out of presents!') for sublist in matrix: print(' '.join(sublist)) if nice_kids_count == given_to_nice: print(f'Good job, Santa! {given_to_nice} happy nice kid/s.') else: print(f'No presents for {nice_kids_count - given_to_nice} nice kid/s.')
# Setup opt = ["yes", "no"] directions = ["left", "right", "forward", "backward"] # Introduction name = input("What is your name, HaCKaToOnEr ?\n") print("Welcome to Toonslate island , " + name + " Let us go on a Minecraft quest!") print("You find yourself in front of a abandoned mineshaft.") print("Can you find your way to explore the shaft and find the treasure chest ?\n") # Start of game response = "" while response not in opt: response = input("Would you like to go inside the Mineshaft?\nyes/no\n") if response == "yes": print("You head into the Mineshaft. You hear grumbling sound of zombies,hissing sound of spidersand rattling of skeletons.\n") elif response == "no": print("You are not ready for this quest. Goodbye, " + name + ".") quit() else: print("I didn't understand that.\n") # Next part of game response = "" while response not in directions: print("To your left, you see a skeleton with a golden armor and a bow .") print("To your right, there is a way to go more inside the shaft.") print("There is a cobble stone wall directly in front of you.") print("Behind you is the mineshaft exit.\n") response = input("What direction would you like to move?\nleft/right/forward/backward\n") if response == "left": print(name+" was shot by an arrow. Farewell :( ") quit() elif response == "right": print("You head deeper into the mineshaft and find the treasure chest ,Kudos!!!.\n") elif response == "forward": print("You broke the stone walls and find out it was a spider spawner, spiders slain you to deeath\n") response = "" elif response == "backward": print("You leave the mineshaft un explored . Goodbye, " + name + ".") quit() else: print("I didn't understand that.\n")
opt = ['yes', 'no'] directions = ['left', 'right', 'forward', 'backward'] name = input('What is your name, HaCKaToOnEr ?\n') print('Welcome to Toonslate island , ' + name + ' Let us go on a Minecraft quest!') print('You find yourself in front of a abandoned mineshaft.') print('Can you find your way to explore the shaft and find the treasure chest ?\n') response = '' while response not in opt: response = input('Would you like to go inside the Mineshaft?\nyes/no\n') if response == 'yes': print('You head into the Mineshaft. You hear grumbling sound of zombies,hissing sound of spidersand rattling of skeletons.\n') elif response == 'no': print('You are not ready for this quest. Goodbye, ' + name + '.') quit() else: print("I didn't understand that.\n") response = '' while response not in directions: print('To your left, you see a skeleton with a golden armor and a bow .') print('To your right, there is a way to go more inside the shaft.') print('There is a cobble stone wall directly in front of you.') print('Behind you is the mineshaft exit.\n') response = input('What direction would you like to move?\nleft/right/forward/backward\n') if response == 'left': print(name + ' was shot by an arrow. Farewell :( ') quit() elif response == 'right': print('You head deeper into the mineshaft and find the treasure chest ,Kudos!!!.\n') elif response == 'forward': print('You broke the stone walls and find out it was a spider spawner, spiders slain you to deeath\n') response = '' elif response == 'backward': print('You leave the mineshaft un explored . Goodbye, ' + name + '.') quit() else: print("I didn't understand that.\n")
#Julian Conneely, 21/03/18 #WhileIF loop with increment #first 5 is printed #then it is decreased to 4 #as it is not satisfying i<=2 #it moves on #then 4 is printed #then it is decreased to 3 #as it is not satisfying i<=2,it moves on #then 3 is printed #then it is decreased to 2 #as now i<=2 has completely satisfied, the loop breaks i = 5 while True: print(i) i=i-1 if i<=2: break
i = 5 while True: print(i) i = i - 1 if i <= 2: break
MIN_CONF = 0.3 NMS_THRESH = 0.3 USE_GPU = False MIN_DISTANCE = 50 WEIGHT_PATH = "yolov3-tiny.weights" CONFIG_PATH = "yolov3-tiny.cfg"
min_conf = 0.3 nms_thresh = 0.3 use_gpu = False min_distance = 50 weight_path = 'yolov3-tiny.weights' config_path = 'yolov3-tiny.cfg'
def f(x, y): """ Args: x (Foo y (Bar : description """
def f(x, y): """ Args: x (Foo y (Bar : description """
class Solution: def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ k = 0 for n in nums: k ^= n return k
class Solution: def single_number(self, nums): """ :type nums: List[int] :rtype: int """ k = 0 for n in nums: k ^= n return k
expected_output = { "address_family":{ "ipv4":{ "bfd_sessions_down":0, "bfd_sessions_inactive":1, "bfd_sessions_up":0, "intf_down":1, "intf_up":1, "num_bfd_sessions":1, "num_intf":2, "state":{ "all":{ "sessions":2, "slaves":0, "total":2 }, "backup":{ "sessions":1, "slaves":0, "total":1 }, "init":{ "sessions":1, "slaves":0, "total":1 }, "master":{ "sessions":0, "slaves":0, "total":0 }, "master(owner)":{ "sessions":0, "slaves":0, "total":0 } }, "virtual_addresses_active":0, "virtual_addresses_inactive":2, "vritual_addresses_total":2 }, "ipv6":{ "bfd_sessions_down":0, "bfd_sessions_inactive":0, "bfd_sessions_up":0, "intf_down":0, "intf_up":1, "num_bfd_sessions":0, "num_intf":1, "state":{ "all":{ "sessions":1, "slaves":0, "total":1 }, "backup":{ "sessions":0, "slaves":0, "total":0 }, "init":{ "sessions":0, "slaves":0, "total":0 }, "master":{ "sessions":1, "slaves":0, "total":1 }, "master(owner)":{ "sessions":0, "slaves":0, "total":0 } }, "virtual_addresses_active":1, "virtual_addresses_inactive":0, "vritual_addresses_total":1 }, "num_tracked_objects":2, "tracked_objects_down":2, "tracked_objects_up":0 } }
expected_output = {'address_family': {'ipv4': {'bfd_sessions_down': 0, 'bfd_sessions_inactive': 1, 'bfd_sessions_up': 0, 'intf_down': 1, 'intf_up': 1, 'num_bfd_sessions': 1, 'num_intf': 2, 'state': {'all': {'sessions': 2, 'slaves': 0, 'total': 2}, 'backup': {'sessions': 1, 'slaves': 0, 'total': 1}, 'init': {'sessions': 1, 'slaves': 0, 'total': 1}, 'master': {'sessions': 0, 'slaves': 0, 'total': 0}, 'master(owner)': {'sessions': 0, 'slaves': 0, 'total': 0}}, 'virtual_addresses_active': 0, 'virtual_addresses_inactive': 2, 'vritual_addresses_total': 2}, 'ipv6': {'bfd_sessions_down': 0, 'bfd_sessions_inactive': 0, 'bfd_sessions_up': 0, 'intf_down': 0, 'intf_up': 1, 'num_bfd_sessions': 0, 'num_intf': 1, 'state': {'all': {'sessions': 1, 'slaves': 0, 'total': 1}, 'backup': {'sessions': 0, 'slaves': 0, 'total': 0}, 'init': {'sessions': 0, 'slaves': 0, 'total': 0}, 'master': {'sessions': 1, 'slaves': 0, 'total': 1}, 'master(owner)': {'sessions': 0, 'slaves': 0, 'total': 0}}, 'virtual_addresses_active': 1, 'virtual_addresses_inactive': 0, 'vritual_addresses_total': 1}, 'num_tracked_objects': 2, 'tracked_objects_down': 2, 'tracked_objects_up': 0}}
class Stack(): def __init__(self): self.items=[] def isEmpty(self): return self.items==[] def push(self,item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[-1] def size(self): return len(self.items) s=Stack() s.isEmpty() s.push(5) s.push(56) s.push('sdfg') s.push(9) print(s.peek()) print(s.pop()) print(s.peek()) print(s.size())
class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[-1] def size(self): return len(self.items) s = stack() s.isEmpty() s.push(5) s.push(56) s.push('sdfg') s.push(9) print(s.peek()) print(s.pop()) print(s.peek()) print(s.size())
hola = True adiosguillermomurielsanchezlafuente = True if (adiosguillermomurielsanchezlafuente and hola): print("ok con nombre muy largo")
hola = True adiosguillermomurielsanchezlafuente = True if adiosguillermomurielsanchezlafuente and hola: print('ok con nombre muy largo')
for i in range(1, int(input()) + 1): quadrado = i ** 2 cubo = i ** 3 print(f'{i} {quadrado} {cubo}') print(f'{i} {quadrado + 1} {cubo + 1}')
for i in range(1, int(input()) + 1): quadrado = i ** 2 cubo = i ** 3 print(f'{i} {quadrado} {cubo}') print(f'{i} {quadrado + 1} {cubo + 1}')
Scale.default = Scale.chromatic Root.default = 0 Clock.bpm = 120 var.ch = var(P[1,5,0,3],8) ~p1 >> play('m', amp=.8, dur=PDur(3,8), rate=[1,(1,2)]) ~p2 >> play('-', amp=.5, dur=2, hpf=2000, hpr=linvar([.1,1],16), sample=1).often('stutter', 4, dur=3).every(8, 'sample.offadd', 1) ~p3 >> play('{ ppP[pP][Pp]}', amp=.8, dur=.5, sample=PRand(7), rate=PRand([.5,1,2])) ~p4 >> play('V', amp=.8, dur=1) ~p5 >> play('#', amp=1.2, dur=16, drive=.1, chop=128, formant=1) ~s1 >> glass(var.ch+(0,5,12), amp=1, dur=8, coarse=8) ~s2 >> piano(var.ch+(0,[5,5,3,7],12), amp=1, dur=8, delay=(0,.25,.5)) Group(p1, p2, p3).stop() p4.lpf = linvar([4000,10],[32,0]) p4.stop() s2.stop() ~s3 >> saw(var.ch+PWalk(), amp=PRand([0,.8])[:24], dur=PDur(3,8), scale=Scale.minor, oct=PRand([4,5,6])[:32], drive=.05, room=1, mix=.5).spread() ~s3 >> saw(var.ch+PWalk(), amp=PRand([0,.8])[:20], dur=PDur(5,8), scale=Scale.minor, oct=PRand([4,5,6])[:32], drive=.05, room=1, mix=.5).spread() ~s3 >> saw(var.ch+PWalk(), amp=PRand([0,.8])[:64], dur=.25, scale=Scale.minor, oct=PRand([4,5,6])[:32], drive=.05, room=1, mix=.5).spread() ~p4 >> play('V', amp=.5, dur=1, room=1, lpf=1200).every(7, 'stutter', cycle=16) ~p6 >> play('n', amp=.5, dur=1, delay=.5, room=1, hpf=linvar([2000,4000],16), hpr=.1) s1.oct = 4 s1.formant = 1 ~p3 >> play('{ ppP[pP][Pp]}', amp=.5, dur=.5, sample=PRand(7), rate=PRand([.5,1,2]), room=1, mix=.25) Group(p6, s3).stop() ~s2 >> piano(var.ch+([12,0],[5,5,3,7],[0,12]), amp=1, dur=8, delay=(0,.25,.5), room=1, mix=.5, drive=.05, chop=32, echo=[1,2,1,4]) Group(p3, s1).stop() Clock.clear()
Scale.default = Scale.chromatic Root.default = 0 Clock.bpm = 120 var.ch = var(P[1, 5, 0, 3], 8) ~p1 >> play('m', amp=0.8, dur=p_dur(3, 8), rate=[1, (1, 2)]) ~p2 >> play('-', amp=0.5, dur=2, hpf=2000, hpr=linvar([0.1, 1], 16), sample=1).often('stutter', 4, dur=3).every(8, 'sample.offadd', 1) ~p3 >> play('{ ppP[pP][Pp]}', amp=0.8, dur=0.5, sample=p_rand(7), rate=p_rand([0.5, 1, 2])) ~p4 >> play('V', amp=0.8, dur=1) ~p5 >> play('#', amp=1.2, dur=16, drive=0.1, chop=128, formant=1) ~s1 >> glass(var.ch + (0, 5, 12), amp=1, dur=8, coarse=8) ~s2 >> piano(var.ch + (0, [5, 5, 3, 7], 12), amp=1, dur=8, delay=(0, 0.25, 0.5)) group(p1, p2, p3).stop() p4.lpf = linvar([4000, 10], [32, 0]) p4.stop() s2.stop() ~s3 >> saw(var.ch + p_walk(), amp=p_rand([0, 0.8])[:24], dur=p_dur(3, 8), scale=Scale.minor, oct=p_rand([4, 5, 6])[:32], drive=0.05, room=1, mix=0.5).spread() ~s3 >> saw(var.ch + p_walk(), amp=p_rand([0, 0.8])[:20], dur=p_dur(5, 8), scale=Scale.minor, oct=p_rand([4, 5, 6])[:32], drive=0.05, room=1, mix=0.5).spread() ~s3 >> saw(var.ch + p_walk(), amp=p_rand([0, 0.8])[:64], dur=0.25, scale=Scale.minor, oct=p_rand([4, 5, 6])[:32], drive=0.05, room=1, mix=0.5).spread() ~p4 >> play('V', amp=0.5, dur=1, room=1, lpf=1200).every(7, 'stutter', cycle=16) ~p6 >> play('n', amp=0.5, dur=1, delay=0.5, room=1, hpf=linvar([2000, 4000], 16), hpr=0.1) s1.oct = 4 s1.formant = 1 ~p3 >> play('{ ppP[pP][Pp]}', amp=0.5, dur=0.5, sample=p_rand(7), rate=p_rand([0.5, 1, 2]), room=1, mix=0.25) group(p6, s3).stop() ~s2 >> piano(var.ch + ([12, 0], [5, 5, 3, 7], [0, 12]), amp=1, dur=8, delay=(0, 0.25, 0.5), room=1, mix=0.5, drive=0.05, chop=32, echo=[1, 2, 1, 4]) group(p3, s1).stop() Clock.clear()
def namedArgumentFunction(a, b, c): print("the values are a: {}, b: {}, c: {}".format(a,b,c)) namedArgumentFunction(100, 200, 300) # positional arguments namedArgumentFunction(c=3, a=1, b=2) # named arguments #namedArgumentFunction(181, a=102, b=103) # mix of position + name error namedArgumentFunction(101, b=102, c=103) # mix of position + no error
def named_argument_function(a, b, c): print('the values are a: {}, b: {}, c: {}'.format(a, b, c)) named_argument_function(100, 200, 300) named_argument_function(c=3, a=1, b=2) named_argument_function(101, b=102, c=103)
# Basic String Operations (Title) # Reading # Iterating over a String with the 'for' Loop (section) # General Format: # for variable in string: # statement # statement # etc. name = 'Juliet' for ch in name: print(ch) # This program counts the number of times the letter T # (uppercase or lowercase) appears in a string. # (with 'for' loop) def main(): count = 0 my_string = input('Enter a sentence: ') for ch in my_string: if ch == 'T' or ch == 't': count += 1 print(f'The letter T appears {count} times.') if __name__ == '__main__': main() # Indexing (section) my_string = 'Roses are red' ch = my_string[6] my_string = 'Roses are red' print(my_string[0], my_string[6], my_string[10]) # negative numbers my_string = 'Roses are red' print(my_string[-1], my_string[-2], my_string[-13]) # IndexError Exceptions (section) # Occur if index out of range for a particular string city = 'Boston' print(city[6]) city = 'Boston' index = 0 while index < 7: print(city[index]) index += 1 # The 'len' Function (section) # useful to prevent loops from iterating beyond the end # of a string. city = 'Boston' size = len(city) print(size) city = 'Boston' index = 0 while index < len(city): print(city[index]) index += 1 # String Concatenation (section) name = 'Kelly' name += ' ' name += 'Yvonne' name += ' ' name += 'Smith' print(name) # Strings are immutable (section) # This program concatenates strings. def main(): name = 'Carmen' print(f'The name is: {name}') name = name + ' Brown' print(f'Now the name is: {name}') if __name__ == '__main__': main() # no string[index] on left side of an assignment operator # Error below friend = 'Bill' friend[0] = 'J' # End # Checkpoint # 8.1 Assume the variable 'name' references a string. Write a # 'for' loop that prints each character in the string. name = 'name' for letter in name: print(letter) # 8.2 What is the index of the first character in a string? # A. 0 # 8.3 If a string has 10 characters, what is the index of the # last character? # A. 9 # 8.4 What happeneds if you try to use an invalid index to # access a character in a string? # A. An IndexError exception will occur if you try to use an # index that is out of range for a particular string. # 8.5 How do you find the length of a string? # A. Use the built-in len function. # 8.6 What is wrong with the following code? animal = 'Tiger' animal [0] = 'L' # A. The second statement attempts to assign a value to an # individual character in the string. Strings are immutable, # however, so the expression animal [0] cannot appear on the # left side of an assignment operator. # End
name = 'Juliet' for ch in name: print(ch) def main(): count = 0 my_string = input('Enter a sentence: ') for ch in my_string: if ch == 'T' or ch == 't': count += 1 print(f'The letter T appears {count} times.') if __name__ == '__main__': main() my_string = 'Roses are red' ch = my_string[6] my_string = 'Roses are red' print(my_string[0], my_string[6], my_string[10]) my_string = 'Roses are red' print(my_string[-1], my_string[-2], my_string[-13]) city = 'Boston' print(city[6]) city = 'Boston' index = 0 while index < 7: print(city[index]) index += 1 city = 'Boston' size = len(city) print(size) city = 'Boston' index = 0 while index < len(city): print(city[index]) index += 1 name = 'Kelly' name += ' ' name += 'Yvonne' name += ' ' name += 'Smith' print(name) def main(): name = 'Carmen' print(f'The name is: {name}') name = name + ' Brown' print(f'Now the name is: {name}') if __name__ == '__main__': main() friend = 'Bill' friend[0] = 'J' name = 'name' for letter in name: print(letter) animal = 'Tiger' animal[0] = 'L'
height = int(input()) apartments = int(input()) is_first = True isit = 0 for f in range(height, 0, -1): for s in range(0, apartments, 1): if is_first == True: isit += 1 print(f"L{f}{s}", end=" ") if isit == apartments: is_first = False continue if is_first == False: if f % 2 == 0: print(f"O{f}{s}", end=" ") else: print(f"A{f}{s}", end=" ") print(end="\n")
height = int(input()) apartments = int(input()) is_first = True isit = 0 for f in range(height, 0, -1): for s in range(0, apartments, 1): if is_first == True: isit += 1 print(f'L{f}{s}', end=' ') if isit == apartments: is_first = False continue if is_first == False: if f % 2 == 0: print(f'O{f}{s}', end=' ') else: print(f'A{f}{s}', end=' ') print(end='\n')
#!/usr/bin/python3 # https://practice.geeksforgeeks.org/problems/twice-counter/0 def sol(words): h = {} res = 0 for word in words: h[word] = h[word] + 1 if word in h else 1 for word in h: if h[word] == 2: res+=1 return res
def sol(words): h = {} res = 0 for word in words: h[word] = h[word] + 1 if word in h else 1 for word in h: if h[word] == 2: res += 1 return res
class Solution: # Reverse Format String (Accepted), O(1) time and space def reverseBits(self, n: int) -> int: s = '{:032b}'.format(n)[::-1] return int(s, 2) # Bit Manipulation (Top Voted), O(1) time and space def reverseBits(self, n: int) -> int: ans = 0 for i in range(32): ans = (ans << 1) + (n & 1) n >>= 1 return ans
class Solution: def reverse_bits(self, n: int) -> int: s = '{:032b}'.format(n)[::-1] return int(s, 2) def reverse_bits(self, n: int) -> int: ans = 0 for i in range(32): ans = (ans << 1) + (n & 1) n >>= 1 return ans
def count_frequency(a): freq = dict() for items in a: freq[items] = a.count(items) return freq def solution(data, n): frequency = count_frequency(data) for key, value in frequency.items(): if value > n: data = list(filter(lambda a: a != key, data)) return data print(solution([1, 2, 3], 0)) print(solution([5, 10, 15, 10, 7], 1)) print(solution([1, 2, 2, 3, 3, 3, 4, 5, 5], 1))
def count_frequency(a): freq = dict() for items in a: freq[items] = a.count(items) return freq def solution(data, n): frequency = count_frequency(data) for (key, value) in frequency.items(): if value > n: data = list(filter(lambda a: a != key, data)) return data print(solution([1, 2, 3], 0)) print(solution([5, 10, 15, 10, 7], 1)) print(solution([1, 2, 2, 3, 3, 3, 4, 5, 5], 1))
# Copyright 2020 Google LLC. # # 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. # [START root_tag] # [START nested_tag] def nested_method(): return 'nested' # [END nested_tag] def root_method(): return 'root' # [END root_tag] # [START root_tag] def another_root_method(): return 'another root' # [END root_tag]
def nested_method(): return 'nested' def root_method(): return 'root' def another_root_method(): return 'another root'
inventory = {'croissant': 19, 'bagel': 4, 'muffin': 8, 'cake': 1} print(f'{inventory =}') stock_list = inventory.copy() print(f'{stock_list =}') stock_list['hot cheetos'] = 25 stock_list.update({'cookie' : 18}) stock_list.pop('cake') print(f'{stock_list =}')
inventory = {'croissant': 19, 'bagel': 4, 'muffin': 8, 'cake': 1} print(f'inventory ={inventory!r}') stock_list = inventory.copy() print(f'stock_list ={stock_list!r}') stock_list['hot cheetos'] = 25 stock_list.update({'cookie': 18}) stock_list.pop('cake') print(f'stock_list ={stock_list!r}')
#Program to change a given string to a new string where the first and last chars have been exchanged. string=str(input("Enter a string :")) first=string[0] #store first index element of string in variable last=string[-1] #store last index element of string in variable new=last+string[1:-1]+first #concatenate last the middle part and first part print(new)
string = str(input('Enter a string :')) first = string[0] last = string[-1] new = last + string[1:-1] + first print(new)
""" Class hierarchy for company management """ class Company: def __init__(self, company_name, location): self.company_name = company_name self.location = location def __str__(self): return f"Company: {self.company_name}, {self.location}" def __repr(self): return f"Company: {self.company_name}, {self.location}" class Management(Company): def __init__(self, company_name, location, employee, position, management_type, **kwargs): self.management_type = management_type self.employee = employee self.position = position super().__init__(company_name, location) def __str__(self): return f"{self.employee}: {self.position} in {self.management_type} management at {self.company_name}" def __repr__(self): return f"{self.employee}: {self.position} in {self.management_type} management at {self.company_name}" def type(self): return f"{self.management_type}" def position(self): return f"{self.position}" class TopLevelManagement(Management): def __init__(self, company_name, location, employee, position, **kwargs): super().__init__(company_name, location, employee, position, management_type='Top level', **kwargs) @classmethod def chairman(cls) -> 'TopLevelManagement': return cls('Xamarin Ltd', 'John Doe', 'Chairman', 'United States') @classmethod def vice_president(cls) -> 'TopLevelManagement': return cls('Xamarin Ltd', 'Jane Doe', 'Vice President', 'United States') @classmethod def ceo(cls) -> 'TopLevelManagement': return cls('Xamarin Ltd', 'Jeanne Donne', 'CEO', 'United States') class MiddleManagement(Management): def __init__(self, company_name, location, employee, position, **kwargs): super().__init__(company_name, location, employee, position, management_type='Middle', **kwargs) @classmethod def general_manager(cls) -> 'MiddleManagement': return cls('Xamarin Ltd', 'Aran Diego', 'General Manager', 'United States') @classmethod def regional_manager(cls) -> 'MiddleManagement': return cls('Xamarin Ltd', 'Antuan Doe', 'General Manager', 'United States') class FirstLineManagement(Management): def __init__(self, company_name, location, employee, position, **kwargs): super().__init__(company_name, location, employee, position, management_type='First line', **kwargs) @classmethod def supervisor(cls) -> 'FirstLineManagement': return cls('Xamarin Ltd', 'Sam Pauline', 'Supervisor', 'United States') @classmethod def office_manager(cls) -> 'FirstLineManagement': return cls('Xamarin Ltd', 'Sarah Jones', 'Office Manager', 'United States') @classmethod def team_leader(cls) -> 'FirstLineManagement': return cls('Xamarin Ltd', 'Amy Joe', 'Team Leader', 'United States') def main(): company = Company('Xamarin Ltd', 'United States') print(company) chairman = TopLevelManagement.chairman() print(chairman) ceo = TopLevelManagement.ceo() print(ceo) general_manager = MiddleManagement.general_manager() print(general_manager) regional_manager = MiddleManagement.regional_manager() print(regional_manager) supervisor = FirstLineManagement.supervisor() print(supervisor) office_manager = FirstLineManagement.office_manager() print(office_manager) team_leader = FirstLineManagement.team_leader() print(team_leader) if __name__ == '__main__': main()
""" Class hierarchy for company management """ class Company: def __init__(self, company_name, location): self.company_name = company_name self.location = location def __str__(self): return f'Company: {self.company_name}, {self.location}' def __repr(self): return f'Company: {self.company_name}, {self.location}' class Management(Company): def __init__(self, company_name, location, employee, position, management_type, **kwargs): self.management_type = management_type self.employee = employee self.position = position super().__init__(company_name, location) def __str__(self): return f'{self.employee}: {self.position} in {self.management_type} management at {self.company_name}' def __repr__(self): return f'{self.employee}: {self.position} in {self.management_type} management at {self.company_name}' def type(self): return f'{self.management_type}' def position(self): return f'{self.position}' class Toplevelmanagement(Management): def __init__(self, company_name, location, employee, position, **kwargs): super().__init__(company_name, location, employee, position, management_type='Top level', **kwargs) @classmethod def chairman(cls) -> 'TopLevelManagement': return cls('Xamarin Ltd', 'John Doe', 'Chairman', 'United States') @classmethod def vice_president(cls) -> 'TopLevelManagement': return cls('Xamarin Ltd', 'Jane Doe', 'Vice President', 'United States') @classmethod def ceo(cls) -> 'TopLevelManagement': return cls('Xamarin Ltd', 'Jeanne Donne', 'CEO', 'United States') class Middlemanagement(Management): def __init__(self, company_name, location, employee, position, **kwargs): super().__init__(company_name, location, employee, position, management_type='Middle', **kwargs) @classmethod def general_manager(cls) -> 'MiddleManagement': return cls('Xamarin Ltd', 'Aran Diego', 'General Manager', 'United States') @classmethod def regional_manager(cls) -> 'MiddleManagement': return cls('Xamarin Ltd', 'Antuan Doe', 'General Manager', 'United States') class Firstlinemanagement(Management): def __init__(self, company_name, location, employee, position, **kwargs): super().__init__(company_name, location, employee, position, management_type='First line', **kwargs) @classmethod def supervisor(cls) -> 'FirstLineManagement': return cls('Xamarin Ltd', 'Sam Pauline', 'Supervisor', 'United States') @classmethod def office_manager(cls) -> 'FirstLineManagement': return cls('Xamarin Ltd', 'Sarah Jones', 'Office Manager', 'United States') @classmethod def team_leader(cls) -> 'FirstLineManagement': return cls('Xamarin Ltd', 'Amy Joe', 'Team Leader', 'United States') def main(): company = company('Xamarin Ltd', 'United States') print(company) chairman = TopLevelManagement.chairman() print(chairman) ceo = TopLevelManagement.ceo() print(ceo) general_manager = MiddleManagement.general_manager() print(general_manager) regional_manager = MiddleManagement.regional_manager() print(regional_manager) supervisor = FirstLineManagement.supervisor() print(supervisor) office_manager = FirstLineManagement.office_manager() print(office_manager) team_leader = FirstLineManagement.team_leader() print(team_leader) if __name__ == '__main__': main()
# Make sure to rename this file as "config.py" before running the bot. verbose=True api_token='0000000000:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' # Enter the user ID and a readable name for each user in your group. # TODO make balaguer automatically collect user IDs. # But that's only useful if the bot actually gathers widespread usage. all_users={ 000000000: 'Readable Name', 000000000: 'Readable Name', 000000000: 'Readable Name', 000000000: 'Readable Name', } # A list containing the user IDs of who can access the admin features of the bot. admins = [000000000, 000000000, 000000000, 000000000] # A list of the groups where the bot is allowed to operate (usually the main group and an admin test group) approved_groups = [-000000000, -000000000]
verbose = True api_token = '0000000000:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' all_users = {0: 'Readable Name', 0: 'Readable Name', 0: 'Readable Name', 0: 'Readable Name'} admins = [0, 0, 0, 0] approved_groups = [-0, -0]
class GameException(Exception): pass class GameFlowException(GameException): pass class EndProgram(GameFlowException): pass class InvalidPlayException(GameException): pass
class Gameexception(Exception): pass class Gameflowexception(GameException): pass class Endprogram(GameFlowException): pass class Invalidplayexception(GameException): pass
# Copyright 2018 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. """Partial response utilities for an Endpoints v1 over webapp2 service. Grammar of a fields partial response string: fields: selector [,selector]* selector: path [(fields)]? path: name [/name]* name: [A-Za-z_][A-Za-z0-9_]* | \* Examples: fields=a Response includes the value of the "a" field. fields=a,b Response includes the values of the "a" and "b" fields. fields=a/b Response includes the value of the "b" field of "a". If "a" is an array, response includes the values of the "b" fields of every element in the array. fields=a/*/c For every element or field of "a", response includes the value of that element or field's "c" field. fields=a(b,c) Equivalent to fields=a/b union fields=a/c. """ class ParsingError(Exception): """Indicates an error during parsing. Fields: index: The index the error occurred at. message: The error message. """ def __init__(self, index, message): super(ParsingError, self).__init__('%d: %s' % (index, message)) self.index = index self.message = message def _merge(source, destination): """Recursively merges the source dict into the destination dict. Args: source: A dict whose values are source dicts. destination: A dict whose values are destination dicts. """ for key, value in source.iteritems(): if destination.get(key): _merge(value, destination[key]) else: destination[key] = value class _ParsingContext(object): """Encapsulates parsing information. Attributes: accumulator: A list of field name characters accumulated so far. expecting_name: Whether or not a field name is expected. fields: A dict of accumulated fields. """ def __init__(self): """Initializes a new instance of ParsingContext.""" # Pointer to the subfield dict of the last added field. self._last = None self.accumulator = [] self.expecting_name = True self.fields = {} def accumulate(self, char): """Accumulates the given char. Args: char: The character to accumulate. """ # Accumulate all characters even if they aren't allowed by the grammar. # In the worst case there will be extra keys in the fields dict which will # be ignored when the mask is applied because they don't match any legal # field name. It won't cause incorrect masks to be applied. The exception is # / which has special meaning. See add_field below. Note that * has special # meaning while applying the mask but not while parsing. See _apply below. self.accumulator.append(char) def add_field(self, i): """Records the field name in the accumulator then clears the accumulator. Args: i: The index the parser is at. """ # Reset the index to the start of the accumulated string. i -= len(self.accumulator) path = ''.join(self.accumulator).strip() if not path: raise ParsingError(i, 'expected name') # Advance i to the first non-space char. for char in self.accumulator: if char != ' ': break i += 1 # / has special meaning; a/b/c is shorthand for a(b(c)). Add subfield dicts # recursively. E.g. if the fields dict is empty then parsing a/b/c is like # setting fields["a"] = {"b": {"c": {}} and pointing last to c's value. pointer = self.fields for part in path.split('/'): if not part: raise ParsingError(i, 'empty name in path') pointer = pointer.setdefault(part, {}) # Increment the index by the length of this part as well as the /. i += len(part) + 1 self._last = pointer self.accumulator = [] def add_subfields(self, subfields): """Adds the given subfields to the last added field. Args: subfields: A dict of accumulated subfields. Returns: False if there was no last added field to add subfields to, else True. """ if self._last is None: return False _merge(subfields, self._last) return True def _parse(fields): """Parses the given partial response string into a partial response mask. Args: fields: A fields partial response string. Returns: A dict which can be used to mask another dict. Raises: ParsingError: If fields wasn't a valid partial response string. """ stack = [_ParsingContext()] i = 0 while i < len(fields): # Invariants maintained below. # Stack invariant: The stack always has at least one context. assert stack, fields # Accumulator invariant: Non-empty accumulator implies expecting a name. assert not stack[-1].accumulator or stack[-1].expecting_name, fields if fields[i] == ',': # If we just returned from a lower context, no name is expected. if stack[-1].expecting_name: stack[-1].add_field(i) stack[-1].expecting_name = True elif fields[i] == '(': # Maintain accumulator invariant. # A name must occur before any (. stack[-1].add_field(i) stack[-1].expecting_name = False # Enter a new context. When we return from this context we don't expect to # accumulate another name. There must be , or a return to a higher context # (or the end of the string altogether). stack.append(_ParsingContext()) elif fields[i] == ')': # If we just returned from a lower context, no name is expected. if stack[-1].expecting_name: stack[-1].add_field(i) # Return to a higher context. Maintain stack invariant. subfields = stack.pop().fields if not stack: # Mismatched (). raise ParsingError(i, 'unexpected )') # See accumulator invariant maintenance above. assert not stack[-1].expecting_name, fields if not stack[-1].add_subfields(subfields): # ) before any field. raise ParsingError(i, 'unexpected (') else: # If we just returned from a lower context, no name is expected. if not stack[-1].expecting_name: raise ParsingError(i, 'unexpected name') stack[-1].accumulate(fields[i]) i += 1 if len(stack) != 1: # Mismatched (). raise ParsingError(i, 'expected )') # If we just returned from a lower context, no name is expected. if stack[-1].expecting_name: stack[-1].add_field(i) return stack[0].fields def _apply(response, partial): """Applies the given partial response dict to the given response. Args: response: A dict to be updated in place. partial: A partial response dict as returned by _parse. May be modified, but will not have its masking behavior changed. Returns: The masked response. """ for key, value in response.items(): pointer = None if key in partial: if partial[key]: # If the subfield dict is non-empty, include all of *'s subfields. _merge(partial.get('*', {}), partial[key]) pointer = partial[key] elif '*' in partial: pointer = partial['*'] if pointer is None: response.pop(key) elif pointer: if isinstance(value, dict) and value: _apply(value, pointer) if not value: # No subfields were kept, remove this field. response.pop(key) elif isinstance(value, list) and value: new_values = [] for v in value: # In a dict constructed from a protorpc.message.Message list elements # always have the same type. Here we allow list elements to have mixed # types and only recursively apply the mask to dicts. if isinstance(v, dict): _apply(v, pointer) if v: # Subfields were kept, include this element. new_values.append(v) else: # Non-dict, include this element. new_values.append(v) response[key] = new_values if not new_values: # No elements were kept, remove this field. response.pop(key) return response def mask(response, fields): """Applies the given fields partial response string to the given response. Args: response: A dict encoded using protorpc.protojson.ProtoJson.encode_message to be updated in place. fields: A fields partial response string. Returns: The masked response. Raises: ParsingError: If fields wasn't a valid partial response string. """ return _apply(response, _parse(fields))
"""Partial response utilities for an Endpoints v1 over webapp2 service. Grammar of a fields partial response string: fields: selector [,selector]* selector: path [(fields)]? path: name [/name]* name: [A-Za-z_][A-Za-z0-9_]* | \\* Examples: fields=a Response includes the value of the "a" field. fields=a,b Response includes the values of the "a" and "b" fields. fields=a/b Response includes the value of the "b" field of "a". If "a" is an array, response includes the values of the "b" fields of every element in the array. fields=a/*/c For every element or field of "a", response includes the value of that element or field's "c" field. fields=a(b,c) Equivalent to fields=a/b union fields=a/c. """ class Parsingerror(Exception): """Indicates an error during parsing. Fields: index: The index the error occurred at. message: The error message. """ def __init__(self, index, message): super(ParsingError, self).__init__('%d: %s' % (index, message)) self.index = index self.message = message def _merge(source, destination): """Recursively merges the source dict into the destination dict. Args: source: A dict whose values are source dicts. destination: A dict whose values are destination dicts. """ for (key, value) in source.iteritems(): if destination.get(key): _merge(value, destination[key]) else: destination[key] = value class _Parsingcontext(object): """Encapsulates parsing information. Attributes: accumulator: A list of field name characters accumulated so far. expecting_name: Whether or not a field name is expected. fields: A dict of accumulated fields. """ def __init__(self): """Initializes a new instance of ParsingContext.""" self._last = None self.accumulator = [] self.expecting_name = True self.fields = {} def accumulate(self, char): """Accumulates the given char. Args: char: The character to accumulate. """ self.accumulator.append(char) def add_field(self, i): """Records the field name in the accumulator then clears the accumulator. Args: i: The index the parser is at. """ i -= len(self.accumulator) path = ''.join(self.accumulator).strip() if not path: raise parsing_error(i, 'expected name') for char in self.accumulator: if char != ' ': break i += 1 pointer = self.fields for part in path.split('/'): if not part: raise parsing_error(i, 'empty name in path') pointer = pointer.setdefault(part, {}) i += len(part) + 1 self._last = pointer self.accumulator = [] def add_subfields(self, subfields): """Adds the given subfields to the last added field. Args: subfields: A dict of accumulated subfields. Returns: False if there was no last added field to add subfields to, else True. """ if self._last is None: return False _merge(subfields, self._last) return True def _parse(fields): """Parses the given partial response string into a partial response mask. Args: fields: A fields partial response string. Returns: A dict which can be used to mask another dict. Raises: ParsingError: If fields wasn't a valid partial response string. """ stack = [__parsing_context()] i = 0 while i < len(fields): assert stack, fields assert not stack[-1].accumulator or stack[-1].expecting_name, fields if fields[i] == ',': if stack[-1].expecting_name: stack[-1].add_field(i) stack[-1].expecting_name = True elif fields[i] == '(': stack[-1].add_field(i) stack[-1].expecting_name = False stack.append(__parsing_context()) elif fields[i] == ')': if stack[-1].expecting_name: stack[-1].add_field(i) subfields = stack.pop().fields if not stack: raise parsing_error(i, 'unexpected )') assert not stack[-1].expecting_name, fields if not stack[-1].add_subfields(subfields): raise parsing_error(i, 'unexpected (') else: if not stack[-1].expecting_name: raise parsing_error(i, 'unexpected name') stack[-1].accumulate(fields[i]) i += 1 if len(stack) != 1: raise parsing_error(i, 'expected )') if stack[-1].expecting_name: stack[-1].add_field(i) return stack[0].fields def _apply(response, partial): """Applies the given partial response dict to the given response. Args: response: A dict to be updated in place. partial: A partial response dict as returned by _parse. May be modified, but will not have its masking behavior changed. Returns: The masked response. """ for (key, value) in response.items(): pointer = None if key in partial: if partial[key]: _merge(partial.get('*', {}), partial[key]) pointer = partial[key] elif '*' in partial: pointer = partial['*'] if pointer is None: response.pop(key) elif pointer: if isinstance(value, dict) and value: _apply(value, pointer) if not value: response.pop(key) elif isinstance(value, list) and value: new_values = [] for v in value: if isinstance(v, dict): _apply(v, pointer) if v: new_values.append(v) else: new_values.append(v) response[key] = new_values if not new_values: response.pop(key) return response def mask(response, fields): """Applies the given fields partial response string to the given response. Args: response: A dict encoded using protorpc.protojson.ProtoJson.encode_message to be updated in place. fields: A fields partial response string. Returns: The masked response. Raises: ParsingError: If fields wasn't a valid partial response string. """ return _apply(response, _parse(fields))
def count_vowels(txt): vs = "a, e, i, o, u".split(', ') return sum([1 for t in txt if t in vs]) print(count_vowels('Hello world'))
def count_vowels(txt): vs = 'a, e, i, o, u'.split(', ') return sum([1 for t in txt if t in vs]) print(count_vowels('Hello world'))
class GroupTransform: """ GroupTransform """ def __init__(self): pass def getTransform(self): pass def getTransforms(self): pass def setTransforms(self, transforms): pass def size(self): pass def push_back(self, transform): pass def clear(self): pass def empty(self): pass
class Grouptransform: """ GroupTransform """ def __init__(self): pass def get_transform(self): pass def get_transforms(self): pass def set_transforms(self, transforms): pass def size(self): pass def push_back(self, transform): pass def clear(self): pass def empty(self): pass
class KarmaCard(object): info = {'type': ['number', 'wild'], 'trait': ['4', '5', '6', '7', '8', '9', 'J', 'Q', 'K', 'A', '2', '3', '10', 'draw'], 'order': ['4:4', '4:3', '4:2', '4:1', '5:4', '5:3', '5:2', '5:1', '6:4', '6:3', '6:2', '6:1', '7:4', '7:3', '7:2', '7:1', '8:4', '8:3', '8:2', '8:1', '9:4', '9:3', '9:2', '9:1', 'J:4', 'J:3', 'J:2', 'J:1', 'Q:4', 'Q:3', 'Q:2', 'Q:1', 'K:1', 'K:2', 'K:3', 'K:4', 'A:1', 'A:2', 'A:3', 'A:4', '2:1', '2:2', '2:3', '2:4', '3:1', '3:2', '3:3', '3:4', '10:1', '10:2', '10:3', '10:4', 'draw:1'], 'order_start': ['4:4', '4:3', '4:2', '4:1', '5:4', '5:3', '5:2', '5:1', '6:4', '6:3', '6:2', '6:1', '7:4', '7:3', '7:2', '7:1', '8:4', '8:3', '8:2', '8:1', '9:4', '9:3', '9:2', '9:1', 'J:1', 'J:2', 'J:3', 'J:4', 'Q:1', 'Q:2', 'Q:3', 'Q:4', 'K:1', 'K:2', 'K:3', 'K:4', 'A:1', 'A:2', 'A:3', 'A:4', '2:1', '2:2', '2:3', '2:4', '3:1', '3:2', '3:3', '3:4', '10:1', '10:2', '10:3', '10:4', 'draw:1'] } def __init__(self, card_type, trait): ''' Initialize the class of UnoCard Args: card_type (str): The type of card trait (str): The trait of card ''' self.type = card_type self.trait = trait self.str = self.get_str() def get_str(self): ''' Get the string representation of card Return: (str): The string of card's trait ''' return self.trait def get_index(self): ''' Get the index of trait Return: (int): The index of card's trait (value) ''' return self.info['trait'].index(self.trait) @staticmethod def print_cards(cards): ''' Print out card in a nice form Args: card (str or list): The string form or a list of a Karma card ''' if isinstance(cards, str): cards = [cards] for i, card in enumerate(cards): print(card, end='') if i < len(cards) - 1: print(', ', end='')
class Karmacard(object): info = {'type': ['number', 'wild'], 'trait': ['4', '5', '6', '7', '8', '9', 'J', 'Q', 'K', 'A', '2', '3', '10', 'draw'], 'order': ['4:4', '4:3', '4:2', '4:1', '5:4', '5:3', '5:2', '5:1', '6:4', '6:3', '6:2', '6:1', '7:4', '7:3', '7:2', '7:1', '8:4', '8:3', '8:2', '8:1', '9:4', '9:3', '9:2', '9:1', 'J:4', 'J:3', 'J:2', 'J:1', 'Q:4', 'Q:3', 'Q:2', 'Q:1', 'K:1', 'K:2', 'K:3', 'K:4', 'A:1', 'A:2', 'A:3', 'A:4', '2:1', '2:2', '2:3', '2:4', '3:1', '3:2', '3:3', '3:4', '10:1', '10:2', '10:3', '10:4', 'draw:1'], 'order_start': ['4:4', '4:3', '4:2', '4:1', '5:4', '5:3', '5:2', '5:1', '6:4', '6:3', '6:2', '6:1', '7:4', '7:3', '7:2', '7:1', '8:4', '8:3', '8:2', '8:1', '9:4', '9:3', '9:2', '9:1', 'J:1', 'J:2', 'J:3', 'J:4', 'Q:1', 'Q:2', 'Q:3', 'Q:4', 'K:1', 'K:2', 'K:3', 'K:4', 'A:1', 'A:2', 'A:3', 'A:4', '2:1', '2:2', '2:3', '2:4', '3:1', '3:2', '3:3', '3:4', '10:1', '10:2', '10:3', '10:4', 'draw:1']} def __init__(self, card_type, trait): """ Initialize the class of UnoCard Args: card_type (str): The type of card trait (str): The trait of card """ self.type = card_type self.trait = trait self.str = self.get_str() def get_str(self): """ Get the string representation of card Return: (str): The string of card's trait """ return self.trait def get_index(self): """ Get the index of trait Return: (int): The index of card's trait (value) """ return self.info['trait'].index(self.trait) @staticmethod def print_cards(cards): """ Print out card in a nice form Args: card (str or list): The string form or a list of a Karma card """ if isinstance(cards, str): cards = [cards] for (i, card) in enumerate(cards): print(card, end='') if i < len(cards) - 1: print(', ', end='')
#!/usr/bin/env python # pylint: disable=too-few-public-methods """Reusable string literals.""" class DockerAuthentication: """ https://github.com/docker/distribution/blob/master/docs/spec/auth/token.md https://github.com/docker/distribution/blob/master/docs/spec/auth/scope.md """ DOCKERHUB_URL_PATTERN = ( "{0}?service={1}&scope={2}&client_id=docker-registry-client-async" ) SCOPE_REGISTRY_CATALOG = "registry:catalog:*" SCOPE_REPOSITORY_PULL_PATTERN = "repository:{0}:pull" SCOPE_REPOSITORY_PUSH_PATTERN = "repository:{0}:push" SCOPE_REPOSITORY_ALL_PATTERN = "repository:{0}:pull,push" class DockerMediaTypes: """https://github.com/docker/distribution/blob/master/docs/spec/manifest-v2-2.md#manifest-list""" CONTAINER_IMAGE_V1 = "application/vnd.docker.container.image.v1+json" DISTRIBUTION_MANIFEST_LIST_V2 = ( "application/vnd.docker.distribution.manifest.list.v2+json" ) DISTRIBUTION_MANIFEST_V1 = "application/vnd.docker.distribution.manifest.v1+json" DISTRIBUTION_MANIFEST_V1_SIGNED = ( "application/vnd.docker.distribution.manifest.v1+prettyjws" ) DISTRIBUTION_MANIFEST_V2 = "application/vnd.docker.distribution.manifest.v2+json" IMAGE_ROOTFS_DIFF = "application/vnd.docker.image.rootfs.diff.tar.gzip" IMAGE_ROOTFS_FOREIGN_DIFF = ( "application/vnd.docker.image.rootfs.foreign.diff.tar.gzip" ) PLUGIN_V1 = "application/vnd.docker.plugin.v1+json" class Indices: """Common registry indices.""" DOCKERHUB = "index.docker.io" QUAY = "quay.io" class QuayAuthentication: """ https://docs.quay.io/api/ """ QUAY_URL_PATTERN = ( "{0}?service={1}&scope={2}&client_id=docker-registry-client-async" ) SCOPE_REPOSITORY_PULL_PATTERN = "repo:{0}:read" SCOPE_REPOSITORY_PUSH_PATTERN = "repo:{0}:write" SCOPE_REPOSITORY_ALL_PATTERN = "repo:{0}:read,write" class MediaTypes: """Generic mime types.""" APPLICATION_JSON = "application/json" APPLICATION_OCTET_STREAM = "application/octet-stream" APPLICATION_YAML = "application/yaml" class OCIMediaTypes: """https://github.com/opencontainers/image-spec/blob/master/media-types.md""" DESCRIPTOR_V1 = "application/vnd.oci.descriptor.v1+json" IMAGE_CONFIG_V1 = "application/vnd.oci.image.config.v1+json" IMAGE_INDEX_V1 = "application/vnd.oci.image.index.v1+json" IMAGE_LAYER_V1 = "application/vnd.oci.image.layer.v1.tar" IMAGE_LAYER_GZIP_V1 = "application/vnd.oci.image.layer.v1.tar+gzip" IMAGE_LAYER_ZSTD_V1 = "application/vnd.oci.image.layer.v1.tar+zstd" IMAGE_LAYER_NONDISTRIBUTABLE_V1 = ( "application/vnd.oci.image.layer.nondistributable.v1.tar" ) IMAGE_LAYER_NONDISTRIBUTABLE_GZIP_V1 = ( "application/vnd.oci.image.layer.nondistributable.v1.tar+gzip" ) IMAGE_LAYER_NONDISTRIBUTABLE_ZSTD_V1 = ( "application/vnd.oci.image.layer.nondistributable.v1.tar+zstd" ) IMAGE_MANIFEST_V1 = "application/vnd.oci.image.manifest.v1+json" LAYOUT_HEADER_V1 = "application/vnd.oci.layout.header.v1+json"
"""Reusable string literals.""" class Dockerauthentication: """ https://github.com/docker/distribution/blob/master/docs/spec/auth/token.md https://github.com/docker/distribution/blob/master/docs/spec/auth/scope.md """ dockerhub_url_pattern = '{0}?service={1}&scope={2}&client_id=docker-registry-client-async' scope_registry_catalog = 'registry:catalog:*' scope_repository_pull_pattern = 'repository:{0}:pull' scope_repository_push_pattern = 'repository:{0}:push' scope_repository_all_pattern = 'repository:{0}:pull,push' class Dockermediatypes: """https://github.com/docker/distribution/blob/master/docs/spec/manifest-v2-2.md#manifest-list""" container_image_v1 = 'application/vnd.docker.container.image.v1+json' distribution_manifest_list_v2 = 'application/vnd.docker.distribution.manifest.list.v2+json' distribution_manifest_v1 = 'application/vnd.docker.distribution.manifest.v1+json' distribution_manifest_v1_signed = 'application/vnd.docker.distribution.manifest.v1+prettyjws' distribution_manifest_v2 = 'application/vnd.docker.distribution.manifest.v2+json' image_rootfs_diff = 'application/vnd.docker.image.rootfs.diff.tar.gzip' image_rootfs_foreign_diff = 'application/vnd.docker.image.rootfs.foreign.diff.tar.gzip' plugin_v1 = 'application/vnd.docker.plugin.v1+json' class Indices: """Common registry indices.""" dockerhub = 'index.docker.io' quay = 'quay.io' class Quayauthentication: """ https://docs.quay.io/api/ """ quay_url_pattern = '{0}?service={1}&scope={2}&client_id=docker-registry-client-async' scope_repository_pull_pattern = 'repo:{0}:read' scope_repository_push_pattern = 'repo:{0}:write' scope_repository_all_pattern = 'repo:{0}:read,write' class Mediatypes: """Generic mime types.""" application_json = 'application/json' application_octet_stream = 'application/octet-stream' application_yaml = 'application/yaml' class Ocimediatypes: """https://github.com/opencontainers/image-spec/blob/master/media-types.md""" descriptor_v1 = 'application/vnd.oci.descriptor.v1+json' image_config_v1 = 'application/vnd.oci.image.config.v1+json' image_index_v1 = 'application/vnd.oci.image.index.v1+json' image_layer_v1 = 'application/vnd.oci.image.layer.v1.tar' image_layer_gzip_v1 = 'application/vnd.oci.image.layer.v1.tar+gzip' image_layer_zstd_v1 = 'application/vnd.oci.image.layer.v1.tar+zstd' image_layer_nondistributable_v1 = 'application/vnd.oci.image.layer.nondistributable.v1.tar' image_layer_nondistributable_gzip_v1 = 'application/vnd.oci.image.layer.nondistributable.v1.tar+gzip' image_layer_nondistributable_zstd_v1 = 'application/vnd.oci.image.layer.nondistributable.v1.tar+zstd' image_manifest_v1 = 'application/vnd.oci.image.manifest.v1+json' layout_header_v1 = 'application/vnd.oci.layout.header.v1+json'
def test_see_for_top_level(result): assert ( "usage: vantage [-a PATH] [-e NAME ...] [-v KEY=[VALUE] ...] [--verbose] [-h] COMMAND..." in result.stdout_ )
def test_see_for_top_level(result): assert 'usage: vantage [-a PATH] [-e NAME ...] [-v KEY=[VALUE] ...] [--verbose] [-h] COMMAND...' in result.stdout_
def wordBreakDP(word, dic): n = len(word) if word in dic: return True if len(dic) == 0: return False dp = [False for i in range(n + 1)] dp[0] = True for i in range(1, n + 1): for j in range(i - 1, -1, -1): if dp[j] == True: substring = word[j:i] if substring in dic: dp[i] = True break return dp[-1] def wordBreakRecursive(word, dic, startIndex=0): if word in dic: return True if len(dic) == 0: return false if startIndex == len(word): return True for endIndex in range(startIndex + 1, len(word) + 1): if word[startIndex: endIndex] in dic and wordBreakRecursive(word, dic, endIndex): return True return False def wordBreakMemo(word, dic, startIndex=0, memo=None): if word in dic: return True if len(dic) == 0: return False if memo == None: memo = dict() if startIndex in memo: return memo[startIndex] for endIndex in range(startIndex + 1, len(word) + 1): if word[startIndex: endIndex] in dic and wordBreakRecursive(word, dic, endIndex): memo[startIndex] = True return memo[startIndex] memo[startIndex] = False return memo[startIndex] word = "papapapokerface" dic = {"pa", "poker", "face"} print(wordBreakDP(word, dic)) print(wordBreakRecursive(word, dic)) print(wordBreakMemo(word, dic))
def word_break_dp(word, dic): n = len(word) if word in dic: return True if len(dic) == 0: return False dp = [False for i in range(n + 1)] dp[0] = True for i in range(1, n + 1): for j in range(i - 1, -1, -1): if dp[j] == True: substring = word[j:i] if substring in dic: dp[i] = True break return dp[-1] def word_break_recursive(word, dic, startIndex=0): if word in dic: return True if len(dic) == 0: return false if startIndex == len(word): return True for end_index in range(startIndex + 1, len(word) + 1): if word[startIndex:endIndex] in dic and word_break_recursive(word, dic, endIndex): return True return False def word_break_memo(word, dic, startIndex=0, memo=None): if word in dic: return True if len(dic) == 0: return False if memo == None: memo = dict() if startIndex in memo: return memo[startIndex] for end_index in range(startIndex + 1, len(word) + 1): if word[startIndex:endIndex] in dic and word_break_recursive(word, dic, endIndex): memo[startIndex] = True return memo[startIndex] memo[startIndex] = False return memo[startIndex] word = 'papapapokerface' dic = {'pa', 'poker', 'face'} print(word_break_dp(word, dic)) print(word_break_recursive(word, dic)) print(word_break_memo(word, dic))
file1= "db_breakfast_menu.txt" file2= "db_lunch_menu.txt" file3= "db_dinner_menu.txt" file4 = "db_label_text.txt" retail = [] title = [] label = [] with open(file1, "r") as f: data = f.readlines() for line in data: w = line.split(":") title.append(w[1]) for line in data: w = line.split("$") price = w[1] price.rstrip('\n') conv = float(price) retail.append(conv) f.close() with open (file4, "r") as f: data = f.readlines() for line in data: i = 1 w = line.split(":") string1 = w[i] i+=1 string2 = w[i] string = ("%s\n%s" %(string1,string2)) label.append(string) f.close()
file1 = 'db_breakfast_menu.txt' file2 = 'db_lunch_menu.txt' file3 = 'db_dinner_menu.txt' file4 = 'db_label_text.txt' retail = [] title = [] label = [] with open(file1, 'r') as f: data = f.readlines() for line in data: w = line.split(':') title.append(w[1]) for line in data: w = line.split('$') price = w[1] price.rstrip('\n') conv = float(price) retail.append(conv) f.close() with open(file4, 'r') as f: data = f.readlines() for line in data: i = 1 w = line.split(':') string1 = w[i] i += 1 string2 = w[i] string = '%s\n%s' % (string1, string2) label.append(string) f.close()
class Guesser: def __init__(self, number, lives): self.number = number self.lives = lives def guess(self,n): if self.lives < 1: raise Exception("Omae wa mo shindeiru") match = n == self.number if not match: self.lives -= 1 return match
class Guesser: def __init__(self, number, lives): self.number = number self.lives = lives def guess(self, n): if self.lives < 1: raise exception('Omae wa mo shindeiru') match = n == self.number if not match: self.lives -= 1 return match
def get_assign(user_input): key, value = user_input.split("gets") key = key.strip() value = int(value.strip()) my_dict[key] = value print(my_dict) def add_values(num1, num2): return num1 + num2 print("Welcome to the Adder REPL.") my_dict = dict() while True: user_input = input("???") if 'gets' in user_input: get_assign(user_input) if 'input' in user_input: print("Enter a value for :") input_assign() if 'adds' in user_input: a, b = user_input.split("adds") if 'print' in user_input: print_values() if 'quit' in user_input: print("GoodBye") exit()
def get_assign(user_input): (key, value) = user_input.split('gets') key = key.strip() value = int(value.strip()) my_dict[key] = value print(my_dict) def add_values(num1, num2): return num1 + num2 print('Welcome to the Adder REPL.') my_dict = dict() while True: user_input = input('???') if 'gets' in user_input: get_assign(user_input) if 'input' in user_input: print('Enter a value for :') input_assign() if 'adds' in user_input: (a, b) = user_input.split('adds') if 'print' in user_input: print_values() if 'quit' in user_input: print('GoodBye') exit()
""" Solution for Sort Integers by The Power Value: https://leetcode.com/problems/sort-integers-by-the-power-value/ """ class Solution: def getKth(self, lo: int, hi: int, k: int) -> int: # Can I calculate the power of an integer? # if two ints have same power, sort by the ints # power of 1 = 0 steps # [1] -> 1 # no zeros for now # assume no negatives def calculate_steps(range_int: int) -> int: # i = range_int # init a variable to count the number of steps at 0 steps = 0 # iterate while the number not equal to zero while range_int != 1: # transform it using the right eq, based on even or odd if range_int % 2 == 0: range_int /= 2 else: # should be odd range_int = 3 * range_int + 1 steps += 1 # return the steps return steps """ steps = 9 range_int = 1 """ power_ints = dict() # n = hi - lo + 1 # iterate over all the integers in the range for num in range(lo, hi + 1): # n iterations # calulate the power of the integer power = calculate_steps(num) # map each integer of the power -> range_int if power in power_ints: # O(1) power_ints[power].append(num) else: power_ints[power] = [num] # sort the range ints into an seq, based on the powers sorted_powers = sorted(power_ints) # O(n log n) sorted_ints = list() for power in sorted_powers: # n iterations ints = power_ints[power] ints.sort() sorted_ints.extend(ints) # # return the k - 1 element return sorted_ints[k - 1] # Time O(n * calculate_power + n log n) # Space O(n) """ """ """ lo = 12 hi = 15 k = 2 power_ints = { 9: [12, 13] 17: [14, 15] } sorted_powers = [9, 17] sorted_ints = [12, 13, 14, 15] ints = [14, 15] power = 17 num = 12 power = 9 """
""" Solution for Sort Integers by The Power Value: https://leetcode.com/problems/sort-integers-by-the-power-value/ """ class Solution: def get_kth(self, lo: int, hi: int, k: int) -> int: def calculate_steps(range_int: int) -> int: steps = 0 while range_int != 1: if range_int % 2 == 0: range_int /= 2 else: range_int = 3 * range_int + 1 steps += 1 return steps '\n steps = 9\n \n range_int = 1\n ' power_ints = dict() for num in range(lo, hi + 1): power = calculate_steps(num) if power in power_ints: power_ints[power].append(num) else: power_ints[power] = [num] sorted_powers = sorted(power_ints) sorted_ints = list() for power in sorted_powers: ints = power_ints[power] ints.sort() sorted_ints.extend(ints) return sorted_ints[k - 1] '\n \n ' '\n lo = 12\n hi = 15\n k = 2\n \n power_ints = {\n 9: [12, 13]\n 17: [14, 15]\n }\n sorted_powers = [9, 17]\n sorted_ints = [12, 13, 14, 15]\n ints = [14, 15]\n power = 17\n num = 12\n power = 9\n \n '
try: for i in ['a', 'b', 'c']: print(i ** 2) except TypeError: print("An error occured!") x = 5 y = 0 try: z = x /y print(z) except ZeroDivisionError: print("Can't devide by zero") finally: print("All done") def ask(): while True: try: val = int(input("Input an integer: ")) except: print("An error occured! Please try again") else: break print("Thank you, you number sqared is: ", val ** 2) ask()
try: for i in ['a', 'b', 'c']: print(i ** 2) except TypeError: print('An error occured!') x = 5 y = 0 try: z = x / y print(z) except ZeroDivisionError: print("Can't devide by zero") finally: print('All done') def ask(): while True: try: val = int(input('Input an integer: ')) except: print('An error occured! Please try again') else: break print('Thank you, you number sqared is: ', val ** 2) ask()
NR_CLASSES = 10 hyperparameters = { "number-epochs" : 30, "batch-size" : 100, "learning-rate" : 0.005, "weight-decay" : 1e-9, "learning-decay" : 1e-3 }
nr_classes = 10 hyperparameters = {'number-epochs': 30, 'batch-size': 100, 'learning-rate': 0.005, 'weight-decay': 1e-09, 'learning-decay': 0.001}
class DoublyLinkedList: """ Private Node Class """ class _Node: def __init__(self, value): self.value = value self.next = None self.prev = None def __str__(self): return self.value def __init__(self): self.head = None self.tail = None self.length = 0 def push_beginning(self, value): node = self._Node(value) if self.length == 0: self.head = node self.tail = node else: node.next = self.head self.head.prev = node self.head = node self.length += 1 return True def push_end(self, value): node = self._Node(value) if self.length == 0: self.head = node self.tail = node else: node.prev = self.tail self.tail.next = node self.tail = node self.length += 1 return True def push_at_index(self, value, index): if self._is_empty(): raise IndexError("List is empty") self._is_out_of_bounds(index) if index == 0: self.push_beginning(value) if index >= self.length - 1: self.push_end(value) else: node = self._Node(value) i = 0 temp_node = self.head while i < index - 1: temp_node = temp_node.next i += 1 node.next = temp_node.next temp_node.next.prev = node node.prev = temp_node temp_node.next = node self.length += 1 return True def remove_beginning(self): if self._is_empty(): raise IndexError("List is empty") value = self.head.value self.head = self.head.next self.head.prev.next = None self.head.prev = None self.length -= 1 return value def remove_end(self): if self._is_empty(): raise IndexError("List is empty") value = self.tail.value self.tail = self.tail.prev self.tail.next.prev = None self.tail.next = None self.length -= 1 return value def remove_at_index(self, index): if self._is_empty(): raise IndexError("List is empty") self._is_out_of_bounds(index) if index == 0: self.remove_beginning() if index >= self.length - 1: self.remove_end() else: i = 0 temp_node = self.head while i < index - 1: temp_node = temp_node.next i += 1 node_remove = temp_node.next value = node_remove.value temp_node.next = node_remove.next node_remove.next = None temp_node.next.prev = temp_node node_remove.prev = None return value def get_value_at(self, index): if self._is_empty(): raise IndexError("List is empty") self._is_out_of_bounds(index) i = 0 temp_node = self.head while i < index: temp_node = temp_node.next i += 1 return temp_node.value def set_value_at(self, value, index): if self._is_empty(): raise IndexError("List is empty") self._is_out_of_bounds(index) i = 0 temp_node = self.head while i < index: temp_node = temp_node.next i += 1 temp_node.value = value return True def reverse_list(self): temp_node_head = self.head temp_node_tail = self.tail i = 0 while i < int(self.length / 2): temp_value = temp_node_tail.value temp_node_tail.value = temp_node_head.value temp_node_head.value = temp_value temp_node_tail = temp_node_tail.prev temp_node_head = temp_node_head.next i += 1 return True """ Helper methods """ def size(self): return self.length def _is_empty(self): return self.length == 0 def _is_out_of_bounds(self, idx): if idx >= self.length: raise IndexError('Index out of bounds') def __str__(self): temp_node = self.head lst_str = "[" while temp_node is not None: lst_str += str(temp_node.value) if temp_node.next is not None: lst_str += "," temp_node = temp_node.next lst_str += "]" return lst_str
class Doublylinkedlist: """ Private Node Class """ class _Node: def __init__(self, value): self.value = value self.next = None self.prev = None def __str__(self): return self.value def __init__(self): self.head = None self.tail = None self.length = 0 def push_beginning(self, value): node = self._Node(value) if self.length == 0: self.head = node self.tail = node else: node.next = self.head self.head.prev = node self.head = node self.length += 1 return True def push_end(self, value): node = self._Node(value) if self.length == 0: self.head = node self.tail = node else: node.prev = self.tail self.tail.next = node self.tail = node self.length += 1 return True def push_at_index(self, value, index): if self._is_empty(): raise index_error('List is empty') self._is_out_of_bounds(index) if index == 0: self.push_beginning(value) if index >= self.length - 1: self.push_end(value) else: node = self._Node(value) i = 0 temp_node = self.head while i < index - 1: temp_node = temp_node.next i += 1 node.next = temp_node.next temp_node.next.prev = node node.prev = temp_node temp_node.next = node self.length += 1 return True def remove_beginning(self): if self._is_empty(): raise index_error('List is empty') value = self.head.value self.head = self.head.next self.head.prev.next = None self.head.prev = None self.length -= 1 return value def remove_end(self): if self._is_empty(): raise index_error('List is empty') value = self.tail.value self.tail = self.tail.prev self.tail.next.prev = None self.tail.next = None self.length -= 1 return value def remove_at_index(self, index): if self._is_empty(): raise index_error('List is empty') self._is_out_of_bounds(index) if index == 0: self.remove_beginning() if index >= self.length - 1: self.remove_end() else: i = 0 temp_node = self.head while i < index - 1: temp_node = temp_node.next i += 1 node_remove = temp_node.next value = node_remove.value temp_node.next = node_remove.next node_remove.next = None temp_node.next.prev = temp_node node_remove.prev = None return value def get_value_at(self, index): if self._is_empty(): raise index_error('List is empty') self._is_out_of_bounds(index) i = 0 temp_node = self.head while i < index: temp_node = temp_node.next i += 1 return temp_node.value def set_value_at(self, value, index): if self._is_empty(): raise index_error('List is empty') self._is_out_of_bounds(index) i = 0 temp_node = self.head while i < index: temp_node = temp_node.next i += 1 temp_node.value = value return True def reverse_list(self): temp_node_head = self.head temp_node_tail = self.tail i = 0 while i < int(self.length / 2): temp_value = temp_node_tail.value temp_node_tail.value = temp_node_head.value temp_node_head.value = temp_value temp_node_tail = temp_node_tail.prev temp_node_head = temp_node_head.next i += 1 return True ' Helper methods ' def size(self): return self.length def _is_empty(self): return self.length == 0 def _is_out_of_bounds(self, idx): if idx >= self.length: raise index_error('Index out of bounds') def __str__(self): temp_node = self.head lst_str = '[' while temp_node is not None: lst_str += str(temp_node.value) if temp_node.next is not None: lst_str += ',' temp_node = temp_node.next lst_str += ']' return lst_str
#!/usr/bin/python3 ''' BubbleSort.py by Xiaoguang Zhu ''' array = [] print("Enter at least two numbers to start bubble-sorting.") print("(You can end inputing anytime by entering nonnumeric)") # get numbers while True: try: array.append(float(input(">> "))) except ValueError: # exit inputing break print("\nThe array you've entered was:"); print(array) print("\nNow sorting...") # sorting for x in range(len(array)-1, 0, -1): for y in range(x): if array[y] > array[y+1]: array[y], array[y+1] = array[y+1], array[y] print(array) # output print("\nAll done! Now the moment of truth!") print(array)
""" BubbleSort.py by Xiaoguang Zhu """ array = [] print('Enter at least two numbers to start bubble-sorting.') print('(You can end inputing anytime by entering nonnumeric)') while True: try: array.append(float(input('>> '))) except ValueError: break print("\nThe array you've entered was:") print(array) print('\nNow sorting...') for x in range(len(array) - 1, 0, -1): for y in range(x): if array[y] > array[y + 1]: (array[y], array[y + 1]) = (array[y + 1], array[y]) print(array) print('\nAll done! Now the moment of truth!') print(array)
medida = float(input("uma distancai em metros: ")) cm = medida * 100 mm = medida * 1000 dm = medida / 10 dam = medida * 1000000 hm = medida / 100 km = medida * 0.001 ml = medida * 0.000621371 m = medida * 100000 print("A medida de {:.0f}m corresponde a {:.0f} mm \n{:.0f} cm \n{:.0f} dm \n{:.0f} dam \n{:.0f} hm \n{:.2f} km \n{:.2f} ml" .format (medida, cm, mm, dm, dam, hm, km, ml))
medida = float(input('uma distancai em metros: ')) cm = medida * 100 mm = medida * 1000 dm = medida / 10 dam = medida * 1000000 hm = medida / 100 km = medida * 0.001 ml = medida * 0.000621371 m = medida * 100000 print('A medida de {:.0f}m corresponde a {:.0f} mm \n{:.0f} cm \n{:.0f} dm \n{:.0f} dam \n{:.0f} hm \n{:.2f} km \n{:.2f} ml'.format(medida, cm, mm, dm, dam, hm, km, ml))
def create_supervised_data(env, agents, num_runs=50): val = [] # the data threeple action_history = [] predict_history = [] mental_history = [] character_history = [] episode_history = [] traj_history = [] grids = [] ep_length = env.maxtime filler = env.get_filler() obs = env.reset(setting=setting, num_visible=num_goals) for ep in tqdm.tqdm(range(num_runs*eps_per_run)): buffer_s = [np.zeros(obs[0].shape) for _ in range(env.maxtime)] if (ep % eps_per_run) == eps_per_run-1: obs = env.reset(setting=setting, num_visible=num_goals) else: obs = env.reset() if ep % eps_per_run == 0: episode_number = 0 #clear ep_history here? for agent in agents: if not unarbitrary_prefs: agent.reset_prefs() else: agent.hardcode_prefs() prevact = None prevpos = None agentpos = agents[0].pos episode_time = 0 while not env.done: if rendering and ((ep % eps_per_run) == eps_per_run-1): env.render() buffer_s.append(obs[0]) actions = [agent.action(torch.FloatTensor([buffer_s[-env.maxtime:]]).cuda()),] agentpos = agents[0].pos thistraj = env.get_trajectory(agentpos, prevact, prevpos) prevpos = agentpos #without agent position, thisact of none is pretty meaningless prevact = actions[0] traj_history += [thistraj, ] #moved this to before following if episode_time += 1 if ((ep % eps_per_run) == eps_per_run-1): # each step in last episode #episode number is 3 if visualize: render_path(env, ep, episode_time, vispath) #print(actions) run = np.zeros((eps_per_run, ep_length, *filler.shape)) if eps_per_run > 1: run[-episode_number-1:-1] = episode_history[-episode_number:] episode = np.zeros((ep_length, *filler.shape)) episode[ep_length-episode_time:] = traj_history[-episode_time] run[-1] = episode shortterm = np.asarray(traj_history[-1]) action_history += [one_hot(5, actions[0]),] character_history += [run,] mental_history += [episode,] predict_history += [shortterm,] if not env.full_test: break obs, _, _, = env.step(actions) # end of episode episode = np.zeros((ep_length, *filler.shape)) episode[ep_length-episode_time:] = traj_history[-episode_time:] episode_history += [episode, ] episode_number += 1 return character_history, mental_history, predict_history, action_history def format_data_torch(data, **train_kwargs): char = np.asarray(data[0]).astype('float32') # (N, Ep, F, W, H, C) = first.shape #first.reshape((N, Ep, F, C, H, W)) char = np.swapaxes(char, 3, 5) mental = np.asarray(data[1]).astype('float32') # (N, F, W, H, C) = first.shape #first.reshape((N, F, C, H, W)) mental = np.swapaxes(mental, 2, 4) query = np.asarray(data[2][:]).astype('float32') # (N, W, H, C) = second.shape #second.reshape((N, C, H, W)) query = np.swapaxes(query, 1, 3) act = np.asarray(data[3][:]).astype('int32') char1 = torch.Tensor(char).cuda()#[:, 0, :, :, :, :] mental1 = torch.Tensor(mental).cuda() query1 = torch.Tensor(query).cuda()#[:, 0, :, :, :] act1 = torch.Tensor(act).cuda() dataset = torch.utils.data.TensorDataset(char1, mental1, query1, act1) return torch.utils.data.DataLoader(dataset, **train_kwargs) def supervised_training(env, agents, data): dummies = [Dummy(steps, model) for agent in agents] class DummyAgent(): ''' railroads the agent for some steps, then switches to an alternate model. railroaded steps should be included in environment's test condition, returned as the final value of reset() predefined strategies after the railroaded steps are compared with the alt model's output ''' def __init__(self, railroad, strategies, model): self.n = -1 self.length = len(railroad) self.model = model self.rails = railroad self.strats = strategies def choose_action(self, obs): if n <= self.length: self.n += 1 return self.railroad[self.n], [0 for x in self.strats] else: self.n += 1 act = self.model.choose_action(obs) return act, [act == x[self.n] for x in self.strats] def reset(railroad, strategies): self.length = len(railroad) self.rails = railroad self.strats = strategies
def create_supervised_data(env, agents, num_runs=50): val = [] action_history = [] predict_history = [] mental_history = [] character_history = [] episode_history = [] traj_history = [] grids = [] ep_length = env.maxtime filler = env.get_filler() obs = env.reset(setting=setting, num_visible=num_goals) for ep in tqdm.tqdm(range(num_runs * eps_per_run)): buffer_s = [np.zeros(obs[0].shape) for _ in range(env.maxtime)] if ep % eps_per_run == eps_per_run - 1: obs = env.reset(setting=setting, num_visible=num_goals) else: obs = env.reset() if ep % eps_per_run == 0: episode_number = 0 for agent in agents: if not unarbitrary_prefs: agent.reset_prefs() else: agent.hardcode_prefs() prevact = None prevpos = None agentpos = agents[0].pos episode_time = 0 while not env.done: if rendering and ep % eps_per_run == eps_per_run - 1: env.render() buffer_s.append(obs[0]) actions = [agent.action(torch.FloatTensor([buffer_s[-env.maxtime:]]).cuda())] agentpos = agents[0].pos thistraj = env.get_trajectory(agentpos, prevact, prevpos) prevpos = agentpos prevact = actions[0] traj_history += [thistraj] episode_time += 1 if ep % eps_per_run == eps_per_run - 1: if visualize: render_path(env, ep, episode_time, vispath) run = np.zeros((eps_per_run, ep_length, *filler.shape)) if eps_per_run > 1: run[-episode_number - 1:-1] = episode_history[-episode_number:] episode = np.zeros((ep_length, *filler.shape)) episode[ep_length - episode_time:] = traj_history[-episode_time] run[-1] = episode shortterm = np.asarray(traj_history[-1]) action_history += [one_hot(5, actions[0])] character_history += [run] mental_history += [episode] predict_history += [shortterm] if not env.full_test: break (obs, _, _) = env.step(actions) episode = np.zeros((ep_length, *filler.shape)) episode[ep_length - episode_time:] = traj_history[-episode_time:] episode_history += [episode] episode_number += 1 return (character_history, mental_history, predict_history, action_history) def format_data_torch(data, **train_kwargs): char = np.asarray(data[0]).astype('float32') char = np.swapaxes(char, 3, 5) mental = np.asarray(data[1]).astype('float32') mental = np.swapaxes(mental, 2, 4) query = np.asarray(data[2][:]).astype('float32') query = np.swapaxes(query, 1, 3) act = np.asarray(data[3][:]).astype('int32') char1 = torch.Tensor(char).cuda() mental1 = torch.Tensor(mental).cuda() query1 = torch.Tensor(query).cuda() act1 = torch.Tensor(act).cuda() dataset = torch.utils.data.TensorDataset(char1, mental1, query1, act1) return torch.utils.data.DataLoader(dataset, **train_kwargs) def supervised_training(env, agents, data): dummies = [dummy(steps, model) for agent in agents] class Dummyagent: """ railroads the agent for some steps, then switches to an alternate model. railroaded steps should be included in environment's test condition, returned as the final value of reset() predefined strategies after the railroaded steps are compared with the alt model's output """ def __init__(self, railroad, strategies, model): self.n = -1 self.length = len(railroad) self.model = model self.rails = railroad self.strats = strategies def choose_action(self, obs): if n <= self.length: self.n += 1 return (self.railroad[self.n], [0 for x in self.strats]) else: self.n += 1 act = self.model.choose_action(obs) return (act, [act == x[self.n] for x in self.strats]) def reset(railroad, strategies): self.length = len(railroad) self.rails = railroad self.strats = strategies
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def mergeKLists(self, lists: list): """ :type lists: List[ListNode] :rtype: ListNode """ if len(lists) == 0: return None if len(lists) == 1: return lists[0] node_result = self.merge_two_sorted_lists(lists.pop(), lists.pop()) while lists: node_result = self.merge_two_sorted_lists(node_result, lists.pop()) return node_result def merge_two_sorted_lists(self, node_a, node_b): head_node = ListNode(-1) cur_node = head_node while node_a and node_b: if node_a.val < node_b.val: cur_node.next = node_a node_a = node_a.next else: cur_node.next = node_b node_b = node_b.next cur_node = cur_node.next cur_node.next = node_a or node_b return head_node.next
class Listnode: def __init__(self, x): self.val = x self.next = None class Solution: def merge_k_lists(self, lists: list): """ :type lists: List[ListNode] :rtype: ListNode """ if len(lists) == 0: return None if len(lists) == 1: return lists[0] node_result = self.merge_two_sorted_lists(lists.pop(), lists.pop()) while lists: node_result = self.merge_two_sorted_lists(node_result, lists.pop()) return node_result def merge_two_sorted_lists(self, node_a, node_b): head_node = list_node(-1) cur_node = head_node while node_a and node_b: if node_a.val < node_b.val: cur_node.next = node_a node_a = node_a.next else: cur_node.next = node_b node_b = node_b.next cur_node = cur_node.next cur_node.next = node_a or node_b return head_node.next
def create_path(path:str): """ :param path:path is the relative path from the pixel images folder :return: return the relative path from roots of project """ return current_path + path #a function name is before the parameters and after the def #function parameters: the values that the function knows, inside the parantheses #function typehinting: tells the code that it should be a string... #docstrings: tells what the function does, what parameters are, what it returns
def create_path(path: str): """ :param path:path is the relative path from the pixel images folder :return: return the relative path from roots of project """ return current_path + path
def rep_hill(x, n): """Dimensionless production rate for a gene repressed by x. Parameters ---------- x : float or NumPy array Concentration of repressor. n : float Hill coefficient. Returns ------- output : NumPy array or float 1 / (1 + x**n) """ return 1.0 / (1.0 + x ** n) def act_hill(x, n): """Dimensionless production rate for a gene activated by x. Parameters ---------- x : float or NumPy array Concentration of activator. n : float Hill coefficient. Returns ------- output : NumPy array or float x**n / (1 + x**n) """ return 1.0 - rep_hill(x, n) def aa_and(x, y, nx, ny): """Dimensionless production rate for a gene regulated by two activators with AND logic in the absence of leakage. Parameters ---------- x : float or NumPy array Concentration of first activator. y : float or NumPy array Concentration of second activator. nx : float Hill coefficient for first activator. ny : float Hill coefficient for second activator. Returns ------- output : NumPy array or float x**nx * y**ny / (1 + x**nx) / (1 + y**ny) """ return x ** nx * y ** ny / (1.0 + x ** nx) / (1.0 + y ** ny) def aa_or(x, y, nx, ny): """Dimensionless production rate for a gene regulated by two activators with OR logic in the absence of leakage. Parameters ---------- x : float or NumPy array Concentration of first activator. y : float or NumPy array Concentration of second activator. nx : float Hill coefficient for first activator. ny : float Hill coefficient for second activator. Returns ------- output : NumPy array or float (x**nx + y**ny + x**nx * y**ny) / (1 + x**nx) / (1 + y**ny) """ denom = (1.0 + x ** nx) * (1.0 + y ** ny) return (denom - 1.0) / denom def aa_or_single(x, y, nx, ny): """Dimensionless production rate for a gene regulated by two activators with OR logic in the absence of leakage with single occupancy. Parameters ---------- x : float or NumPy array Concentration of first activator. y : float or NumPy array Concentration of second activator. nx : float Hill coefficient for first activator. ny : float Hill coefficient for second activator. Returns ------- output : NumPy array or float (x**nx + y**ny) / (1 + x**nx + y**ny) """ num = x ** nx + y ** ny return num / (1.0 + num) def rr_and(x, y, nx, ny): """Dimensionless production rate for a gene regulated by two repressors with AND logic in the absence of leakage. Parameters ---------- x : float or NumPy array Concentration of first repressor. y : float or NumPy array Concentration of second repressor. nx : float Hill coefficient for first repressor. ny : float Hill coefficient for second repressor. Returns ------- output : NumPy array or float 1 / (1 + x**nx) / (1 + y**ny) """ return 1.0 / (1.0 + x ** nx) / (1.0 + y ** ny) def rr_and_single(x, y, nx, ny): """Dimensionless production rate for a gene regulated by two repressors with AND logic in the absence of leakage with single occupancy. Parameters ---------- x : float or NumPy array Concentration of first repressor. y : float or NumPy array Concentration of second repressor. nx : float Hill coefficient for first repressor. ny : float Hill coefficient for second repressor. Returns ------- output : NumPy array or float 1 / (1 + x**nx + y**ny) """ return 1.0 / (1.0 + x ** nx + y ** ny) def rr_or(x, y, nx, ny): """Dimensionless production rate for a gene regulated by two repressors with OR logic in the absence of leakage. Parameters ---------- x : float or NumPy array Concentration of first repressor. y : float or NumPy array Concentration of second repressor. nx : float Hill coefficient for first repressor. ny : float Hill coefficient for second repressor. Returns ------- output : NumPy array or float (1 + x**nx + y**ny) / (1 + x**nx) / (1 + y**ny) """ return (1.0 + x ** nx + y ** ny) / (1.0 + x ** nx) / (1.0 + y ** ny) def ar_and(x, y, nx, ny): """Dimensionless production rate for a gene regulated by one activator and one repressor with AND logic in the absence of leakage. Parameters ---------- x : float or NumPy array Concentration of activator. y : float or NumPy array Concentration of repressor. nx : float Hill coefficient for activator. ny : float Hill coefficient for repressor. Returns ------- output : NumPy array or float x ** nx / (1 + x**nx) / (1 + y**ny) """ return x ** nx / (1.0 + x ** nx) / (1.0 + y ** ny) def ar_or(x, y, nx, ny): """Dimensionless production rate for a gene regulated by one activator and one repressor with OR logic in the absence of leakage. Parameters ---------- x : float or NumPy array Concentration of activator. y : float or NumPy array Concentration of repressor. nx : float Hill coefficient for activator. ny : float Hill coefficient for repressor. Returns ------- output : NumPy array or float (1 + x**nx + x**nx * y**ny)) / (1 + x**nx) / (1 + y**ny) """ return (1.0 + x ** nx * (1.0 + y ** ny)) / (1.0 + x ** nx) / (1.0 + y ** ny) def ar_and_single(x, y, nx, ny): """Dimensionless production rate for a gene regulated by one activator and one repressor with AND logic in the absence of leakage with single occupancy. Parameters ---------- x : float or NumPy array Concentration of activator. y : float or NumPy array Concentration of repressor. nx : float Hill coefficient for activator. ny : float Hill coefficient for repressor. Returns ------- output : NumPy array or float x ** nx / (1 + x**nx + y**ny) """ return x ** nx / (1.0 + x ** nx + y ** ny) def ar_or_single(x, y, nx, ny): """Dimensionless production rate for a gene regulated by one activator and one repressor with OR logic in the absence of leakage with single occupancy. Parameters ---------- x : float or NumPy array Concentration of activator. y : float or NumPy array Concentration of repressor. nx : float Hill coefficient for activator. ny : float Hill coefficient for repressor. Returns ------- output : NumPy array or float (1 + x**nx) / (1 + x**nx + y**ny) """ return (1.0 + x ** nx) / (1.0 + x ** nx + y ** ny)
def rep_hill(x, n): """Dimensionless production rate for a gene repressed by x. Parameters ---------- x : float or NumPy array Concentration of repressor. n : float Hill coefficient. Returns ------- output : NumPy array or float 1 / (1 + x**n) """ return 1.0 / (1.0 + x ** n) def act_hill(x, n): """Dimensionless production rate for a gene activated by x. Parameters ---------- x : float or NumPy array Concentration of activator. n : float Hill coefficient. Returns ------- output : NumPy array or float x**n / (1 + x**n) """ return 1.0 - rep_hill(x, n) def aa_and(x, y, nx, ny): """Dimensionless production rate for a gene regulated by two activators with AND logic in the absence of leakage. Parameters ---------- x : float or NumPy array Concentration of first activator. y : float or NumPy array Concentration of second activator. nx : float Hill coefficient for first activator. ny : float Hill coefficient for second activator. Returns ------- output : NumPy array or float x**nx * y**ny / (1 + x**nx) / (1 + y**ny) """ return x ** nx * y ** ny / (1.0 + x ** nx) / (1.0 + y ** ny) def aa_or(x, y, nx, ny): """Dimensionless production rate for a gene regulated by two activators with OR logic in the absence of leakage. Parameters ---------- x : float or NumPy array Concentration of first activator. y : float or NumPy array Concentration of second activator. nx : float Hill coefficient for first activator. ny : float Hill coefficient for second activator. Returns ------- output : NumPy array or float (x**nx + y**ny + x**nx * y**ny) / (1 + x**nx) / (1 + y**ny) """ denom = (1.0 + x ** nx) * (1.0 + y ** ny) return (denom - 1.0) / denom def aa_or_single(x, y, nx, ny): """Dimensionless production rate for a gene regulated by two activators with OR logic in the absence of leakage with single occupancy. Parameters ---------- x : float or NumPy array Concentration of first activator. y : float or NumPy array Concentration of second activator. nx : float Hill coefficient for first activator. ny : float Hill coefficient for second activator. Returns ------- output : NumPy array or float (x**nx + y**ny) / (1 + x**nx + y**ny) """ num = x ** nx + y ** ny return num / (1.0 + num) def rr_and(x, y, nx, ny): """Dimensionless production rate for a gene regulated by two repressors with AND logic in the absence of leakage. Parameters ---------- x : float or NumPy array Concentration of first repressor. y : float or NumPy array Concentration of second repressor. nx : float Hill coefficient for first repressor. ny : float Hill coefficient for second repressor. Returns ------- output : NumPy array or float 1 / (1 + x**nx) / (1 + y**ny) """ return 1.0 / (1.0 + x ** nx) / (1.0 + y ** ny) def rr_and_single(x, y, nx, ny): """Dimensionless production rate for a gene regulated by two repressors with AND logic in the absence of leakage with single occupancy. Parameters ---------- x : float or NumPy array Concentration of first repressor. y : float or NumPy array Concentration of second repressor. nx : float Hill coefficient for first repressor. ny : float Hill coefficient for second repressor. Returns ------- output : NumPy array or float 1 / (1 + x**nx + y**ny) """ return 1.0 / (1.0 + x ** nx + y ** ny) def rr_or(x, y, nx, ny): """Dimensionless production rate for a gene regulated by two repressors with OR logic in the absence of leakage. Parameters ---------- x : float or NumPy array Concentration of first repressor. y : float or NumPy array Concentration of second repressor. nx : float Hill coefficient for first repressor. ny : float Hill coefficient for second repressor. Returns ------- output : NumPy array or float (1 + x**nx + y**ny) / (1 + x**nx) / (1 + y**ny) """ return (1.0 + x ** nx + y ** ny) / (1.0 + x ** nx) / (1.0 + y ** ny) def ar_and(x, y, nx, ny): """Dimensionless production rate for a gene regulated by one activator and one repressor with AND logic in the absence of leakage. Parameters ---------- x : float or NumPy array Concentration of activator. y : float or NumPy array Concentration of repressor. nx : float Hill coefficient for activator. ny : float Hill coefficient for repressor. Returns ------- output : NumPy array or float x ** nx / (1 + x**nx) / (1 + y**ny) """ return x ** nx / (1.0 + x ** nx) / (1.0 + y ** ny) def ar_or(x, y, nx, ny): """Dimensionless production rate for a gene regulated by one activator and one repressor with OR logic in the absence of leakage. Parameters ---------- x : float or NumPy array Concentration of activator. y : float or NumPy array Concentration of repressor. nx : float Hill coefficient for activator. ny : float Hill coefficient for repressor. Returns ------- output : NumPy array or float (1 + x**nx + x**nx * y**ny)) / (1 + x**nx) / (1 + y**ny) """ return (1.0 + x ** nx * (1.0 + y ** ny)) / (1.0 + x ** nx) / (1.0 + y ** ny) def ar_and_single(x, y, nx, ny): """Dimensionless production rate for a gene regulated by one activator and one repressor with AND logic in the absence of leakage with single occupancy. Parameters ---------- x : float or NumPy array Concentration of activator. y : float or NumPy array Concentration of repressor. nx : float Hill coefficient for activator. ny : float Hill coefficient for repressor. Returns ------- output : NumPy array or float x ** nx / (1 + x**nx + y**ny) """ return x ** nx / (1.0 + x ** nx + y ** ny) def ar_or_single(x, y, nx, ny): """Dimensionless production rate for a gene regulated by one activator and one repressor with OR logic in the absence of leakage with single occupancy. Parameters ---------- x : float or NumPy array Concentration of activator. y : float or NumPy array Concentration of repressor. nx : float Hill coefficient for activator. ny : float Hill coefficient for repressor. Returns ------- output : NumPy array or float (1 + x**nx) / (1 + x**nx + y**ny) """ return (1.0 + x ** nx) / (1.0 + x ** nx + y ** ny)
n = int(input()) vip_guest = set() regular_guest = set() for _ in range(n): reservation_code = input() if reservation_code[0].isdigit(): vip_guest.add(reservation_code) else: regular_guest.add(reservation_code) command = input() while command != "END": if command[0].isdigit(): vip_guest.discard(command) else: regular_guest.discard(command) command = input() missing_guest = len(vip_guest) + len(regular_guest) print(missing_guest) for vip in sorted(vip_guest): print(vip) for regular in sorted(regular_guest): print(regular)
n = int(input()) vip_guest = set() regular_guest = set() for _ in range(n): reservation_code = input() if reservation_code[0].isdigit(): vip_guest.add(reservation_code) else: regular_guest.add(reservation_code) command = input() while command != 'END': if command[0].isdigit(): vip_guest.discard(command) else: regular_guest.discard(command) command = input() missing_guest = len(vip_guest) + len(regular_guest) print(missing_guest) for vip in sorted(vip_guest): print(vip) for regular in sorted(regular_guest): print(regular)
class alttprException(Exception): pass class alttprFailedToRetrieve(Exception): pass class alttprFailedToGenerate(Exception): pass
class Alttprexception(Exception): pass class Alttprfailedtoretrieve(Exception): pass class Alttprfailedtogenerate(Exception): pass
EXPECTED_TABULATED_HTML = """ <table> <thead> <tr> <th>category</th> <th>date</th> <th>downloads</th> </tr> </thead> <tbody> <tr> <td align="left">2.6</td> <td align="left">2018-08-15</td> <td align="right">51</td> </tr> <tr> <td align="left">2.7</td> <td align="left">2018-08-15</td> <td align="right">63,749</td> </tr> <tr> <td align="left">3.2</td> <td align="left">2018-08-15</td> <td align="right">2</td> </tr> <tr> <td align="left">3.3</td> <td align="left">2018-08-15</td> <td align="right">40</td> </tr> <tr> <td align="left">3.4</td> <td align="left">2018-08-15</td> <td align="right">6,095</td> </tr> <tr> <td align="left">3.5</td> <td align="left">2018-08-15</td> <td align="right">20,358</td> </tr> <tr> <td align="left">3.6</td> <td align="left">2018-08-15</td> <td align="right">35,274</td> </tr> <tr> <td align="left">3.7</td> <td align="left">2018-08-15</td> <td align="right">6,595</td> </tr> <tr> <td align="left">3.8</td> <td align="left">2018-08-15</td> <td align="right">3</td> </tr> <tr> <td align="left">null</td> <td align="left">2018-08-15</td> <td align="right">1,019</td> </tr> </tbody> </table> """ EXPECTED_TABULATED_MD = """ | category | date | downloads | |----------|------------|----------:| | 2.6 | 2018-08-15 | 51 | | 2.7 | 2018-08-15 | 63,749 | | 3.2 | 2018-08-15 | 2 | | 3.3 | 2018-08-15 | 40 | | 3.4 | 2018-08-15 | 6,095 | | 3.5 | 2018-08-15 | 20,358 | | 3.6 | 2018-08-15 | 35,274 | | 3.7 | 2018-08-15 | 6,595 | | 3.8 | 2018-08-15 | 3 | | null | 2018-08-15 | 1,019 | """ EXPECTED_TABULATED_RST = """ .. table:: ========== ============ =========== category date downloads ========== ============ =========== 2.6 2018-08-15 51 2.7 2018-08-15 63,749 3.2 2018-08-15 2 3.3 2018-08-15 40 3.4 2018-08-15 6,095 3.5 2018-08-15 20,358 3.6 2018-08-15 35,274 3.7 2018-08-15 6,595 3.8 2018-08-15 3 null 2018-08-15 1,019 ========== ============ =========== """ # noqa: W291 EXPECTED_TABULATED_TSV = """ "category" \t "date" \t "downloads" "2.6" \t "2018-08-15" \t 51 "2.7" \t "2018-08-15" \t 63,749 "3.2" \t "2018-08-15" \t 2 "3.3" \t "2018-08-15" \t 40 "3.4" \t "2018-08-15" \t 6,095 "3.5" \t "2018-08-15" \t 20,358 "3.6" \t "2018-08-15" \t 35,274 "3.7" \t "2018-08-15" \t 6,595 "3.8" \t "2018-08-15" \t 3 "null" \t "2018-08-15" \t 1,019 """ # noqa: W291
expected_tabulated_html = '\n<table>\n <thead>\n <tr>\n <th>category</th>\n <th>date</th>\n <th>downloads</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td align="left">2.6</td>\n <td align="left">2018-08-15</td>\n <td align="right">51</td>\n </tr>\n <tr>\n <td align="left">2.7</td>\n <td align="left">2018-08-15</td>\n <td align="right">63,749</td>\n </tr>\n <tr>\n <td align="left">3.2</td>\n <td align="left">2018-08-15</td>\n <td align="right">2</td>\n </tr>\n <tr>\n <td align="left">3.3</td>\n <td align="left">2018-08-15</td>\n <td align="right">40</td>\n </tr>\n <tr>\n <td align="left">3.4</td>\n <td align="left">2018-08-15</td>\n <td align="right">6,095</td>\n </tr>\n <tr>\n <td align="left">3.5</td>\n <td align="left">2018-08-15</td>\n <td align="right">20,358</td>\n </tr>\n <tr>\n <td align="left">3.6</td>\n <td align="left">2018-08-15</td>\n <td align="right">35,274</td>\n </tr>\n <tr>\n <td align="left">3.7</td>\n <td align="left">2018-08-15</td>\n <td align="right">6,595</td>\n </tr>\n <tr>\n <td align="left">3.8</td>\n <td align="left">2018-08-15</td>\n <td align="right">3</td>\n </tr>\n <tr>\n <td align="left">null</td>\n <td align="left">2018-08-15</td>\n <td align="right">1,019</td>\n </tr>\n </tbody>\n</table>\n ' expected_tabulated_md = '\n| category | date | downloads |\n|----------|------------|----------:|\n| 2.6 | 2018-08-15 | 51 |\n| 2.7 | 2018-08-15 | 63,749 |\n| 3.2 | 2018-08-15 | 2 |\n| 3.3 | 2018-08-15 | 40 |\n| 3.4 | 2018-08-15 | 6,095 |\n| 3.5 | 2018-08-15 | 20,358 |\n| 3.6 | 2018-08-15 | 35,274 |\n| 3.7 | 2018-08-15 | 6,595 |\n| 3.8 | 2018-08-15 | 3 |\n| null | 2018-08-15 | 1,019 |\n' expected_tabulated_rst = '\n.. table:: \n\n ========== ============ ===========\n category date downloads \n ========== ============ ===========\n 2.6 2018-08-15 51 \n 2.7 2018-08-15 63,749 \n 3.2 2018-08-15 2 \n 3.3 2018-08-15 40 \n 3.4 2018-08-15 6,095 \n 3.5 2018-08-15 20,358 \n 3.6 2018-08-15 35,274 \n 3.7 2018-08-15 6,595 \n 3.8 2018-08-15 3 \n null 2018-08-15 1,019 \n ========== ============ ===========\n' expected_tabulated_tsv = '\n"category" \t "date" \t "downloads" \n "2.6" \t "2018-08-15" \t 51 \n "2.7" \t "2018-08-15" \t 63,749 \n "3.2" \t "2018-08-15" \t 2 \n "3.3" \t "2018-08-15" \t 40 \n "3.4" \t "2018-08-15" \t 6,095 \n "3.5" \t "2018-08-15" \t 20,358 \n "3.6" \t "2018-08-15" \t 35,274 \n "3.7" \t "2018-08-15" \t 6,595 \n "3.8" \t "2018-08-15" \t 3 \n "null" \t "2018-08-15" \t 1,019 \n'
# Runtime: 84 ms, faster than 22.95% of Python3 online submissions for Lowest Common Ancestor of a Binary Tree. # Memory Usage: 23.1 MB, less than 91.67% of Python3 online submissions for Lowest Common Ancestor of a Binary Tree. # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': # Method 1 # ans = [None] # def lca(node): # if not node: # return False # mid = (node is p or node is q) # left = lca(node.left) # right = lca(node.right) # if mid + left + right >= 2: # ans[0] = node # return mid or left or right # lca(root) # return ans[0] # Method 2 # Time: O(n) # Space: O(h) if root is None: return None if root is p or root is q: return root left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q) if left and right: return root else: return left or right
class Solution: def lowest_common_ancestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if root is None: return None if root is p or root is q: return root left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q) if left and right: return root else: return left or right
load( "//tensorflow/core/platform:rules_cc.bzl", "cc_library", ) def poplar_cc_library(**kwargs): """ Wrapper for inserting poplar specific build options. """ if not "copts" in kwargs: kwargs["copts"] = [] copts = kwargs["copts"] copts.append("-Werror=return-type") cc_library(**kwargs)
load('//tensorflow/core/platform:rules_cc.bzl', 'cc_library') def poplar_cc_library(**kwargs): """ Wrapper for inserting poplar specific build options. """ if not 'copts' in kwargs: kwargs['copts'] = [] copts = kwargs['copts'] copts.append('-Werror=return-type') cc_library(**kwargs)
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Question: Determine whether an integer is a palindrome. Do this without extra space. Some hints: Could negative integers be palindromes? (ie, -1) If you are thinking of converting the integer to string, note the restriction of using extra space. You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case? There is a more generic way of solving this problem. ''' class Solution(object): def isPalindrome(self, x): """ :type x: int :rtype: bool """ if x < 0: return False digits = 1 while x/digits >= 10: digits *= 10 while digits > 1: right = x % 10 left = int(x/digits) if left != right: return False x = int((x%digits) / 10) digits /= 100 return True
""" Question: Determine whether an integer is a palindrome. Do this without extra space. Some hints: Could negative integers be palindromes? (ie, -1) If you are thinking of converting the integer to string, note the restriction of using extra space. You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case? There is a more generic way of solving this problem. """ class Solution(object): def is_palindrome(self, x): """ :type x: int :rtype: bool """ if x < 0: return False digits = 1 while x / digits >= 10: digits *= 10 while digits > 1: right = x % 10 left = int(x / digits) if left != right: return False x = int(x % digits / 10) digits /= 100 return True
# Copyright (C) 2018 Garth N. Wells # # SPDX-License-Identifier: MIT """This module provides a model for a monitoring station, and tools for manipulating/modifying station data """ class MonitoringStation: """This class represents a river level monitoring station""" def __init__(self, station_id, measure_id, label, coord, typical_range, river, town): self.station_id = station_id self.measure_id = measure_id # Handle case of erroneous data where data system returns # '[label, label]' rather than 'label' self.name = label if isinstance(label, list): self.name = label[0] self.coord = coord self.typical_range = typical_range self.river = river self.town = town self.latest_level = None def __repr__(self): d = "Station name: {}\n".format(self.name) d += " id: {}\n".format(self.station_id) d += " measure id: {}\n".format(self.measure_id) d += " coordinate: {}\n".format(self.coord) d += " town: {}\n".format(self.town) d += " river: {}\n".format(self.river) d += " typical range: {}".format(self.typical_range) return d def typical_range_consistent(self): """Return True if the data is consistent and False if the data is inconsistent or unavailable.""" # inconsistent if data is unavailable if self.typical_range == None: return False # inconsistent if low range is higher than high range elif self.typical_range[0] > self.typical_range[1]: return False # else consistent else: return True def relative_water_level(self): """Returns the latest water level as a fraction of the typical range. Returns None if data is not available or is inconsistent""" # Return None if data is not available or is inconsistent if self.latest_level == None: return None elif self.typical_range_consistent() == False: return None # Return latest water level as a fraction of the typical range else: return (self.latest_level - self.typical_range[0])/( self.typical_range[1] - self.typical_range[0]) def inconsistent_typical_range_stations(stations): """Returns a list of stations that have inconsistent data. The input is stations, which is a list of MonitoringStation objects.""" # return list of stations with inconsistent data ranges return [station.name for station in stations if station.typical_range_consistent() == False]
"""This module provides a model for a monitoring station, and tools for manipulating/modifying station data """ class Monitoringstation: """This class represents a river level monitoring station""" def __init__(self, station_id, measure_id, label, coord, typical_range, river, town): self.station_id = station_id self.measure_id = measure_id self.name = label if isinstance(label, list): self.name = label[0] self.coord = coord self.typical_range = typical_range self.river = river self.town = town self.latest_level = None def __repr__(self): d = 'Station name: {}\n'.format(self.name) d += ' id: {}\n'.format(self.station_id) d += ' measure id: {}\n'.format(self.measure_id) d += ' coordinate: {}\n'.format(self.coord) d += ' town: {}\n'.format(self.town) d += ' river: {}\n'.format(self.river) d += ' typical range: {}'.format(self.typical_range) return d def typical_range_consistent(self): """Return True if the data is consistent and False if the data is inconsistent or unavailable.""" if self.typical_range == None: return False elif self.typical_range[0] > self.typical_range[1]: return False else: return True def relative_water_level(self): """Returns the latest water level as a fraction of the typical range. Returns None if data is not available or is inconsistent""" if self.latest_level == None: return None elif self.typical_range_consistent() == False: return None else: return (self.latest_level - self.typical_range[0]) / (self.typical_range[1] - self.typical_range[0]) def inconsistent_typical_range_stations(stations): """Returns a list of stations that have inconsistent data. The input is stations, which is a list of MonitoringStation objects.""" return [station.name for station in stations if station.typical_range_consistent() == False]
a = input("Enter the string:") b = a.find("@") c = a.find("#") print("The original string is:",a) print("The substring between @ and # is:",a[b+1:c])
a = input('Enter the string:') b = a.find('@') c = a.find('#') print('The original string is:', a) print('The substring between @ and # is:', a[b + 1:c])
def fahrenheit_to_celsius(F): ''' Function to compute Celsius from Fahrenheit ''' K = fahrenheit_to_kelvin(F) C = kelvin_to_celsius(K) return C
def fahrenheit_to_celsius(F): """ Function to compute Celsius from Fahrenheit """ k = fahrenheit_to_kelvin(F) c = kelvin_to_celsius(K) return C
def read_lines(file_path): with open(file_path, 'r') as handle: return [line.strip() for line in handle] def count_bits(numbers): counts = [0] * len(numbers[0]) for num in numbers: for i, bit in enumerate(num): counts[i] += int(bit) return counts lines = read_lines('test.txt') counts = count_bits(lines) total_lines = len(lines) gamma = [int(c > total_lines/2) for c in counts] epsilon = [int(not bit) for bit in gamma] gamma = int(''.join(str(bit) for bit in gamma), 2) epsilon = int(''.join(str(bit) for bit in epsilon), 2) print(f'Part 1:\n {gamma * epsilon}\n') oxygen_rating = lines co2_rating = lines for i in range(len(oxygen_rating[0])): counts = count_bits(oxygen_rating) total = len(oxygen_rating) more_common_bit = int(counts[i] >= total/2) oxygen_rating = [num for num in oxygen_rating if int(num[i]) == more_common_bit] if len(oxygen_rating) == 1: break for i in range(len(co2_rating[0])): counts = count_bits(co2_rating) total = len(co2_rating) more_common_bit = int(counts[i] >= total/2) co2_rating = [num for num in co2_rating if int(num[i]) != more_common_bit] if len(co2_rating) == 1: break oxygen_rating = int(oxygen_rating[0], 2) co2_rating = int(co2_rating[0], 2) print('Part 2') print(f' Oxygen rating: {oxygen_rating}') print(f' CO2 rating: {co2_rating}') print(' ' + str(oxygen_rating * co2_rating))
def read_lines(file_path): with open(file_path, 'r') as handle: return [line.strip() for line in handle] def count_bits(numbers): counts = [0] * len(numbers[0]) for num in numbers: for (i, bit) in enumerate(num): counts[i] += int(bit) return counts lines = read_lines('test.txt') counts = count_bits(lines) total_lines = len(lines) gamma = [int(c > total_lines / 2) for c in counts] epsilon = [int(not bit) for bit in gamma] gamma = int(''.join((str(bit) for bit in gamma)), 2) epsilon = int(''.join((str(bit) for bit in epsilon)), 2) print(f'Part 1:\n {gamma * epsilon}\n') oxygen_rating = lines co2_rating = lines for i in range(len(oxygen_rating[0])): counts = count_bits(oxygen_rating) total = len(oxygen_rating) more_common_bit = int(counts[i] >= total / 2) oxygen_rating = [num for num in oxygen_rating if int(num[i]) == more_common_bit] if len(oxygen_rating) == 1: break for i in range(len(co2_rating[0])): counts = count_bits(co2_rating) total = len(co2_rating) more_common_bit = int(counts[i] >= total / 2) co2_rating = [num for num in co2_rating if int(num[i]) != more_common_bit] if len(co2_rating) == 1: break oxygen_rating = int(oxygen_rating[0], 2) co2_rating = int(co2_rating[0], 2) print('Part 2') print(f' Oxygen rating: {oxygen_rating}') print(f' CO2 rating: {co2_rating}') print(' ' + str(oxygen_rating * co2_rating))
famous_name = "albert einstein" motto = "A person who never made a mistake never tried anything new." message = famous_name.title() + "once said, " + '"' + motto + '"' print(message)
famous_name = 'albert einstein' motto = 'A person who never made a mistake never tried anything new.' message = famous_name.title() + 'once said, ' + '"' + motto + '"' print(message)
JIRA_DOMAIN = {'RD2': ['innodiv-hwacom.atlassian.net','innodiv-hwacom.atlassian.net'], 'RD5': ['srddiv5-hwacom.atlassian.net']} API_PREFIX = 'rest/agile/1.0' # project_id : column_name STORY_POINT_COL_NAME = {'10005': 'customfield_10027', '10006': 'customfield_10027', '10004': 'customfield_10026' }
jira_domain = {'RD2': ['innodiv-hwacom.atlassian.net', 'innodiv-hwacom.atlassian.net'], 'RD5': ['srddiv5-hwacom.atlassian.net']} api_prefix = 'rest/agile/1.0' story_point_col_name = {'10005': 'customfield_10027', '10006': 'customfield_10027', '10004': 'customfield_10026'}
class PixelMeasurer: def __init__(self, coordinate_store, is_one_calib_block, correction_factor): self.coordinate_store = coordinate_store self.is_one_calib_block = is_one_calib_block self.correction_factor = correction_factor def get_distance(self, calibration_length): distance_per_pixel = calibration_length / self.pixel_distance_calibration() if not self.is_one_calib_block: calibration_difference = float(self.pixel_distance_calibration_side()) / \ float(self.pixel_distance_calibration()) distance_correction = 1 - self.correction_factor*(1 - calibration_difference) return self.pixel_distance_between_wheels() * distance_per_pixel * distance_correction else: return self.pixel_distance_between_wheels() * distance_per_pixel def get_left_wheel_midpoint(self): points = self.coordinate_store.get_left_wheel_points() return int(abs(points[0][0] + points[1][0]) / 2) def get_right_wheel_midpoint(self): points = self.coordinate_store.get_right_wheel_points(is_one_calib_block=self.is_one_calib_block) return int(abs(points[0][0] + points[1][0]) / 2) def pixel_distance_between_wheels(self): return abs(self.get_right_wheel_midpoint() - self.get_left_wheel_midpoint()) def pixel_distance_calibration(self): calibration_points = self.coordinate_store.get_middle_calib_points() return abs(calibration_points[0][0] - calibration_points[1][0]) def pixel_distance_calibration_side(self): calibration_points = self.coordinate_store.get_side_calib_points() return abs(calibration_points[0][0] - calibration_points[1][0])
class Pixelmeasurer: def __init__(self, coordinate_store, is_one_calib_block, correction_factor): self.coordinate_store = coordinate_store self.is_one_calib_block = is_one_calib_block self.correction_factor = correction_factor def get_distance(self, calibration_length): distance_per_pixel = calibration_length / self.pixel_distance_calibration() if not self.is_one_calib_block: calibration_difference = float(self.pixel_distance_calibration_side()) / float(self.pixel_distance_calibration()) distance_correction = 1 - self.correction_factor * (1 - calibration_difference) return self.pixel_distance_between_wheels() * distance_per_pixel * distance_correction else: return self.pixel_distance_between_wheels() * distance_per_pixel def get_left_wheel_midpoint(self): points = self.coordinate_store.get_left_wheel_points() return int(abs(points[0][0] + points[1][0]) / 2) def get_right_wheel_midpoint(self): points = self.coordinate_store.get_right_wheel_points(is_one_calib_block=self.is_one_calib_block) return int(abs(points[0][0] + points[1][0]) / 2) def pixel_distance_between_wheels(self): return abs(self.get_right_wheel_midpoint() - self.get_left_wheel_midpoint()) def pixel_distance_calibration(self): calibration_points = self.coordinate_store.get_middle_calib_points() return abs(calibration_points[0][0] - calibration_points[1][0]) def pixel_distance_calibration_side(self): calibration_points = self.coordinate_store.get_side_calib_points() return abs(calibration_points[0][0] - calibration_points[1][0])
# Programming for the Puzzled -- Srini Devadas # You Will All Conform # Input is a vector of F's and B's, in terms of forwards and backwards caps # Output is a set of commands (printed out) to get either all F's or all B's # Fewest commands are the goal caps = ['F', 'F', 'B', 'B', 'B', 'F', 'B', 'B', 'B', 'F', 'F', 'B', 'F'] cap2 = ['F', 'F', 'B', 'B', 'B', 'F', 'B', 'B', 'B', 'F', 'F', 'F', 'F'] def pleaseConform(caps): # Initialization start = 0 forward = 0 backward = 0 intervals = [] # Determine intervals where caps are on in the same direction for i in range(len(caps)): if caps[start] != caps[i]: # each interval is a tuple with 3 elements (start, end, type) intervals.append((start, i - 1, caps[start])) if caps[start] == 'F': forward += 1 else: backward += 1 start = i # Need to add the last interval after for loop completes execution intervals.append((start, len(caps) - 1, caps[start])) if caps[start] == 'F': forward += 1 else: backward += 1 ## print (intervals) ## print (forward, backward) if forward < backward: flip = 'F' else: flip = 'B' for t in intervals: if t[2] == flip: # Exercise: if t[0] == t[1] change the printing! if t[0] == t[1]: print('Person at position', t[0], 'flip your cap!') else: print('People in positions', t[0], 'through', t[1], 'flip your caps!') pleaseConform(caps) ##pleaseConform(cap2)
caps = ['F', 'F', 'B', 'B', 'B', 'F', 'B', 'B', 'B', 'F', 'F', 'B', 'F'] cap2 = ['F', 'F', 'B', 'B', 'B', 'F', 'B', 'B', 'B', 'F', 'F', 'F', 'F'] def please_conform(caps): start = 0 forward = 0 backward = 0 intervals = [] for i in range(len(caps)): if caps[start] != caps[i]: intervals.append((start, i - 1, caps[start])) if caps[start] == 'F': forward += 1 else: backward += 1 start = i intervals.append((start, len(caps) - 1, caps[start])) if caps[start] == 'F': forward += 1 else: backward += 1 if forward < backward: flip = 'F' else: flip = 'B' for t in intervals: if t[2] == flip: if t[0] == t[1]: print('Person at position', t[0], 'flip your cap!') else: print('People in positions', t[0], 'through', t[1], 'flip your caps!') please_conform(caps)
s=input() t=input() ss=sorted(map(s.count,set(s))) tt=sorted(map(t.count,set(t))) print('Yes' if ss==tt else 'No')
s = input() t = input() ss = sorted(map(s.count, set(s))) tt = sorted(map(t.count, set(t))) print('Yes' if ss == tt else 'No')
def anagrams(word, words): agrams = [] s1 = sorted(word) for i in range (0, len(words)): s2 = sorted(words[i]) if s1 == s2: agrams.append(words[i]) return agrams
def anagrams(word, words): agrams = [] s1 = sorted(word) for i in range(0, len(words)): s2 = sorted(words[i]) if s1 == s2: agrams.append(words[i]) return agrams
#!/usr/bin/env python """ WhatIsCode This extremely simple script was an inspiration driven by a combination of Paul Ford's article on Bloomberg Business Week, "What is Code?"[1] and Haddaway's song, "What is Love"[2]. It is probably best enjoyed while watching an 8-bit demake of the song[3], or 16-bit if you prefer[4]. :-) [1] http://www.bloomberg.com/graphics/2015-paul-ford-what-is-code/ [2] https://en.wikipedia.org/wiki/What_Is_Love_%28Haddaway_song%29 [3] https://www.youtube.com/watch?v=CT8t_1JXWn8 [4] https://www.youtube.com/watch?v=I2ufcU7I9-I Usage Instructions/Examples: In a REPL or other program: # Import the module. from what_is_code import WhatIsCode # Instantiate the object. song = WhatIsCode() # Output the song. song.sing() As a standalone script on the shell: Make sure the script is executable: chmod +x what_is_code.py Run the script: ./what_is_code.py Enjoy! :-) Copyright 2015 Carlo Costino 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. """ class WhatIsCode(object): def __init__(self): """ Initialize the main refrain and verses used throughout the song. """ self.main_refrain = [ 'What is code?', 'Program don\'t crash now', 'Don\'t crash now, again', ] self.first_verse = [ 'I don\'t know why you don\'t work', 'I type things in right, but you just fail', 'So what is True?', 'And what is False?', 'Gimme a break', ] self.second_verse = [ 'Oh, I give up, nothing I do', 'Will work in this app, that I called foo', 'I wrote some tests', 'And they all pass', 'But my app fails', ] self.third_verse = [ 'Can you please just work, just work as I want', 'This is insane, wasted time', 'I thought this was easy, I though this was simple', 'Is it code?', ] @property def secondary_refrain(self): """ The secondary refrain is just the last two parts of the main refrain. """ return self.main_refrain[1:] @property def tertiary_refrain(self): """ A tertiary refrain appears once toward the end of the song made up of a substring of the last line in the main refrain. """ return [self.main_refrain[2][:-7]] * 2 @property def what_is_code(self): """ "What is code?" is repeated many times throughout the song, so let's make it easy to repeat on its own. """ return self.main_refrain[0] def sing_line(self, line=''): """ Outputs a single string with a newline character at the end for proper formatting. """ return '%s\n' % line def sing_lines(self, lines=[]): """ Outputs a list of strings with a newline character at the end of each string, including the last one. """ return '%s\n' % '\n'.join(lines) def sing(self): """ Sings the entire song by printing out every line found within it. Yes, this is brute force and somewhat ugly, but also simple. """ print(self.sing_lines(self.main_refrain)) print(self.sing_lines(self.secondary_refrain)) print(self.sing_line(self.what_is_code)) print('Damn it\n') print(self.sing_lines(self.first_verse)) print(self.sing_lines(self.main_refrain)) print(self.sing_lines(self.main_refrain)) print(self.sing_lines(self.second_verse)) print(self.sing_lines(self.main_refrain)) print(self.sing_lines(self.main_refrain)) print(self.sing_line(self.what_is_code)) print(self.sing_line(self.what_is_code)) print(self.sing_lines(self.main_refrain)) print(self.sing_lines(self.tertiary_refrain)) print(self.sing_lines(self.third_verse)) print(self.sing_lines(self.main_refrain)) print(self.sing_lines(self.main_refrain)) print('Damn\n') print(self.sing_lines(self.main_refrain)) print(self.sing_lines(self.main_refrain)) print(self.sing_lines(self.secondary_refrain)) print(self.sing_lines(self.secondary_refrain)) print(self.sing_line(self.what_is_code)) # If this module is being run as a standalone script, output the song # immediately. if __name__ == '__main__': song = WhatIsCode() song.sing()
""" WhatIsCode This extremely simple script was an inspiration driven by a combination of Paul Ford's article on Bloomberg Business Week, "What is Code?"[1] and Haddaway's song, "What is Love"[2]. It is probably best enjoyed while watching an 8-bit demake of the song[3], or 16-bit if you prefer[4]. :-) [1] http://www.bloomberg.com/graphics/2015-paul-ford-what-is-code/ [2] https://en.wikipedia.org/wiki/What_Is_Love_%28Haddaway_song%29 [3] https://www.youtube.com/watch?v=CT8t_1JXWn8 [4] https://www.youtube.com/watch?v=I2ufcU7I9-I Usage Instructions/Examples: In a REPL or other program: # Import the module. from what_is_code import WhatIsCode # Instantiate the object. song = WhatIsCode() # Output the song. song.sing() As a standalone script on the shell: Make sure the script is executable: chmod +x what_is_code.py Run the script: ./what_is_code.py Enjoy! :-) Copyright 2015 Carlo Costino 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. """ class Whatiscode(object): def __init__(self): """ Initialize the main refrain and verses used throughout the song. """ self.main_refrain = ['What is code?', "Program don't crash now", "Don't crash now, again"] self.first_verse = ["I don't know why you don't work", 'I type things in right, but you just fail', 'So what is True?', 'And what is False?', 'Gimme a break'] self.second_verse = ['Oh, I give up, nothing I do', 'Will work in this app, that I called foo', 'I wrote some tests', 'And they all pass', 'But my app fails'] self.third_verse = ['Can you please just work, just work as I want', 'This is insane, wasted time', 'I thought this was easy, I though this was simple', 'Is it code?'] @property def secondary_refrain(self): """ The secondary refrain is just the last two parts of the main refrain. """ return self.main_refrain[1:] @property def tertiary_refrain(self): """ A tertiary refrain appears once toward the end of the song made up of a substring of the last line in the main refrain. """ return [self.main_refrain[2][:-7]] * 2 @property def what_is_code(self): """ "What is code?" is repeated many times throughout the song, so let's make it easy to repeat on its own. """ return self.main_refrain[0] def sing_line(self, line=''): """ Outputs a single string with a newline character at the end for proper formatting. """ return '%s\n' % line def sing_lines(self, lines=[]): """ Outputs a list of strings with a newline character at the end of each string, including the last one. """ return '%s\n' % '\n'.join(lines) def sing(self): """ Sings the entire song by printing out every line found within it. Yes, this is brute force and somewhat ugly, but also simple. """ print(self.sing_lines(self.main_refrain)) print(self.sing_lines(self.secondary_refrain)) print(self.sing_line(self.what_is_code)) print('Damn it\n') print(self.sing_lines(self.first_verse)) print(self.sing_lines(self.main_refrain)) print(self.sing_lines(self.main_refrain)) print(self.sing_lines(self.second_verse)) print(self.sing_lines(self.main_refrain)) print(self.sing_lines(self.main_refrain)) print(self.sing_line(self.what_is_code)) print(self.sing_line(self.what_is_code)) print(self.sing_lines(self.main_refrain)) print(self.sing_lines(self.tertiary_refrain)) print(self.sing_lines(self.third_verse)) print(self.sing_lines(self.main_refrain)) print(self.sing_lines(self.main_refrain)) print('Damn\n') print(self.sing_lines(self.main_refrain)) print(self.sing_lines(self.main_refrain)) print(self.sing_lines(self.secondary_refrain)) print(self.sing_lines(self.secondary_refrain)) print(self.sing_line(self.what_is_code)) if __name__ == '__main__': song = what_is_code() song.sing()
initialScore = int(input()) def count_solutions(score, turn): if score > 50 or turn > 4: return 0 if score == 50: return 1 result = count_solutions(score + 1, turn + 1) for i in range(2, 13): result += 2 * count_solutions(score + i, turn + 1) return result print(count_solutions(initialScore, 0))
initial_score = int(input()) def count_solutions(score, turn): if score > 50 or turn > 4: return 0 if score == 50: return 1 result = count_solutions(score + 1, turn + 1) for i in range(2, 13): result += 2 * count_solutions(score + i, turn + 1) return result print(count_solutions(initialScore, 0))