content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
option='y' while option=='y': print("Enter the number whose factorial to find") num=int(input()) fac=1 while(num!=1): fac=fac*num num=num-1 print("Factorial is "+str(fac)) print("Do you want to continue?(y/n)") option=input() print('Thank you for using this programme')
option = 'y' while option == 'y': print('Enter the number whose factorial to find') num = int(input()) fac = 1 while num != 1: fac = fac * num num = num - 1 print('Factorial is ' + str(fac)) print('Do you want to continue?(y/n)') option = input() print('Thank you for using this programme')
def poly(a, x): val = 0 for ai in reversed(a): val *= x val += ai return val def diff(a): return [a[i + 1] * (i + 1) for i in range(len(a) - 1)] def divroot(a, x0): b, a[-1] = a[-1], 0 for i in reversed(range(len(a) - 1)): a[i], b = a[i + 1] * x0 + b, a[i] a.pop() return a
def poly(a, x): val = 0 for ai in reversed(a): val *= x val += ai return val def diff(a): return [a[i + 1] * (i + 1) for i in range(len(a) - 1)] def divroot(a, x0): (b, a[-1]) = (a[-1], 0) for i in reversed(range(len(a) - 1)): (a[i], b) = (a[i + 1] * x0 + b, a[i]) a.pop() return a
tickers = [ 'aapl', 'tsla', ]
tickers = ['aapl', 'tsla']
LAMBDA_232 = 4.934E-11#Amelin and Zaitsev, 2002. # LAMBDA_232 = 4.9475E-11 #old value, used in isoplot ERR_LAMBDA_232 = 0.015E-11#Amelin and Zaitsev, 2002. LAMBDA_235 = 9.8485E-10 #ERR_LAMBDA_235 = LAMBDA_238 = 1.55125E-10 #ERR_LAMBDA_238 = U238_U235 = 137.817 #https://doi.org/10.1016/j.gca.2018.06.014 # U238_U235 = 137.88 #old value, used in isoplot ERR_U238_U235 = 0.031 ##https://doi.org/10.1016/j.gca.2018.06.014 lambdas = [LAMBDA_238, LAMBDA_235, LAMBDA_232] isotope_ratios = ["U238_Pb206", "U235_Pb207", "Th232_Pb208", "Pb206_Pb207"] minerals = ["zircon", "baddeleyite", "perovskite", "monazite", "apatite"] EarthAge = 4600 sqrt2pi = 2.506628274631 listColumnNames = ['Th232/Pb208', 'err.Th232/Pb208', '206Pb/207Pb', 'err.206Pb/207Pb', '235U/207Pb', 'err.235U/207Pb', '238U/206Pb', 'err.238U/206Pb', 'corr.', 'Age_232Th/208Pb', 'err.Age_232Th/208Pb', 'Age_206Pb/207Pb', 'err.Age_206Pb/207Pb', 'Age_238U/206Pb', 'err.Age_238U/206Pb', 'Age_235U/207Pb', 'err.Age_235U/207Pb', '%disc.67-86', '%disc.86-57', 'is grain good?']
lambda_232 = 4.934e-11 err_lambda_232 = 1.5e-13 lambda_235 = 9.8485e-10 lambda_238 = 1.55125e-10 u238_u235 = 137.817 err_u238_u235 = 0.031 lambdas = [LAMBDA_238, LAMBDA_235, LAMBDA_232] isotope_ratios = ['U238_Pb206', 'U235_Pb207', 'Th232_Pb208', 'Pb206_Pb207'] minerals = ['zircon', 'baddeleyite', 'perovskite', 'monazite', 'apatite'] earth_age = 4600 sqrt2pi = 2.506628274631 list_column_names = ['Th232/Pb208', 'err.Th232/Pb208', '206Pb/207Pb', 'err.206Pb/207Pb', '235U/207Pb', 'err.235U/207Pb', '238U/206Pb', 'err.238U/206Pb', 'corr.', 'Age_232Th/208Pb', 'err.Age_232Th/208Pb', 'Age_206Pb/207Pb', 'err.Age_206Pb/207Pb', 'Age_238U/206Pb', 'err.Age_238U/206Pb', 'Age_235U/207Pb', 'err.Age_235U/207Pb', '%disc.67-86', '%disc.86-57', 'is grain good?']
# Bar chart # a graph that represents the category of data with rectangular bars with lengths and heights that are proportional # to the values which they represent. # Can be vertical or horizontal. Can also be grouped. # matplotlib fig, ax = plt.subplots(1, figsize=(24,14)) plt.bar(wrestling_count.index, wrestling_count.ID, width=0.9, color='xkcd:plum', edgecolor='ivory', linewidth=0, hatch='-') plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode='anchor') plt.title('\nHUNGARIAN WRESTLERS\n', fontsize=55, loc='left') ax.tick_params(axis='x', size=8, labelsize=26) ax.tick_params(axis='y', size=8, labelsize=26) fig.show() # plotly of the above fig = px.bar( wrestling_count, x='Games', y='ID', labels={'index':'Games'}, title='HUNGARIAN WRESTLERS', text="ID", color="ID", template = "plotly_dark", ) fig.update_traces(textfont_size=12, textangle=0, textposition="outside", cliponaxis=False) fig.show() # horizontal bars y = np.array(winter_games_gold_fs['Games']) x = np.array(winter_games_gold_fs['Age']) fig, ax = plt.subplots(1, figsize=(24,15)) ax.barh(y, x, color='xkcd:darkblue', edgecolor='ivory', linewidth=0, hatch='-') ax.set_yticks(y, labels=winter_games_gold_fs['Games'], fontsize=20) ax.invert_yaxis() ax.set_xlabel('Age', fontsize=35) ax.set_title("\nFREESTYLE SKIER'S AGES -\nGOLD MEDALISTS\n", fontsize=44, loc='left') ax.tick_params(axis='x', labelsize=30) ax.tick_params(axis='y', labelsize=30) plt.show() # plotly of the above fig = px.bar( winter_games_gold_fs, x='Age', y='Games', title="FREESTYLE SKIER'S AGES - GOLD MEDALISTS", text="Age", color="Age", color_continuous_scale='Bluered_r', template = "plotly_dark", orientation="h" ) fig.update_traces(textfont_size=12, textangle=0, textposition="inside", cliponaxis=False) fig.show() # grouped bars fig, ax = plt.subplots(figsize = (30,20)) width = 0.4 labels = gymnists_fn.Year.unique() label_locations = np.arange(len(gymnists_fn.Games.unique())) y_m = np.array(gymnists_fn_m.ID) y_w = np.array(gymnists_fn_w.ID) semi_bar_m = ax.bar(label_locations-width/2, y_m, width, label="M", color='xkcd:brown') semi_bar_w = ax.bar(label_locations+width/2, y_w, width, label="F", color='purple') ax.set_ylabel('Athlete Count', fontsize=30) ax.set_title('\nFRENCH GYMNISTS FROM 1952 \n', fontsize=46, loc='left') ax.set_xticks(label_locations, labels, fontsize=30) ax.tick_params(axis='y', labelsize=26) ax.legend(prop={'size': 36}, shadow=True) ax.bar_label(semi_bar_m, padding=3, fontsize=24) ax.bar_label(semi_bar_w, padding=3, fontsize=24) plt.show() # plotly of the above # done with graph objects fig = go.Figure() fig.add_trace(go.Bar( x=labels, y= y_m, name='Male', marker_color='saddlebrown' )) fig.add_trace(go.Bar( x=labels, y=y_w, name='Female', marker_color='lightsalmon' )) # Here we modify the tickangle of the xaxis, resulting in rotated labels. fig.update_layout(barmode='group', xaxis_tickangle=-45, font=dict(size=18), title="FRENCH GYMNISTS FROM 1952") fig.show()
(fig, ax) = plt.subplots(1, figsize=(24, 14)) plt.bar(wrestling_count.index, wrestling_count.ID, width=0.9, color='xkcd:plum', edgecolor='ivory', linewidth=0, hatch='-') plt.setp(ax.get_xticklabels(), rotation=45, ha='right', rotation_mode='anchor') plt.title('\nHUNGARIAN WRESTLERS\n', fontsize=55, loc='left') ax.tick_params(axis='x', size=8, labelsize=26) ax.tick_params(axis='y', size=8, labelsize=26) fig.show() fig = px.bar(wrestling_count, x='Games', y='ID', labels={'index': 'Games'}, title='HUNGARIAN WRESTLERS', text='ID', color='ID', template='plotly_dark') fig.update_traces(textfont_size=12, textangle=0, textposition='outside', cliponaxis=False) fig.show() y = np.array(winter_games_gold_fs['Games']) x = np.array(winter_games_gold_fs['Age']) (fig, ax) = plt.subplots(1, figsize=(24, 15)) ax.barh(y, x, color='xkcd:darkblue', edgecolor='ivory', linewidth=0, hatch='-') ax.set_yticks(y, labels=winter_games_gold_fs['Games'], fontsize=20) ax.invert_yaxis() ax.set_xlabel('Age', fontsize=35) ax.set_title("\nFREESTYLE SKIER'S AGES -\nGOLD MEDALISTS\n", fontsize=44, loc='left') ax.tick_params(axis='x', labelsize=30) ax.tick_params(axis='y', labelsize=30) plt.show() fig = px.bar(winter_games_gold_fs, x='Age', y='Games', title="FREESTYLE SKIER'S AGES - GOLD MEDALISTS", text='Age', color='Age', color_continuous_scale='Bluered_r', template='plotly_dark', orientation='h') fig.update_traces(textfont_size=12, textangle=0, textposition='inside', cliponaxis=False) fig.show() (fig, ax) = plt.subplots(figsize=(30, 20)) width = 0.4 labels = gymnists_fn.Year.unique() label_locations = np.arange(len(gymnists_fn.Games.unique())) y_m = np.array(gymnists_fn_m.ID) y_w = np.array(gymnists_fn_w.ID) semi_bar_m = ax.bar(label_locations - width / 2, y_m, width, label='M', color='xkcd:brown') semi_bar_w = ax.bar(label_locations + width / 2, y_w, width, label='F', color='purple') ax.set_ylabel('Athlete Count', fontsize=30) ax.set_title('\nFRENCH GYMNISTS FROM 1952 \n', fontsize=46, loc='left') ax.set_xticks(label_locations, labels, fontsize=30) ax.tick_params(axis='y', labelsize=26) ax.legend(prop={'size': 36}, shadow=True) ax.bar_label(semi_bar_m, padding=3, fontsize=24) ax.bar_label(semi_bar_w, padding=3, fontsize=24) plt.show() fig = go.Figure() fig.add_trace(go.Bar(x=labels, y=y_m, name='Male', marker_color='saddlebrown')) fig.add_trace(go.Bar(x=labels, y=y_w, name='Female', marker_color='lightsalmon')) fig.update_layout(barmode='group', xaxis_tickangle=-45, font=dict(size=18), title='FRENCH GYMNISTS FROM 1952') fig.show()
{ "targets": [ { "target_name": "gles3", "sources": [ "src/node-gles3.cpp" ], 'include_dirs': [ 'src', 'src/include' ], 'cflags':[], 'conditions': [ ['OS=="mac"', { 'libraries': [ '-lGLEW', '-framework OpenGL' ], 'include_dirs': [ './node_modules/native-graphics-deps/include' ], 'library_dirs': [ '../node_modules/native-graphics-deps/lib/macos/glew' ], 'xcode_settings': { 'MACOSX_DEPLOYMENT_TARGET': '10.13', 'OTHER_CFLAGS': [ "-Wno-unused-but-set-variable","-Wno-unused-parameter","-Wno-unused-variable","-Wno-int-to-void-pointer-cast" ], } } ], ['OS=="linux"', { 'libraries': [ '-lGLEW','-lGL'] } ], ['OS=="win"', { 'include_dirs': [ './node_modules/native-graphics-deps/include', ], 'library_dirs': [ './node_modules/native-graphics-deps/lib/windows/glew', 'lib/<(target_arch)', ], 'libraries': [ 'glew32.lib', 'opengl32.lib' ], 'defines' : [ 'WIN32_LEAN_AND_MEAN', 'VC_EXTRALEAN' ], 'msvs_settings' : { 'VCCLCompilerTool' : { 'AdditionalOptions' : [] }, 'VCLinkerTool' : { 'AdditionalOptions' : ['/OPT:REF','/OPT:ICF','/LTCG'] }, }, 'copies': [ { 'destination': './build/<(CONFIGURATION_NAME)/', 'files': [ './node_modules/native-graphics-deps/lib/windows/glew/glew32.dll' ] } ], } ], ], }, { "target_name": "glfw3", "sources": [ "src/node-glfw3.cpp" ], 'include_dirs': [ 'src', 'src/include' ], 'cflags':[], 'conditions': [ ['OS=="mac"', { 'libraries': [ '-framework Cocoa', '../node_modules/native-graphics-deps/lib/macos/glfw/libglfw3.a' ], 'include_dirs': [ './node_modules/native-graphics-deps/include' ], 'library_dirs': [ ], 'xcode_settings': { 'MACOSX_DEPLOYMENT_TARGET': '10.13', 'OTHER_CFLAGS': [ "-Wno-unused-but-set-variable","-Wno-unused-parameter","-Wno-unused-variable" ], } } ], ['OS=="linux"', { 'libraries': [] } ], ['OS=="win"', { 'include_dirs': [ './node_modules/native-graphics-deps/include', ], 'library_dirs': [ './node_modules/native-graphics-deps/lib/windows/glfw' ], 'libraries': [ 'glfw3dll.lib' ], 'defines' : [ 'WIN32_LEAN_AND_MEAN', 'VC_EXTRALEAN' ], 'msvs_settings' : { 'VCCLCompilerTool' : { 'AdditionalOptions' : [] }, 'VCLinkerTool' : { 'AdditionalOptions' : ['/OPT:REF','/OPT:ICF','/LTCG'] }, }, 'copies': [ { 'destination': './build/<(CONFIGURATION_NAME)/', 'files': [ './node_modules/native-graphics-deps/lib/windows/glfw/glfw3.dll' ] } ], } ], ], }, { "target_name": "openvr", "sources": [ "src/node-openvr.cpp" ], 'include_dirs': [ './node_modules/native-graphics-deps/include', './node_modules/native-openvr-deps/headers', 'src', 'src/include' ], "cflags": ["-std=c++11", "-Wall", "-pedantic"], 'conditions': [ ['OS=="mac"', { 'libraries': [ ], 'library_dirs': [ ], 'xcode_settings': { 'MACOSX_DEPLOYMENT_TARGET': '10.13', 'OTHER_CFLAGS': [ "-Wno-unused-but-set-variable","-Wno-unused-parameter","-Wno-unused-variable","-Wno-int-to-void-pointer-cast" ], }, 'copies': [ { 'destination': './build/<(CONFIGURATION_NAME)/', 'files': [ './node_modules/native-openvr-deps/lib/osx32/libopenvr_api.dylib' ] } ], } ], ['OS=="linux"', { 'libraries': [ '-lGLEW','-lGL'] } ], ['OS=="win"', { 'library_dirs': [ './node_modules/native-openvr-deps/lib/win64', ], 'libraries': [ 'openvr_api.lib' ], 'defines' : [ 'WIN32_LEAN_AND_MEAN', 'VC_EXTRALEAN' ], 'msvs_settings' : { 'VCCLCompilerTool' : { 'AdditionalOptions' : [] }, 'VCLinkerTool' : { 'AdditionalOptions' : ['/OPT:REF','/OPT:ICF','/LTCG'] }, }, 'copies': [ { 'destination': './build/<(CONFIGURATION_NAME)/', 'files': [ './node_modules/native-openvr-deps/bin/win64/openvr_api.dll' ] } ], } ], ], }, { "target_name": "audio", "sources": [ "src/node-audio.cpp" ], "defines": [], "cflags": ["-std=c++11", "-Wall", "-pedantic"], 'cflags!': [ '-fno-exceptions' ], 'cflags_cc!': [ '-fno-exceptions' ], "include_dirs": [ "<!(node -p \"require('node-addon-api').include_dir\")", "src/miniaudio.h" ], "libraries": [], "dependencies": [], "conditions": [ ['OS=="win"', { 'msvs_settings': { 'VCCLCompilerTool': { 'ExceptionHandling': 1 }, } }], ['OS=="mac"', { 'cflags+': ['-fvisibility=hidden'], 'xcode_settings': { 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', 'CLANG_CXX_LIBRARY': 'libc++', 'MACOSX_DEPLOYMENT_TARGET': '10.7', 'GCC_SYMBOLS_PRIVATE_EXTERN': 'YES', # -fvisibility=hidden }, }], ['OS=="linux"', {}], ], }, { "target_name": "zed", "sources": [], "defines": [], "cflags": ["-std=c++11", "-Wall", "-pedantic"], "include_dirs": [ "<!(node -p \"require('node-addon-api').include_dir\")", ], "libraries": [], "dependencies": [], "conditions": [ ['OS=="win"', { "sources": [ "src/node-zed.cpp" ], 'include_dirs': [ "$(CUDA_PATH)/include", "$(ZED_SDK_ROOT_DIR)/include"], 'library_dirs': [ '$(ZED_SDK_ROOT_DIR)/lib', ], 'libraries': [ 'sl_zed64.lib' ], 'msvs_settings': { 'VCCLCompilerTool': { 'ExceptionHandling': 1 } } }], ['OS=="mac"', { 'cflags+': ['-fvisibility=hidden'], 'xcode_settings': {}, }], ['OS=="linux"', {}], ], }, { "target_name": "realsense", "sources": [ "src/node-realsense.cpp" ], "defines": [], "cflags": ["-std=c++11", "-Wall", "-pedantic"], "include_dirs": [ "<!(node -p \"require('node-addon-api').include_dir\")" ], "libraries": [], "dependencies": [], "conditions": [ ['OS=="win"', { 'include_dirs': [ "C:\\Program Files (x86)\\Intel RealSense SDK 2.0\\include" ], 'library_dirs': [ 'C:\\Program Files (x86)\\Intel RealSense SDK 2.0\\lib\\x64', ], 'libraries': [ '-lrealsense2.lib' ], 'msvs_settings': { 'VCCLCompilerTool': { 'ExceptionHandling': 1 } }, "copies": [{ 'destination': './build/<(CONFIGURATION_NAME)/', 'files': ['C:\\Program Files (x86)\\Intel RealSense SDK 2.0\\bin\\x64\\realsense2.dll'] }] }], ['OS=="mac"', { 'cflags+': ['-fvisibility=hidden'], 'xcode_settings': {}, }], ['OS=="linux"', {}], ], } ] }
{'targets': [{'target_name': 'gles3', 'sources': ['src/node-gles3.cpp'], 'include_dirs': ['src', 'src/include'], 'cflags': [], 'conditions': [['OS=="mac"', {'libraries': ['-lGLEW', '-framework OpenGL'], 'include_dirs': ['./node_modules/native-graphics-deps/include'], 'library_dirs': ['../node_modules/native-graphics-deps/lib/macos/glew'], 'xcode_settings': {'MACOSX_DEPLOYMENT_TARGET': '10.13', 'OTHER_CFLAGS': ['-Wno-unused-but-set-variable', '-Wno-unused-parameter', '-Wno-unused-variable', '-Wno-int-to-void-pointer-cast']}}], ['OS=="linux"', {'libraries': ['-lGLEW', '-lGL']}], ['OS=="win"', {'include_dirs': ['./node_modules/native-graphics-deps/include'], 'library_dirs': ['./node_modules/native-graphics-deps/lib/windows/glew', 'lib/<(target_arch)'], 'libraries': ['glew32.lib', 'opengl32.lib'], 'defines': ['WIN32_LEAN_AND_MEAN', 'VC_EXTRALEAN'], 'msvs_settings': {'VCCLCompilerTool': {'AdditionalOptions': []}, 'VCLinkerTool': {'AdditionalOptions': ['/OPT:REF', '/OPT:ICF', '/LTCG']}}, 'copies': [{'destination': './build/<(CONFIGURATION_NAME)/', 'files': ['./node_modules/native-graphics-deps/lib/windows/glew/glew32.dll']}]}]]}, {'target_name': 'glfw3', 'sources': ['src/node-glfw3.cpp'], 'include_dirs': ['src', 'src/include'], 'cflags': [], 'conditions': [['OS=="mac"', {'libraries': ['-framework Cocoa', '../node_modules/native-graphics-deps/lib/macos/glfw/libglfw3.a'], 'include_dirs': ['./node_modules/native-graphics-deps/include'], 'library_dirs': [], 'xcode_settings': {'MACOSX_DEPLOYMENT_TARGET': '10.13', 'OTHER_CFLAGS': ['-Wno-unused-but-set-variable', '-Wno-unused-parameter', '-Wno-unused-variable']}}], ['OS=="linux"', {'libraries': []}], ['OS=="win"', {'include_dirs': ['./node_modules/native-graphics-deps/include'], 'library_dirs': ['./node_modules/native-graphics-deps/lib/windows/glfw'], 'libraries': ['glfw3dll.lib'], 'defines': ['WIN32_LEAN_AND_MEAN', 'VC_EXTRALEAN'], 'msvs_settings': {'VCCLCompilerTool': {'AdditionalOptions': []}, 'VCLinkerTool': {'AdditionalOptions': ['/OPT:REF', '/OPT:ICF', '/LTCG']}}, 'copies': [{'destination': './build/<(CONFIGURATION_NAME)/', 'files': ['./node_modules/native-graphics-deps/lib/windows/glfw/glfw3.dll']}]}]]}, {'target_name': 'openvr', 'sources': ['src/node-openvr.cpp'], 'include_dirs': ['./node_modules/native-graphics-deps/include', './node_modules/native-openvr-deps/headers', 'src', 'src/include'], 'cflags': ['-std=c++11', '-Wall', '-pedantic'], 'conditions': [['OS=="mac"', {'libraries': [], 'library_dirs': [], 'xcode_settings': {'MACOSX_DEPLOYMENT_TARGET': '10.13', 'OTHER_CFLAGS': ['-Wno-unused-but-set-variable', '-Wno-unused-parameter', '-Wno-unused-variable', '-Wno-int-to-void-pointer-cast']}, 'copies': [{'destination': './build/<(CONFIGURATION_NAME)/', 'files': ['./node_modules/native-openvr-deps/lib/osx32/libopenvr_api.dylib']}]}], ['OS=="linux"', {'libraries': ['-lGLEW', '-lGL']}], ['OS=="win"', {'library_dirs': ['./node_modules/native-openvr-deps/lib/win64'], 'libraries': ['openvr_api.lib'], 'defines': ['WIN32_LEAN_AND_MEAN', 'VC_EXTRALEAN'], 'msvs_settings': {'VCCLCompilerTool': {'AdditionalOptions': []}, 'VCLinkerTool': {'AdditionalOptions': ['/OPT:REF', '/OPT:ICF', '/LTCG']}}, 'copies': [{'destination': './build/<(CONFIGURATION_NAME)/', 'files': ['./node_modules/native-openvr-deps/bin/win64/openvr_api.dll']}]}]]}, {'target_name': 'audio', 'sources': ['src/node-audio.cpp'], 'defines': [], 'cflags': ['-std=c++11', '-Wall', '-pedantic'], 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exceptions'], 'include_dirs': ['<!(node -p "require(\'node-addon-api\').include_dir")', 'src/miniaudio.h'], 'libraries': [], 'dependencies': [], 'conditions': [['OS=="win"', {'msvs_settings': {'VCCLCompilerTool': {'ExceptionHandling': 1}}}], ['OS=="mac"', {'cflags+': ['-fvisibility=hidden'], 'xcode_settings': {'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', 'CLANG_CXX_LIBRARY': 'libc++', 'MACOSX_DEPLOYMENT_TARGET': '10.7', 'GCC_SYMBOLS_PRIVATE_EXTERN': 'YES'}}], ['OS=="linux"', {}]]}, {'target_name': 'zed', 'sources': [], 'defines': [], 'cflags': ['-std=c++11', '-Wall', '-pedantic'], 'include_dirs': ['<!(node -p "require(\'node-addon-api\').include_dir")'], 'libraries': [], 'dependencies': [], 'conditions': [['OS=="win"', {'sources': ['src/node-zed.cpp'], 'include_dirs': ['$(CUDA_PATH)/include', '$(ZED_SDK_ROOT_DIR)/include'], 'library_dirs': ['$(ZED_SDK_ROOT_DIR)/lib'], 'libraries': ['sl_zed64.lib'], 'msvs_settings': {'VCCLCompilerTool': {'ExceptionHandling': 1}}}], ['OS=="mac"', {'cflags+': ['-fvisibility=hidden'], 'xcode_settings': {}}], ['OS=="linux"', {}]]}, {'target_name': 'realsense', 'sources': ['src/node-realsense.cpp'], 'defines': [], 'cflags': ['-std=c++11', '-Wall', '-pedantic'], 'include_dirs': ['<!(node -p "require(\'node-addon-api\').include_dir")'], 'libraries': [], 'dependencies': [], 'conditions': [['OS=="win"', {'include_dirs': ['C:\\Program Files (x86)\\Intel RealSense SDK 2.0\\include'], 'library_dirs': ['C:\\Program Files (x86)\\Intel RealSense SDK 2.0\\lib\\x64'], 'libraries': ['-lrealsense2.lib'], 'msvs_settings': {'VCCLCompilerTool': {'ExceptionHandling': 1}}, 'copies': [{'destination': './build/<(CONFIGURATION_NAME)/', 'files': ['C:\\Program Files (x86)\\Intel RealSense SDK 2.0\\bin\\x64\\realsense2.dll']}]}], ['OS=="mac"', {'cflags+': ['-fvisibility=hidden'], 'xcode_settings': {}}], ['OS=="linux"', {}]]}]}
''' Created on 7 jan. 2013 @author: sander ''' # The following Key ID values are defined by this specification as used # in any packet type that references a Key ID field: # # Name Number Defined in #----------------------------------------------- # None 0 n/a # HMAC-SHA-1-96 1 [RFC2404] # HMAC-SHA-256-128 2 [RFC6234] KEY_ID_NONE = 0 KEY_ID_HMAC_SHA_1_96 = 1 KEY_ID_HMAC_SHA_256_128 = 2
""" Created on 7 jan. 2013 @author: sander """ key_id_none = 0 key_id_hmac_sha_1_96 = 1 key_id_hmac_sha_256_128 = 2
#!/usr/bin/python3 # ref: https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange#Cryptographic_explanation # ref: https://en.wikipedia.org/wiki/RSA_(cryptosystem) shared_modulus = 23 shared_base = 5 print("shared modulus: %s" % shared_modulus) print("shared base: %s" % shared_base) print("-"*40) alice_secret = 4 bob_secret = 3 print("alice's secret key: %s" % alice_secret) print("bob's secret key: %s" % bob_secret) print("-"*40) A = (shared_base**alice_secret) % shared_modulus B = (shared_base**bob_secret) % shared_modulus print("alice's public key: %s" % A) print("bob's public key: %s" % B) print("-"*40) alice_s = (B**alice_secret) % shared_modulus bob_s = (A**bob_secret) % shared_modulus print("alice's shared secret key: %s" % alice_s) print("bob's shared secret key: %s" % bob_s)
shared_modulus = 23 shared_base = 5 print('shared modulus: %s' % shared_modulus) print('shared base: %s' % shared_base) print('-' * 40) alice_secret = 4 bob_secret = 3 print("alice's secret key: %s" % alice_secret) print("bob's secret key: %s" % bob_secret) print('-' * 40) a = shared_base ** alice_secret % shared_modulus b = shared_base ** bob_secret % shared_modulus print("alice's public key: %s" % A) print("bob's public key: %s" % B) print('-' * 40) alice_s = B ** alice_secret % shared_modulus bob_s = A ** bob_secret % shared_modulus print("alice's shared secret key: %s" % alice_s) print("bob's shared secret key: %s" % bob_s)
#!/usr/bin/env python # @Time : 2019-06-03 # @Author : hongshu BUFF_SIZE = 32 * 1024
buff_size = 32 * 1024
# from functools import wraps # def debugMethod(func, cls=None): # '''decorator for debugging passed function''' # @wraps(func) # def wrapper(*args, **kwargs): # print({ # 'class': cls, # class object, not string # 'method': func.__qualname__, # method name, string # 'args': args, # all args, including self # 'kwargs': kwargs # }) # return func(*args, **kwargs) # return wrapper class Meta(type): # def __new__(cls, clsname, bases, clsdict): # obj = super().__new__(cls, clsname, bases, clsdict) # def IS_DUNDER(x): return x.startswith("__") and x.endswith("__") # for item, val in vars(obj).items(): # if callable(val): # # setattr(obj, item, debugMethod(val, cls=cls)) # pass # return obj def __getattribute__(self, name): print({'action': "get", 'attr': name}) return object.__getattribute__(self, name) class A(object, metaclass=Meta): # def __init__(self): # pass # def __setattr__(self, name, value): # print("setting attribute", name, value) # return super().__setattr__(name, value) # def __getattribute__(self, name): # print("getting attribute", name) # return super().__getattribute__(name) def add(self, x, y): return x+y def mul(self, x, y): return x*y a = A() # a.mul(2, 3) # a.mul(0, 100) # a.mul(2, 100) # a.mul(2323, 3) # a.mul(2, 2) # a.mul(2, 3414) # another setter a.x = 200 # print(vars(a)) # # settter # a.x = 1000 # # setter # a.x = "23931903" # # finally a getter # my_getter_val = a.x
class Meta(type): def __getattribute__(self, name): print({'action': 'get', 'attr': name}) return object.__getattribute__(self, name) class A(object, metaclass=Meta): def add(self, x, y): return x + y def mul(self, x, y): return x * y a = a() a.x = 200
class NCBaseError(Exception): def __init__(self, message) -> None: super(NCBaseError, self).__init__(message) class DataTypeMismatchError(Exception): def __init__(self, provided_data, place:str=None, required_data_type:str=None) -> None: message = f"{provided_data} datatype isn't supported for {place}.\nRequired datatype is: {required_data_type}, got: {str(type(provided_data).__name__)}" super(DataTypeMismatchError, self).__init__(message) class InsufficientArgumentsError(Exception): def __init__(self, message): message = f"Insufficient arguments.\n{message}" super(InsufficientArgumentsError, self).__init__(message) class InvalidArgumentsError(Exception): def __init__(self, message:str) -> None: super(InvalidArgumentsError, self).__init__(message) class DirectoryAlreadyExistsError(Exception): def __init__(self,project_dir): message = f"{project_dir} already exists at the location." super(DirectoryAlreadyExistsError, self).__init__(message) class ImportNameNotFoundError(Exception): def __init__(self, location) -> None: message = f"import_name notm provided for the sister app at {location}" super(ImportNameNotFoundError, self).__init__(message) class ConfigurationError(Exception): def __init__(self, message) -> None: super(ConfigurationError, self).__init__(message)
class Ncbaseerror(Exception): def __init__(self, message) -> None: super(NCBaseError, self).__init__(message) class Datatypemismatcherror(Exception): def __init__(self, provided_data, place: str=None, required_data_type: str=None) -> None: message = f"{provided_data} datatype isn't supported for {place}.\nRequired datatype is: {required_data_type}, got: {str(type(provided_data).__name__)}" super(DataTypeMismatchError, self).__init__(message) class Insufficientargumentserror(Exception): def __init__(self, message): message = f'Insufficient arguments.\n{message}' super(InsufficientArgumentsError, self).__init__(message) class Invalidargumentserror(Exception): def __init__(self, message: str) -> None: super(InvalidArgumentsError, self).__init__(message) class Directoryalreadyexistserror(Exception): def __init__(self, project_dir): message = f'{project_dir} already exists at the location.' super(DirectoryAlreadyExistsError, self).__init__(message) class Importnamenotfounderror(Exception): def __init__(self, location) -> None: message = f'import_name notm provided for the sister app at {location}' super(ImportNameNotFoundError, self).__init__(message) class Configurationerror(Exception): def __init__(self, message) -> None: super(ConfigurationError, self).__init__(message)
class Node: def __init__(self, data): self.data= data self.previous= None self.next= None class DoublyLinkedList: def __init__(self): self.head= None def create_list(self, arr): start= self.head n= len(arr) temp= start i=0 while(i<n): new_node= Node(arr[i]) if (i==0): start= new_node temp= start else: temp.next= new_node new_node.prev= temp temp= temp.next i+=1 self.head= start return start def count_elements(self): temp= self.head count=0 while(temp): count+=1 temp=temp.next return count def insert_node(self, value, pos): temp= self.head count_of_elem= self.count_elements() #index is 6, count is 5, valid #index is 7, count is 5, if (count_of_elem+1<pos): return temp new_node= Node(value) if (pos==1): new_node.next= temp temp.previous= new_node self.head= new_node return self.head if (pos==count_of_elem+1): while(temp.next): temp= temp.next temp.next= new_node new_node.previous= temp return self.head counter = 1 while (counter < pos): temp = temp.next counter += 1 node_at_target = temp previous_node = node_at_target.previous previous_node.next = new_node new_node.previous = previous_node new_node.next = node_at_target node_at_target.previous = new_node return self.head def delete_node(self, pos): temp= self.head count_of_elem= self.count_elements() if (count_of_elem<pos): return 'delete position {} is greater than list size {}'.format(pos, count_of_elem) if (pos==1): temp= temp.next self.head=temp return self.head if(pos==count_of_elem): while(temp.next and temp.next.next): temp=temp.next temp.next= None return self.head i=1 while(i<pos-1): temp= temp.next i+=1 prev_node= temp target_node= temp.next next_node= target_node.next next_node.previous= prev_node prev_node.next= next_node return self.head def print_list(self): temp= self.head linked_list= "head=>" while(temp.next): linked_list+= str(temp.data)+"<=>" temp= temp.next linked_list+= str(temp.data) print(linked_list) arr= [1,2,3,4,5] dll= DoublyLinkedList() dll.create_list(arr) dll.print_list() dll.count_elements() dll.insert_node(6,3) dll.print_list() dll.count_elements() dll.insert_node(10000,3) dll.print_list() # dll.delete_node(2) # dll.print_list()
class Node: def __init__(self, data): self.data = data self.previous = None self.next = None class Doublylinkedlist: def __init__(self): self.head = None def create_list(self, arr): start = self.head n = len(arr) temp = start i = 0 while i < n: new_node = node(arr[i]) if i == 0: start = new_node temp = start else: temp.next = new_node new_node.prev = temp temp = temp.next i += 1 self.head = start return start def count_elements(self): temp = self.head count = 0 while temp: count += 1 temp = temp.next return count def insert_node(self, value, pos): temp = self.head count_of_elem = self.count_elements() if count_of_elem + 1 < pos: return temp new_node = node(value) if pos == 1: new_node.next = temp temp.previous = new_node self.head = new_node return self.head if pos == count_of_elem + 1: while temp.next: temp = temp.next temp.next = new_node new_node.previous = temp return self.head counter = 1 while counter < pos: temp = temp.next counter += 1 node_at_target = temp previous_node = node_at_target.previous previous_node.next = new_node new_node.previous = previous_node new_node.next = node_at_target node_at_target.previous = new_node return self.head def delete_node(self, pos): temp = self.head count_of_elem = self.count_elements() if count_of_elem < pos: return 'delete position {} is greater than list size {}'.format(pos, count_of_elem) if pos == 1: temp = temp.next self.head = temp return self.head if pos == count_of_elem: while temp.next and temp.next.next: temp = temp.next temp.next = None return self.head i = 1 while i < pos - 1: temp = temp.next i += 1 prev_node = temp target_node = temp.next next_node = target_node.next next_node.previous = prev_node prev_node.next = next_node return self.head def print_list(self): temp = self.head linked_list = 'head=>' while temp.next: linked_list += str(temp.data) + '<=>' temp = temp.next linked_list += str(temp.data) print(linked_list) arr = [1, 2, 3, 4, 5] dll = doubly_linked_list() dll.create_list(arr) dll.print_list() dll.count_elements() dll.insert_node(6, 3) dll.print_list() dll.count_elements() dll.insert_node(10000, 3) dll.print_list()
# The ranges below are as specified in the Yellow Paper. # Note: range(s, e) excludes e, hence the +1 valid_opcodes = [ *range(0x00, 0x0b + 1), *range(0x10, 0x1d + 1), 0x20, *range(0x30, 0x3f + 1), *range(0x40, 0x48 + 1), *range(0x50, 0x5b + 1), *range(0x60, 0x6f + 1), *range(0x70, 0x7f + 1), *range(0x80, 0x8f + 1), *range(0x90, 0x9f + 1), *range(0xa0, 0xa4 + 1), # Note: 0xfe is considered assigned. *range(0xf0, 0xf5 + 1), 0xfa, 0xfd, 0xfe, 0xff ] # STOP, RETURN, REVERT, INVALID, SELFDESTRUCT terminating_opcodes = [ 0x00, 0xf3, 0xfd, 0xfe, 0xff ] # Only for PUSH1..PUSH32 immediate_sizes = 256 * [0] for opcode in range(0x60, 0x7f + 1): # PUSH1..PUSH32 immediate_sizes[opcode] = opcode - 0x60 + 1 # Fails with assertion on invalid code def validate_code(code: bytes): # Note that EOF1 already asserts this with the code section requirements assert len(code) > 0 opcode = 0 pos = 0 while pos < len(code): # Ensure the opcode is valid opcode = code[pos] pos += 1 assert opcode in valid_opcodes # Skip immediates pos += immediate_sizes[opcode] # Ensure last opcode's immediate doesn't go over code end assert pos == len(code) # opcode is the *last opcode* assert opcode in terminating_opcodes def test_validate_code(code: bytes) -> bool: try: validate_code(code) return True except: return False # Some valid opcodes assert test_validate_code(b'\x30\x00') == True assert test_validate_code(b'\x50\x00') == True assert test_validate_code(b'\xfe\x00') == True assert test_validate_code(b'\xff\x00') == True # PUSHes with valid immediates assert test_validate_code(b'\x60\x00\x00') == True assert test_validate_code(b'\x61' + b'\x00' * 2 + b'\x00') == True assert test_validate_code(b'\x62' + b'\x00' * 3 + b'\x00') == True assert test_validate_code(b'\x63' + b'\x00' * 4 + b'\x00') == True assert test_validate_code(b'\x64' + b'\x00' * 5 + b'\x00') == True assert test_validate_code(b'\x65' + b'\x00' * 6 + b'\x00') == True assert test_validate_code(b'\x66' + b'\x00' * 7 + b'\x00') == True assert test_validate_code(b'\x67' + b'\x00' * 8 + b'\x00') == True assert test_validate_code(b'\x68' + b'\x00' * 9 + b'\x00') == True assert test_validate_code(b'\x69' + b'\x00' * 10 + b'\x00') == True assert test_validate_code(b'\x6a' + b'\x00' * 11 + b'\x00') == True assert test_validate_code(b'\x6b' + b'\x00' * 12 + b'\x00') == True assert test_validate_code(b'\x6c' + b'\x00' * 13 + b'\x00') == True assert test_validate_code(b'\x6d' + b'\x00' * 14 + b'\x00') == True assert test_validate_code(b'\x6e' + b'\x00' * 15 + b'\x00') == True assert test_validate_code(b'\x6f' + b'\x00' * 16 + b'\x00') == True assert test_validate_code(b'\x70' + b'\x00' * 17 + b'\x00') == True assert test_validate_code(b'\x71' + b'\x00' * 18 + b'\x00') == True assert test_validate_code(b'\x72' + b'\x00' * 19 + b'\x00') == True assert test_validate_code(b'\x73' + b'\x00' * 20 + b'\x00') == True assert test_validate_code(b'\x74' + b'\x00' * 21 + b'\x00') == True assert test_validate_code(b'\x75' + b'\x00' * 22 + b'\x00') == True assert test_validate_code(b'\x76' + b'\x00' * 23 + b'\x00') == True assert test_validate_code(b'\x77' + b'\x00' * 24 + b'\x00') == True assert test_validate_code(b'\x78' + b'\x00' * 25 + b'\x00') == True assert test_validate_code(b'\x79' + b'\x00' * 26 + b'\x00') == True assert test_validate_code(b'\x7a' + b'\x00' * 27 + b'\x00') == True assert test_validate_code(b'\x7b' + b'\x00' * 28 + b'\x00') == True assert test_validate_code(b'\x7c' + b'\x00' * 29 + b'\x00') == True assert test_validate_code(b'\x7d' + b'\x00' * 30 + b'\x00') == True assert test_validate_code(b'\x7e' + b'\x00' * 31 + b'\x00') == True assert test_validate_code(b'\x7f' + b'\x00' * 32 + b'\x00') == True # Valid code terminators assert test_validate_code(b'\x00') == True assert test_validate_code(b'\xf3') == True assert test_validate_code(b'\xfd') == True assert test_validate_code(b'\xfe') == True # Empty code assert test_validate_code(b'') == False # Valid opcode, but invalid as terminator assert test_validate_code(b'\x5b') == False # Invalid opcodes assert test_validate_code(b'\x0c\x00') == False assert test_validate_code(b'\x0d\x00') == False assert test_validate_code(b'\x0e\x00') == False assert test_validate_code(b'\x0f\x00') == False assert test_validate_code(b'\x1e\x00') == False assert test_validate_code(b'\x1f\x00') == False assert test_validate_code(b'\x21\x00') == False assert test_validate_code(b'\x22\x00') == False assert test_validate_code(b'\x23\x00') == False assert test_validate_code(b'\x24\x00') == False assert test_validate_code(b'\x25\x00') == False assert test_validate_code(b'\x26\x00') == False assert test_validate_code(b'\x27\x00') == False assert test_validate_code(b'\x28\x00') == False assert test_validate_code(b'\x29\x00') == False assert test_validate_code(b'\x2a\x00') == False assert test_validate_code(b'\x2b\x00') == False assert test_validate_code(b'\x2c\x00') == False assert test_validate_code(b'\x2d\x00') == False assert test_validate_code(b'\x2e\x00') == False assert test_validate_code(b'\x2f\x00') == False assert test_validate_code(b'\x49\x00') == False assert test_validate_code(b'\x4a\x00') == False assert test_validate_code(b'\x4b\x00') == False assert test_validate_code(b'\x4c\x00') == False assert test_validate_code(b'\x4d\x00') == False assert test_validate_code(b'\x4e\x00') == False assert test_validate_code(b'\x4f\x00') == False assert test_validate_code(b'\x5c\x00') == False assert test_validate_code(b'\x5d\x00') == False assert test_validate_code(b'\x5e\x00') == False assert test_validate_code(b'\x5f\x00') == False assert test_validate_code(b'\xa5\x00') == False assert test_validate_code(b'\xa6\x00') == False assert test_validate_code(b'\xa7\x00') == False assert test_validate_code(b'\xa8\x00') == False assert test_validate_code(b'\xa9\x00') == False assert test_validate_code(b'\xaa\x00') == False assert test_validate_code(b'\xab\x00') == False assert test_validate_code(b'\xac\x00') == False assert test_validate_code(b'\xad\x00') == False assert test_validate_code(b'\xae\x00') == False assert test_validate_code(b'\xaf\x00') == False assert test_validate_code(b'\xb0\x00') == False assert test_validate_code(b'\xb1\x00') == False assert test_validate_code(b'\xb2\x00') == False assert test_validate_code(b'\xb3\x00') == False assert test_validate_code(b'\xb4\x00') == False assert test_validate_code(b'\xb5\x00') == False assert test_validate_code(b'\xb6\x00') == False assert test_validate_code(b'\xb7\x00') == False assert test_validate_code(b'\xb8\x00') == False assert test_validate_code(b'\xb9\x00') == False assert test_validate_code(b'\xba\x00') == False assert test_validate_code(b'\xbb\x00') == False assert test_validate_code(b'\xbc\x00') == False assert test_validate_code(b'\xbd\x00') == False assert test_validate_code(b'\xbe\x00') == False assert test_validate_code(b'\xbf\x00') == False assert test_validate_code(b'\xc0\x00') == False assert test_validate_code(b'\xc1\x00') == False assert test_validate_code(b'\xc2\x00') == False assert test_validate_code(b'\xc3\x00') == False assert test_validate_code(b'\xc4\x00') == False assert test_validate_code(b'\xc5\x00') == False assert test_validate_code(b'\xc6\x00') == False assert test_validate_code(b'\xc7\x00') == False assert test_validate_code(b'\xc8\x00') == False assert test_validate_code(b'\xc9\x00') == False assert test_validate_code(b'\xca\x00') == False assert test_validate_code(b'\xcb\x00') == False assert test_validate_code(b'\xcc\x00') == False assert test_validate_code(b'\xcd\x00') == False assert test_validate_code(b'\xce\x00') == False assert test_validate_code(b'\xcf\x00') == False assert test_validate_code(b'\xd0\x00') == False assert test_validate_code(b'\xd1\x00') == False assert test_validate_code(b'\xd2\x00') == False assert test_validate_code(b'\xd3\x00') == False assert test_validate_code(b'\xd4\x00') == False assert test_validate_code(b'\xd5\x00') == False assert test_validate_code(b'\xd6\x00') == False assert test_validate_code(b'\xd7\x00') == False assert test_validate_code(b'\xd8\x00') == False assert test_validate_code(b'\xd9\x00') == False assert test_validate_code(b'\xda\x00') == False assert test_validate_code(b'\xdb\x00') == False assert test_validate_code(b'\xdc\x00') == False assert test_validate_code(b'\xdd\x00') == False assert test_validate_code(b'\xde\x00') == False assert test_validate_code(b'\xdf\x00') == False assert test_validate_code(b'\xe0\x00') == False assert test_validate_code(b'\xe1\x00') == False assert test_validate_code(b'\xe2\x00') == False assert test_validate_code(b'\xe3\x00') == False assert test_validate_code(b'\xe4\x00') == False assert test_validate_code(b'\xe5\x00') == False assert test_validate_code(b'\xe6\x00') == False assert test_validate_code(b'\xe7\x00') == False assert test_validate_code(b'\xe8\x00') == False assert test_validate_code(b'\xe9\x00') == False assert test_validate_code(b'\xea\x00') == False assert test_validate_code(b'\xeb\x00') == False assert test_validate_code(b'\xec\x00') == False assert test_validate_code(b'\xed\x00') == False assert test_validate_code(b'\xee\x00') == False assert test_validate_code(b'\xef\x00') == False assert test_validate_code(b'\xf6\x00') == False assert test_validate_code(b'\xf7\x00') == False assert test_validate_code(b'\xf8\x00') == False assert test_validate_code(b'\xf9\x00') == False assert test_validate_code(b'\xfb\x00') == False assert test_validate_code(b'\xfc\x00') == False # PUSHes with truncated immediates assert test_validate_code(b'\x60\x00') == False assert test_validate_code(b'\x61' + b'\x00' * 1 + b'\x00') == False assert test_validate_code(b'\x62' + b'\x00' * 2 + b'\x00') == False assert test_validate_code(b'\x63' + b'\x00' * 3 + b'\x00') == False assert test_validate_code(b'\x64' + b'\x00' * 4 + b'\x00') == False assert test_validate_code(b'\x65' + b'\x00' * 5 + b'\x00') == False assert test_validate_code(b'\x66' + b'\x00' * 6 + b'\x00') == False assert test_validate_code(b'\x67' + b'\x00' * 7 + b'\x00') == False assert test_validate_code(b'\x68' + b'\x00' * 8 + b'\x00') == False assert test_validate_code(b'\x69' + b'\x00' * 9 + b'\x00') == False assert test_validate_code(b'\x6a' + b'\x00' * 10 + b'\x00') == False assert test_validate_code(b'\x6b' + b'\x00' * 11 + b'\x00') == False assert test_validate_code(b'\x6c' + b'\x00' * 12 + b'\x00') == False assert test_validate_code(b'\x6d' + b'\x00' * 13 + b'\x00') == False assert test_validate_code(b'\x6e' + b'\x00' * 14 + b'\x00') == False assert test_validate_code(b'\x6f' + b'\x00' * 15 + b'\x00') == False assert test_validate_code(b'\x70' + b'\x00' * 16 + b'\x00') == False assert test_validate_code(b'\x71' + b'\x00' * 17 + b'\x00') == False assert test_validate_code(b'\x72' + b'\x00' * 18 + b'\x00') == False assert test_validate_code(b'\x73' + b'\x00' * 19 + b'\x00') == False assert test_validate_code(b'\x74' + b'\x00' * 20 + b'\x00') == False assert test_validate_code(b'\x75' + b'\x00' * 21 + b'\x00') == False assert test_validate_code(b'\x76' + b'\x00' * 22 + b'\x00') == False assert test_validate_code(b'\x77' + b'\x00' * 23 + b'\x00') == False assert test_validate_code(b'\x78' + b'\x00' * 24 + b'\x00') == False assert test_validate_code(b'\x79' + b'\x00' * 25 + b'\x00') == False assert test_validate_code(b'\x7a' + b'\x00' * 26 + b'\x00') == False assert test_validate_code(b'\x7b' + b'\x00' * 27 + b'\x00') == False assert test_validate_code(b'\x7c' + b'\x00' * 28 + b'\x00') == False assert test_validate_code(b'\x7d' + b'\x00' * 29 + b'\x00') == False assert test_validate_code(b'\x7e' + b'\x00' * 30 + b'\x00') == False assert test_validate_code(b'\x7f' + b'\x00' * 31 + b'\x00') == False
valid_opcodes = [*range(0, 11 + 1), *range(16, 29 + 1), 32, *range(48, 63 + 1), *range(64, 72 + 1), *range(80, 91 + 1), *range(96, 111 + 1), *range(112, 127 + 1), *range(128, 143 + 1), *range(144, 159 + 1), *range(160, 164 + 1), *range(240, 245 + 1), 250, 253, 254, 255] terminating_opcodes = [0, 243, 253, 254, 255] immediate_sizes = 256 * [0] for opcode in range(96, 127 + 1): immediate_sizes[opcode] = opcode - 96 + 1 def validate_code(code: bytes): assert len(code) > 0 opcode = 0 pos = 0 while pos < len(code): opcode = code[pos] pos += 1 assert opcode in valid_opcodes pos += immediate_sizes[opcode] assert pos == len(code) assert opcode in terminating_opcodes def test_validate_code(code: bytes) -> bool: try: validate_code(code) return True except: return False assert test_validate_code(b'0\x00') == True assert test_validate_code(b'P\x00') == True assert test_validate_code(b'\xfe\x00') == True assert test_validate_code(b'\xff\x00') == True assert test_validate_code(b'`\x00\x00') == True assert test_validate_code(b'a' + b'\x00' * 2 + b'\x00') == True assert test_validate_code(b'b' + b'\x00' * 3 + b'\x00') == True assert test_validate_code(b'c' + b'\x00' * 4 + b'\x00') == True assert test_validate_code(b'd' + b'\x00' * 5 + b'\x00') == True assert test_validate_code(b'e' + b'\x00' * 6 + b'\x00') == True assert test_validate_code(b'f' + b'\x00' * 7 + b'\x00') == True assert test_validate_code(b'g' + b'\x00' * 8 + b'\x00') == True assert test_validate_code(b'h' + b'\x00' * 9 + b'\x00') == True assert test_validate_code(b'i' + b'\x00' * 10 + b'\x00') == True assert test_validate_code(b'j' + b'\x00' * 11 + b'\x00') == True assert test_validate_code(b'k' + b'\x00' * 12 + b'\x00') == True assert test_validate_code(b'l' + b'\x00' * 13 + b'\x00') == True assert test_validate_code(b'm' + b'\x00' * 14 + b'\x00') == True assert test_validate_code(b'n' + b'\x00' * 15 + b'\x00') == True assert test_validate_code(b'o' + b'\x00' * 16 + b'\x00') == True assert test_validate_code(b'p' + b'\x00' * 17 + b'\x00') == True assert test_validate_code(b'q' + b'\x00' * 18 + b'\x00') == True assert test_validate_code(b'r' + b'\x00' * 19 + b'\x00') == True assert test_validate_code(b's' + b'\x00' * 20 + b'\x00') == True assert test_validate_code(b't' + b'\x00' * 21 + b'\x00') == True assert test_validate_code(b'u' + b'\x00' * 22 + b'\x00') == True assert test_validate_code(b'v' + b'\x00' * 23 + b'\x00') == True assert test_validate_code(b'w' + b'\x00' * 24 + b'\x00') == True assert test_validate_code(b'x' + b'\x00' * 25 + b'\x00') == True assert test_validate_code(b'y' + b'\x00' * 26 + b'\x00') == True assert test_validate_code(b'z' + b'\x00' * 27 + b'\x00') == True assert test_validate_code(b'{' + b'\x00' * 28 + b'\x00') == True assert test_validate_code(b'|' + b'\x00' * 29 + b'\x00') == True assert test_validate_code(b'}' + b'\x00' * 30 + b'\x00') == True assert test_validate_code(b'~' + b'\x00' * 31 + b'\x00') == True assert test_validate_code(b'\x7f' + b'\x00' * 32 + b'\x00') == True assert test_validate_code(b'\x00') == True assert test_validate_code(b'\xf3') == True assert test_validate_code(b'\xfd') == True assert test_validate_code(b'\xfe') == True assert test_validate_code(b'') == False assert test_validate_code(b'[') == False assert test_validate_code(b'\x0c\x00') == False assert test_validate_code(b'\r\x00') == False assert test_validate_code(b'\x0e\x00') == False assert test_validate_code(b'\x0f\x00') == False assert test_validate_code(b'\x1e\x00') == False assert test_validate_code(b'\x1f\x00') == False assert test_validate_code(b'!\x00') == False assert test_validate_code(b'"\x00') == False assert test_validate_code(b'#\x00') == False assert test_validate_code(b'$\x00') == False assert test_validate_code(b'%\x00') == False assert test_validate_code(b'&\x00') == False assert test_validate_code(b"'\x00") == False assert test_validate_code(b'(\x00') == False assert test_validate_code(b')\x00') == False assert test_validate_code(b'*\x00') == False assert test_validate_code(b'+\x00') == False assert test_validate_code(b',\x00') == False assert test_validate_code(b'-\x00') == False assert test_validate_code(b'.\x00') == False assert test_validate_code(b'/\x00') == False assert test_validate_code(b'I\x00') == False assert test_validate_code(b'J\x00') == False assert test_validate_code(b'K\x00') == False assert test_validate_code(b'L\x00') == False assert test_validate_code(b'M\x00') == False assert test_validate_code(b'N\x00') == False assert test_validate_code(b'O\x00') == False assert test_validate_code(b'\\\x00') == False assert test_validate_code(b']\x00') == False assert test_validate_code(b'^\x00') == False assert test_validate_code(b'_\x00') == False assert test_validate_code(b'\xa5\x00') == False assert test_validate_code(b'\xa6\x00') == False assert test_validate_code(b'\xa7\x00') == False assert test_validate_code(b'\xa8\x00') == False assert test_validate_code(b'\xa9\x00') == False assert test_validate_code(b'\xaa\x00') == False assert test_validate_code(b'\xab\x00') == False assert test_validate_code(b'\xac\x00') == False assert test_validate_code(b'\xad\x00') == False assert test_validate_code(b'\xae\x00') == False assert test_validate_code(b'\xaf\x00') == False assert test_validate_code(b'\xb0\x00') == False assert test_validate_code(b'\xb1\x00') == False assert test_validate_code(b'\xb2\x00') == False assert test_validate_code(b'\xb3\x00') == False assert test_validate_code(b'\xb4\x00') == False assert test_validate_code(b'\xb5\x00') == False assert test_validate_code(b'\xb6\x00') == False assert test_validate_code(b'\xb7\x00') == False assert test_validate_code(b'\xb8\x00') == False assert test_validate_code(b'\xb9\x00') == False assert test_validate_code(b'\xba\x00') == False assert test_validate_code(b'\xbb\x00') == False assert test_validate_code(b'\xbc\x00') == False assert test_validate_code(b'\xbd\x00') == False assert test_validate_code(b'\xbe\x00') == False assert test_validate_code(b'\xbf\x00') == False assert test_validate_code(b'\xc0\x00') == False assert test_validate_code(b'\xc1\x00') == False assert test_validate_code(b'\xc2\x00') == False assert test_validate_code(b'\xc3\x00') == False assert test_validate_code(b'\xc4\x00') == False assert test_validate_code(b'\xc5\x00') == False assert test_validate_code(b'\xc6\x00') == False assert test_validate_code(b'\xc7\x00') == False assert test_validate_code(b'\xc8\x00') == False assert test_validate_code(b'\xc9\x00') == False assert test_validate_code(b'\xca\x00') == False assert test_validate_code(b'\xcb\x00') == False assert test_validate_code(b'\xcc\x00') == False assert test_validate_code(b'\xcd\x00') == False assert test_validate_code(b'\xce\x00') == False assert test_validate_code(b'\xcf\x00') == False assert test_validate_code(b'\xd0\x00') == False assert test_validate_code(b'\xd1\x00') == False assert test_validate_code(b'\xd2\x00') == False assert test_validate_code(b'\xd3\x00') == False assert test_validate_code(b'\xd4\x00') == False assert test_validate_code(b'\xd5\x00') == False assert test_validate_code(b'\xd6\x00') == False assert test_validate_code(b'\xd7\x00') == False assert test_validate_code(b'\xd8\x00') == False assert test_validate_code(b'\xd9\x00') == False assert test_validate_code(b'\xda\x00') == False assert test_validate_code(b'\xdb\x00') == False assert test_validate_code(b'\xdc\x00') == False assert test_validate_code(b'\xdd\x00') == False assert test_validate_code(b'\xde\x00') == False assert test_validate_code(b'\xdf\x00') == False assert test_validate_code(b'\xe0\x00') == False assert test_validate_code(b'\xe1\x00') == False assert test_validate_code(b'\xe2\x00') == False assert test_validate_code(b'\xe3\x00') == False assert test_validate_code(b'\xe4\x00') == False assert test_validate_code(b'\xe5\x00') == False assert test_validate_code(b'\xe6\x00') == False assert test_validate_code(b'\xe7\x00') == False assert test_validate_code(b'\xe8\x00') == False assert test_validate_code(b'\xe9\x00') == False assert test_validate_code(b'\xea\x00') == False assert test_validate_code(b'\xeb\x00') == False assert test_validate_code(b'\xec\x00') == False assert test_validate_code(b'\xed\x00') == False assert test_validate_code(b'\xee\x00') == False assert test_validate_code(b'\xef\x00') == False assert test_validate_code(b'\xf6\x00') == False assert test_validate_code(b'\xf7\x00') == False assert test_validate_code(b'\xf8\x00') == False assert test_validate_code(b'\xf9\x00') == False assert test_validate_code(b'\xfb\x00') == False assert test_validate_code(b'\xfc\x00') == False assert test_validate_code(b'`\x00') == False assert test_validate_code(b'a' + b'\x00' * 1 + b'\x00') == False assert test_validate_code(b'b' + b'\x00' * 2 + b'\x00') == False assert test_validate_code(b'c' + b'\x00' * 3 + b'\x00') == False assert test_validate_code(b'd' + b'\x00' * 4 + b'\x00') == False assert test_validate_code(b'e' + b'\x00' * 5 + b'\x00') == False assert test_validate_code(b'f' + b'\x00' * 6 + b'\x00') == False assert test_validate_code(b'g' + b'\x00' * 7 + b'\x00') == False assert test_validate_code(b'h' + b'\x00' * 8 + b'\x00') == False assert test_validate_code(b'i' + b'\x00' * 9 + b'\x00') == False assert test_validate_code(b'j' + b'\x00' * 10 + b'\x00') == False assert test_validate_code(b'k' + b'\x00' * 11 + b'\x00') == False assert test_validate_code(b'l' + b'\x00' * 12 + b'\x00') == False assert test_validate_code(b'm' + b'\x00' * 13 + b'\x00') == False assert test_validate_code(b'n' + b'\x00' * 14 + b'\x00') == False assert test_validate_code(b'o' + b'\x00' * 15 + b'\x00') == False assert test_validate_code(b'p' + b'\x00' * 16 + b'\x00') == False assert test_validate_code(b'q' + b'\x00' * 17 + b'\x00') == False assert test_validate_code(b'r' + b'\x00' * 18 + b'\x00') == False assert test_validate_code(b's' + b'\x00' * 19 + b'\x00') == False assert test_validate_code(b't' + b'\x00' * 20 + b'\x00') == False assert test_validate_code(b'u' + b'\x00' * 21 + b'\x00') == False assert test_validate_code(b'v' + b'\x00' * 22 + b'\x00') == False assert test_validate_code(b'w' + b'\x00' * 23 + b'\x00') == False assert test_validate_code(b'x' + b'\x00' * 24 + b'\x00') == False assert test_validate_code(b'y' + b'\x00' * 25 + b'\x00') == False assert test_validate_code(b'z' + b'\x00' * 26 + b'\x00') == False assert test_validate_code(b'{' + b'\x00' * 27 + b'\x00') == False assert test_validate_code(b'|' + b'\x00' * 28 + b'\x00') == False assert test_validate_code(b'}' + b'\x00' * 29 + b'\x00') == False assert test_validate_code(b'~' + b'\x00' * 30 + b'\x00') == False assert test_validate_code(b'\x7f' + b'\x00' * 31 + b'\x00') == False
QUESTIONS = { 'a1': { 'Q': 'What is the chemical symbol for gold?', 'A': 'au' }, 'a2': { 'Q': '', 'A': '' }, 'a3': { 'Q': '', 'A': '' }, 'a4': { 'Q': '', 'A': '' }, 'b1': { 'Q': '', 'A': '' }, 'b2': { 'Q': '', 'A': '' }, 'b3': { 'Q': '', 'A': '' }, 'b4': { 'Q': '', 'A': '' }, 'c1': { 'Q': '', 'A': '' }, 'c2': { 'Q': '', 'A': '' }, 'c3': { 'Q': '', 'A': '' }, 'c4': { 'Q': '', 'A': '' }, 'd1': { 'Q': '', 'A': '' }, 'd2': { 'Q': '', 'A': '' }, 'd3': { 'Q': '', 'A': '' }, 'd4': { 'Q': '', 'A': '' }, }
questions = {'a1': {'Q': 'What is the chemical symbol for gold?', 'A': 'au'}, 'a2': {'Q': '', 'A': ''}, 'a3': {'Q': '', 'A': ''}, 'a4': {'Q': '', 'A': ''}, 'b1': {'Q': '', 'A': ''}, 'b2': {'Q': '', 'A': ''}, 'b3': {'Q': '', 'A': ''}, 'b4': {'Q': '', 'A': ''}, 'c1': {'Q': '', 'A': ''}, 'c2': {'Q': '', 'A': ''}, 'c3': {'Q': '', 'A': ''}, 'c4': {'Q': '', 'A': ''}, 'd1': {'Q': '', 'A': ''}, 'd2': {'Q': '', 'A': ''}, 'd3': {'Q': '', 'A': ''}, 'd4': {'Q': '', 'A': ''}}
#!/usr/bin/python3 ''' Collects Weather Forecast by Indian Meterological Department, by parsing webpages :) ''' __version__ = '0.2.0' __author__ = 'Anjan Roy<[email protected]>'
""" Collects Weather Forecast by Indian Meterological Department, by parsing webpages :) """ __version__ = '0.2.0' __author__ = 'Anjan Roy<[email protected]>'
# Contains all the basic info about awards class Award: count = 0 def __init__(self, url, number, name, type, application, restrictions, renewable, value, due, description, sequence): self.url = url self.number = number self.name = name self.type = type self.application = application self.restrictions = restrictions self.renewable = renewable self.value = value self.due = due self.description = description self.sequence = sequence Award.count += 1 def displayCount(self): return "There are a total of %d awards" % Award.count def displayAward(self): return "Award Number: ", self.number, ", Name: ", self.name, ", Type: ", self.type, ", Application: ", self.application, ", Restrictions: ", self.restrictions, ", Renewable: ", self.renewable, ", Value: ", self.value, ", Due Day: ", self.due, ", description: ", self.description, ", URL: ", self.url
class Award: count = 0 def __init__(self, url, number, name, type, application, restrictions, renewable, value, due, description, sequence): self.url = url self.number = number self.name = name self.type = type self.application = application self.restrictions = restrictions self.renewable = renewable self.value = value self.due = due self.description = description self.sequence = sequence Award.count += 1 def display_count(self): return 'There are a total of %d awards' % Award.count def display_award(self): return ('Award Number: ', self.number, ', Name: ', self.name, ', Type: ', self.type, ', Application: ', self.application, ', Restrictions: ', self.restrictions, ', Renewable: ', self.renewable, ', Value: ', self.value, ', Due Day: ', self.due, ', description: ', self.description, ', URL: ', self.url)
class Solution: def dailyTemperatures(self, T: List[int]) -> List[int]: warmer_day = [0]*len(T) recent_day = [2**31-1]*101 MAXLEN = 30000 for i in range(len(T)-1, -1, -1): minday = 2**31-1 for warmer_temp in range(T[i]+1, 101): if recent_day[warmer_temp] <= MAXLEN: minday = min(minday, recent_day[warmer_temp]-i) if minday <= MAXLEN: warmer_day[i] = minday recent_day[T[i]] = i return warmer_day
class Solution: def daily_temperatures(self, T: List[int]) -> List[int]: warmer_day = [0] * len(T) recent_day = [2 ** 31 - 1] * 101 maxlen = 30000 for i in range(len(T) - 1, -1, -1): minday = 2 ** 31 - 1 for warmer_temp in range(T[i] + 1, 101): if recent_day[warmer_temp] <= MAXLEN: minday = min(minday, recent_day[warmer_temp] - i) if minday <= MAXLEN: warmer_day[i] = minday recent_day[T[i]] = i return warmer_day
# encoding: utf-8 class Animals(object): def __init__(self, sound): self.sound = sound def speak(self): return self.sound
class Animals(object): def __init__(self, sound): self.sound = sound def speak(self): return self.sound
# Copyright 2021 Nokia # Licensed under the BSD 3-Clause License. # SPDX-License-Identifier: BSD-3-Clause class ApiVersion(object): def __init__(self, group: str, version: str): self.group = group self.version = version class Kind(ApiVersion): def __init__(self, group: str, version: str, kind: str): super().__init__(group, version) self.kind = kind class Resource(ApiVersion): def __init__(self, group: str, version: str, kind: str): super().__init__(group, version) self.resource = kind def parse_api_version(api_version: str) -> ApiVersion: if '/' in api_version: return ApiVersion(*api_version.split('/', 1)) return ApiVersion('', api_version)
class Apiversion(object): def __init__(self, group: str, version: str): self.group = group self.version = version class Kind(ApiVersion): def __init__(self, group: str, version: str, kind: str): super().__init__(group, version) self.kind = kind class Resource(ApiVersion): def __init__(self, group: str, version: str, kind: str): super().__init__(group, version) self.resource = kind def parse_api_version(api_version: str) -> ApiVersion: if '/' in api_version: return api_version(*api_version.split('/', 1)) return api_version('', api_version)
_base_ = '../cascade_rcnn/cascade_mask_rcnn_r50_fpn_mstrain_3x_coco.py' model = dict( backbone=dict( type='ResNeXt', depth=101, groups=32, base_width=8, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=False), style='pytorch', init_cfg=dict( type='Pretrained', checkpoint='open-mmlab://detectron2/resnext101_32x8d')), roi_head=dict( _delete_=True, type='KeypointCascadeRoIHead', output_heatmaps=False, keypoint_decoder=dict(type='HeatmapDecodeOneKeypoint', upscale=4), num_keypoints=5, num_stages=3, stage_loss_weights=[1, 0.5, 0.25], bbox_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32]), bbox_head=[ dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.1, 0.1, 0.2, 0.2]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.05, 0.05, 0.1, 0.1]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), dict( type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0., 0., 0., 0.], target_stds=[0.033, 0.033, 0.067, 0.067]), reg_class_agnostic=True, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)) ], mask_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32]), mask_head=dict( type='FCNMaskHead', num_convs=4, in_channels=256, conv_out_channels=256, num_classes=80, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0))) )
_base_ = '../cascade_rcnn/cascade_mask_rcnn_r50_fpn_mstrain_3x_coco.py' model = dict(backbone=dict(type='ResNeXt', depth=101, groups=32, base_width=8, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=False), style='pytorch', init_cfg=dict(type='Pretrained', checkpoint='open-mmlab://detectron2/resnext101_32x8d')), roi_head=dict(_delete_=True, type='KeypointCascadeRoIHead', output_heatmaps=False, keypoint_decoder=dict(type='HeatmapDecodeOneKeypoint', upscale=4), num_keypoints=5, num_stages=3, stage_loss_weights=[1, 0.5, 0.25], bbox_roi_extractor=dict(type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32]), bbox_head=[dict(type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict(type='DeltaXYWHBBoxCoder', target_means=[0.0, 0.0, 0.0, 0.0], target_stds=[0.1, 0.1, 0.2, 0.2]), reg_class_agnostic=True, loss_cls=dict(type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), dict(type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict(type='DeltaXYWHBBoxCoder', target_means=[0.0, 0.0, 0.0, 0.0], target_stds=[0.05, 0.05, 0.1, 0.1]), reg_class_agnostic=True, loss_cls=dict(type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0)), dict(type='Shared2FCBBoxHead', in_channels=256, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict(type='DeltaXYWHBBoxCoder', target_means=[0.0, 0.0, 0.0, 0.0], target_stds=[0.033, 0.033, 0.067, 0.067]), reg_class_agnostic=True, loss_cls=dict(type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0))], mask_roi_extractor=dict(type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32]), mask_head=dict(type='FCNMaskHead', num_convs=4, in_channels=256, conv_out_channels=256, num_classes=80, loss_mask=dict(type='CrossEntropyLoss', use_mask=True, loss_weight=1.0))))
def find_missing(S): if len(S) > 0: m = max(S) vals = [ 0 for i in range(m)] for x in S: if x < 0: print("Warning {} is <0. Ignoring it.".format(x)) else: vals[x-1] += 1 return [x+1 for x in range(m) if vals[x] == 0] else: print("Warning: list is empty. Returning None") if __name__ == "__main__": S = [1,9,7, 7, 4, 3, 3, 3] S1 = list(range(10)) print(find_missing(S)) print(find_missing(S1)) print(find_missing([])) S2 = [1, -72, 4, -3, -3, 3,10] M = find_missing(S2) print(M)
def find_missing(S): if len(S) > 0: m = max(S) vals = [0 for i in range(m)] for x in S: if x < 0: print('Warning {} is <0. Ignoring it.'.format(x)) else: vals[x - 1] += 1 return [x + 1 for x in range(m) if vals[x] == 0] else: print('Warning: list is empty. Returning None') if __name__ == '__main__': s = [1, 9, 7, 7, 4, 3, 3, 3] s1 = list(range(10)) print(find_missing(S)) print(find_missing(S1)) print(find_missing([])) s2 = [1, -72, 4, -3, -3, 3, 10] m = find_missing(S2) print(M)
def solution(inpnum): upnum = int(str(9)*inpnum) lownum = int(str(1)+(str(0)*(inpnum-1))) ansnum = None for i in range(upnum,lownum,-1): if len(str(i))==len(set(str(i))): if 2**(i-1)%i==1: ansnum = i break return ansnum
def solution(inpnum): upnum = int(str(9) * inpnum) lownum = int(str(1) + str(0) * (inpnum - 1)) ansnum = None for i in range(upnum, lownum, -1): if len(str(i)) == len(set(str(i))): if 2 ** (i - 1) % i == 1: ansnum = i break return ansnum
class Solution: def toHex(self, num: int) -> str: if num == 0: return '0' chars, result = '0123456789abcdef', [] if num < 0: num += (1 << 32) while num > 0: result.insert(0, chars[num % 16]) num //= 16 return ''.join(result)
class Solution: def to_hex(self, num: int) -> str: if num == 0: return '0' (chars, result) = ('0123456789abcdef', []) if num < 0: num += 1 << 32 while num > 0: result.insert(0, chars[num % 16]) num //= 16 return ''.join(result)
# Space: O(1) # Time: O(n) # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def diameterOfBinaryTree(self, root): self.res = 0 self.dfs(root) return self.res def dfs(self, root): if root is None: return 0 left, right = 0, 0 if root.left: left = self.dfs(root.left) + 1 if root.right: right = self.dfs(root.right) + 1 self.res = max(self.res, left + right) return max(left, right)
class Solution: def diameter_of_binary_tree(self, root): self.res = 0 self.dfs(root) return self.res def dfs(self, root): if root is None: return 0 (left, right) = (0, 0) if root.left: left = self.dfs(root.left) + 1 if root.right: right = self.dfs(root.right) + 1 self.res = max(self.res, left + right) return max(left, right)
try: n = int(input("Enter number")) print(n*n) except: print("Non integer entered")
try: n = int(input('Enter number')) print(n * n) except: print('Non integer entered')
height = int(input()) for i in range(0,height+1): for j in range(0,i+1): if(j == i): print(i,end=" ") else: print("*",end=" ") print() # Sample Input :- 5 # Output :- # 0 # * 1 # * * 2 # * * * 3 # * * * * 4 # * * * * * 5
height = int(input()) for i in range(0, height + 1): for j in range(0, i + 1): if j == i: print(i, end=' ') else: print('*', end=' ') print()
statement_one = False statement_two = True credits = 120 gpa = 1.8 if not credits >= 120: print('You do not have enough credits to graduate.') if not gpa >= 2.0: print('Your GPA is not high enough to graduate.') if not (credits >= 120) and not (gpa >= 2.0): print('You do not meet either requirement to graduate!')
statement_one = False statement_two = True credits = 120 gpa = 1.8 if not credits >= 120: print('You do not have enough credits to graduate.') if not gpa >= 2.0: print('Your GPA is not high enough to graduate.') if not credits >= 120 and (not gpa >= 2.0): print('You do not meet either requirement to graduate!')
LOCALHOST_EQUIVALENTS = frozenset(( 'localhost', '127.0.0.1', '0.0.0.0', '0:0:0:0:0:0:0:0', '0:0:0:0:0:0:0:1', '::1', '::', ))
localhost_equivalents = frozenset(('localhost', '127.0.0.1', '0.0.0.0', '0:0:0:0:0:0:0:0', '0:0:0:0:0:0:0:1', '::1', '::'))
count = int(input()) for i in range(count): print("@"*(count*5)) for i in range(count*3): print("@"*(count)," "*(count*3),"@"*(count),sep="") for i in range(count): print("@"*(count*5))
count = int(input()) for i in range(count): print('@' * (count * 5)) for i in range(count * 3): print('@' * count, ' ' * (count * 3), '@' * count, sep='') for i in range(count): print('@' * (count * 5))
a = input("Enter some list of numbers =") for i in a: print(i) print(type(a))
a = input('Enter some list of numbers =') for i in a: print(i) print(type(a))
# Cache bitcode CACHE = False # Save object file for module ASM = False # Write LLVM dump to file DUMP = True # Enable AST debugging dump DEBUG = True # Write dump files to same directory as module? # if False, this will write all dumps to one "debug" file in the main dir DUMP_TO_DIR = False
cache = False asm = False dump = True debug = True dump_to_dir = False
''' Common settings for using in a project scope ''' MODEL_ZIP_FILE_NAME_ENV_VAR = 'TF_AWS_MODEL_ZIP_FILE_NAME' MODEL_PROTOBUF_FILE_NAME_ENV_VAR = 'TF_AWS_MODEL_PROTOBUF_FILE_NAME' S3_MODEL_BUCKET_NAME_ENV_VAR = 'TF_AWS_S3_MODEL_BUCKET_NAME'
""" Common settings for using in a project scope """ model_zip_file_name_env_var = 'TF_AWS_MODEL_ZIP_FILE_NAME' model_protobuf_file_name_env_var = 'TF_AWS_MODEL_PROTOBUF_FILE_NAME' s3_model_bucket_name_env_var = 'TF_AWS_S3_MODEL_BUCKET_NAME'
expected_output = { 'pid': 'CISCO3945-CHASSIS', 'os': 'ios', 'platform': 'c3900', 'version': '15.0(1)M7', }
expected_output = {'pid': 'CISCO3945-CHASSIS', 'os': 'ios', 'platform': 'c3900', 'version': '15.0(1)M7'}
class RobertException(Exception): def __init__(self, message: str = None): message = 'An fatal error has occurred' if message is None else message super().__init__(message) class LanguageNotSupported(RobertException): def __init__(self): super().__init__('That language is not supported') class UnknownSafeSearchType(RobertException): def __init__(self, type): super().__init__(f'Safe search {type} does not exist')
class Robertexception(Exception): def __init__(self, message: str=None): message = 'An fatal error has occurred' if message is None else message super().__init__(message) class Languagenotsupported(RobertException): def __init__(self): super().__init__('That language is not supported') class Unknownsafesearchtype(RobertException): def __init__(self, type): super().__init__(f'Safe search {type} does not exist')
# TODO: Use these simplified dataclasses once support for Python 3.6 is # dropped. Meanwhile we'll use the "polyfill" classes defined below. # # from dataclasses import dataclass, field # # @dataclass # class Client: # user_id: str # user_type: str = field(default="client", init=False) # # # @dataclass # class Team: # user_id: str # user_type: str = field(default="team", init=False) # # # @dataclass # class User: # user_id: str # user_type: str = field(default="user", init=False) class Client: user_id: str user_type: str def __init__(self, user_id): self.user_id = user_id self.user_type = "client" class Team: user_id: str user_type: str def __init__(self, user_id): self.user_id = user_id self.user_type = "team" class User: user_id: str user_type: str def __init__(self, user_id): self.user_id = user_id self.user_type = "user" def asdict(obj): return obj.__dict__
class Client: user_id: str user_type: str def __init__(self, user_id): self.user_id = user_id self.user_type = 'client' class Team: user_id: str user_type: str def __init__(self, user_id): self.user_id = user_id self.user_type = 'team' class User: user_id: str user_type: str def __init__(self, user_id): self.user_id = user_id self.user_type = 'user' def asdict(obj): return obj.__dict__
add = 3+2 print (add) subtract = 3-2 print (subtract) multiply = 3*2 print (multiply) division = 3/2 print (division) modulus = 3%2 print (modulus) lessThan = 3<2 print (lessThan) greaterThan = 3>2 print(greaterThan) equals = 3==3 print (equals) logicalAnd = (2==2) and (3==3) and (4==4) print (logicalAnd) logicalOr = (2==1) or (2==2) or (2==3) print (logicalOr) logicalNot = not (3==2) print (logicalNot)
add = 3 + 2 print(add) subtract = 3 - 2 print(subtract) multiply = 3 * 2 print(multiply) division = 3 / 2 print(division) modulus = 3 % 2 print(modulus) less_than = 3 < 2 print(lessThan) greater_than = 3 > 2 print(greaterThan) equals = 3 == 3 print(equals) logical_and = 2 == 2 and 3 == 3 and (4 == 4) print(logicalAnd) logical_or = 2 == 1 or 2 == 2 or 2 == 3 print(logicalOr) logical_not = not 3 == 2 print(logicalNot)
#!/usr/bin/env python3 #variable delaration names = [] address = [] age = [] institute = [] dept = [] print('------+++++++Welcome to student info software+++++++------\n') names.insert(0, input('Enter your Full name: ')) address.insert(0, input('Enter your Address: ')) age.insert(0, input('Enter your Age: ')) institute.insert(0, input('Enter your School: ')) dept.insert(0, input('Enter your Departiment: ')) print('\n\n') print('-----+++++Your information is below+++++-----\n') print("Name is: {} \nAddress is: {} \nAge is: {} \nInstitute is: {} \nDept is: {}".format(names,address,age,institute,dept))
names = [] address = [] age = [] institute = [] dept = [] print('------+++++++Welcome to student info software+++++++------\n') names.insert(0, input('Enter your Full name: ')) address.insert(0, input('Enter your Address: ')) age.insert(0, input('Enter your Age: ')) institute.insert(0, input('Enter your School: ')) dept.insert(0, input('Enter your Departiment: ')) print('\n\n') print('-----+++++Your information is below+++++-----\n') print('Name is: {} \nAddress is: {} \nAge is: {} \nInstitute is: {} \nDept is: {}'.format(names, address, age, institute, dept))
def valid_palindrome(str): left, right = 0, len(str) - 1 while left < right: if not str[left].isalnum(): left += 1 elif not str[right].isalnum(): right -= 1 else: if str[left].lower() != str[right].lower(): print('False') return False else: left += 1 right -= 1 print('True') return True test = "A man, a plan, a canal: Panama" valid_palindrome(test)
def valid_palindrome(str): (left, right) = (0, len(str) - 1) while left < right: if not str[left].isalnum(): left += 1 elif not str[right].isalnum(): right -= 1 elif str[left].lower() != str[right].lower(): print('False') return False else: left += 1 right -= 1 print('True') return True test = 'A man, a plan, a canal: Panama' valid_palindrome(test)
{ 4 : { "operator" : "aggregation", "numgroups" : 1000000 } }
{4: {'operator': 'aggregation', 'numgroups': 1000000}}
def get_numbers_between(set_a, set_b): numbers_between = 0 for candidate in range(1, 101): found = True for item in set_a: if candidate % item: found = False break if not found: continue for item in set_b: if item % candidate: found = False break if found: numbers_between += 1 return numbers_between if __name__ == "__main__": n, m = input().strip().split(' ') n, m = [int(n), int(m)] a = list(map(int, input().strip().split(' '))) b = list(map(int, input().strip().split(' '))) total = get_numbers_between(a, b) print(total)
def get_numbers_between(set_a, set_b): numbers_between = 0 for candidate in range(1, 101): found = True for item in set_a: if candidate % item: found = False break if not found: continue for item in set_b: if item % candidate: found = False break if found: numbers_between += 1 return numbers_between if __name__ == '__main__': (n, m) = input().strip().split(' ') (n, m) = [int(n), int(m)] a = list(map(int, input().strip().split(' '))) b = list(map(int, input().strip().split(' '))) total = get_numbers_between(a, b) print(total)
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") def python_dependencies_early(): http_archive( name = "rules_python", url = "https://github.com/bazelbuild/rules_python/releases/download/0.0.1/rules_python-0.0.1.tar.gz", sha256 = "aa96a691d3a8177f3215b14b0edc9641787abaaa30363a080165d06ab65e1161", )
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive') def python_dependencies_early(): http_archive(name='rules_python', url='https://github.com/bazelbuild/rules_python/releases/download/0.0.1/rules_python-0.0.1.tar.gz', sha256='aa96a691d3a8177f3215b14b0edc9641787abaaa30363a080165d06ab65e1161')
# Pow(x, n): https://leetcode.com/problems/powx-n/ # Implement pow(x, n), which calculates x raised to the power n (i.e., xn). # This problem is pretty straight forward we simply iterate over the n times # multiplying the input every time. The only tricky thing is that if we have # a negative number we need to make sure to set it to 1/x before multiplying together class Solution: def myPow(self, x: float, n: int) -> float: if n == 0: return 1.0 if x == 0: return 0 if n < 0: x = 1/x n *= -1 result = 1 for _ in range(n): result *= x return result # The above works! The code runs in o(N) steps and uses o(1) space the problem is this isn't the fastest we can do! # This is based off of the math that 2 ^ 10 == 4 ^ 5 = 4 * 16 ^ 2 = 4 * 256 ^ 1 = 1024 # If you look at the above we can reduce n by half in every single iteration which means that we can have a resulting # o(logn) solution def myPowOptimus(self, x: float, n: int) -> float: if n == 0: return 1.0 if x == 0: return 0 if n < 0: x = 1/x n *= -1 result = 1.0 current = x index = n while index > 0: # If we have an odd number we mutliply the result times the current factor so we can make our factor even # so we can multiply it by itslef to reduce to half if index % 2 == 1: result = result * current # Multiply current by current to reduce exponent in half current = current * current # Make sure our iterator is decreased by half index = index // 2 return result # Score Card # Did I need hints? Yes because I forgot that I switched my index to equal n to make things more clear # Did you finish within 30 min? 20 # Was the solution optimal? Oh yeah this runs in o(logn) and o(1) # Were there any bugs? Yeah i forgot to make my odd exponent check use the right variable # 3 5 5 3 = 4
class Solution: def my_pow(self, x: float, n: int) -> float: if n == 0: return 1.0 if x == 0: return 0 if n < 0: x = 1 / x n *= -1 result = 1 for _ in range(n): result *= x return result def my_pow_optimus(self, x: float, n: int) -> float: if n == 0: return 1.0 if x == 0: return 0 if n < 0: x = 1 / x n *= -1 result = 1.0 current = x index = n while index > 0: if index % 2 == 1: result = result * current current = current * current index = index // 2 return result
# User input num1=float(input("Enter the 1st number: ")) num2=float(input("Enter your 2nd number: ")) # Operations the program should perform sum = num1 + num2 difference = num1 - num2 product = num1 * num2 divide = num1 / num2 modulus = num1 % num2 # Computer output print(sum) print(difference) print(product) print(divide) print(modulus)
num1 = float(input('Enter the 1st number: ')) num2 = float(input('Enter your 2nd number: ')) sum = num1 + num2 difference = num1 - num2 product = num1 * num2 divide = num1 / num2 modulus = num1 % num2 print(sum) print(difference) print(product) print(divide) print(modulus)
def main(): print("Iterative:") print("n=0 ->", fibonacci_iterative(0)) print("n=1 ->", fibonacci_iterative(1)) print("n=6 ->", fibonacci_iterative(6)) print() print("Recursive:") print("n=0 ->", fibonacci_recursive(0)) print("n=1 ->", fibonacci_recursive(1)) print("n=6 ->", fibonacci_recursive(6)) def fibonacci_iterative(n): fib = [0, 1] if n < 2: return fib[n] for i in range(n - 1): fib.append(fib[i] + fib[i + 1]) return fib[n] def fibonacci_recursive(n): if n < 2: return n return fibonacci_recursive(n - 2) + fibonacci_recursive(n - 1) main()
def main(): print('Iterative:') print('n=0 ->', fibonacci_iterative(0)) print('n=1 ->', fibonacci_iterative(1)) print('n=6 ->', fibonacci_iterative(6)) print() print('Recursive:') print('n=0 ->', fibonacci_recursive(0)) print('n=1 ->', fibonacci_recursive(1)) print('n=6 ->', fibonacci_recursive(6)) def fibonacci_iterative(n): fib = [0, 1] if n < 2: return fib[n] for i in range(n - 1): fib.append(fib[i] + fib[i + 1]) return fib[n] def fibonacci_recursive(n): if n < 2: return n return fibonacci_recursive(n - 2) + fibonacci_recursive(n - 1) main()
wanted_income = float(input()) total_income = 0 cocktail = input() while cocktail != "Party!": order = int(input()) cocktail_price = len(cocktail) cocktail_price = order * cocktail_price if cocktail_price % 2 != 0: discount = cocktail_price - (cocktail_price * 0.25) total_income += discount else: total_income += cocktail_price if total_income >= wanted_income: break cocktail = input() if cocktail == "Party!": print(f"We need {wanted_income - total_income:.2f} leva more.") elif total_income >= wanted_income: print("Target acquired.") print(f"Club income - {total_income:.2f} leva.")
wanted_income = float(input()) total_income = 0 cocktail = input() while cocktail != 'Party!': order = int(input()) cocktail_price = len(cocktail) cocktail_price = order * cocktail_price if cocktail_price % 2 != 0: discount = cocktail_price - cocktail_price * 0.25 total_income += discount else: total_income += cocktail_price if total_income >= wanted_income: break cocktail = input() if cocktail == 'Party!': print(f'We need {wanted_income - total_income:.2f} leva more.') elif total_income >= wanted_income: print('Target acquired.') print(f'Club income - {total_income:.2f} leva.')
#!/usr/bin/env python3 strings = [ "sszojmmrrkwuftyv", "isaljhemltsdzlum", "fujcyucsrxgatisb", "qiqqlmcgnhzparyg", "oijbmduquhfactbc", "jqzuvtggpdqcekgk", "zwqadogmpjmmxijf", "uilzxjythsqhwndh", "gtssqejjknzkkpvw", "wrggegukhhatygfi", "vhtcgqzerxonhsye", "tedlwzdjfppbmtdx", "iuvrelxiapllaxbg", "feybgiimfthtplui", "qxmmcnirvkzfrjwd", "vfarmltinsriqxpu", "oanqfyqirkraesfq", "xilodxfuxphuiiii", "yukhnchvjkfwcbiq", "bdaibcbzeuxqplop", "ivegnnpbiyxqsion", "ybahkbzpditgwdgt", "dmebdomwabxgtctu", "ibtvimgfaeonknoh", "jsqraroxudetmfyw", "dqdbcwtpintfcvuz", "tiyphjunlxddenpj", "fgqwjgntxagidhah", "nwenhxmakxqkeehg", "zdoheaxqpcnlhnen", "tfetfqojqcdzlpbm", "qpnxkuldeiituggg", "xwttlbdwxohahwar", "hjkwzadmtrkegzye", "koksqrqcfwcaxeof", "wulwmrptktliyxeq", "gyufbedqhhyqgqzj", "txpunzodohikzlmj", "jloqfuejfkemcrvu", "amnflshcheuddqtc", "pdvcsduggcogbiia", "yrioavgfmeafjpcz", "uyhbtmbutozzqfvq", "mwhgfwsgyuwcdzik", "auqylgxhmullxpaa", "lgelzivplaeoivzh", "uyvcepielfcmswoa", "qhirixgwkkccuzlp", "zoonniyosmkeejfg", "iayfetpixkedyana", "ictqeyzyqswdskiy", "ejsgqteafvmorwxe", "lhaiqrlqqwfbrqdx", "ydjyboqwhfpqfydc", "dwhttezyanrnbybv", "edgzkqeqkyojowvr", "rmjfdwsqamjqehdq", "ozminkgnkwqctrxz", "bztjhxpjthchhfcd", "vrtioawyxkivrpiq", "dpbcsznkpkaaclyy", "vpoypksymdwttpvz", "hhdlruwclartkyap", "bqkrcbrksbzcggbo", "jerbbbnxlwfvlaiw", "dwkasufidwjrjfbf", "kkfxtjhbnmqbmfwf", "vmnfziwqxmioukmj", "rqxvcultipkecdtu", "fhmfdibhtjzkiqsd", "hdpjbuzzbyafqrpd", "emszboysjuvwwvts", "msyigmwcuybfiooq", "druyksfnbluvnwoh", "fvgstvynnfbvxhsx", "bmzalvducnqtuune", "lzwkzfzttsvpllei", "olmplpvjamynfyfd", "padcwfkhystsvyfb", "wjhbvxkwtbfqdilb", "hruaqjwphonnterf", "bufjobjtvxtzjpmj", "oiedrjvmlbtwyyuy", "sgiemafwfztwsyju", "nsoqqfudrtwszyqf", "vonbxquiiwxnazyl", "yvnmjxtptujwqudn", "rrnybqhvrcgwvrkq", "taktoxzgotzxntfu", "quffzywzpxyaepxa", "rfvjebfiddcfgmwv", "iaeozntougqwnzoh", "scdqyrhoqmljhoil", "bfmqticltmfhxwld", "brbuktbyqlyfpsdl", "oidnyhjkeqenjlhd", "kujsaiqojopvrygg", "vebzobmdbzvjnjtk", "uunoygzqjopwgmbg", "piljqxgicjzgifso", "ikgptwcjzywswqnw", "pujqsixoisvhdvwi", "trtuxbgigogfsbbk", "mplstsqclhhdyaqk", "gzcwflvmstogdpvo", "tfjywbkmimyyqcjd", "gijutvhruqcsiznq", "ibxkhjvzzxgavkha", "btnxeqvznkxjsgmq", "tjgofgauxaelmjoq", "sokshvyhlkxerjrv", "ltogbivktqmtezta", "uduwytzvqvfluyuf", "msuckpthtgzhdxan", "fqmcglidvhvpirzr", "gwztkqpcwnutvfga", "bsjfgsrntdhlpqbx", "xloczbqybxmiopwt", "orvevzyjliomkkgu", "mzjbhmfjjvaziget", "tlsdxuhwdmghdyjb", "atoecyjhwmznaewi", "pyxpyvvipbqibiox", "ajbfmpqqobfsmesj", "siknbzefjblnohgd", "eqfhgewbblwdfkmc", "opylbscrotckkrbk", "lbwxbofgjkzdxkle", "ceixfjstaptdomvm", "hnkrqxifjmmjktie", "aqykzeuzvvetoygd", "fouahjimfcisxima", "prkzhutbqsyrhjzx", "qqwliakathnsbzne", "sayhgqtlcqqidqhj", "ygduolbysehdudra", "zricvxhdzznuxuce", "ucvzakslykpgsixd", "udirhgcttmyspgsb", "yuwzppjzfsjhhdzi", "gtqergjiuwookwre", "xvxexbjyjkxovvwf", "mlpaqhnnkqxrmwmm", "ezuqbrjozwuqafhb", "mcarusdthcbsonoq", "weeguqeheeiigrue", "pngtfugozxofaqxv", "copphvbjcmfspenv", "jiyahihykjjkdaya", "gdqnmesvptuyrfwp", "vbdscfywqmfxbohh", "crtrfuxyjypzubrg", "seihvevtxywxhflp", "fvvpmgttnapklwou", "qmqaqsajmqwhetpk", "zetxvrgjmblxvakr", "kpvwblrizaabmnhz", "mwpvvzaaicntrkcp", "clqyjiegtdsswqfm", "ymrcnqgcpldgfwtm", "nzyqpdenetncgnwq", "cmkzevgacnmdkqro", "kzfdsnamjqbeirhi", "kpxrvgvvxapqlued", "rzskbnfobevzrtqu", "vjoahbfwtydugzap", "ykbbldkoijlvicbl", "mfdmroiztsgjlasb", "quoigfyxwtwprmdr", "ekxjqafwudgwfqjm", "obtvyjkiycxfcdpb", "lhoihfnbuqelthof", "eydwzitgxryktddt", "rxsihfybacnpoyny", "bsncccxlplqgygtw", "rvmlaudsifnzhcqh", "huxwsyjyebckcsnn", "gtuqzyihwhqvjtes", "zreeyomtngvztveq", "nwddzjingsarhkxb", "nuqxqtctpoldrlsh", "wkvnrwqgjooovhpf", "kwgueyiyffudtbyg", "tpkzapnjxefqnmew", "ludwccvkihagvxal", "lfdtzhfadvabghna", "njqmlsnrkcfhtvbb", "cajzbqleghhnlgap", "vmitdcozzvqvzatp", "eelzefwqwjiywbcz", "uyztcuptfqvymjpi", "aorhnrpkjqqtgnfo", "lfrxfdrduoeqmwwp", "vszpjvbctblplinh", "zexhadgpqfifcqrz", "ueirfnshekpemqua", "qfremlntihbwabtb", "nwznunammfexltjc", "zkyieokaaogjehwt", "vlrxgkpclzeslqkq", "xrqrwfsuacywczhs", "olghlnfjdiwgdbqc", "difnlxnedpqcsrdf", "dgpuhiisybjpidsj", "vlwmwrikmitmoxbt", "sazpcmcnviynoktm", "pratafauetiknhln", "ilgteekhzwlsfwcn", "ywvwhrwhkaubvkbl", "qlaxivzwxyhvrxcf", "hbtlwjdriizqvjfb", "nrmsononytuwslsa", "mpxqgdthpoipyhjc", "mcdiwmiqeidwcglk", "vfbaeavmjjemfrmo", "qzcbzmisnynzibrc", "shzmpgxhehhcejhb", "wirtjadsqzydtyxd", "qjlrnjfokkqvnpue", "dxawdvjntlbxtuqc", "wttfmnrievfestog", "eamjfvsjhvzzaobg", "pbvfcwzjgxahlrag", "omvmjkqqnobvnzkn", "lcwmeibxhhlxnkzv", "uiaeroqfbvlazegs", "twniyldyuonfyzqw", "wgjkmsbwgfotdabi", "hnomamxoxvrzvtew", "ycrcfavikkrxxfgw", "isieyodknagzhaxy", "mgzdqwikzullzyco", "mumezgtxjrrejtrs", "nwmwjcgrqiwgfqel", "wjgxmebfmyjnxyyp", "durpspyljdykvzxf", "zuslbrpooyetgafh", "kuzrhcjwbdouhyme", "wyxuvbciodscbvfm", "kbnpvuqwmxwfqtqe", "zddzercqogdpxmft", "sigrdchxtgavzzjh", "lznjolnorbuddgcs", "ycnqabxlcajagwbt", "bnaudeaexahdgxsj", "rlnykxvoctfwanms", "jngyetkoplrstfzt", "tdpxknwacksotdub", "yutqgssfoptvizgr", "lzmqnxeqjfnsxmsa", "iqpgfsfmukovsdgu", "qywreehbidowtjyz", "iozamtgusdctvnkw", "ielmujhtmynlwcfd", "hzxnhtbnmmejlkyf", "ftbslbzmiqkzebtd", "bcwdqgiiizmohack", "dqhfkzeddjzbdlxu", "mxopokqffisxosci", "vciatxhtuechbylk", "khtkhcvelidjdena", "blatarwzfqcapkdt", "elamngegnczctcck", "xeicefdbwrxhuxuf", "sawvdhjoeahlgcdr", "kmdcimzsfkdfpnir", "axjayzqlosrduajb", "mfhzreuzzumvoggr", "iqlbkbhrkptquldb", "xcvztvlshiefuhgb", "pkvwyqmyoazocrio", "ajsxkdnerbmhyxaj", "tudibgsbnpnizvsi", "cxuiydkgdccrqvkh", "cyztpjesdzmbcpot", "nnazphxpanegwitx", "uphymczbmjalmsct", "yyxiwnlrogyzwqmg", "gmqwnahjvvdyhnfa", "utolskxpuoheugyl", "mseszdhyzoyavepd", "ycqknvbuvcjfgmlc", "sknrxhxbfpvpeorn", "zqxqjetooqcodwml", "sesylkpvbndrdhsy", "fryuxvjnsvnjrxlw", "mfxusewqurscujnu", "mbitdjjtgzchvkfv", "ozwlyxtaalxofovd", "wdqcduaykxbunpie", "rlnhykxiraileysk", "wgoqfrygttlamobg", "kflxzgxvcblkpsbz", "tmkisflhativzhde", "owsdrfgkaamogjzd", "gaupjkvkzavhfnes", "wknkurddcknbdleg", "lltviwincmbtduap", "qwzvspgbcksyzzmb", "ydzzkumecryfjgnk", "jzvmwgjutxoysaam", "icrwpyhxllbardkr", "jdopyntshmvltrve", "afgkigxcuvmdbqou", "mfzzudntmvuyhjzt", "duxhgtwafcgrpihc", "tsnhrkvponudumeb", "sqtvnbeiigdzbjgv", "eczmkqwvnsrracuo", "mhehsgqwiczaiaxv", "kaudmfvifovrimpd", "lupikgivechdbwfr", "mwaaysrndiutuiqx", "aacuiiwgaannunmm", "tjqjbftaqitukwzp", "lrcqyskykbjpaekn", "lirrvofbcqpjzxmr", "jurorvzpplyelfml", "qonbllojmloykjqe", "sllkzqujfnbauuqp", "auexjwsvphvikali", "usuelbssqmbrkxyc", "wyuokkfjexikptvv", "wmfedauwjgbrgytl", "sfwvtlzzebxzmuvw", "rdhqxuechjsjcvaf", "kpavhqkukugocsxu", "ovnjtumxowbxduts", "zgerpjufauptxgat", "pevvnzjfwhjxdoxq", "pmmfwxajgfziszcs", "difmeqvaghuitjhs", "icpwjbzcmlcterwm", "ngqpvhajttxuegyh", "mosjlqswdngwqsmi", "frlvgpxrjolgodlu", "eazwgrpcxjgoszeg", "bbtsthgkjrpkiiyk", "tjonoglufuvsvabe", "xhkbcrofytmbzrtk", "kqftfzdmpbxjynps", "kmeqpocbnikdtfyv", "qjjymgqxhnjwxxhp", "dmgicrhgbngdtmjt", "zdxrhdhbdutlawnc", "afvoekuhdboxghvx", "hiipezngkqcnihty", "bbmqgheidenweeov", "suprgwxgxwfsgjnx", "adeagikyamgqphrj", "zzifqinoeqaorjxg", "adhgppljizpaxzld", "lvxyieypvvuqjiyc", "nljoakatwwwoovzn", "fcrkfxclcacshhmx", "ownnxqtdhqbgthch", "lmfylrcdmdkgpwnj", "hlwjfbvlswbzpbjr", "mkofhdtljdetcyvp", "synyxhifbetzarpo", "agnggugngadrcxoc", "uhttadmdmhidpyjw", "ohfwjfhunalbubpr", "pzkkkkwrlvxiuysn", "kmidbxmyzkjrwjhu", "egtitdydwjxmajnw", "civoeoiuwtwgbqqs", "dfptsguzfinqoslk", "tdfvkreormspprer", "zvnvbrmthatzztwi", "ffkyddccrrfikjde", "hrrmraevdnztiwff", "qaeygykcpbtjwjbr", "purwhitkmrtybslh", "qzziznlswjaussel", "dfcxkvdpqccdqqxj", "tuotforulrrytgyn", "gmtgfofgucjywkev", "wkyoxudvdkbgpwhd", "qbvktvfvipftztnn", "otckgmojziezmojb", "inxhvzbtgkjxflay", "qvxapbiatuudseno", "krpvqosbesnjntut", "oqeukkgjsfuqkjbb", "prcjnyymnqwqksiz", "vuortvjxgckresko", "orqlyobvkuwgathr", "qnpyxlnazyfuijox", "zwlblfkoklqmqzkw", "hmwurwtpwnrcsanl", "jzvxohuakopuzgpf", "sfcpnxrviphhvxmx", "qtwdeadudtqhbely", "dbmkmloasqphnlgj", "olylnjtkxgrubmtk", "nxsdbqjuvwrrdbpq", "wbabpirnpcsmpipw", "hjnkyiuxpqrlvims", "enzpntcjnxdpuqch", "vvvqhlstzcizyimn", "triozhqndbttglhv", "fukvgteitwaagpzx", "uhcvukfbmrvskpen", "tizcyupztftzxdmt", "vtkpnbpdzsaluczz", "wodfoyhoekidxttm", "otqocljrmwfqbxzu", "linfbsnfvixlwykn", "vxsluutrwskslnye", "zbshygtwugixjvsi", "zdcqwxvwytmzhvoo", "wrseozkkcyctrmei", "fblgtvogvkpqzxiy", "opueqnuyngegbtnf", "qxbovietpacqqxok", "zacrdrrkohfygddn", "gbnnvjqmkdupwzpq", "qgrgmsxeotozvcak", "hnppukzvzfmlokid", "dzbheurndscrrtcl", "wbgdkadtszebbrcw", "fdmzppzphhpzyuiz", "bukomunhrjrypohj", "ohodhelegxootqbj", "rsplgzarlrknqjyh", "punjjwpsxnhpzgvu", "djdfahypfjvpvibm", "mlgrqsmhaozatsvy", "xwktrgyuhqiquxgn", "wvfaoolwtkbrisvf", "plttjdmguxjwmeqr", "zlvvbwvlhauyjykw", "cigwkbyjhmepikej", "masmylenrusgtyxs", "hviqzufwyetyznze", "nzqfuhrooswxxhus", "pdbdetaqcrqzzwxf", "oehmvziiqwkzhzib", "icgpyrukiokmytoy", "ooixfvwtiafnwkce", "rvnmgqggpjopkihs", "wywualssrmaqigqk", "pdbvflnwfswsrirl", "jeaezptokkccpbuj", "mbdwjntysntsaaby", "ldlgcawkzcwuxzpz", "lwktbgrzswbsweht", "ecspepmzarzmgpjm", "qmfyvulkmkxjncai", "izftypvwngiukrns", "zgmnyjfeqffbooww", "nyrkhggnprhedows", "yykzzrjmlevgffah", "mavaemfxhlfejfki", "cmegmfjbkvpncqwf", "zxidlodrezztcrij", "fseasudpgvgnysjv", "fupcimjupywzpqzp", "iqhgokavirrcvyys", "wjmkcareucnmfhui", "nftflsqnkgjaexhq", "mgklahzlcbapntgw", "kfbmeavfxtppnrxn", "nuhyvhknlufdynvn", "nviogjxbluwrcoec", "tyozixxxaqiuvoys", "kgwlvmvgtsvxojpr", "moeektyhyonfdhrb", "kahvevmmfsmiiqex", "xcywnqzcdqtvhiwd", "fnievhiyltbvtvem", "jlmndqufirwgtdxd", "muypbfttoeelsnbs", "rypxzbnujitfwkou", "ubmmjbznskildeoj", "ofnmizdeicrmkjxp", "rekvectjbmdnfcib", "yohrojuvdexbctdh", "gwfnfdeibynzjmhz", "jfznhfcqdwlpjull", "scrinzycfhwkmmso", "mskutzossrwoqqsi", "rygoebkzgyzushhr", "jpjqiycflqkexemx", "arbufysjqmgaapnl", "dbjerflevtgweeoj", "snybnnjlmwjvhois", "fszuzplntraprmbj", "mkvaatolvuggikvg", "zpuzuqygoxesnuyc", "wnpxvmxvllxalulm", "eivuuafkvudeouwy", "rvzckdyixetfuehr", "qgmnicdoqhveahyx", "miawwngyymshjmpj", "pvckyoncpqeqkbmx", "llninfenrfjqxurv", "kzbjnlgsqjfuzqtp", "rveqcmxomvpjcwte", "bzotkawzbopkosnx", "ktqvpiribpypaymu", "wvlzkivbukhnvram", "uohntlcoguvjqqdo", "ajlsiksjrcnzepkt", "xsqatbldqcykwusd", "ihbivgzrwpmowkop", "vfayesfojmibkjpb", "uaqbnijtrhvqxjtb", "hhovshsfmvkvymba", "jerwmyxrfeyvxcgg", "hncafjwrlvdcupma", "qyvigggxfylbbrzt", "hiiixcyohmvnkpgk", "mmitpwopgxuftdfu", "iaxderqpceboixoa", "zodfmjhuzhnsqfcb", "sthtcbadrclrazsi", "bkkkkcwegvypbrio", "wmpcofuvzemunlhj", "gqwebiifvqoeynro", "juupusqdsvxcpsgv", "rbhdfhthxelolyse", "kjimpwnjfrqlqhhz", "rcuigrjzarzpjgfq", "htxcejfyzhydinks", "sxucpdxhvqjxxjwf", "omsznfcimbcwaxal", "gufmtdlhgrsvcosb", "bssshaqujtmluerz", "uukotwjkstgwijtr", "kbqkneobbrdogrxk", "ljqopjcjmelgrakz", "rwtfnvnzryujwkfb", "dedjjbrndqnilbeh", "nzinsxnpptzagwlb", "lwqanydfirhnhkxy", "hrjuzfumbvfccxno", "okismsadkbseumnp", "sfkmiaiwlktxqvwa", "hauwpjjwowbunbjj", "nowkofejwvutcnui", "bqzzppwoslaeixro", "urpfgufwbtzenkpj", "xgeszvuqwxeykhef", "yxoldvkyuikwqyeq", "onbbhxrnmohzskgg", "qcikuxakrqeugpoa", "lnudcqbtyzhlpers", "nxduvwfrgzaailgl", "xniuwvxufzxjjrwz", "ljwithcqmgvntjdj", "awkftfagrfzywkhs", "uedtpzxyubeveuek", "bhcqdwidbjkqqhzl", "iyneqjdmlhowwzxx", "kvshzltcrrururty", "zgfpiwajegwezupo", "tkrvyanujjwmyyri", "ercsefuihcmoaiep", "ienjrxpmetinvbos", "jnwfutjbgenlipzq", "bgohjmrptfuamzbz", "rtsyamajrhxbcncw", "tfjdssnmztvbnscs", "bgaychdlmchngqlp", "kfjljiobynhwfkjo", "owtdxzcpqleftbvn", "ltjtimxwstvzwzjj", "wbrvjjjajuombokf", "zblpbpuaqbkvsxye", "gwgdtbpnlhyqspdi", "abipqjihjqfofmkx", "nlqymnuvjpvvgova", "avngotmhodpoufzn", "qmdyivtzitnrjuae", "xfwjmqtqdljuerxi", "csuellnlcyqaaamq", "slqyrcurcyuoxquo", "dcjmxyzbzpohzprl", "uqfnmjwniyqgsowb", "rbmxpqoblyxdocqc", "ebjclrdbqjhladem", "ainnfhxnsgwqnmyo", "eyytjjwhvodtzquf", "iabjgmbbhilrcyyp", "pqfnehkivuelyccc", "xgjbyhfgmtseiimt", "jwxyqhdbjiqqqeyy", "gxsbrncqkmvaryln", "vhjisxjkinaejytk", "seexagcdmaedpcvh", "lvudfgrcpjxzdpvd", "fxtegyrqjzhmqean", "dnoiseraqcoossmc", "nwrhmwwbykvwmgep", "udmzskejvizmtlce", "hbzvqhvudfdlegaa", "cghmlfqejbxewskv", "bntcmjqfwomtbwsb", "qezhowyopjdyhzng", "todzsocdkgfxanbz", "zgjkssrjlwxuhwbk", "eibzljqsieriyrzr", "wamxvzqyycrxotjp", "epzvfkispwqynadu", "dwlpfhtrafrxlyie", "qhgzujhgdruowoug", "girstvkahaemmxvh", "baitcrqmxhazyhbl", "xyanqcchbhkajdmc", "gfvjmmcgfhvgnfdq", "tdfdbslwncbnkzyz", "jojuselkpmnnbcbb", "hatdslkgxtqpmavj", "dvelfeddvgjcyxkj", "gnsofhkfepgwltse", "mdngnobasfpewlno", "qssnbcyjgmkyuoga", "glvcmmjytmprqwvn", "gwrixumjbcdffsdl", "lozravlzvfqtsuiq", "sicaflbqdxbmdlch", "inwfjkyyqbwpmqlq", "cuvszfotxywuzhzi", "igfxyoaacoarlvay", "ucjfhgdmnjvgvuni", "rvvkzjsytqgiposh", "jduinhjjntrmqroz", "yparkxbgsfnueyll", "lyeqqeisxzfsqzuj", "woncskbibjnumydm", "lltucklragtjmxtl", "ubiyvmyhlesfxotj", "uecjseeicldqrqww", "xxlxkbcthufnjbnm", "lhqijovvhlffpxga", "fzdgqpzijitlogjz", "efzzjqvwphomxdpd", "jvgzvuyzobeazssc", "hejfycgxywfjgbfw", "yhjjmvkqfbnbliks", "sffvfyywtlntsdsz", "dwmxqudvxqdenrur", "asnukgppdemxrzaz", "nwqfnumblwvdpphx", "kqsmkkspqvxzuket", "cpnraovljzqiquaz", "qrzgrdlyyzbyykhg", "opoahcbiydyhsmqe", "hjknnfdauidjeydr", "hczdjjlygoezadow", "rtflowzqycimllfv", "sfsrgrerzlnychhq", "bpahuvlblcolpjmj", "albgnjkgmcrlaicl", "pijyqdhfxpaxzdex", "eeymiddvcwkpbpux", "rqwkqoabywgggnln", "vckbollyhgbgmgwh", "ylzlgvnuvpynybkm", "hpmbxtpfosbsjixt", "ocebeihnhvkhjfqz", "tvctyxoujdgwayze", "efvhwxtuhapqxjen", "rusksgefyidldmpo", "nkmtjvddfmhirmzz", "whvtsuadwofzmvrt", "iiwjqvsdxudhdzzk", "gucirgxaxgcassyo", "rmhfasfzexeykwmr", "hynlxcvsbgosjbis", "huregszrcaocueen", "pifezpoolrnbdqtv", "unatnixzvdbqeyox", "xtawlpduxgacchfe", "bdvdbflqfphndduf", "xtdsnjnmzccfptyt", "nkhsdkhqtzqbphhg", "aqcubmfkczlaxiyb", "moziflxpsfubucmv", "srdgnnjtfehiimqx", "pwfalehdfyykrohf", "sysxssmvewyfjrve", "brsemdzosgqvvlxe", "bimbjoshuvflkiat", "hkgjasmljkpkwwku", "sbnmwjvodygobpqc", "bbbqycejueruihhd", "corawswvlvneipyc", "gcyhknmwsczcxedh", "kppakbffdhntmcqp", "ynulzwkfaemkcefp", "pyroowjekeurlbii", "iwksighrswdcnmxf", "glokrdmugreygnsg", "xkmvvumnfzckryop", "aesviofpufygschi", "csloawlirnegsssq", "fkqdqqmlzuxbkzbc", "uzlhzcfenxdfjdzp", "poaaidrktteusvyf", "zrlyfzmjzfvivcfr", "qwjulskbniitgqtx", "gjeszjksbfsuejki", "vczdejdbfixbduaq", "knjdrjthitjxluth", "jweydeginrnicirl", "bottrfgccqhyycsl", "eiquffofoadmbuhk", "lbqfutmzoksscswf", "xfmdvnvfcnzjprba", "uvugkjbkhlaoxmyx", "wadlgtpczgvcaqqv", "inzrszbtossflsxk", "dbzbtashaartczrj", "qbjiqpccefcfkvod", "hluujmokjywotvzy", "thwlliksfztcmwzh", "arahybspdaqdexrq", "nuojrmsgyipdvwyx", "hnajdwjwmzattvst", "sulcgaxezkprjbgu", "rjowuugwdpkjtypw", "oeugzwuhnrgiaqga", "wvxnyymwftfoswij", "pqxklzkjpcqscvde", "tuymjzknntekglqj", "odteewktugcwlhln", "exsptotlfecmgehc", "eeswfcijtvzgrqel", "vjhrkiwmunuiwqau", "zhlixepkeijoemne", "pavfsmwesuvebzdd", "jzovbklnngfdmyws", "nbajyohtzfeoiixz", "ciozmhrsjzrwxvhz", "gwucrxieqbaqfjuv", "uayrxrltnohexawc", "flmrbhwsfbcquffm", "gjyabmngkitawlxc", "rwwtggvaygfbovhg", "xquiegaisynictjq", "oudzwuhexrwwdbyy", "lengxmguyrwhrebb", "uklxpglldbgqsjls", "dbmvlfeyguydfsxq", "zspdwdqcrmtmdtsc", "mqfnzwbfqlauvrgc", "amcrkzptgacywvhv", "ndxmskrwrqysrndf", "mwjyhsufeqhwisju", "srlrukoaenyevykt", "tnpjtpwawrxbikct", "geczalxmgxejulcv", "tvkcbqdhmuwcxqci", "tiovluvwezwwgaox", "zrjhtbgajkjqzmfo", "vcrywduwsklepirs", "lofequdigsszuioy", "wxsdzomkjqymlzat", "iabaczqtrfbmypuy", "ibdlmudbajikcncr", "rqcvkzsbwmavdwnv", "ypxoyjelhllhbeog", "fdnszbkezyjbttbg", "uxnhrldastpdjkdz", "xfrjbehtxnlyzcka", "omjyfhbibqwgcpbv", "eguucnoxaoprszmp", "xfpypldgcmcllyzz", "aypnmgqjxjqceelv", "mgzharymejlafvgf", "tzowgwsubbaigdok", "ilsehjqpcjwmylxc", "pfmouwntfhfnmrwk", "csgokybgdqwnduwp", "eaxwvxvvwbrovypz", "nmluqvobbbmdiwwb", "lnkminvfjjzqbmio", "mjiiqzycqdhfietz", "towlrzriicyraevq", "obiloewdvbrsfwjo", "lmeooaajlthsfltw", "ichygipzpykkesrw", "gfysloxmqdsfskvt", "saqzntehjldvwtsx", "pqddoemaufpfcaew", "mjrxvbvwcreaybwe", "ngfbrwfqnxqosoai", "nesyewxreiqvhald", "kqhqdlquywotcyfy", "liliptyoqujensfi", "nsahsaxvaepzneqq", "zaickulfjajhctye", "gxjzahtgbgbabtht", "koxbuopaqhlsyhrp", "jhzejdjidqqtjnwe", "dekrkdvprfqpcqki", "linwlombdqtdeyop", "dvckqqbnigdcmwmx", "yaxygbjpzkvnnebv", "rlzkdkgaagmcpxah", "cfzuyxivtknirqvt", "obivkajhsjnrxxhn", "lmjhayymgpseuynn", "bbjyewkwadaipyju", "lmzyhwomfypoftuu", "gtzhqlgltvatxack", "jfflcfaqqkrrltgq", "txoummmnzfrlrmcg", "ohemsbfuqqpucups", "imsfvowcbieotlok", "tcnsnccdszxfcyde", "qkcdtkwuaquajazz", "arcfnhmdjezdbqku", "srnocgyqrlcvlhkb", "mppbzvfmcdirbyfw", "xiuarktilpldwgwd", "ypufwmhrvzqmexpc", "itpdnsfkwgrdujmj", "cmpxnodtsswkyxkr", "wayyxtjklfrmvbfp", "mfaxphcnjczhbbwy", "sjxhgwdnqcofbdra", "pnxmujuylqccjvjm", "ivamtjbvairwjqwl", "deijtmzgpfxrclss", "bzkqcaqagsynlaer", "tycefobvxcvwaulz", "ctbhnywezxkdsswf", "urrxxebxrthtjvib", "fpfelcigwqwdjucv", "ngfcyyqpqulwcphb", "rltkzsiipkpzlgpw", "qfdsymzwhqqdkykc", "balrhhxipoqzmihj", "rnwalxgigswxomga", "ghqnxeogckshphgr", "lyyaentdizaumnla", "exriodwfzosbeoib", "speswfggibijfejk", "yxmxgfhvmshqszrq", "hcqhngvahzgawjga", "qmhlsrfpesmeksur", "eviafjejygakodla", "kvcfeiqhynqadbzv", "fusvyhowslfzqttg", "girqmvwmcvntrwau", "yuavizroykfkdekz", "jmcwohvmzvowrhxf", "kzimlcpavapynfue", "wjudcdtrewfabppq", "yqpteuxqgbmqfgxh", "xdgiszbuhdognniu", "jsguxfwhpftlcjoh", "whakkvspssgjzxre", "ggvnvjurlyhhijgm", "krvbhjybnpemeptr", "pqedgfojyjybfbzr", "jzhcrsgmnkwwtpdo", "yyscxoxwofslncmp", "gzjhnxytmyntzths", "iteigbnqbtpvqumi", "zjevfzusnjukqpfw", "xippcyhkfuounxqk", "mcnhrcfonfdgpkyh", "pinkcyuhjkexbmzj", "lotxrswlxbxlxufs", "fmqajrtoabpckbnu", "wfkwsgmcffdgaqxg", "qfrsiwnohoyfbidr", "czfqbsbmiuyusaqs", "ieknnjeecucghpoo", "cevdgqnugupvmsge", "gjkajcyjnxdrtuvr", "udzhrargnujxiclq", "zqqrhhmjwermjssg", "ggdivtmgoqajydzz", "wnpfsgtxowkjiivl", "afbhqawjbotxnqpd", "xjpkifkhfjeqifdn", "oyfggzsstfhvticp", "kercaetahymeawxy", "khphblhcgmbupmzt", "iggoqtqpvaebtiol", "ofknifysuasshoya", "qxuewroccsbogrbv", "apsbnbkiopopytgu", "zyahfroovfjlythh", "bxhjwfgeuxlviydq", "uvbhdtvaypasaswa", "qamcjzrmesqgqdiz", "hjnjyzrxntiycyel", "wkcrwqwniczwdxgq", "hibxlvkqakusswkx", "mzjyuenepwdgrkty", "tvywsoqslfsulses", "jqwcwuuisrclircv", "xanwaoebfrzhurct", "ykriratovsvxxasf", "qyebvtqqxbjuuwuo", "telrvlwvriylnder", "acksrrptgnhkeiaa", "yemwfjhiqlzsvdxf", "banrornfkcymmkcc", "ytbhxvaeiigjpcgm", "crepyazgxquposkn", "xlqwdrytzwnxzwzv", "xtrbfbwopxscftps", "kwbytzukgseeyjla", "qtfdvavvjogybxjg", "ytbmvmrcxwfkgvzw", "nbscbdskdeocnfzr", "sqquwjbdxsxhcseg", "ewqxhigqcgszfsuw", "cvkyfcyfmubzwsee", "dcoawetekigxgygd", "ohgqnqhfimyuqhvi", "otisopzzpvnhctte", "bauieohjejamzien", "ewnnopzkujbvhwce", "aeyqlskpaehagdiv", "pncudvivwnnqspxy", "ytugesilgveokxcg", "zoidxeelqdjesxpr", "ducjccsuaygfchzj", "smhgllqqqcjfubfc", "nlbyyywergronmir", "prdawpbjhrzsbsvj", "nmgzhnjhlpcplmui", "eflaogtjghdjmxxz", "qolvpngucbkprrdc", "ixywxcienveltgho", "mwnpqtocagenkxut", "iskrfbwxonkguywx", "ouhtbvcaczqzmpua", "srewprgddfgmdbao", "dyufrltacelchlvu", "czmzcbrkecixuwzz", "dtbeojcztzauofuk", "prrgoehpqhngfgmw", "baolzvfrrevxsyke", "zqadgxshwiarkzwh", "vsackherluvurqqj", "surbpxdulvcvgjbd", "wqxytarcxzgxhvtx", "vbcubqvejcfsgrac", "zqnjfeapshjowzja", "hekvbhtainkvbynx", "knnugxoktxpvoxnh", "knoaalcefpgtvlwm", "qoakaunowmsuvkus", "ypkvlzcduzlezqcb", "ujhcagawtyepyogh", "wsilcrxncnffaxjf", "gbbycjuscquaycrk", "aduojapeaqwivnly", "ceafyxrakviagcjy", "nntajnghicgnrlst", "vdodpeherjmmvbje", "wyyhrnegblwvdobn", "xlfurpghkpbzhhif", "xyppnjiljvirmqjo", "kglzqahipnddanpi", "omjateouxikwxowr", "ocifnoopfglmndcx", "emudcukfbadyijev", "ooktviixetfddfmh", "wtvrhloyjewdeycg", "cgjncqykgutfjhvb", "nkwvpswppeffmwad", "hqbcmfhzkxmnrivg", "mdskbvzguxvieilr", "anjcvqpavhdloaqh", "erksespdevjylenq", "fadxwbmisazyegup", "iyuiffjmcaahowhj", "ygkdezmynmltodbv", "fytneukxqkjattvh", "woerxfadbfrvdcnz", "iwsljvkyfastccoa", "movylhjranlorofe", "drdmicdaiwukemep", "knfgtsmuhfcvvshg", "ibstpbevqmdlhajn", "tstwsswswrxlzrqs", "estyydmzothggudf", "jezogwvymvikszwa", "izmqcwdyggibliet", "nzpxbegurwnwrnca", "kzkojelnvkwfublh", "xqcssgozuxfqtiwi", "tcdoigumjrgvczfv", "ikcjyubjmylkwlwq", "kqfivwystpqzvhan", "bzukgvyoqewniivj", "iduapzclhhyfladn", "fbpyzxdfmkrtfaeg", "yzsmlbnftftgwadz" ] def part1(): def contains_three_vowels(x): n = 0 for c in x: if c in "aeiou": n += 1 return n >= 3 def contains_dubble(x): for i in range(len(x) - 1): if x[i] == x[i + 1]: return True return False def contains_forbidden(x): forbidden = ["ab", "cd", "pq", "xy"] for i in range(len(x) - 1): if x[i] + x[i + 1] in forbidden: return True return False n = 0 for x in strings: if contains_three_vowels(x) and contains_dubble(x) and not contains_forbidden(x): n += 1 print("Number of nice strings: {}".format(n)) def part2(): def contains_pairs(x): for i in range(len(x) - 3): if x.find(x[i] + x[i + 1], i + 2) >= 0: return True return False def contains_dubble(x): for i in range(len(x) - 2): if x[i] == x[i + 2]: return True return False n = 0 for x in strings: if contains_pairs(x) and contains_dubble(x): n += 1 print("Number of nice strings: {}".format(n)) part1() part2()
strings = ['sszojmmrrkwuftyv', 'isaljhemltsdzlum', 'fujcyucsrxgatisb', 'qiqqlmcgnhzparyg', 'oijbmduquhfactbc', 'jqzuvtggpdqcekgk', 'zwqadogmpjmmxijf', 'uilzxjythsqhwndh', 'gtssqejjknzkkpvw', 'wrggegukhhatygfi', 'vhtcgqzerxonhsye', 'tedlwzdjfppbmtdx', 'iuvrelxiapllaxbg', 'feybgiimfthtplui', 'qxmmcnirvkzfrjwd', 'vfarmltinsriqxpu', 'oanqfyqirkraesfq', 'xilodxfuxphuiiii', 'yukhnchvjkfwcbiq', 'bdaibcbzeuxqplop', 'ivegnnpbiyxqsion', 'ybahkbzpditgwdgt', 'dmebdomwabxgtctu', 'ibtvimgfaeonknoh', 'jsqraroxudetmfyw', 'dqdbcwtpintfcvuz', 'tiyphjunlxddenpj', 'fgqwjgntxagidhah', 'nwenhxmakxqkeehg', 'zdoheaxqpcnlhnen', 'tfetfqojqcdzlpbm', 'qpnxkuldeiituggg', 'xwttlbdwxohahwar', 'hjkwzadmtrkegzye', 'koksqrqcfwcaxeof', 'wulwmrptktliyxeq', 'gyufbedqhhyqgqzj', 'txpunzodohikzlmj', 'jloqfuejfkemcrvu', 'amnflshcheuddqtc', 'pdvcsduggcogbiia', 'yrioavgfmeafjpcz', 'uyhbtmbutozzqfvq', 'mwhgfwsgyuwcdzik', 'auqylgxhmullxpaa', 'lgelzivplaeoivzh', 'uyvcepielfcmswoa', 'qhirixgwkkccuzlp', 'zoonniyosmkeejfg', 'iayfetpixkedyana', 'ictqeyzyqswdskiy', 'ejsgqteafvmorwxe', 'lhaiqrlqqwfbrqdx', 'ydjyboqwhfpqfydc', 'dwhttezyanrnbybv', 'edgzkqeqkyojowvr', 'rmjfdwsqamjqehdq', 'ozminkgnkwqctrxz', 'bztjhxpjthchhfcd', 'vrtioawyxkivrpiq', 'dpbcsznkpkaaclyy', 'vpoypksymdwttpvz', 'hhdlruwclartkyap', 'bqkrcbrksbzcggbo', 'jerbbbnxlwfvlaiw', 'dwkasufidwjrjfbf', 'kkfxtjhbnmqbmfwf', 'vmnfziwqxmioukmj', 'rqxvcultipkecdtu', 'fhmfdibhtjzkiqsd', 'hdpjbuzzbyafqrpd', 'emszboysjuvwwvts', 'msyigmwcuybfiooq', 'druyksfnbluvnwoh', 'fvgstvynnfbvxhsx', 'bmzalvducnqtuune', 'lzwkzfzttsvpllei', 'olmplpvjamynfyfd', 'padcwfkhystsvyfb', 'wjhbvxkwtbfqdilb', 'hruaqjwphonnterf', 'bufjobjtvxtzjpmj', 'oiedrjvmlbtwyyuy', 'sgiemafwfztwsyju', 'nsoqqfudrtwszyqf', 'vonbxquiiwxnazyl', 'yvnmjxtptujwqudn', 'rrnybqhvrcgwvrkq', 'taktoxzgotzxntfu', 'quffzywzpxyaepxa', 'rfvjebfiddcfgmwv', 'iaeozntougqwnzoh', 'scdqyrhoqmljhoil', 'bfmqticltmfhxwld', 'brbuktbyqlyfpsdl', 'oidnyhjkeqenjlhd', 'kujsaiqojopvrygg', 'vebzobmdbzvjnjtk', 'uunoygzqjopwgmbg', 'piljqxgicjzgifso', 'ikgptwcjzywswqnw', 'pujqsixoisvhdvwi', 'trtuxbgigogfsbbk', 'mplstsqclhhdyaqk', 'gzcwflvmstogdpvo', 'tfjywbkmimyyqcjd', 'gijutvhruqcsiznq', 'ibxkhjvzzxgavkha', 'btnxeqvznkxjsgmq', 'tjgofgauxaelmjoq', 'sokshvyhlkxerjrv', 'ltogbivktqmtezta', 'uduwytzvqvfluyuf', 'msuckpthtgzhdxan', 'fqmcglidvhvpirzr', 'gwztkqpcwnutvfga', 'bsjfgsrntdhlpqbx', 'xloczbqybxmiopwt', 'orvevzyjliomkkgu', 'mzjbhmfjjvaziget', 'tlsdxuhwdmghdyjb', 'atoecyjhwmznaewi', 'pyxpyvvipbqibiox', 'ajbfmpqqobfsmesj', 'siknbzefjblnohgd', 'eqfhgewbblwdfkmc', 'opylbscrotckkrbk', 'lbwxbofgjkzdxkle', 'ceixfjstaptdomvm', 'hnkrqxifjmmjktie', 'aqykzeuzvvetoygd', 'fouahjimfcisxima', 'prkzhutbqsyrhjzx', 'qqwliakathnsbzne', 'sayhgqtlcqqidqhj', 'ygduolbysehdudra', 'zricvxhdzznuxuce', 'ucvzakslykpgsixd', 'udirhgcttmyspgsb', 'yuwzppjzfsjhhdzi', 'gtqergjiuwookwre', 'xvxexbjyjkxovvwf', 'mlpaqhnnkqxrmwmm', 'ezuqbrjozwuqafhb', 'mcarusdthcbsonoq', 'weeguqeheeiigrue', 'pngtfugozxofaqxv', 'copphvbjcmfspenv', 'jiyahihykjjkdaya', 'gdqnmesvptuyrfwp', 'vbdscfywqmfxbohh', 'crtrfuxyjypzubrg', 'seihvevtxywxhflp', 'fvvpmgttnapklwou', 'qmqaqsajmqwhetpk', 'zetxvrgjmblxvakr', 'kpvwblrizaabmnhz', 'mwpvvzaaicntrkcp', 'clqyjiegtdsswqfm', 'ymrcnqgcpldgfwtm', 'nzyqpdenetncgnwq', 'cmkzevgacnmdkqro', 'kzfdsnamjqbeirhi', 'kpxrvgvvxapqlued', 'rzskbnfobevzrtqu', 'vjoahbfwtydugzap', 'ykbbldkoijlvicbl', 'mfdmroiztsgjlasb', 'quoigfyxwtwprmdr', 'ekxjqafwudgwfqjm', 'obtvyjkiycxfcdpb', 'lhoihfnbuqelthof', 'eydwzitgxryktddt', 'rxsihfybacnpoyny', 'bsncccxlplqgygtw', 'rvmlaudsifnzhcqh', 'huxwsyjyebckcsnn', 'gtuqzyihwhqvjtes', 'zreeyomtngvztveq', 'nwddzjingsarhkxb', 'nuqxqtctpoldrlsh', 'wkvnrwqgjooovhpf', 'kwgueyiyffudtbyg', 'tpkzapnjxefqnmew', 'ludwccvkihagvxal', 'lfdtzhfadvabghna', 'njqmlsnrkcfhtvbb', 'cajzbqleghhnlgap', 'vmitdcozzvqvzatp', 'eelzefwqwjiywbcz', 'uyztcuptfqvymjpi', 'aorhnrpkjqqtgnfo', 'lfrxfdrduoeqmwwp', 'vszpjvbctblplinh', 'zexhadgpqfifcqrz', 'ueirfnshekpemqua', 'qfremlntihbwabtb', 'nwznunammfexltjc', 'zkyieokaaogjehwt', 'vlrxgkpclzeslqkq', 'xrqrwfsuacywczhs', 'olghlnfjdiwgdbqc', 'difnlxnedpqcsrdf', 'dgpuhiisybjpidsj', 'vlwmwrikmitmoxbt', 'sazpcmcnviynoktm', 'pratafauetiknhln', 'ilgteekhzwlsfwcn', 'ywvwhrwhkaubvkbl', 'qlaxivzwxyhvrxcf', 'hbtlwjdriizqvjfb', 'nrmsononytuwslsa', 'mpxqgdthpoipyhjc', 'mcdiwmiqeidwcglk', 'vfbaeavmjjemfrmo', 'qzcbzmisnynzibrc', 'shzmpgxhehhcejhb', 'wirtjadsqzydtyxd', 'qjlrnjfokkqvnpue', 'dxawdvjntlbxtuqc', 'wttfmnrievfestog', 'eamjfvsjhvzzaobg', 'pbvfcwzjgxahlrag', 'omvmjkqqnobvnzkn', 'lcwmeibxhhlxnkzv', 'uiaeroqfbvlazegs', 'twniyldyuonfyzqw', 'wgjkmsbwgfotdabi', 'hnomamxoxvrzvtew', 'ycrcfavikkrxxfgw', 'isieyodknagzhaxy', 'mgzdqwikzullzyco', 'mumezgtxjrrejtrs', 'nwmwjcgrqiwgfqel', 'wjgxmebfmyjnxyyp', 'durpspyljdykvzxf', 'zuslbrpooyetgafh', 'kuzrhcjwbdouhyme', 'wyxuvbciodscbvfm', 'kbnpvuqwmxwfqtqe', 'zddzercqogdpxmft', 'sigrdchxtgavzzjh', 'lznjolnorbuddgcs', 'ycnqabxlcajagwbt', 'bnaudeaexahdgxsj', 'rlnykxvoctfwanms', 'jngyetkoplrstfzt', 'tdpxknwacksotdub', 'yutqgssfoptvizgr', 'lzmqnxeqjfnsxmsa', 'iqpgfsfmukovsdgu', 'qywreehbidowtjyz', 'iozamtgusdctvnkw', 'ielmujhtmynlwcfd', 'hzxnhtbnmmejlkyf', 'ftbslbzmiqkzebtd', 'bcwdqgiiizmohack', 'dqhfkzeddjzbdlxu', 'mxopokqffisxosci', 'vciatxhtuechbylk', 'khtkhcvelidjdena', 'blatarwzfqcapkdt', 'elamngegnczctcck', 'xeicefdbwrxhuxuf', 'sawvdhjoeahlgcdr', 'kmdcimzsfkdfpnir', 'axjayzqlosrduajb', 'mfhzreuzzumvoggr', 'iqlbkbhrkptquldb', 'xcvztvlshiefuhgb', 'pkvwyqmyoazocrio', 'ajsxkdnerbmhyxaj', 'tudibgsbnpnizvsi', 'cxuiydkgdccrqvkh', 'cyztpjesdzmbcpot', 'nnazphxpanegwitx', 'uphymczbmjalmsct', 'yyxiwnlrogyzwqmg', 'gmqwnahjvvdyhnfa', 'utolskxpuoheugyl', 'mseszdhyzoyavepd', 'ycqknvbuvcjfgmlc', 'sknrxhxbfpvpeorn', 'zqxqjetooqcodwml', 'sesylkpvbndrdhsy', 'fryuxvjnsvnjrxlw', 'mfxusewqurscujnu', 'mbitdjjtgzchvkfv', 'ozwlyxtaalxofovd', 'wdqcduaykxbunpie', 'rlnhykxiraileysk', 'wgoqfrygttlamobg', 'kflxzgxvcblkpsbz', 'tmkisflhativzhde', 'owsdrfgkaamogjzd', 'gaupjkvkzavhfnes', 'wknkurddcknbdleg', 'lltviwincmbtduap', 'qwzvspgbcksyzzmb', 'ydzzkumecryfjgnk', 'jzvmwgjutxoysaam', 'icrwpyhxllbardkr', 'jdopyntshmvltrve', 'afgkigxcuvmdbqou', 'mfzzudntmvuyhjzt', 'duxhgtwafcgrpihc', 'tsnhrkvponudumeb', 'sqtvnbeiigdzbjgv', 'eczmkqwvnsrracuo', 'mhehsgqwiczaiaxv', 'kaudmfvifovrimpd', 'lupikgivechdbwfr', 'mwaaysrndiutuiqx', 'aacuiiwgaannunmm', 'tjqjbftaqitukwzp', 'lrcqyskykbjpaekn', 'lirrvofbcqpjzxmr', 'jurorvzpplyelfml', 'qonbllojmloykjqe', 'sllkzqujfnbauuqp', 'auexjwsvphvikali', 'usuelbssqmbrkxyc', 'wyuokkfjexikptvv', 'wmfedauwjgbrgytl', 'sfwvtlzzebxzmuvw', 'rdhqxuechjsjcvaf', 'kpavhqkukugocsxu', 'ovnjtumxowbxduts', 'zgerpjufauptxgat', 'pevvnzjfwhjxdoxq', 'pmmfwxajgfziszcs', 'difmeqvaghuitjhs', 'icpwjbzcmlcterwm', 'ngqpvhajttxuegyh', 'mosjlqswdngwqsmi', 'frlvgpxrjolgodlu', 'eazwgrpcxjgoszeg', 'bbtsthgkjrpkiiyk', 'tjonoglufuvsvabe', 'xhkbcrofytmbzrtk', 'kqftfzdmpbxjynps', 'kmeqpocbnikdtfyv', 'qjjymgqxhnjwxxhp', 'dmgicrhgbngdtmjt', 'zdxrhdhbdutlawnc', 'afvoekuhdboxghvx', 'hiipezngkqcnihty', 'bbmqgheidenweeov', 'suprgwxgxwfsgjnx', 'adeagikyamgqphrj', 'zzifqinoeqaorjxg', 'adhgppljizpaxzld', 'lvxyieypvvuqjiyc', 'nljoakatwwwoovzn', 'fcrkfxclcacshhmx', 'ownnxqtdhqbgthch', 'lmfylrcdmdkgpwnj', 'hlwjfbvlswbzpbjr', 'mkofhdtljdetcyvp', 'synyxhifbetzarpo', 'agnggugngadrcxoc', 'uhttadmdmhidpyjw', 'ohfwjfhunalbubpr', 'pzkkkkwrlvxiuysn', 'kmidbxmyzkjrwjhu', 'egtitdydwjxmajnw', 'civoeoiuwtwgbqqs', 'dfptsguzfinqoslk', 'tdfvkreormspprer', 'zvnvbrmthatzztwi', 'ffkyddccrrfikjde', 'hrrmraevdnztiwff', 'qaeygykcpbtjwjbr', 'purwhitkmrtybslh', 'qzziznlswjaussel', 'dfcxkvdpqccdqqxj', 'tuotforulrrytgyn', 'gmtgfofgucjywkev', 'wkyoxudvdkbgpwhd', 'qbvktvfvipftztnn', 'otckgmojziezmojb', 'inxhvzbtgkjxflay', 'qvxapbiatuudseno', 'krpvqosbesnjntut', 'oqeukkgjsfuqkjbb', 'prcjnyymnqwqksiz', 'vuortvjxgckresko', 'orqlyobvkuwgathr', 'qnpyxlnazyfuijox', 'zwlblfkoklqmqzkw', 'hmwurwtpwnrcsanl', 'jzvxohuakopuzgpf', 'sfcpnxrviphhvxmx', 'qtwdeadudtqhbely', 'dbmkmloasqphnlgj', 'olylnjtkxgrubmtk', 'nxsdbqjuvwrrdbpq', 'wbabpirnpcsmpipw', 'hjnkyiuxpqrlvims', 'enzpntcjnxdpuqch', 'vvvqhlstzcizyimn', 'triozhqndbttglhv', 'fukvgteitwaagpzx', 'uhcvukfbmrvskpen', 'tizcyupztftzxdmt', 'vtkpnbpdzsaluczz', 'wodfoyhoekidxttm', 'otqocljrmwfqbxzu', 'linfbsnfvixlwykn', 'vxsluutrwskslnye', 'zbshygtwugixjvsi', 'zdcqwxvwytmzhvoo', 'wrseozkkcyctrmei', 'fblgtvogvkpqzxiy', 'opueqnuyngegbtnf', 'qxbovietpacqqxok', 'zacrdrrkohfygddn', 'gbnnvjqmkdupwzpq', 'qgrgmsxeotozvcak', 'hnppukzvzfmlokid', 'dzbheurndscrrtcl', 'wbgdkadtszebbrcw', 'fdmzppzphhpzyuiz', 'bukomunhrjrypohj', 'ohodhelegxootqbj', 'rsplgzarlrknqjyh', 'punjjwpsxnhpzgvu', 'djdfahypfjvpvibm', 'mlgrqsmhaozatsvy', 'xwktrgyuhqiquxgn', 'wvfaoolwtkbrisvf', 'plttjdmguxjwmeqr', 'zlvvbwvlhauyjykw', 'cigwkbyjhmepikej', 'masmylenrusgtyxs', 'hviqzufwyetyznze', 'nzqfuhrooswxxhus', 'pdbdetaqcrqzzwxf', 'oehmvziiqwkzhzib', 'icgpyrukiokmytoy', 'ooixfvwtiafnwkce', 'rvnmgqggpjopkihs', 'wywualssrmaqigqk', 'pdbvflnwfswsrirl', 'jeaezptokkccpbuj', 'mbdwjntysntsaaby', 'ldlgcawkzcwuxzpz', 'lwktbgrzswbsweht', 'ecspepmzarzmgpjm', 'qmfyvulkmkxjncai', 'izftypvwngiukrns', 'zgmnyjfeqffbooww', 'nyrkhggnprhedows', 'yykzzrjmlevgffah', 'mavaemfxhlfejfki', 'cmegmfjbkvpncqwf', 'zxidlodrezztcrij', 'fseasudpgvgnysjv', 'fupcimjupywzpqzp', 'iqhgokavirrcvyys', 'wjmkcareucnmfhui', 'nftflsqnkgjaexhq', 'mgklahzlcbapntgw', 'kfbmeavfxtppnrxn', 'nuhyvhknlufdynvn', 'nviogjxbluwrcoec', 'tyozixxxaqiuvoys', 'kgwlvmvgtsvxojpr', 'moeektyhyonfdhrb', 'kahvevmmfsmiiqex', 'xcywnqzcdqtvhiwd', 'fnievhiyltbvtvem', 'jlmndqufirwgtdxd', 'muypbfttoeelsnbs', 'rypxzbnujitfwkou', 'ubmmjbznskildeoj', 'ofnmizdeicrmkjxp', 'rekvectjbmdnfcib', 'yohrojuvdexbctdh', 'gwfnfdeibynzjmhz', 'jfznhfcqdwlpjull', 'scrinzycfhwkmmso', 'mskutzossrwoqqsi', 'rygoebkzgyzushhr', 'jpjqiycflqkexemx', 'arbufysjqmgaapnl', 'dbjerflevtgweeoj', 'snybnnjlmwjvhois', 'fszuzplntraprmbj', 'mkvaatolvuggikvg', 'zpuzuqygoxesnuyc', 'wnpxvmxvllxalulm', 'eivuuafkvudeouwy', 'rvzckdyixetfuehr', 'qgmnicdoqhveahyx', 'miawwngyymshjmpj', 'pvckyoncpqeqkbmx', 'llninfenrfjqxurv', 'kzbjnlgsqjfuzqtp', 'rveqcmxomvpjcwte', 'bzotkawzbopkosnx', 'ktqvpiribpypaymu', 'wvlzkivbukhnvram', 'uohntlcoguvjqqdo', 'ajlsiksjrcnzepkt', 'xsqatbldqcykwusd', 'ihbivgzrwpmowkop', 'vfayesfojmibkjpb', 'uaqbnijtrhvqxjtb', 'hhovshsfmvkvymba', 'jerwmyxrfeyvxcgg', 'hncafjwrlvdcupma', 'qyvigggxfylbbrzt', 'hiiixcyohmvnkpgk', 'mmitpwopgxuftdfu', 'iaxderqpceboixoa', 'zodfmjhuzhnsqfcb', 'sthtcbadrclrazsi', 'bkkkkcwegvypbrio', 'wmpcofuvzemunlhj', 'gqwebiifvqoeynro', 'juupusqdsvxcpsgv', 'rbhdfhthxelolyse', 'kjimpwnjfrqlqhhz', 'rcuigrjzarzpjgfq', 'htxcejfyzhydinks', 'sxucpdxhvqjxxjwf', 'omsznfcimbcwaxal', 'gufmtdlhgrsvcosb', 'bssshaqujtmluerz', 'uukotwjkstgwijtr', 'kbqkneobbrdogrxk', 'ljqopjcjmelgrakz', 'rwtfnvnzryujwkfb', 'dedjjbrndqnilbeh', 'nzinsxnpptzagwlb', 'lwqanydfirhnhkxy', 'hrjuzfumbvfccxno', 'okismsadkbseumnp', 'sfkmiaiwlktxqvwa', 'hauwpjjwowbunbjj', 'nowkofejwvutcnui', 'bqzzppwoslaeixro', 'urpfgufwbtzenkpj', 'xgeszvuqwxeykhef', 'yxoldvkyuikwqyeq', 'onbbhxrnmohzskgg', 'qcikuxakrqeugpoa', 'lnudcqbtyzhlpers', 'nxduvwfrgzaailgl', 'xniuwvxufzxjjrwz', 'ljwithcqmgvntjdj', 'awkftfagrfzywkhs', 'uedtpzxyubeveuek', 'bhcqdwidbjkqqhzl', 'iyneqjdmlhowwzxx', 'kvshzltcrrururty', 'zgfpiwajegwezupo', 'tkrvyanujjwmyyri', 'ercsefuihcmoaiep', 'ienjrxpmetinvbos', 'jnwfutjbgenlipzq', 'bgohjmrptfuamzbz', 'rtsyamajrhxbcncw', 'tfjdssnmztvbnscs', 'bgaychdlmchngqlp', 'kfjljiobynhwfkjo', 'owtdxzcpqleftbvn', 'ltjtimxwstvzwzjj', 'wbrvjjjajuombokf', 'zblpbpuaqbkvsxye', 'gwgdtbpnlhyqspdi', 'abipqjihjqfofmkx', 'nlqymnuvjpvvgova', 'avngotmhodpoufzn', 'qmdyivtzitnrjuae', 'xfwjmqtqdljuerxi', 'csuellnlcyqaaamq', 'slqyrcurcyuoxquo', 'dcjmxyzbzpohzprl', 'uqfnmjwniyqgsowb', 'rbmxpqoblyxdocqc', 'ebjclrdbqjhladem', 'ainnfhxnsgwqnmyo', 'eyytjjwhvodtzquf', 'iabjgmbbhilrcyyp', 'pqfnehkivuelyccc', 'xgjbyhfgmtseiimt', 'jwxyqhdbjiqqqeyy', 'gxsbrncqkmvaryln', 'vhjisxjkinaejytk', 'seexagcdmaedpcvh', 'lvudfgrcpjxzdpvd', 'fxtegyrqjzhmqean', 'dnoiseraqcoossmc', 'nwrhmwwbykvwmgep', 'udmzskejvizmtlce', 'hbzvqhvudfdlegaa', 'cghmlfqejbxewskv', 'bntcmjqfwomtbwsb', 'qezhowyopjdyhzng', 'todzsocdkgfxanbz', 'zgjkssrjlwxuhwbk', 'eibzljqsieriyrzr', 'wamxvzqyycrxotjp', 'epzvfkispwqynadu', 'dwlpfhtrafrxlyie', 'qhgzujhgdruowoug', 'girstvkahaemmxvh', 'baitcrqmxhazyhbl', 'xyanqcchbhkajdmc', 'gfvjmmcgfhvgnfdq', 'tdfdbslwncbnkzyz', 'jojuselkpmnnbcbb', 'hatdslkgxtqpmavj', 'dvelfeddvgjcyxkj', 'gnsofhkfepgwltse', 'mdngnobasfpewlno', 'qssnbcyjgmkyuoga', 'glvcmmjytmprqwvn', 'gwrixumjbcdffsdl', 'lozravlzvfqtsuiq', 'sicaflbqdxbmdlch', 'inwfjkyyqbwpmqlq', 'cuvszfotxywuzhzi', 'igfxyoaacoarlvay', 'ucjfhgdmnjvgvuni', 'rvvkzjsytqgiposh', 'jduinhjjntrmqroz', 'yparkxbgsfnueyll', 'lyeqqeisxzfsqzuj', 'woncskbibjnumydm', 'lltucklragtjmxtl', 'ubiyvmyhlesfxotj', 'uecjseeicldqrqww', 'xxlxkbcthufnjbnm', 'lhqijovvhlffpxga', 'fzdgqpzijitlogjz', 'efzzjqvwphomxdpd', 'jvgzvuyzobeazssc', 'hejfycgxywfjgbfw', 'yhjjmvkqfbnbliks', 'sffvfyywtlntsdsz', 'dwmxqudvxqdenrur', 'asnukgppdemxrzaz', 'nwqfnumblwvdpphx', 'kqsmkkspqvxzuket', 'cpnraovljzqiquaz', 'qrzgrdlyyzbyykhg', 'opoahcbiydyhsmqe', 'hjknnfdauidjeydr', 'hczdjjlygoezadow', 'rtflowzqycimllfv', 'sfsrgrerzlnychhq', 'bpahuvlblcolpjmj', 'albgnjkgmcrlaicl', 'pijyqdhfxpaxzdex', 'eeymiddvcwkpbpux', 'rqwkqoabywgggnln', 'vckbollyhgbgmgwh', 'ylzlgvnuvpynybkm', 'hpmbxtpfosbsjixt', 'ocebeihnhvkhjfqz', 'tvctyxoujdgwayze', 'efvhwxtuhapqxjen', 'rusksgefyidldmpo', 'nkmtjvddfmhirmzz', 'whvtsuadwofzmvrt', 'iiwjqvsdxudhdzzk', 'gucirgxaxgcassyo', 'rmhfasfzexeykwmr', 'hynlxcvsbgosjbis', 'huregszrcaocueen', 'pifezpoolrnbdqtv', 'unatnixzvdbqeyox', 'xtawlpduxgacchfe', 'bdvdbflqfphndduf', 'xtdsnjnmzccfptyt', 'nkhsdkhqtzqbphhg', 'aqcubmfkczlaxiyb', 'moziflxpsfubucmv', 'srdgnnjtfehiimqx', 'pwfalehdfyykrohf', 'sysxssmvewyfjrve', 'brsemdzosgqvvlxe', 'bimbjoshuvflkiat', 'hkgjasmljkpkwwku', 'sbnmwjvodygobpqc', 'bbbqycejueruihhd', 'corawswvlvneipyc', 'gcyhknmwsczcxedh', 'kppakbffdhntmcqp', 'ynulzwkfaemkcefp', 'pyroowjekeurlbii', 'iwksighrswdcnmxf', 'glokrdmugreygnsg', 'xkmvvumnfzckryop', 'aesviofpufygschi', 'csloawlirnegsssq', 'fkqdqqmlzuxbkzbc', 'uzlhzcfenxdfjdzp', 'poaaidrktteusvyf', 'zrlyfzmjzfvivcfr', 'qwjulskbniitgqtx', 'gjeszjksbfsuejki', 'vczdejdbfixbduaq', 'knjdrjthitjxluth', 'jweydeginrnicirl', 'bottrfgccqhyycsl', 'eiquffofoadmbuhk', 'lbqfutmzoksscswf', 'xfmdvnvfcnzjprba', 'uvugkjbkhlaoxmyx', 'wadlgtpczgvcaqqv', 'inzrszbtossflsxk', 'dbzbtashaartczrj', 'qbjiqpccefcfkvod', 'hluujmokjywotvzy', 'thwlliksfztcmwzh', 'arahybspdaqdexrq', 'nuojrmsgyipdvwyx', 'hnajdwjwmzattvst', 'sulcgaxezkprjbgu', 'rjowuugwdpkjtypw', 'oeugzwuhnrgiaqga', 'wvxnyymwftfoswij', 'pqxklzkjpcqscvde', 'tuymjzknntekglqj', 'odteewktugcwlhln', 'exsptotlfecmgehc', 'eeswfcijtvzgrqel', 'vjhrkiwmunuiwqau', 'zhlixepkeijoemne', 'pavfsmwesuvebzdd', 'jzovbklnngfdmyws', 'nbajyohtzfeoiixz', 'ciozmhrsjzrwxvhz', 'gwucrxieqbaqfjuv', 'uayrxrltnohexawc', 'flmrbhwsfbcquffm', 'gjyabmngkitawlxc', 'rwwtggvaygfbovhg', 'xquiegaisynictjq', 'oudzwuhexrwwdbyy', 'lengxmguyrwhrebb', 'uklxpglldbgqsjls', 'dbmvlfeyguydfsxq', 'zspdwdqcrmtmdtsc', 'mqfnzwbfqlauvrgc', 'amcrkzptgacywvhv', 'ndxmskrwrqysrndf', 'mwjyhsufeqhwisju', 'srlrukoaenyevykt', 'tnpjtpwawrxbikct', 'geczalxmgxejulcv', 'tvkcbqdhmuwcxqci', 'tiovluvwezwwgaox', 'zrjhtbgajkjqzmfo', 'vcrywduwsklepirs', 'lofequdigsszuioy', 'wxsdzomkjqymlzat', 'iabaczqtrfbmypuy', 'ibdlmudbajikcncr', 'rqcvkzsbwmavdwnv', 'ypxoyjelhllhbeog', 'fdnszbkezyjbttbg', 'uxnhrldastpdjkdz', 'xfrjbehtxnlyzcka', 'omjyfhbibqwgcpbv', 'eguucnoxaoprszmp', 'xfpypldgcmcllyzz', 'aypnmgqjxjqceelv', 'mgzharymejlafvgf', 'tzowgwsubbaigdok', 'ilsehjqpcjwmylxc', 'pfmouwntfhfnmrwk', 'csgokybgdqwnduwp', 'eaxwvxvvwbrovypz', 'nmluqvobbbmdiwwb', 'lnkminvfjjzqbmio', 'mjiiqzycqdhfietz', 'towlrzriicyraevq', 'obiloewdvbrsfwjo', 'lmeooaajlthsfltw', 'ichygipzpykkesrw', 'gfysloxmqdsfskvt', 'saqzntehjldvwtsx', 'pqddoemaufpfcaew', 'mjrxvbvwcreaybwe', 'ngfbrwfqnxqosoai', 'nesyewxreiqvhald', 'kqhqdlquywotcyfy', 'liliptyoqujensfi', 'nsahsaxvaepzneqq', 'zaickulfjajhctye', 'gxjzahtgbgbabtht', 'koxbuopaqhlsyhrp', 'jhzejdjidqqtjnwe', 'dekrkdvprfqpcqki', 'linwlombdqtdeyop', 'dvckqqbnigdcmwmx', 'yaxygbjpzkvnnebv', 'rlzkdkgaagmcpxah', 'cfzuyxivtknirqvt', 'obivkajhsjnrxxhn', 'lmjhayymgpseuynn', 'bbjyewkwadaipyju', 'lmzyhwomfypoftuu', 'gtzhqlgltvatxack', 'jfflcfaqqkrrltgq', 'txoummmnzfrlrmcg', 'ohemsbfuqqpucups', 'imsfvowcbieotlok', 'tcnsnccdszxfcyde', 'qkcdtkwuaquajazz', 'arcfnhmdjezdbqku', 'srnocgyqrlcvlhkb', 'mppbzvfmcdirbyfw', 'xiuarktilpldwgwd', 'ypufwmhrvzqmexpc', 'itpdnsfkwgrdujmj', 'cmpxnodtsswkyxkr', 'wayyxtjklfrmvbfp', 'mfaxphcnjczhbbwy', 'sjxhgwdnqcofbdra', 'pnxmujuylqccjvjm', 'ivamtjbvairwjqwl', 'deijtmzgpfxrclss', 'bzkqcaqagsynlaer', 'tycefobvxcvwaulz', 'ctbhnywezxkdsswf', 'urrxxebxrthtjvib', 'fpfelcigwqwdjucv', 'ngfcyyqpqulwcphb', 'rltkzsiipkpzlgpw', 'qfdsymzwhqqdkykc', 'balrhhxipoqzmihj', 'rnwalxgigswxomga', 'ghqnxeogckshphgr', 'lyyaentdizaumnla', 'exriodwfzosbeoib', 'speswfggibijfejk', 'yxmxgfhvmshqszrq', 'hcqhngvahzgawjga', 'qmhlsrfpesmeksur', 'eviafjejygakodla', 'kvcfeiqhynqadbzv', 'fusvyhowslfzqttg', 'girqmvwmcvntrwau', 'yuavizroykfkdekz', 'jmcwohvmzvowrhxf', 'kzimlcpavapynfue', 'wjudcdtrewfabppq', 'yqpteuxqgbmqfgxh', 'xdgiszbuhdognniu', 'jsguxfwhpftlcjoh', 'whakkvspssgjzxre', 'ggvnvjurlyhhijgm', 'krvbhjybnpemeptr', 'pqedgfojyjybfbzr', 'jzhcrsgmnkwwtpdo', 'yyscxoxwofslncmp', 'gzjhnxytmyntzths', 'iteigbnqbtpvqumi', 'zjevfzusnjukqpfw', 'xippcyhkfuounxqk', 'mcnhrcfonfdgpkyh', 'pinkcyuhjkexbmzj', 'lotxrswlxbxlxufs', 'fmqajrtoabpckbnu', 'wfkwsgmcffdgaqxg', 'qfrsiwnohoyfbidr', 'czfqbsbmiuyusaqs', 'ieknnjeecucghpoo', 'cevdgqnugupvmsge', 'gjkajcyjnxdrtuvr', 'udzhrargnujxiclq', 'zqqrhhmjwermjssg', 'ggdivtmgoqajydzz', 'wnpfsgtxowkjiivl', 'afbhqawjbotxnqpd', 'xjpkifkhfjeqifdn', 'oyfggzsstfhvticp', 'kercaetahymeawxy', 'khphblhcgmbupmzt', 'iggoqtqpvaebtiol', 'ofknifysuasshoya', 'qxuewroccsbogrbv', 'apsbnbkiopopytgu', 'zyahfroovfjlythh', 'bxhjwfgeuxlviydq', 'uvbhdtvaypasaswa', 'qamcjzrmesqgqdiz', 'hjnjyzrxntiycyel', 'wkcrwqwniczwdxgq', 'hibxlvkqakusswkx', 'mzjyuenepwdgrkty', 'tvywsoqslfsulses', 'jqwcwuuisrclircv', 'xanwaoebfrzhurct', 'ykriratovsvxxasf', 'qyebvtqqxbjuuwuo', 'telrvlwvriylnder', 'acksrrptgnhkeiaa', 'yemwfjhiqlzsvdxf', 'banrornfkcymmkcc', 'ytbhxvaeiigjpcgm', 'crepyazgxquposkn', 'xlqwdrytzwnxzwzv', 'xtrbfbwopxscftps', 'kwbytzukgseeyjla', 'qtfdvavvjogybxjg', 'ytbmvmrcxwfkgvzw', 'nbscbdskdeocnfzr', 'sqquwjbdxsxhcseg', 'ewqxhigqcgszfsuw', 'cvkyfcyfmubzwsee', 'dcoawetekigxgygd', 'ohgqnqhfimyuqhvi', 'otisopzzpvnhctte', 'bauieohjejamzien', 'ewnnopzkujbvhwce', 'aeyqlskpaehagdiv', 'pncudvivwnnqspxy', 'ytugesilgveokxcg', 'zoidxeelqdjesxpr', 'ducjccsuaygfchzj', 'smhgllqqqcjfubfc', 'nlbyyywergronmir', 'prdawpbjhrzsbsvj', 'nmgzhnjhlpcplmui', 'eflaogtjghdjmxxz', 'qolvpngucbkprrdc', 'ixywxcienveltgho', 'mwnpqtocagenkxut', 'iskrfbwxonkguywx', 'ouhtbvcaczqzmpua', 'srewprgddfgmdbao', 'dyufrltacelchlvu', 'czmzcbrkecixuwzz', 'dtbeojcztzauofuk', 'prrgoehpqhngfgmw', 'baolzvfrrevxsyke', 'zqadgxshwiarkzwh', 'vsackherluvurqqj', 'surbpxdulvcvgjbd', 'wqxytarcxzgxhvtx', 'vbcubqvejcfsgrac', 'zqnjfeapshjowzja', 'hekvbhtainkvbynx', 'knnugxoktxpvoxnh', 'knoaalcefpgtvlwm', 'qoakaunowmsuvkus', 'ypkvlzcduzlezqcb', 'ujhcagawtyepyogh', 'wsilcrxncnffaxjf', 'gbbycjuscquaycrk', 'aduojapeaqwivnly', 'ceafyxrakviagcjy', 'nntajnghicgnrlst', 'vdodpeherjmmvbje', 'wyyhrnegblwvdobn', 'xlfurpghkpbzhhif', 'xyppnjiljvirmqjo', 'kglzqahipnddanpi', 'omjateouxikwxowr', 'ocifnoopfglmndcx', 'emudcukfbadyijev', 'ooktviixetfddfmh', 'wtvrhloyjewdeycg', 'cgjncqykgutfjhvb', 'nkwvpswppeffmwad', 'hqbcmfhzkxmnrivg', 'mdskbvzguxvieilr', 'anjcvqpavhdloaqh', 'erksespdevjylenq', 'fadxwbmisazyegup', 'iyuiffjmcaahowhj', 'ygkdezmynmltodbv', 'fytneukxqkjattvh', 'woerxfadbfrvdcnz', 'iwsljvkyfastccoa', 'movylhjranlorofe', 'drdmicdaiwukemep', 'knfgtsmuhfcvvshg', 'ibstpbevqmdlhajn', 'tstwsswswrxlzrqs', 'estyydmzothggudf', 'jezogwvymvikszwa', 'izmqcwdyggibliet', 'nzpxbegurwnwrnca', 'kzkojelnvkwfublh', 'xqcssgozuxfqtiwi', 'tcdoigumjrgvczfv', 'ikcjyubjmylkwlwq', 'kqfivwystpqzvhan', 'bzukgvyoqewniivj', 'iduapzclhhyfladn', 'fbpyzxdfmkrtfaeg', 'yzsmlbnftftgwadz'] def part1(): def contains_three_vowels(x): n = 0 for c in x: if c in 'aeiou': n += 1 return n >= 3 def contains_dubble(x): for i in range(len(x) - 1): if x[i] == x[i + 1]: return True return False def contains_forbidden(x): forbidden = ['ab', 'cd', 'pq', 'xy'] for i in range(len(x) - 1): if x[i] + x[i + 1] in forbidden: return True return False n = 0 for x in strings: if contains_three_vowels(x) and contains_dubble(x) and (not contains_forbidden(x)): n += 1 print('Number of nice strings: {}'.format(n)) def part2(): def contains_pairs(x): for i in range(len(x) - 3): if x.find(x[i] + x[i + 1], i + 2) >= 0: return True return False def contains_dubble(x): for i in range(len(x) - 2): if x[i] == x[i + 2]: return True return False n = 0 for x in strings: if contains_pairs(x) and contains_dubble(x): n += 1 print('Number of nice strings: {}'.format(n)) part1() part2()
minha_matriz1 = [[1], [2], [3]] minha_matriz2 = [[1, 2, 3], [4, 5, 6]] def imprime_matriz(matriz): for i in matriz: linha = '' for j in i: linha += str(j) print(" ".join(linha), end="") print() # imprime_matriz(minha_matriz1) # imprime_matriz(minha_matriz2)
minha_matriz1 = [[1], [2], [3]] minha_matriz2 = [[1, 2, 3], [4, 5, 6]] def imprime_matriz(matriz): for i in matriz: linha = '' for j in i: linha += str(j) print(' '.join(linha), end='') print()
def get_column(game, col_num): ''' Get the columns ''' col = col_num result = [] for i in range(0, 3): temp = game[i] result.append(temp[col]) return result def print_odd_cubes_to_number(number): ''' Print odds and their cubes ''' if number < 1: print('ERROR: number must be at least 1') else: for i in range(1, number + 1): if i % 2 != 0: print(i, '*', i, '*', i, '=', i ** 3) def print_hundred(nums): ''' Rewrite with while-loop ''' total = 0 i = 0 while total <= 100 and i < len(nums): total = nums[i] + total print(nums[i]) i = i + 1 def my_enumerate(items): ''' Like enumerate() ''' temp = [] for i in range(0, len(items)): temp_1 = (i, items[i]) temp.append(temp_1) return temp def num_rushes(slope_height, rush_height_gain, back_sliding): ''' Use the template ''' current_height = 0 rushes = 0 while current_height < slope_height: current_height = current_height + rush_height_gain rushes = rushes + 1 if current_height >= slope_height: break else: current_height = current_height - back_sliding return rushes def rumbletron(strings): ''' Reserve and capitalize ''' temp = [] for i in range(0, len(strings)): string = strings[i] string = string[::-1] string = string.upper() temp.append(string) return temp
def get_column(game, col_num): """ Get the columns """ col = col_num result = [] for i in range(0, 3): temp = game[i] result.append(temp[col]) return result def print_odd_cubes_to_number(number): """ Print odds and their cubes """ if number < 1: print('ERROR: number must be at least 1') else: for i in range(1, number + 1): if i % 2 != 0: print(i, '*', i, '*', i, '=', i ** 3) def print_hundred(nums): """ Rewrite with while-loop """ total = 0 i = 0 while total <= 100 and i < len(nums): total = nums[i] + total print(nums[i]) i = i + 1 def my_enumerate(items): """ Like enumerate() """ temp = [] for i in range(0, len(items)): temp_1 = (i, items[i]) temp.append(temp_1) return temp def num_rushes(slope_height, rush_height_gain, back_sliding): """ Use the template """ current_height = 0 rushes = 0 while current_height < slope_height: current_height = current_height + rush_height_gain rushes = rushes + 1 if current_height >= slope_height: break else: current_height = current_height - back_sliding return rushes def rumbletron(strings): """ Reserve and capitalize """ temp = [] for i in range(0, len(strings)): string = strings[i] string = string[::-1] string = string.upper() temp.append(string) return temp
class Transformer(object): mappings = {} value_mappings_functions = {} def __init__(self, initial_data): self.initial_data = initial_data def transform_dict(self, obj: dict): result = {} for k, v in obj.items(): if k in self.mappings.keys(): if k in self.value_mappings_functions.keys(): result[self.mappings.get(k)] = self.value_mappings_functions[k](v) else: result[self.mappings.get(k)] = v return result def transform(self): if type(self.initial_data) == list: return [self.transform_dict(i) for i in self.initial_data] return self.transform_dict(self.initial_data)
class Transformer(object): mappings = {} value_mappings_functions = {} def __init__(self, initial_data): self.initial_data = initial_data def transform_dict(self, obj: dict): result = {} for (k, v) in obj.items(): if k in self.mappings.keys(): if k in self.value_mappings_functions.keys(): result[self.mappings.get(k)] = self.value_mappings_functions[k](v) else: result[self.mappings.get(k)] = v return result def transform(self): if type(self.initial_data) == list: return [self.transform_dict(i) for i in self.initial_data] return self.transform_dict(self.initial_data)
# Main driver file for user input and displaying # Also checks legal moves and keep a move log class GameState(): def __init__(self): # Initial board state # Board is 8x8 2d list with each element having 2 characters # First character represents the color: w = white & b = black # Second character represents the type: R = Rook, K = King, etc. # "--" represents a empty space self.board = [ ["bR", "bN", "bB", "bQ", "bK", "bB", "bN", "bR"], ["bp", "bp", "bp", "bp", "bp", "bp", "bp", "bp"], ["--", "--", "--", "--", "--", "--", "--", "--"], ["--", "--", "--", "--", "--", "--", "--", "--"], ["--", "--", "--", "--", "--", "--", "--", "--"], ["--", "--", "--", "--", "--", "--", "--", "--"], ["wp", "wp", "wp", "wp", "wp", "wp", "wp", "wp"], ["wR", "wN", "wB", "wQ", "wK", "wB", "wN", "wR"] ] self.moveFunctions = {"p" : self.getPawnMoves, "R" : self.getRookMoves, "N" : self.getKnightMoves, "Q" : self.getQueenMoves, "K" : self.getKingMoves, "B" : self.getBishopMoves} self.whiteToMove = True self.moveLog = [] self.whiteKingLocation = (7, 4) self.blackKingLocation = (0, 4) self.checkMate = False self.stalemate = False self.enpassantPossible = () self.currentCastlingRight = CastleRights(True, True, True, True) self.castleRightsLog = [CastleRights(self.currentCastlingRight.wks, self.currentCastlingRight.bks, self.currentCastlingRight.wqs, self.currentCastlingRight.bqs)] #Takes a move as a parameter and executes it, doesn't work for castling, pawn promotion and en-passant def makeMove(self, move): self.board[move.startRow][move.startCol] = "--" self.board[move.endRow][move.endCol] = move.pieceMoved self.moveLog.append(move) # Log the move to see history/undo last move self.whiteToMove = not self.whiteToMove # Switch turn to other player # Updates King's position if moved if move.pieceMoved == "wK": self.whiteKingLocation = (move.endRow, move.endCol) if move.pieceMoved == "bK": self.blackKingLocation = (move.endRow, move.endCol) # Pawn promotion if move.isPawnPromotion: self.board[move.endRow][move.endCol] = move.pieceMoved[0] + move.promotionChoice # En-passant move if move.isEnpassantMove: self.board[move.startRow][move.endCol] = "--" # Update enpassantPossible variable if move.pieceMoved[1] == "p" and abs(move.startRow - move.endRow) == 2: self.enpassantPossible = ((move.startRow + move.endRow) // 2, move.startCol) else: self.enpassantPossible = () # Castle move if move.isCastlingMove: if move.endCol - move.startCol == 2: # Kingside castle self.board[move.endRow][move.endCol-1] = self.board[move.endRow][move.endCol+1] # Moves the rook self.board[move.endRow][move.endCol+1] = "--" else: # Queenside castle self.board[move.endRow][move.endCol+1] = self.board[move.endRow][move.endCol-2] self.board[move.endRow][move.endCol-2] = "--" # Updating Castling rights self.updateCastleRights(move) self.castleRightsLog.append(CastleRights(self.currentCastlingRight.wks, self.currentCastlingRight.bks, self.currentCastlingRight.wqs, self.currentCastlingRight.bqs)) def undoMove(self): if len(self.moveLog) != 0: move = self.moveLog.pop() # Gets last move and removes it from movelog self.board[move.startRow][move.startCol] = move.pieceMoved self.board[move.endRow][move.endCol] = move.pieceCaptured self.whiteToMove = not self.whiteToMove # Switches turn back to other player # Updates King's position if moved if move.pieceMoved == "wK": self.whiteKingLocation = (move.startRow, move.startCol) elif move.pieceMoved == "bK": self.blackKingLocation = (move.startRow, move.startCol) if move.isEnpassantMove: self.board[move.endRow][move.endCol] = "--" self.board[move.startRow][move.endCol] = move.pieceCaptured self.enpassantPossible = (move.endRow, move.endCol) if move.pieceMoved[1] == "p" and abs(move.startRow - move.endRow) == 2: self.enpassantPossible = () # Undo-ing castling rights self.castleRightsLog.pop() self.currentCastlingRight = self.castleRightsLog[-1] # Undo-ing castle move if move.isCastlingMove: if move.endCol - move.startCol == 2: # Kingside castle self.board[move.endRow][move.endCol+1] = self.board[move.endRow][move.endCol-1] self.board[move.endRow][move.endCol-1] = "--" else: self.board[move.endRow][move.endCol-2] = self.board[move.endRow][move.endCol+1] self.board[move.endRow][move.endCol+1] = "--" def updateCastleRights(self, move): if move.pieceMoved == "wK": self.currentCastlingRight.wks = False self.currentCastlingRight.wqs = False elif move.pieceMoved == "bK": self.currentCastlingRight.bks = False self.currentCastlingRight.bqs = False elif move.pieceMoved == "wR": if move.startRow == 7: if move.startCol == 0: self.currentCastlingRight.wqs = False elif move.startCol == 7: self.currentCastlingRight.wks = False elif move.pieceMoved == "bR": if move.startRow == 0: if move.startCol == 0: self.currentCastlingRight.bqs = False elif move.startCol == 7: self.currentCastlingRight.bks = False # All posible moves when in check def getValidMoves(self): tempEnpassantPossible = self.enpassantPossible tempCastleRights = CastleRights(self.currentCastlingRight.wks, self.currentCastlingRight.bks, self.currentCastlingRight.wqs, self.currentCastlingRight.bqs) moves = self.getLegalMoves() if self.whiteToMove: self.getCastleMoves(self.whiteKingLocation[0], self.whiteKingLocation[1], moves) else: self.getCastleMoves(self.blackKingLocation[0], self.blackKingLocation[1], moves) for i in range(len(moves)-1, -1, -1): self.makeMove(moves[i]) self.whiteToMove = not self.whiteToMove if self.inCheck(): moves.remove(moves[i]) self.whiteToMove = not self.whiteToMove self.undoMove() if len(moves) == 0: # Either Check Mate of Stalemate if self.inCheck(): self.checkMate = True else: self.stalemate = True self.enpassantPossible = tempEnpassantPossible self.currentCastlingRight = tempCastleRights return moves # Determine if King is under attack def inCheck(self): if self.whiteToMove: return self.squareUnderAttack(self.whiteKingLocation[0], self.whiteKingLocation[1]) else: return self.squareUnderAttack(self.blackKingLocation[0], self.blackKingLocation[1]) # Determine if the enemy can attack a certain square def squareUnderAttack(self, r, c): self.whiteToMove = not self.whiteToMove # switch to opponent to see their moves oppMoves = self.getLegalMoves() self.whiteToMove = not self.whiteToMove for move in oppMoves: if move.endRow == r and move.endCol == c: return True return False # All legal moves without being in check def getLegalMoves(self): moves = [] for r in range(len(self.board)): for c in range(len(self.board[r])): turn = self.board[r][c][0] if (turn == "w" and self.whiteToMove) or (turn == "b" and not self.whiteToMove): piece = self.board[r][c][1] self.moveFunctions[piece](r, c, moves) # Calls the appropriate move function depending on the piece return moves #Define all possible moves for each piece def getPawnMoves(self, r, c, moves): if self.whiteToMove: # White pawn movement if self.board[r-1][c] == "--": moves.append(Move((r, c), (r-1, c), self.board)) if r == 6 and self.board[r-2][c] == "--": moves.append(Move((r, c), (r-2, c), self.board)) if c-1 >= 0: if self.board[r-1][c-1][0] == "b": moves.append(Move((r, c), (r-1, c-1), self.board)) elif (r-1, c-1) == self.enpassantPossible: moves.append(Move((r, c), (r-1, c-1), self.board, isEnpassantMove=True)) if c+1 <= 7: if self.board[r-1][c+1][0] == "b": moves.append(Move((r, c), (r-1, c+1), self.board)) elif (r-1, c+1) == self.enpassantPossible: moves.append(Move((r, c), (r-1, c+1), self.board, isEnpassantMove=True)) else: # Black pawn movement if self.board[r+1][c] == "--": moves.append(Move((r, c), (r+1, c), self.board)) if r == 1 and self.board[r+2][c] == "--": moves.append(Move((r, c), (r+2, c), self.board)) if c-1 >= 0: if self.board[r+1][c-1][0] == "w": moves.append(Move((r, c), (r+1, c-1), self.board)) elif (r+1, c-1) == self.enpassantPossible: moves.append(Move((r, c), (r+1, c-1), self.board, isEnpassantMove=True)) if c+1 <= 7: if self.board[r+1][c+1][0] == "w": moves.append(Move((r, c), (r+1, c+1), self.board)) elif (r+1, c+1) == self.enpassantPossible: moves.append(Move((r, c), (r+1, c+1), self.board, isEnpassantMove=True)) def getRookMoves(self, r, c, moves): directions = ((-1, 0), (0, -1), (1, 0), (0, 1)) enemyColor = "b" if self.whiteToMove else "w" for d in directions: for i in range(1, 8): endRow = r + d[0] * i endCol = c + d[1] * i if 0 <= endRow < 8 and 0 <= endCol < 8: endPiece = self.board[endRow][endCol] if endPiece == "--": moves.append(Move((r, c), (endRow, endCol), self.board)) elif endPiece[0] == enemyColor: moves.append(Move((r, c), (endRow, endCol), self.board)) break else: break else: break def getBishopMoves(self, r, c, moves): directions = ((-1, -1), (1, -1), (1, 1), (-1, 1)) enemyColor = "b" if self.whiteToMove else "w" for d in directions: for i in range(1, 8): endRow = r + d[0] * i endCol = c + d[1] * i if 0 <= endRow < 8 and 0 <= endCol < 8: endPiece = self.board[endRow][endCol] if endPiece == "--": moves.append(Move((r, c), (endRow, endCol), self.board)) elif endPiece[0] == enemyColor: moves.append(Move((r, c), (endRow, endCol), self.board)) break else: break else: break def getKnightMoves(self, r, c, moves): knightMoves = ((-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)) allyColor = "w" if self.whiteToMove else "b" for m in knightMoves: endRow = r + m[0] endCol = c + m[1] if 0 <= endRow < 8 and 0 <= endCol < 8: endPiece = self.board[endRow][endCol] if endPiece[0] != allyColor: moves.append(Move((r, c), (endRow, endCol), self.board)) def getQueenMoves(self, r, c, moves): self.getBishopMoves(r, c, moves) self.getRookMoves(r, c, moves) def getKingMoves(self, r, c, moves): kingMoves = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (1, -1), (1, 1), (1, 0), (0, 1)) allyColor = "w" if self.whiteToMove else "b" for i in range(8): endRow = r + kingMoves[i][0] endCol = c + kingMoves[i][1] if 0 <= endRow < 8 and 0 <= endCol < 8: endPiece = self.board[endRow][endCol] if endPiece[0] != allyColor: moves.append(Move((r, c), (endRow, endCol), self.board)) # Castling handling def getCastleMoves(self, r, c, moves): if self.squareUnderAttack(r, c): return if (self.whiteToMove and self.currentCastlingRight.wks) or (not self.whiteToMove and self.currentCastlingRight.bks): self.getKingSideCastleMoves(r, c, moves) if (self.whiteToMove and self.currentCastlingRight.wqs) or (not self.whiteToMove and self.currentCastlingRight.bqs): self.getQueenSideCastleMoves(r, c, moves) def getKingSideCastleMoves(self, r, c, moves): if self.board[r][c+1] == "--" and self.board[r][c+2] == "--": if not self.squareUnderAttack(r, c+1) and not self.squareUnderAttack(r, c+2): moves.append(Move((r, c), (r, c+2), self.board, isCastlingMove=True, KingSide=True)) def getQueenSideCastleMoves(self, r, c, moves): if self.board[r][c-1] == "--" and self.board[r][c-2] == "--" and self.board[r][c-3] == "--": if not self.squareUnderAttack(r, c-1) and not self.squareUnderAttack(r, c-2): moves.append(Move((r, c), (r, c-2), self.board, isCastlingMove=True, KingSide=False)) class CastleRights(): def __init__(self, wks, bks, wqs, bqs): self.wks = wks self.bks = bks self.wqs = wqs self.bqs = bqs class Move(): # Mapping keys to values ranksToRows = {"1" : 7, "2" : 6, "3" : 5, "4" : 4, "5" : 3, "6" : 2, "7" : 1, "8" : 0} rowsToRanks = {v: k for k, v in ranksToRows.items()} filesToCols = {"h" : 7, "g" : 6, "f" : 5, "e" : 4, "d" : 3, "c" : 2, "b" : 1, "a" : 0} colsToFiles = {v: k for k, v in filesToCols.items()} def __init__(self, startSq, endSq, board, isEnpassantMove=False, isCastlingMove=False, KingSide=False): self.startRow = startSq[0] self.startCol = startSq[1] self.endRow = endSq[0] self.endCol = endSq[1] self.pieceMoved = board[self.startRow][self.startCol] self.pieceCaptured = board[self.endRow][self.endCol] # Pawn promotion self.isPawnPromotion = (self.pieceMoved == "wp" and self.endRow == 0) or (self.pieceMoved == "bp" and self.endRow == 7) self.promotionChoice = "Q" # En-passant self.isEnpassantMove = isEnpassantMove if self.isEnpassantMove: self.pieceCaptured = "wp" if self.pieceMoved == "bp" else "bp" self.isCastlingMove = isCastlingMove self.KingSide = KingSide self.moveID = self.startRow * 1000 + self.startCol * 100 + self.endRow * 10 + self.endCol #Overriding equals method def __eq__(self, other): if isinstance(other, Move): return self.moveID == other.moveID return False def getChessNotation(self): #TODO Disambiguating Moves #TODO Pawn Promotion #TODO Check/Checkmate notation = "" if self.isCastlingMove: if self.KingSide: return "0-0" else: return "0-0-0" if not self.pieceMoved[1] == "p": notation += self.pieceMoved[1] else: if self.pieceCaptured == "--": return self.getRankFile(self.endRow, self.endCol) else: notation = self.getRankFile(self.startRow, self.startCol) return notation[0] + "x" + self.getRankFile(self.endRow, self.endCol) if self.pieceCaptured == "--": return notation + self.getRankFile(self.endRow, self.endCol) else: return notation + "x" + self.getRankFile(self.endRow, self.endCol) def getRankFile(self, r, c): return self.colsToFiles[c] + self.rowsToRanks[r]
class Gamestate: def __init__(self): self.board = [['bR', 'bN', 'bB', 'bQ', 'bK', 'bB', 'bN', 'bR'], ['bp', 'bp', 'bp', 'bp', 'bp', 'bp', 'bp', 'bp'], ['--', '--', '--', '--', '--', '--', '--', '--'], ['--', '--', '--', '--', '--', '--', '--', '--'], ['--', '--', '--', '--', '--', '--', '--', '--'], ['--', '--', '--', '--', '--', '--', '--', '--'], ['wp', 'wp', 'wp', 'wp', 'wp', 'wp', 'wp', 'wp'], ['wR', 'wN', 'wB', 'wQ', 'wK', 'wB', 'wN', 'wR']] self.moveFunctions = {'p': self.getPawnMoves, 'R': self.getRookMoves, 'N': self.getKnightMoves, 'Q': self.getQueenMoves, 'K': self.getKingMoves, 'B': self.getBishopMoves} self.whiteToMove = True self.moveLog = [] self.whiteKingLocation = (7, 4) self.blackKingLocation = (0, 4) self.checkMate = False self.stalemate = False self.enpassantPossible = () self.currentCastlingRight = castle_rights(True, True, True, True) self.castleRightsLog = [castle_rights(self.currentCastlingRight.wks, self.currentCastlingRight.bks, self.currentCastlingRight.wqs, self.currentCastlingRight.bqs)] def make_move(self, move): self.board[move.startRow][move.startCol] = '--' self.board[move.endRow][move.endCol] = move.pieceMoved self.moveLog.append(move) self.whiteToMove = not self.whiteToMove if move.pieceMoved == 'wK': self.whiteKingLocation = (move.endRow, move.endCol) if move.pieceMoved == 'bK': self.blackKingLocation = (move.endRow, move.endCol) if move.isPawnPromotion: self.board[move.endRow][move.endCol] = move.pieceMoved[0] + move.promotionChoice if move.isEnpassantMove: self.board[move.startRow][move.endCol] = '--' if move.pieceMoved[1] == 'p' and abs(move.startRow - move.endRow) == 2: self.enpassantPossible = ((move.startRow + move.endRow) // 2, move.startCol) else: self.enpassantPossible = () if move.isCastlingMove: if move.endCol - move.startCol == 2: self.board[move.endRow][move.endCol - 1] = self.board[move.endRow][move.endCol + 1] self.board[move.endRow][move.endCol + 1] = '--' else: self.board[move.endRow][move.endCol + 1] = self.board[move.endRow][move.endCol - 2] self.board[move.endRow][move.endCol - 2] = '--' self.updateCastleRights(move) self.castleRightsLog.append(castle_rights(self.currentCastlingRight.wks, self.currentCastlingRight.bks, self.currentCastlingRight.wqs, self.currentCastlingRight.bqs)) def undo_move(self): if len(self.moveLog) != 0: move = self.moveLog.pop() self.board[move.startRow][move.startCol] = move.pieceMoved self.board[move.endRow][move.endCol] = move.pieceCaptured self.whiteToMove = not self.whiteToMove if move.pieceMoved == 'wK': self.whiteKingLocation = (move.startRow, move.startCol) elif move.pieceMoved == 'bK': self.blackKingLocation = (move.startRow, move.startCol) if move.isEnpassantMove: self.board[move.endRow][move.endCol] = '--' self.board[move.startRow][move.endCol] = move.pieceCaptured self.enpassantPossible = (move.endRow, move.endCol) if move.pieceMoved[1] == 'p' and abs(move.startRow - move.endRow) == 2: self.enpassantPossible = () self.castleRightsLog.pop() self.currentCastlingRight = self.castleRightsLog[-1] if move.isCastlingMove: if move.endCol - move.startCol == 2: self.board[move.endRow][move.endCol + 1] = self.board[move.endRow][move.endCol - 1] self.board[move.endRow][move.endCol - 1] = '--' else: self.board[move.endRow][move.endCol - 2] = self.board[move.endRow][move.endCol + 1] self.board[move.endRow][move.endCol + 1] = '--' def update_castle_rights(self, move): if move.pieceMoved == 'wK': self.currentCastlingRight.wks = False self.currentCastlingRight.wqs = False elif move.pieceMoved == 'bK': self.currentCastlingRight.bks = False self.currentCastlingRight.bqs = False elif move.pieceMoved == 'wR': if move.startRow == 7: if move.startCol == 0: self.currentCastlingRight.wqs = False elif move.startCol == 7: self.currentCastlingRight.wks = False elif move.pieceMoved == 'bR': if move.startRow == 0: if move.startCol == 0: self.currentCastlingRight.bqs = False elif move.startCol == 7: self.currentCastlingRight.bks = False def get_valid_moves(self): temp_enpassant_possible = self.enpassantPossible temp_castle_rights = castle_rights(self.currentCastlingRight.wks, self.currentCastlingRight.bks, self.currentCastlingRight.wqs, self.currentCastlingRight.bqs) moves = self.getLegalMoves() if self.whiteToMove: self.getCastleMoves(self.whiteKingLocation[0], self.whiteKingLocation[1], moves) else: self.getCastleMoves(self.blackKingLocation[0], self.blackKingLocation[1], moves) for i in range(len(moves) - 1, -1, -1): self.makeMove(moves[i]) self.whiteToMove = not self.whiteToMove if self.inCheck(): moves.remove(moves[i]) self.whiteToMove = not self.whiteToMove self.undoMove() if len(moves) == 0: if self.inCheck(): self.checkMate = True else: self.stalemate = True self.enpassantPossible = tempEnpassantPossible self.currentCastlingRight = tempCastleRights return moves def in_check(self): if self.whiteToMove: return self.squareUnderAttack(self.whiteKingLocation[0], self.whiteKingLocation[1]) else: return self.squareUnderAttack(self.blackKingLocation[0], self.blackKingLocation[1]) def square_under_attack(self, r, c): self.whiteToMove = not self.whiteToMove opp_moves = self.getLegalMoves() self.whiteToMove = not self.whiteToMove for move in oppMoves: if move.endRow == r and move.endCol == c: return True return False def get_legal_moves(self): moves = [] for r in range(len(self.board)): for c in range(len(self.board[r])): turn = self.board[r][c][0] if turn == 'w' and self.whiteToMove or (turn == 'b' and (not self.whiteToMove)): piece = self.board[r][c][1] self.moveFunctions[piece](r, c, moves) return moves def get_pawn_moves(self, r, c, moves): if self.whiteToMove: if self.board[r - 1][c] == '--': moves.append(move((r, c), (r - 1, c), self.board)) if r == 6 and self.board[r - 2][c] == '--': moves.append(move((r, c), (r - 2, c), self.board)) if c - 1 >= 0: if self.board[r - 1][c - 1][0] == 'b': moves.append(move((r, c), (r - 1, c - 1), self.board)) elif (r - 1, c - 1) == self.enpassantPossible: moves.append(move((r, c), (r - 1, c - 1), self.board, isEnpassantMove=True)) if c + 1 <= 7: if self.board[r - 1][c + 1][0] == 'b': moves.append(move((r, c), (r - 1, c + 1), self.board)) elif (r - 1, c + 1) == self.enpassantPossible: moves.append(move((r, c), (r - 1, c + 1), self.board, isEnpassantMove=True)) else: if self.board[r + 1][c] == '--': moves.append(move((r, c), (r + 1, c), self.board)) if r == 1 and self.board[r + 2][c] == '--': moves.append(move((r, c), (r + 2, c), self.board)) if c - 1 >= 0: if self.board[r + 1][c - 1][0] == 'w': moves.append(move((r, c), (r + 1, c - 1), self.board)) elif (r + 1, c - 1) == self.enpassantPossible: moves.append(move((r, c), (r + 1, c - 1), self.board, isEnpassantMove=True)) if c + 1 <= 7: if self.board[r + 1][c + 1][0] == 'w': moves.append(move((r, c), (r + 1, c + 1), self.board)) elif (r + 1, c + 1) == self.enpassantPossible: moves.append(move((r, c), (r + 1, c + 1), self.board, isEnpassantMove=True)) def get_rook_moves(self, r, c, moves): directions = ((-1, 0), (0, -1), (1, 0), (0, 1)) enemy_color = 'b' if self.whiteToMove else 'w' for d in directions: for i in range(1, 8): end_row = r + d[0] * i end_col = c + d[1] * i if 0 <= endRow < 8 and 0 <= endCol < 8: end_piece = self.board[endRow][endCol] if endPiece == '--': moves.append(move((r, c), (endRow, endCol), self.board)) elif endPiece[0] == enemyColor: moves.append(move((r, c), (endRow, endCol), self.board)) break else: break else: break def get_bishop_moves(self, r, c, moves): directions = ((-1, -1), (1, -1), (1, 1), (-1, 1)) enemy_color = 'b' if self.whiteToMove else 'w' for d in directions: for i in range(1, 8): end_row = r + d[0] * i end_col = c + d[1] * i if 0 <= endRow < 8 and 0 <= endCol < 8: end_piece = self.board[endRow][endCol] if endPiece == '--': moves.append(move((r, c), (endRow, endCol), self.board)) elif endPiece[0] == enemyColor: moves.append(move((r, c), (endRow, endCol), self.board)) break else: break else: break def get_knight_moves(self, r, c, moves): knight_moves = ((-2, -1), (-2, 1), (-1, -2), (-1, 2), (1, -2), (1, 2), (2, -1), (2, 1)) ally_color = 'w' if self.whiteToMove else 'b' for m in knightMoves: end_row = r + m[0] end_col = c + m[1] if 0 <= endRow < 8 and 0 <= endCol < 8: end_piece = self.board[endRow][endCol] if endPiece[0] != allyColor: moves.append(move((r, c), (endRow, endCol), self.board)) def get_queen_moves(self, r, c, moves): self.getBishopMoves(r, c, moves) self.getRookMoves(r, c, moves) def get_king_moves(self, r, c, moves): king_moves = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (1, -1), (1, 1), (1, 0), (0, 1)) ally_color = 'w' if self.whiteToMove else 'b' for i in range(8): end_row = r + kingMoves[i][0] end_col = c + kingMoves[i][1] if 0 <= endRow < 8 and 0 <= endCol < 8: end_piece = self.board[endRow][endCol] if endPiece[0] != allyColor: moves.append(move((r, c), (endRow, endCol), self.board)) def get_castle_moves(self, r, c, moves): if self.squareUnderAttack(r, c): return if self.whiteToMove and self.currentCastlingRight.wks or (not self.whiteToMove and self.currentCastlingRight.bks): self.getKingSideCastleMoves(r, c, moves) if self.whiteToMove and self.currentCastlingRight.wqs or (not self.whiteToMove and self.currentCastlingRight.bqs): self.getQueenSideCastleMoves(r, c, moves) def get_king_side_castle_moves(self, r, c, moves): if self.board[r][c + 1] == '--' and self.board[r][c + 2] == '--': if not self.squareUnderAttack(r, c + 1) and (not self.squareUnderAttack(r, c + 2)): moves.append(move((r, c), (r, c + 2), self.board, isCastlingMove=True, KingSide=True)) def get_queen_side_castle_moves(self, r, c, moves): if self.board[r][c - 1] == '--' and self.board[r][c - 2] == '--' and (self.board[r][c - 3] == '--'): if not self.squareUnderAttack(r, c - 1) and (not self.squareUnderAttack(r, c - 2)): moves.append(move((r, c), (r, c - 2), self.board, isCastlingMove=True, KingSide=False)) class Castlerights: def __init__(self, wks, bks, wqs, bqs): self.wks = wks self.bks = bks self.wqs = wqs self.bqs = bqs class Move: ranks_to_rows = {'1': 7, '2': 6, '3': 5, '4': 4, '5': 3, '6': 2, '7': 1, '8': 0} rows_to_ranks = {v: k for (k, v) in ranksToRows.items()} files_to_cols = {'h': 7, 'g': 6, 'f': 5, 'e': 4, 'd': 3, 'c': 2, 'b': 1, 'a': 0} cols_to_files = {v: k for (k, v) in filesToCols.items()} def __init__(self, startSq, endSq, board, isEnpassantMove=False, isCastlingMove=False, KingSide=False): self.startRow = startSq[0] self.startCol = startSq[1] self.endRow = endSq[0] self.endCol = endSq[1] self.pieceMoved = board[self.startRow][self.startCol] self.pieceCaptured = board[self.endRow][self.endCol] self.isPawnPromotion = self.pieceMoved == 'wp' and self.endRow == 0 or (self.pieceMoved == 'bp' and self.endRow == 7) self.promotionChoice = 'Q' self.isEnpassantMove = isEnpassantMove if self.isEnpassantMove: self.pieceCaptured = 'wp' if self.pieceMoved == 'bp' else 'bp' self.isCastlingMove = isCastlingMove self.KingSide = KingSide self.moveID = self.startRow * 1000 + self.startCol * 100 + self.endRow * 10 + self.endCol def __eq__(self, other): if isinstance(other, Move): return self.moveID == other.moveID return False def get_chess_notation(self): notation = '' if self.isCastlingMove: if self.KingSide: return '0-0' else: return '0-0-0' if not self.pieceMoved[1] == 'p': notation += self.pieceMoved[1] elif self.pieceCaptured == '--': return self.getRankFile(self.endRow, self.endCol) else: notation = self.getRankFile(self.startRow, self.startCol) return notation[0] + 'x' + self.getRankFile(self.endRow, self.endCol) if self.pieceCaptured == '--': return notation + self.getRankFile(self.endRow, self.endCol) else: return notation + 'x' + self.getRankFile(self.endRow, self.endCol) def get_rank_file(self, r, c): return self.colsToFiles[c] + self.rowsToRanks[r]
def aumentar(preco,taxa): res = preco * (1 + taxa) return res def diminuir(preco,taxa): res = preco * (1 - taxa) return res def dobro(preco): res = preco * 2 return res def metade(preco): res = preco/2 return res
def aumentar(preco, taxa): res = preco * (1 + taxa) return res def diminuir(preco, taxa): res = preco * (1 - taxa) return res def dobro(preco): res = preco * 2 return res def metade(preco): res = preco / 2 return res
def ps(uid='-1',det='default',suffix='default',shift=.5,logplot='off',figure_number=999): ''' function to determine statistic on line profile (assumes either peak or erf-profile)\n calling sequence: uid='-1',det='default',suffix='default',shift=.5)\n det='default' -> get detector from metadata, otherwise: specify, e.g. det='eiger4m_single'\n suffix='default' -> _stats1_total / _sum_all, otherwise: specify, e.g. suffix='_stats2_total'\n shift: scale for peak presence (0.5 -> peak has to be taller factor 2 above background)\n figure_number: default=999 -> specify figure number for plot ''' #import datetime #import time #import numpy as np #from PIL import Image #from databroker import db, get_fields, get_images, get_table #from matplotlib import pyplot as pltfrom #from lmfit import Model #from lmfit import minimize, Parameters, Parameter, report_fit #from scipy.special import erf # get the scan information: if uid == '-1': uid=-1 if det == 'default': if db[uid].start.detectors[0] == 'elm' and suffix=='default': intensity_field='elm_sum_all' elif db[uid].start.detectors[0] == 'elm': intensity_field='elm'+suffix elif suffix == 'default': intensity_field= db[uid].start.detectors[0]+'_stats1_total' else: intensity_field= db[uid].start.detectors[0]+suffix else: if det=='elm' and suffix == 'default': intensity_field='elm_sum_all' elif det=='elm': intensity_field = 'elm'+suffix elif suffix == 'default': intensity_field=det+'_stats1_total' else: intensity_field=det+suffix field = db[uid].start.motors[0] #field='dcm_b';intensity_field='elm_sum_all' [x,y,t]=get_data(uid,field=field, intensity_field=intensity_field, det=None, debug=False) #need to re-write way to get data x=np.array(x) y=np.array(y) x = np.nan_to_num(x) y = np.nan_to_num(y) PEAK=x[np.argmax(y)] PEAK_y=np.max(y) COM=np.sum(x * y) / np.sum(y) ### from Maksim: assume this is a peak profile: def is_positive(num): return True if num > 0 else False # Normalize values first: ym = (y - np.min(y)) / (np.max(y) - np.min(y)) - shift # roots are at Y=0 positive = is_positive(ym[0]) list_of_roots = [] for i in range(len(y)): current_positive = is_positive(ym[i]) if current_positive != positive: list_of_roots.append(x[i - 1] + (x[i] - x[i - 1]) / (abs(ym[i]) + abs(ym[i - 1])) * abs(ym[i - 1])) positive = not positive if len(list_of_roots) >= 2: FWHM=abs(list_of_roots[-1] - list_of_roots[0]) CEN=list_of_roots[0]+0.5*(list_of_roots[1]-list_of_roots[0]) ps.fwhm=FWHM ps.cen=CEN #return { # 'fwhm': abs(list_of_roots[-1] - list_of_roots[0]), # 'x_range': list_of_roots, #} else: # ok, maybe it's a step function.. print('no peak...trying step function...') ym = ym + shift def err_func(x, x0, k=2, A=1, base=0 ): #### erf fit from Yugang return base - A * erf(k*(x-x0)) mod = Model( err_func ) ### estimate starting values: x0=np.mean(x) #k=0.1*(np.max(x)-np.min(x)) pars = mod.make_params( x0=x0, k=2, A = 1., base = 0. ) result = mod.fit(ym, pars, x = x ) CEN=result.best_values['x0'] FWHM = result.best_values['k'] ps.cen = CEN ps.fwhm = FWHM ### re-plot results: if logplot=='on': plt.close(figure_number) plt.figure(figure_number) plt.semilogy([PEAK,PEAK],[np.min(y),np.max(y)],'k--',label='PEAK') #plt.hold(True) plt.semilogy([CEN,CEN],[np.min(y),np.max(y)],'r-.',label='CEN') plt.semilogy([COM,COM],[np.min(y),np.max(y)],'g.-.',label='COM') plt.semilogy(x,y,'bo-') plt.xlabel(field);plt.ylabel(intensity_field) plt.legend() plt.title('uid: '+str(uid)+' @ '+str(t)+'\nPEAK: '+str(PEAK_y)[:8]+' @ '+str(PEAK)[:8]+' COM @ '+str(COM)[:8]+ '\n FWHM: '+str(FWHM)[:8]+' @ CEN: '+str(CEN)[:8],size=9) plt.show() else: plt.close(figure_number) plt.figure(figure_number) plt.plot([PEAK,PEAK],[np.min(y),np.max(y)],'k--',label='PEAK') #plt.hold(True) plt.plot([CEN,CEN],[np.min(y),np.max(y)],'r-.',label='CEN') plt.plot([COM,COM],[np.min(y),np.max(y)],'g.-.',label='COM') plt.plot(x,y,'bo-') plt.xlabel(field);plt.ylabel(intensity_field) plt.legend() plt.title('uid: '+str(uid)+' @ '+str(t)+'\nPEAK: '+str(PEAK_y)[:8]+' @ '+str(PEAK)[:8]+' COM @ '+str(COM)[:8]+ '\n FWHM: '+str(FWHM)[:8]+' @ CEN: '+str(CEN)[:8],size=9) plt.show() ### assign values of interest as function attributes: ps.peak=PEAK ps.com=COM
def ps(uid='-1', det='default', suffix='default', shift=0.5, logplot='off', figure_number=999): """ function to determine statistic on line profile (assumes either peak or erf-profile) calling sequence: uid='-1',det='default',suffix='default',shift=.5) det='default' -> get detector from metadata, otherwise: specify, e.g. det='eiger4m_single' suffix='default' -> _stats1_total / _sum_all, otherwise: specify, e.g. suffix='_stats2_total' shift: scale for peak presence (0.5 -> peak has to be taller factor 2 above background) figure_number: default=999 -> specify figure number for plot """ if uid == '-1': uid = -1 if det == 'default': if db[uid].start.detectors[0] == 'elm' and suffix == 'default': intensity_field = 'elm_sum_all' elif db[uid].start.detectors[0] == 'elm': intensity_field = 'elm' + suffix elif suffix == 'default': intensity_field = db[uid].start.detectors[0] + '_stats1_total' else: intensity_field = db[uid].start.detectors[0] + suffix elif det == 'elm' and suffix == 'default': intensity_field = 'elm_sum_all' elif det == 'elm': intensity_field = 'elm' + suffix elif suffix == 'default': intensity_field = det + '_stats1_total' else: intensity_field = det + suffix field = db[uid].start.motors[0] [x, y, t] = get_data(uid, field=field, intensity_field=intensity_field, det=None, debug=False) x = np.array(x) y = np.array(y) x = np.nan_to_num(x) y = np.nan_to_num(y) peak = x[np.argmax(y)] peak_y = np.max(y) com = np.sum(x * y) / np.sum(y) def is_positive(num): return True if num > 0 else False ym = (y - np.min(y)) / (np.max(y) - np.min(y)) - shift positive = is_positive(ym[0]) list_of_roots = [] for i in range(len(y)): current_positive = is_positive(ym[i]) if current_positive != positive: list_of_roots.append(x[i - 1] + (x[i] - x[i - 1]) / (abs(ym[i]) + abs(ym[i - 1])) * abs(ym[i - 1])) positive = not positive if len(list_of_roots) >= 2: fwhm = abs(list_of_roots[-1] - list_of_roots[0]) cen = list_of_roots[0] + 0.5 * (list_of_roots[1] - list_of_roots[0]) ps.fwhm = FWHM ps.cen = CEN else: print('no peak...trying step function...') ym = ym + shift def err_func(x, x0, k=2, A=1, base=0): return base - A * erf(k * (x - x0)) mod = model(err_func) x0 = np.mean(x) pars = mod.make_params(x0=x0, k=2, A=1.0, base=0.0) result = mod.fit(ym, pars, x=x) cen = result.best_values['x0'] fwhm = result.best_values['k'] ps.cen = CEN ps.fwhm = FWHM if logplot == 'on': plt.close(figure_number) plt.figure(figure_number) plt.semilogy([PEAK, PEAK], [np.min(y), np.max(y)], 'k--', label='PEAK') plt.semilogy([CEN, CEN], [np.min(y), np.max(y)], 'r-.', label='CEN') plt.semilogy([COM, COM], [np.min(y), np.max(y)], 'g.-.', label='COM') plt.semilogy(x, y, 'bo-') plt.xlabel(field) plt.ylabel(intensity_field) plt.legend() plt.title('uid: ' + str(uid) + ' @ ' + str(t) + '\nPEAK: ' + str(PEAK_y)[:8] + ' @ ' + str(PEAK)[:8] + ' COM @ ' + str(COM)[:8] + '\n FWHM: ' + str(FWHM)[:8] + ' @ CEN: ' + str(CEN)[:8], size=9) plt.show() else: plt.close(figure_number) plt.figure(figure_number) plt.plot([PEAK, PEAK], [np.min(y), np.max(y)], 'k--', label='PEAK') plt.plot([CEN, CEN], [np.min(y), np.max(y)], 'r-.', label='CEN') plt.plot([COM, COM], [np.min(y), np.max(y)], 'g.-.', label='COM') plt.plot(x, y, 'bo-') plt.xlabel(field) plt.ylabel(intensity_field) plt.legend() plt.title('uid: ' + str(uid) + ' @ ' + str(t) + '\nPEAK: ' + str(PEAK_y)[:8] + ' @ ' + str(PEAK)[:8] + ' COM @ ' + str(COM)[:8] + '\n FWHM: ' + str(FWHM)[:8] + ' @ CEN: ' + str(CEN)[:8], size=9) plt.show() ps.peak = PEAK ps.com = COM
# Copyright (c) Ville de Montreal. All rights reserved. # Licensed under the MIT license. # See LICENSE file in the project root for full license information. CITYSCAPE_LABELS = [ ('unlabeled', 0, 0, 0, 0), ('ego vehicle', 1, 0, 0, 0), ('rectification border', 2, 0, 0, 0), ('out of roi', 3, 0, 0, 0), ('static', 4, 0, 0, 0), ('dynamic', 5, 111, 74, 0), ('ground', 6, 81, 0, 81), ('road', 7, 128, 64, 128), ('sidewalk', 8, 244, 35, 232), ('parking', 9, 250, 170, 160), ('rail track', 10, 230, 150, 140), ('building', 11, 70, 70, 70), ('wall', 12, 102, 102, 156), ('fence', 13, 190, 153, 153), ('guard rail', 14, 180, 165, 180), ('bridge', 15, 150, 100, 100), ('tunnel', 16, 150, 120, 90), ('pole', 17, 153, 153, 153), ('polegroup', 18, 153, 153, 153), ('traffic light', 19, 250, 170, 30), ('traffic sign', 20, 220, 220, 0), ('vegetation', 21, 107, 142, 35), ('terrain', 22, 152, 251, 152), ('sky', 23, 70, 130, 180), ('person', 24, 220, 20, 60), ('rider', 25, 255, 0, 0), ('car', 26, 0, 0, 142), ('truck', 27, 0, 0, 70), ('bus', 28, 0, 60, 100), ('caravan', 29, 0, 0, 90), ('trailer', 30, 0, 0, 110), ('train', 31, 0, 80, 100), ('motorcycle', 32, 0, 0, 230), ('bicycle', 33, 119, 11, 32), ('license plate', 34, 0, 0, 142)] CARLA_LABELS = [ ('void', 0, 0, 0, 0), ('building', 1, 70, 70, 70), ('fence', 2, 190, 153, 153), ('other', 3, 250, 170, 160), ('pedestrian', 4, 220, 20, 60), ('pole', 5, 153, 153, 153), ('road line', 6, 157, 234, 50), ('road', 7, 128, 64, 128), ('sidewalk', 8, 244, 35, 232), ('vegetation', 9, 107, 142, 35), ('car', 10, 0, 0, 142), ('wall', 11, 102, 102, 156), ('traffic sign', 12, 220, 220, 0)] CGMU_LABELS = [ ('void', 0, 0, 0, 0), ('pole', 1, 255, 189, 176), ('traffic sign', 2, 255, 181, 0), ('vehicle', 3, 247, 93, 195), ('vegetation', 4, 83, 145, 11), ('median strip', 5, 255, 236, 0), ('building', 6, 123, 0, 255), ('private', 7, 255, 0, 0), ('sidewalk', 8, 0, 205, 255), ('road', 9, 14, 0, 255), ('pedestrian', 10, 0, 255, 4), ('structure', 11, 134, 69, 15), ('construction', 12, 255, 99, 0)]
cityscape_labels = [('unlabeled', 0, 0, 0, 0), ('ego vehicle', 1, 0, 0, 0), ('rectification border', 2, 0, 0, 0), ('out of roi', 3, 0, 0, 0), ('static', 4, 0, 0, 0), ('dynamic', 5, 111, 74, 0), ('ground', 6, 81, 0, 81), ('road', 7, 128, 64, 128), ('sidewalk', 8, 244, 35, 232), ('parking', 9, 250, 170, 160), ('rail track', 10, 230, 150, 140), ('building', 11, 70, 70, 70), ('wall', 12, 102, 102, 156), ('fence', 13, 190, 153, 153), ('guard rail', 14, 180, 165, 180), ('bridge', 15, 150, 100, 100), ('tunnel', 16, 150, 120, 90), ('pole', 17, 153, 153, 153), ('polegroup', 18, 153, 153, 153), ('traffic light', 19, 250, 170, 30), ('traffic sign', 20, 220, 220, 0), ('vegetation', 21, 107, 142, 35), ('terrain', 22, 152, 251, 152), ('sky', 23, 70, 130, 180), ('person', 24, 220, 20, 60), ('rider', 25, 255, 0, 0), ('car', 26, 0, 0, 142), ('truck', 27, 0, 0, 70), ('bus', 28, 0, 60, 100), ('caravan', 29, 0, 0, 90), ('trailer', 30, 0, 0, 110), ('train', 31, 0, 80, 100), ('motorcycle', 32, 0, 0, 230), ('bicycle', 33, 119, 11, 32), ('license plate', 34, 0, 0, 142)] carla_labels = [('void', 0, 0, 0, 0), ('building', 1, 70, 70, 70), ('fence', 2, 190, 153, 153), ('other', 3, 250, 170, 160), ('pedestrian', 4, 220, 20, 60), ('pole', 5, 153, 153, 153), ('road line', 6, 157, 234, 50), ('road', 7, 128, 64, 128), ('sidewalk', 8, 244, 35, 232), ('vegetation', 9, 107, 142, 35), ('car', 10, 0, 0, 142), ('wall', 11, 102, 102, 156), ('traffic sign', 12, 220, 220, 0)] cgmu_labels = [('void', 0, 0, 0, 0), ('pole', 1, 255, 189, 176), ('traffic sign', 2, 255, 181, 0), ('vehicle', 3, 247, 93, 195), ('vegetation', 4, 83, 145, 11), ('median strip', 5, 255, 236, 0), ('building', 6, 123, 0, 255), ('private', 7, 255, 0, 0), ('sidewalk', 8, 0, 205, 255), ('road', 9, 14, 0, 255), ('pedestrian', 10, 0, 255, 4), ('structure', 11, 134, 69, 15), ('construction', 12, 255, 99, 0)]
email = input() while True: commands = input().split() command = commands[0] if command == "Complete": break if command == "Make": case = commands[1] if case == "Upper": email = email.upper() elif case == "Lower": email = email.lower() print(email) elif command == "GetDomain": count = int(commands[1]) print(email[-count:]) elif command == "GetUsername": if "@" not in email: print(f"The email {email} doesn't contain the @ symbol.") else: splitted_email = email.split("@") print(f"{splitted_email[0]}") elif command == "Replace": char = commands[1] email = email.replace(char, "-") print(email) elif command == "Encrypt": for s in email: print(ord(s), end=" ")
email = input() while True: commands = input().split() command = commands[0] if command == 'Complete': break if command == 'Make': case = commands[1] if case == 'Upper': email = email.upper() elif case == 'Lower': email = email.lower() print(email) elif command == 'GetDomain': count = int(commands[1]) print(email[-count:]) elif command == 'GetUsername': if '@' not in email: print(f"The email {email} doesn't contain the @ symbol.") else: splitted_email = email.split('@') print(f'{splitted_email[0]}') elif command == 'Replace': char = commands[1] email = email.replace(char, '-') print(email) elif command == 'Encrypt': for s in email: print(ord(s), end=' ')
#tuples are immutable like strings eggs = ('hello', 42, 0.5) eggs[0] 'hello' eggs[1:3] (42, 0.5) print(len(eggs)) type(('hello',)) #class 'tuple' type(('hello')) #class 'str' #Converting Types with the list() and tuple() Functions tuple(['cat', 'dog', 5]) #('cat', 'dog', 5) list(('cat', 'dog', 5)) #['cat', 'dog', 5] list('hello') #['h', 'e', 'l', 'l', 'o']
eggs = ('hello', 42, 0.5) eggs[0] 'hello' eggs[1:3] (42, 0.5) print(len(eggs)) type(('hello',)) type('hello') tuple(['cat', 'dog', 5]) list(('cat', 'dog', 5)) list('hello')
#!/usr/bin/python class Problem7: ''' 10001st prime Problem 7 104743 By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? ''' def solution(self): primes = [] nextPrime = 2 for i in range(10001): print('%d, %d' % (i, nextPrime)) nextPrime = self.getNextPrime(primes) return nextPrime def getNextPrime(self, primes): if (len(primes) == 0): primes.append(2) return 2 if (len(primes) == 1): primes.append(3) return 3 findNewPrime = False nextPrime = primes[-1] + 2 while not findNewPrime: findNewPrime = True for i in primes: if not nextPrime % i: findNewPrime = False break if (findNewPrime): primes.append(nextPrime) break nextPrime += 2 return nextPrime p = Problem7() print(p.solution())
class Problem7: """ 10001st prime Problem 7 104743 By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? """ def solution(self): primes = [] next_prime = 2 for i in range(10001): print('%d, %d' % (i, nextPrime)) next_prime = self.getNextPrime(primes) return nextPrime def get_next_prime(self, primes): if len(primes) == 0: primes.append(2) return 2 if len(primes) == 1: primes.append(3) return 3 find_new_prime = False next_prime = primes[-1] + 2 while not findNewPrime: find_new_prime = True for i in primes: if not nextPrime % i: find_new_prime = False break if findNewPrime: primes.append(nextPrime) break next_prime += 2 return nextPrime p = problem7() print(p.solution())
class Solution: # Top Down DP (Accepted), O(n^2) time, O(1) space def minimumTotal(self, triangle: List[List[int]]) -> int: for i in range(1, len(triangle)): row = triangle[i] row[0] += triangle[i-1][0] row[-1] += triangle[i-1][-1] for j in range(1, len(row)-1): row[j] += min(triangle[i-1][j], triangle[i-1][j-1]) return min(triangle[-1]) # Bottom Up DP (Top Voted), O(n^2) time, O(1) space def minimumTotal(self, triangle: List[List[int]]) -> int: if not triangle: return for i in range(len(triangle)-2, -1, -1): for j in range(len(triangle[i])): triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1]) return triangle[0][0]
class Solution: def minimum_total(self, triangle: List[List[int]]) -> int: for i in range(1, len(triangle)): row = triangle[i] row[0] += triangle[i - 1][0] row[-1] += triangle[i - 1][-1] for j in range(1, len(row) - 1): row[j] += min(triangle[i - 1][j], triangle[i - 1][j - 1]) return min(triangle[-1]) def minimum_total(self, triangle: List[List[int]]) -> int: if not triangle: return for i in range(len(triangle) - 2, -1, -1): for j in range(len(triangle[i])): triangle[i][j] += min(triangle[i + 1][j], triangle[i + 1][j + 1]) return triangle[0][0]
#! /usr/bin/env python #Asking for input until a list of 10 integers given while True: num = input("Enter a list of 10 integers separated by a ',' : ").split(',') l = len(num) try: for i in range(l): num[i] = int(num[i]) p = (l==10) if p: break except: continue #Finding prime numbers prime_num = [] for x in num: if x > 1: for i in range(2,((x//2)+1)): if x % i == 0: break else: prime_num.append(x) elif x == 1: #Number 1 is not considered as prime continue else: #For any negative numbers or 0 continue if len(prime_num) > 0: print(f'Prime numbers from the given list are : {prime_num}') else: print("There were no prime numbers in the given list") print("\nEnd")
while True: num = input("Enter a list of 10 integers separated by a ',' : ").split(',') l = len(num) try: for i in range(l): num[i] = int(num[i]) p = l == 10 if p: break except: continue prime_num = [] for x in num: if x > 1: for i in range(2, x // 2 + 1): if x % i == 0: break else: prime_num.append(x) elif x == 1: continue else: continue if len(prime_num) > 0: print(f'Prime numbers from the given list are : {prime_num}') else: print('There were no prime numbers in the given list') print('\nEnd')
#!/usr/bin/env python3 # Lists # Create a list list_1 = [] # Creates an empty list using parantheses list_2 = list() # Creates an empty list using the list() builtin # Lists can accomodate different/multiple data types list_2 = [1, 2, 3] list_3 = ["a", "b", "c"] list_4 = ["a", "hello", 1, "5"] # Lists can accomodate other lists list_5 = [[1, 2, 3], [5, 6, 1]] # Combine a list with an existing list list_6 = list_5.__add__(list_4) # Or list_5 + list_4 print(list_6) print(dir()) # Create a copy of a list # # 1. Use `=` # This is an exact copy, which means any change in one goes in the other # The new list name is just a reference to the same memory address list_copy_1 = list_4 print(id(list_copy_1)) print(id(list_4)) list_copy_1 is list_4 # # 2. Add the elements, rather than assigning the list directly list_copy_2 = list_4[:] print(id(list_copy_1)) print(id(list_4)) list_copy_1 is list_4
list_1 = [] list_2 = list() list_2 = [1, 2, 3] list_3 = ['a', 'b', 'c'] list_4 = ['a', 'hello', 1, '5'] list_5 = [[1, 2, 3], [5, 6, 1]] list_6 = list_5.__add__(list_4) print(list_6) print(dir()) list_copy_1 = list_4 print(id(list_copy_1)) print(id(list_4)) list_copy_1 is list_4 list_copy_2 = list_4[:] print(id(list_copy_1)) print(id(list_4)) list_copy_1 is list_4
class File: def __init__(self, name: str, mode: str): self.file = open(name, mode) def write(self, line: str): self.file.write(line + "\n") def write_dict(self, dict): for key, val in dict.items(): self.write(f"{key}: {val}") def close(self): self.file.close()
class File: def __init__(self, name: str, mode: str): self.file = open(name, mode) def write(self, line: str): self.file.write(line + '\n') def write_dict(self, dict): for (key, val) in dict.items(): self.write(f'{key}: {val}') def close(self): self.file.close()
query_set = [ "SELECT subscriber.s_id, subscriber.sub_nbr, \ subscriber.bit_1, subscriber.bit_2, subscriber.bit_3, subscriber.bit_4, subscriber.bit_5, subscriber.bit_6, subscriber.bit_7, \ subscriber.bit_8, subscriber.bit_9, subscriber.bit_10, \ subscriber.hex_1, subscriber.hex_2, subscriber.hex_3, subscriber.hex_4, subscriber.hex_5, subscriber.hex_6, subscriber.hex_7, \ subscriber.hex_8, subscriber.hex_9, subscriber.hex_10, \ subscriber.byte2_1, subscriber.byte2_2, subscriber.byte2_3, subscriber.byte2_4, subscriber.byte2_5, \ subscriber.byte2_6, subscriber.byte2_7, subscriber.byte2_8, subscriber.byte2_9, subscriber.byte2_10, \ subscriber.msc_location, subscriber.vlr_location \ FROM subscriber \ WHERE subscriber.s_id = <non_uniform_rand_int_subscriber_size>; ",35, # was 35 "SELECT call_forwarding.numberx \ FROM special_facility, call_forwarding \ WHERE \ (special_facility.s_id = <non_uniform_rand_int_subscriber_size> \ AND special_facility.sf_type = <rand_int_1_4> \ AND special_facility.is_active = 1) \ AND (call_forwarding.s_id = special_facility.s_id \ AND call_forwarding.sf_type = special_facility.sf_type) \ AND (call_forwarding.start_time <= <rand_0_8_16> \ AND call_forwarding.end_time >= <rand_1_to_24>);",10, # was 10 "SELECT access_info.data1, access_info.data2, access_info.data3, access_info.data4 \ FROM access_info \ WHERE access_info.s_id = <non_uniform_rand_int_subscriber_size> \ AND access_info.ai_type = <rand_int_1_4>;",35, # was 35 "UPDATE subscriber, special_facility \ SET subscriber.bit_1 = <bit_rand>, special_facility.data_a = <rand_int_1_255> \ WHERE subscriber.s_id = <non_uniform_rand_int_subscriber_size> \ AND special_facility.s_id = <non_uniform_rand_int_subscriber_size> \ AND special_facility.sf_type = <rand_int_1_4>;", 2, # Was 2 "UPDATE subscriber \ SET subscriber.vlr_location = <rand_int_1_big> \ WHERE subscriber.sub_nbr = '<non_uniform_rand_int_subscriber_size_string>';",14, # Was 14 "INSERT INTO call_forwarding (call_forwarding.s_id, call_forwarding.sf_type, call_forwarding.start_time, call_forwarding.end_time, call_forwarding.numberx) \ SELECT subscriber.s_id, special_facility.sf_type ,<rand_0_8_16>,<rand_1_to_24>, <non_uniform_rand_int_subscriber_size> \ FROM subscriber \ LEFT OUTER JOIN special_facility ON subscriber.s_id = special_facility.s_id \ WHERE subscriber.sub_nbr = '<non_uniform_rand_int_subscriber_size_string>' \ ORDER BY RAND() LIMIT 1;",2, # Was 2, but self-conflicting was an issue. "DELETE call_forwarding FROM call_forwarding \ INNER JOIN subscriber ON subscriber.s_id = call_forwarding.s_id \ WHERE call_forwarding.sf_type = <rand_int_1_4> \ AND call_forwarding.start_time = <rand_0_8_16> \ AND subscriber.sub_nbr = '<non_uniform_rand_int_subscriber_size_string>';",2, # Was 2 ]
query_set = ['SELECT subscriber.s_id, subscriber.sub_nbr, subscriber.bit_1, subscriber.bit_2, subscriber.bit_3, subscriber.bit_4, subscriber.bit_5, subscriber.bit_6, subscriber.bit_7, subscriber.bit_8, subscriber.bit_9, subscriber.bit_10, subscriber.hex_1, subscriber.hex_2, subscriber.hex_3, subscriber.hex_4, subscriber.hex_5, subscriber.hex_6, subscriber.hex_7, subscriber.hex_8, subscriber.hex_9, subscriber.hex_10, subscriber.byte2_1, subscriber.byte2_2, subscriber.byte2_3, subscriber.byte2_4, subscriber.byte2_5, subscriber.byte2_6, subscriber.byte2_7, subscriber.byte2_8, subscriber.byte2_9, subscriber.byte2_10, subscriber.msc_location, subscriber.vlr_location FROM subscriber WHERE subscriber.s_id = <non_uniform_rand_int_subscriber_size>; ', 35, 'SELECT call_forwarding.numberx FROM special_facility, call_forwarding WHERE (special_facility.s_id = <non_uniform_rand_int_subscriber_size> AND special_facility.sf_type = <rand_int_1_4> AND special_facility.is_active = 1) AND (call_forwarding.s_id = special_facility.s_id AND call_forwarding.sf_type = special_facility.sf_type) AND (call_forwarding.start_time <= <rand_0_8_16> AND call_forwarding.end_time >= <rand_1_to_24>);', 10, 'SELECT access_info.data1, access_info.data2, access_info.data3, access_info.data4 FROM access_info WHERE access_info.s_id = <non_uniform_rand_int_subscriber_size> AND access_info.ai_type = <rand_int_1_4>;', 35, 'UPDATE subscriber, special_facility SET subscriber.bit_1 = <bit_rand>, special_facility.data_a = <rand_int_1_255> WHERE subscriber.s_id = <non_uniform_rand_int_subscriber_size> AND special_facility.s_id = <non_uniform_rand_int_subscriber_size> AND special_facility.sf_type = <rand_int_1_4>;', 2, "UPDATE subscriber SET subscriber.vlr_location = <rand_int_1_big> WHERE subscriber.sub_nbr = '<non_uniform_rand_int_subscriber_size_string>';", 14, "INSERT INTO call_forwarding (call_forwarding.s_id, call_forwarding.sf_type, call_forwarding.start_time, call_forwarding.end_time, call_forwarding.numberx) SELECT subscriber.s_id, special_facility.sf_type ,<rand_0_8_16>,<rand_1_to_24>, <non_uniform_rand_int_subscriber_size> FROM subscriber LEFT OUTER JOIN special_facility ON subscriber.s_id = special_facility.s_id WHERE subscriber.sub_nbr = '<non_uniform_rand_int_subscriber_size_string>' ORDER BY RAND() LIMIT 1;", 2, "DELETE call_forwarding FROM call_forwarding INNER JOIN subscriber ON subscriber.s_id = call_forwarding.s_id WHERE call_forwarding.sf_type = <rand_int_1_4> AND call_forwarding.start_time = <rand_0_8_16> AND subscriber.sub_nbr = '<non_uniform_rand_int_subscriber_size_string>';", 2]
## https://leetcode.com/problems/find-all-duplicates-in-an-array/ ## pretty simple solution -- use a set to keep track of the numbers ## that have already appeared (because lookup time is O(1) given ## the implementation in python via a hash table). Gives me an O(N) ## runtime ## runetime is 79th percentile; memory is 19th percentile class Solution: def findDuplicates(self, nums: List[int]) -> List[int]: already_appeared = set([]) twice = [] while len(nums): n = nums.pop() if n in already_appeared: twice.append(n) else: already_appeared.add(n) return twice
class Solution: def find_duplicates(self, nums: List[int]) -> List[int]: already_appeared = set([]) twice = [] while len(nums): n = nums.pop() if n in already_appeared: twice.append(n) else: already_appeared.add(n) return twice
world_cities = ['Dubai', 'New Orleans', 'Santorini', 'Gaza', 'Seoul'] print('***********') print(world_cities) print('***********') print(sorted(world_cities)) print('***********') print(world_cities) print('***********') print(sorted(world_cities, reverse=True)) print('***********') print(world_cities) print('***********') world_cities.reverse() print('***********') print(world_cities) world_cities.reverse() print('***********') print(world_cities) print('***********') world_cities.sort() print(world_cities)
world_cities = ['Dubai', 'New Orleans', 'Santorini', 'Gaza', 'Seoul'] print('***********') print(world_cities) print('***********') print(sorted(world_cities)) print('***********') print(world_cities) print('***********') print(sorted(world_cities, reverse=True)) print('***********') print(world_cities) print('***********') world_cities.reverse() print('***********') print(world_cities) world_cities.reverse() print('***********') print(world_cities) print('***********') world_cities.sort() print(world_cities)
# Given a non-negative integer num, return the number of steps to reduce it to zero. # If the current number is even, you have to divide it by 2, # otherwise, you have to subtract 1 from it. def count_steps(num): steps = 0 while num != 0: if num % 2 == 1: num -= 1 else: num /= 2 steps += 1 return steps
def count_steps(num): steps = 0 while num != 0: if num % 2 == 1: num -= 1 else: num /= 2 steps += 1 return steps
# https://leetcode.com/problems/is-subsequence/ class Solution: def isSubsequence(self, s: str, t: str) -> bool: if len(s) == 0: return True sIndex = 0 for tIndex, tChar in enumerate(t): if s[sIndex] == tChar: sIndex += 1 if sIndex == len(s): return True return False
class Solution: def is_subsequence(self, s: str, t: str) -> bool: if len(s) == 0: return True s_index = 0 for (t_index, t_char) in enumerate(t): if s[sIndex] == tChar: s_index += 1 if sIndex == len(s): return True return False
# # PySNMP MIB module H3C-FTM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/H3C-FTM-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:09:18 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") h3cCommon, = mibBuilder.importSymbols("HUAWEI-3COM-OID-MIB", "h3cCommon") ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance") MibIdentifier, Gauge32, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, ModuleIdentity, Counter64, iso, ObjectIdentity, Unsigned32, IpAddress, TimeTicks, Counter32, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "Gauge32", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "ModuleIdentity", "Counter64", "iso", "ObjectIdentity", "Unsigned32", "IpAddress", "TimeTicks", "Counter32", "Integer32") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") h3cFtmManMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1)) if mibBuilder.loadTexts: h3cFtmManMIB.setLastUpdated('200401131055Z') if mibBuilder.loadTexts: h3cFtmManMIB.setOrganization('HUAWEI-3COM TECHNOLOGIES.') h3cFtm = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1)) h3cFtmManMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1)) h3cFtmUnitTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1), ) if mibBuilder.loadTexts: h3cFtmUnitTable.setStatus('current') h3cFtmUnitEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1), ).setIndexNames((0, "H3C-FTM-MIB", "h3cFtmIndex")) if mibBuilder.loadTexts: h3cFtmUnitEntry.setStatus('current') h3cFtmIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 1), Integer32()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: h3cFtmIndex.setStatus('current') h3cFtmUnitID = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: h3cFtmUnitID.setStatus('current') h3cFtmUnitName = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 3), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: h3cFtmUnitName.setStatus('current') h3cFtmUnitRole = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("master", 0), ("slave", 1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: h3cFtmUnitRole.setStatus('current') h3cFtmNumberMode = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("automatic", 0), ("manual", 1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: h3cFtmNumberMode.setStatus('current') h3cFtmAuthMode = MibScalar((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("ftm-none", 0), ("ftm-simple", 1), ("ftm-md5", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: h3cFtmAuthMode.setStatus('current') h3cFtmAuthValue = MibScalar((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 3), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: h3cFtmAuthValue.setStatus('current') h3cFtmFabricVlanID = MibScalar((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 4094))).setMaxAccess("readwrite") if mibBuilder.loadTexts: h3cFtmFabricVlanID.setStatus('current') h3cFtmFabricType = MibScalar((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("outofStack", 1), ("line", 2), ("ring", 3), ("mesh", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: h3cFtmFabricType.setStatus('current') h3cFtmManMIBNotification = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 3)) h3cFtmUnitIDChange = NotificationType((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 3, 1)).setObjects(("H3C-FTM-MIB", "h3cFtmIndex"), ("H3C-FTM-MIB", "h3cFtmUnitID")) if mibBuilder.loadTexts: h3cFtmUnitIDChange.setStatus('current') h3cFtmUnitNameChange = NotificationType((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 3, 2)).setObjects(("H3C-FTM-MIB", "h3cFtmIndex"), ("H3C-FTM-MIB", "h3cFtmUnitName")) if mibBuilder.loadTexts: h3cFtmUnitNameChange.setStatus('current') h3cFtmManMIBComformance = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2)) h3cFtmMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 1)) h3cFtmMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 1, 1)).setObjects(("H3C-FTM-MIB", "h3cFtmConfigGroup"), ("H3C-FTM-MIB", "h3cFtmNotificationGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): h3cFtmMIBCompliance = h3cFtmMIBCompliance.setStatus('current') h3cFtmMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 2)) h3cFtmConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 2, 1)).setObjects(("H3C-FTM-MIB", "h3cFtmUnitID"), ("H3C-FTM-MIB", "h3cFtmUnitName"), ("H3C-FTM-MIB", "h3cFtmAuthMode"), ("H3C-FTM-MIB", "h3cFtmAuthValue"), ("H3C-FTM-MIB", "h3cFtmFabricVlanID"), ("H3C-FTM-MIB", "h3cFtmFabricType")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): h3cFtmConfigGroup = h3cFtmConfigGroup.setStatus('current') h3cFtmNotificationGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 2, 2)).setObjects(("H3C-FTM-MIB", "h3cFtmUnitIDChange"), ("H3C-FTM-MIB", "h3cFtmUnitNameChange")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): h3cFtmNotificationGroup = h3cFtmNotificationGroup.setStatus('current') mibBuilder.exportSymbols("H3C-FTM-MIB", h3cFtmUnitID=h3cFtmUnitID, h3cFtmManMIBObjects=h3cFtmManMIBObjects, h3cFtmManMIBNotification=h3cFtmManMIBNotification, h3cFtmFabricVlanID=h3cFtmFabricVlanID, h3cFtmNotificationGroup=h3cFtmNotificationGroup, h3cFtmNumberMode=h3cFtmNumberMode, h3cFtm=h3cFtm, h3cFtmManMIBComformance=h3cFtmManMIBComformance, h3cFtmUnitRole=h3cFtmUnitRole, h3cFtmUnitEntry=h3cFtmUnitEntry, h3cFtmManMIB=h3cFtmManMIB, h3cFtmMIBCompliances=h3cFtmMIBCompliances, h3cFtmMIBCompliance=h3cFtmMIBCompliance, h3cFtmFabricType=h3cFtmFabricType, h3cFtmAuthMode=h3cFtmAuthMode, h3cFtmAuthValue=h3cFtmAuthValue, h3cFtmUnitName=h3cFtmUnitName, PYSNMP_MODULE_ID=h3cFtmManMIB, h3cFtmConfigGroup=h3cFtmConfigGroup, h3cFtmIndex=h3cFtmIndex, h3cFtmMIBGroups=h3cFtmMIBGroups, h3cFtmUnitIDChange=h3cFtmUnitIDChange, h3cFtmUnitTable=h3cFtmUnitTable, h3cFtmUnitNameChange=h3cFtmUnitNameChange)
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, constraints_union, single_value_constraint, value_range_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ConstraintsUnion', 'SingleValueConstraint', 'ValueRangeConstraint', 'ValueSizeConstraint') (h3c_common,) = mibBuilder.importSymbols('HUAWEI-3COM-OID-MIB', 'h3cCommon') (object_group, notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'ObjectGroup', 'NotificationGroup', 'ModuleCompliance') (mib_identifier, gauge32, bits, mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type, module_identity, counter64, iso, object_identity, unsigned32, ip_address, time_ticks, counter32, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibIdentifier', 'Gauge32', 'Bits', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType', 'ModuleIdentity', 'Counter64', 'iso', 'ObjectIdentity', 'Unsigned32', 'IpAddress', 'TimeTicks', 'Counter32', 'Integer32') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') h3c_ftm_man_mib = module_identity((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1)) if mibBuilder.loadTexts: h3cFtmManMIB.setLastUpdated('200401131055Z') if mibBuilder.loadTexts: h3cFtmManMIB.setOrganization('HUAWEI-3COM TECHNOLOGIES.') h3c_ftm = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1)) h3c_ftm_man_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1)) h3c_ftm_unit_table = mib_table((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1)) if mibBuilder.loadTexts: h3cFtmUnitTable.setStatus('current') h3c_ftm_unit_entry = mib_table_row((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1)).setIndexNames((0, 'H3C-FTM-MIB', 'h3cFtmIndex')) if mibBuilder.loadTexts: h3cFtmUnitEntry.setStatus('current') h3c_ftm_index = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 1), integer32()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: h3cFtmIndex.setStatus('current') h3c_ftm_unit_id = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 2), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: h3cFtmUnitID.setStatus('current') h3c_ftm_unit_name = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 3), octet_string()).setMaxAccess('readwrite') if mibBuilder.loadTexts: h3cFtmUnitName.setStatus('current') h3c_ftm_unit_role = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('master', 0), ('slave', 1)))).setMaxAccess('readonly') if mibBuilder.loadTexts: h3cFtmUnitRole.setStatus('current') h3c_ftm_number_mode = mib_table_column((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 1, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('automatic', 0), ('manual', 1)))).setMaxAccess('readonly') if mibBuilder.loadTexts: h3cFtmNumberMode.setStatus('current') h3c_ftm_auth_mode = mib_scalar((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2))).clone(namedValues=named_values(('ftm-none', 0), ('ftm-simple', 1), ('ftm-md5', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: h3cFtmAuthMode.setStatus('current') h3c_ftm_auth_value = mib_scalar((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 3), octet_string()).setMaxAccess('readwrite') if mibBuilder.loadTexts: h3cFtmAuthValue.setStatus('current') h3c_ftm_fabric_vlan_id = mib_scalar((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(2, 4094))).setMaxAccess('readwrite') if mibBuilder.loadTexts: h3cFtmFabricVlanID.setStatus('current') h3c_ftm_fabric_type = mib_scalar((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('outofStack', 1), ('line', 2), ('ring', 3), ('mesh', 4)))).setMaxAccess('readonly') if mibBuilder.loadTexts: h3cFtmFabricType.setStatus('current') h3c_ftm_man_mib_notification = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 3)) h3c_ftm_unit_id_change = notification_type((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 3, 1)).setObjects(('H3C-FTM-MIB', 'h3cFtmIndex'), ('H3C-FTM-MIB', 'h3cFtmUnitID')) if mibBuilder.loadTexts: h3cFtmUnitIDChange.setStatus('current') h3c_ftm_unit_name_change = notification_type((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 3, 2)).setObjects(('H3C-FTM-MIB', 'h3cFtmIndex'), ('H3C-FTM-MIB', 'h3cFtmUnitName')) if mibBuilder.loadTexts: h3cFtmUnitNameChange.setStatus('current') h3c_ftm_man_mib_comformance = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2)) h3c_ftm_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 1)) h3c_ftm_mib_compliance = module_compliance((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 1, 1)).setObjects(('H3C-FTM-MIB', 'h3cFtmConfigGroup'), ('H3C-FTM-MIB', 'h3cFtmNotificationGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): h3c_ftm_mib_compliance = h3cFtmMIBCompliance.setStatus('current') h3c_ftm_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 2)) h3c_ftm_config_group = object_group((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 2, 1)).setObjects(('H3C-FTM-MIB', 'h3cFtmUnitID'), ('H3C-FTM-MIB', 'h3cFtmUnitName'), ('H3C-FTM-MIB', 'h3cFtmAuthMode'), ('H3C-FTM-MIB', 'h3cFtmAuthValue'), ('H3C-FTM-MIB', 'h3cFtmFabricVlanID'), ('H3C-FTM-MIB', 'h3cFtmFabricType')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): h3c_ftm_config_group = h3cFtmConfigGroup.setStatus('current') h3c_ftm_notification_group = notification_group((1, 3, 6, 1, 4, 1, 2011, 10, 2, 1, 1, 2, 2, 2)).setObjects(('H3C-FTM-MIB', 'h3cFtmUnitIDChange'), ('H3C-FTM-MIB', 'h3cFtmUnitNameChange')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): h3c_ftm_notification_group = h3cFtmNotificationGroup.setStatus('current') mibBuilder.exportSymbols('H3C-FTM-MIB', h3cFtmUnitID=h3cFtmUnitID, h3cFtmManMIBObjects=h3cFtmManMIBObjects, h3cFtmManMIBNotification=h3cFtmManMIBNotification, h3cFtmFabricVlanID=h3cFtmFabricVlanID, h3cFtmNotificationGroup=h3cFtmNotificationGroup, h3cFtmNumberMode=h3cFtmNumberMode, h3cFtm=h3cFtm, h3cFtmManMIBComformance=h3cFtmManMIBComformance, h3cFtmUnitRole=h3cFtmUnitRole, h3cFtmUnitEntry=h3cFtmUnitEntry, h3cFtmManMIB=h3cFtmManMIB, h3cFtmMIBCompliances=h3cFtmMIBCompliances, h3cFtmMIBCompliance=h3cFtmMIBCompliance, h3cFtmFabricType=h3cFtmFabricType, h3cFtmAuthMode=h3cFtmAuthMode, h3cFtmAuthValue=h3cFtmAuthValue, h3cFtmUnitName=h3cFtmUnitName, PYSNMP_MODULE_ID=h3cFtmManMIB, h3cFtmConfigGroup=h3cFtmConfigGroup, h3cFtmIndex=h3cFtmIndex, h3cFtmMIBGroups=h3cFtmMIBGroups, h3cFtmUnitIDChange=h3cFtmUnitIDChange, h3cFtmUnitTable=h3cFtmUnitTable, h3cFtmUnitNameChange=h3cFtmUnitNameChange)
# Row-by-column representation of the board BOARD_SIZE = 6, 7 # Define size of each cell in the GUI of the game CELL_SIZE = 100 # Define radius of dot RADIUS = (CELL_SIZE // 2) - 5 # Define size of GUI screen GUI_SIZE = (BOARD_SIZE[0] + 1) * CELL_SIZE, (BOARD_SIZE[1]) * CELL_SIZE # Define various colors used on the GUI of the game RED = 255, 0, 0 BLUE = 0, 0, 255 BLACK = 0, 0, 0 WHITE = 255, 255, 255 YELLOW = 255, 255, 0 # Define various players in the Game HUMAN_PLAYER = 0 Q_ROBOT = 1 RANDOM_ROBOT = 2 MINI_MAX_ROBOT = 3 # Define various rewards REWARD_WIN = 1 REWARD_LOSS = -1 REWARD_DRAW = 0.2 REWARD_NOTHING = 0 # Define various modes of the game GAME_NAME = 'CONNECT-4' GAME_MODES = {0: '2 Players', 1: 'vs Computer'} # Define various modes of learning LEARNING_MODES = {'random_agent': 0, 'trained_agent': 1, 'minimax_agent': 2} NO_TOKEN = 0 # Define location of memory file MEM_LOCATION = 'memory/memory.npy' # Define variable to store no. of iterations to train the game robot ITERATIONS = 100 # Define depth of mini-max player MINI_MAX_DEPTH = 5
board_size = (6, 7) cell_size = 100 radius = CELL_SIZE // 2 - 5 gui_size = ((BOARD_SIZE[0] + 1) * CELL_SIZE, BOARD_SIZE[1] * CELL_SIZE) red = (255, 0, 0) blue = (0, 0, 255) black = (0, 0, 0) white = (255, 255, 255) yellow = (255, 255, 0) human_player = 0 q_robot = 1 random_robot = 2 mini_max_robot = 3 reward_win = 1 reward_loss = -1 reward_draw = 0.2 reward_nothing = 0 game_name = 'CONNECT-4' game_modes = {0: '2 Players', 1: 'vs Computer'} learning_modes = {'random_agent': 0, 'trained_agent': 1, 'minimax_agent': 2} no_token = 0 mem_location = 'memory/memory.npy' iterations = 100 mini_max_depth = 5
'''This tnsertion sort algorithm which is shown in most websites and books, is slower than another insertion sort algorithm.''' def insertion_sort_slow(arr): for i in range(1, len(arr)): key = arr[i] j = i-1 while j >= 0 and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key #insertionSort(arr) #for i in range(len(arr)): # print ("% d" % arr[i])
"""This tnsertion sort algorithm which is shown in most websites and books, is slower than another insertion sort algorithm.""" def insertion_sort_slow(arr): for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and key < arr[j]: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key
# Solution for the problem "Cats and a mouse" # https://www.hackerrank.com/challenges/cats-and-a-mouse/problem # Number of test cases numQueries = int(input()) # Running the queries for queryIndex in range(0, numQueries): # Locations of Cat A, Cat B and mouse locCatA, locCatB, locMouse = map(int, input().strip().split(' ')) # Distance between Cat A and mouse distCatA = abs(locCatA - locMouse) # Distance between Cat B and mouse distCatB = abs(locCatB - locMouse) # Mouse escapes if both distances are equal if distCatA == distCatB: print("Mouse C") # Cat A is nearer elif distCatA < distCatB: print("Cat A") # Cat B is nearer else: print("Cat B")
num_queries = int(input()) for query_index in range(0, numQueries): (loc_cat_a, loc_cat_b, loc_mouse) = map(int, input().strip().split(' ')) dist_cat_a = abs(locCatA - locMouse) dist_cat_b = abs(locCatB - locMouse) if distCatA == distCatB: print('Mouse C') elif distCatA < distCatB: print('Cat A') else: print('Cat B')
# configuration for building the network y_dim = 6 tr_dim = 7 ir_dim = 10 latent_dim = 128 z_dim = 128 batch_size = 128 lr = 0.0002 beta1 = 0.5 # configuration for the supervisor logdir = "./log" sampledir = "./example" max_steps = 30000 sample_every_n_steps = 100 summary_every_n_steps = 1 save_model_secs = 120 checkpoint_basename = "layout" checkpoint_dir = "./checkpoints" filenamequeue = "./dataset/layout_1205.tfrecords" min_after_dequeue = 5000 num_threads = 4
y_dim = 6 tr_dim = 7 ir_dim = 10 latent_dim = 128 z_dim = 128 batch_size = 128 lr = 0.0002 beta1 = 0.5 logdir = './log' sampledir = './example' max_steps = 30000 sample_every_n_steps = 100 summary_every_n_steps = 1 save_model_secs = 120 checkpoint_basename = 'layout' checkpoint_dir = './checkpoints' filenamequeue = './dataset/layout_1205.tfrecords' min_after_dequeue = 5000 num_threads = 4
N = int(input()) s = [input() for _ in range(N)] for y in range(N): for x in range(N): print(s[N - 1 - x][y], end='') print('')
n = int(input()) s = [input() for _ in range(N)] for y in range(N): for x in range(N): print(s[N - 1 - x][y], end='') print('')
S = input() def check_even(stri): if len(stri) % 2 !=0: return False else: half = int(len(stri)/2) if stri[:half] == stri[half:]: return True else: return False for i in range(len(S)): if check_even(S[:-(i+1)]): print(len(S)-(i+1)) exit()
s = input() def check_even(stri): if len(stri) % 2 != 0: return False else: half = int(len(stri) / 2) if stri[:half] == stri[half:]: return True else: return False for i in range(len(S)): if check_even(S[:-(i + 1)]): print(len(S) - (i + 1)) exit()
N = int(input("Cuantos digitos quiere ingresar? ")) lista = [] lista2 = [] for i in range(N): lista.append(int(input("Digite un numero: "))) print("Su lista es: ", lista) for i in range(N): lista2.append(1*(lista[i]+1)) print("La segunda lista es: ", lista2)
n = int(input('Cuantos digitos quiere ingresar? ')) lista = [] lista2 = [] for i in range(N): lista.append(int(input('Digite un numero: '))) print('Su lista es: ', lista) for i in range(N): lista2.append(1 * (lista[i] + 1)) print('La segunda lista es: ', lista2)
# @dependency 001-main/002-createrepository.py frontend.json( "repositories", expect={ "repositories": [critic_json] }) frontend.json( "repositories/1", expect=critic_json) frontend.json( "repositories", params={ "name": "critic" }, expect=critic_json) frontend.json( "repositories/4711", expect={ "error": { "title": "No such resource", "message": "Resource not found: Invalid repository id: 4711" }}, expected_http_status=404) frontend.json( "repositories/critic", expect={ "error": { "title": "Invalid API request", "message": "Invalid numeric id: 'critic'" }}, expected_http_status=400) frontend.json( "repositories", params={ "name": "nosuchrepository" }, expect={ "error": { "title": "No such resource", "message": "Resource not found: Invalid repository name: 'nosuchrepository'" }}, expected_http_status=404) frontend.json( "repositories", params={ "filter": "interesting" }, expect={ "error": { "title": "Invalid API request", "message": "Invalid repository filter parameter: 'interesting'" }}, expected_http_status=400)
frontend.json('repositories', expect={'repositories': [critic_json]}) frontend.json('repositories/1', expect=critic_json) frontend.json('repositories', params={'name': 'critic'}, expect=critic_json) frontend.json('repositories/4711', expect={'error': {'title': 'No such resource', 'message': 'Resource not found: Invalid repository id: 4711'}}, expected_http_status=404) frontend.json('repositories/critic', expect={'error': {'title': 'Invalid API request', 'message': "Invalid numeric id: 'critic'"}}, expected_http_status=400) frontend.json('repositories', params={'name': 'nosuchrepository'}, expect={'error': {'title': 'No such resource', 'message': "Resource not found: Invalid repository name: 'nosuchrepository'"}}, expected_http_status=404) frontend.json('repositories', params={'filter': 'interesting'}, expect={'error': {'title': 'Invalid API request', 'message': "Invalid repository filter parameter: 'interesting'"}}, expected_http_status=400)
#!/usr/bin/env python # -*- coding: utf-8; py-indent-offset:4 -*- ############################################################################### # Copyright (C) 2020 Daniel Rodriguez # Use of this source code is governed by the MIT License ############################################################################### __all__ = [ 'SEED_AVG', 'SEED_LAST', 'SEED_SUM', 'SEED_NONE', 'SEED_ZERO', 'SEED_ZFILL', '_INCPERIOD', '_DECPERIOD', '_MINIDX', '_SERIES', '_MPSERIES', '_SETVAL', '_MPSETVAL', ] SEED_AVG = 0 SEED_LAST = 1 SEED_SUM = 2 SEED_NONE = 4 SEED_ZERO = 5 SEED_ZFILL = 6 def _INCPERIOD(x, p=1): ''' Forces an increase `p` in the minperiod of object `x`. Example: `ta-lib` calculates `+DM` a period of 1 too early, but calculates the depending `+DI` from the right starting point. Increasing the period, without changing the underlying already calculated `+DM` values, allows the `+DI` values to be right ''' x._minperiod += p def _DECPERIOD(x, p=1): ''' Forces an increase `p` in the minperiod of object `x`. Example: `ta-lib` calculates `obv` already when the period is `1`, discarding the needed "close" to "previous close" comparison. The only way to take this into account is to decrease the delivery period of the comparison by 1 to start the calculation before (and using a fixed criterion as to what to do in the absence of a valid close to close comparison) ''' x._minperiod -= p def _MINIDX(x, p=0): ''' Delivers the index to an array which corresponds to `_minperiod` offset by `p`. This allow direct manipulation of single values in arrays like in the `obv` scenario in which a seed value is needed for the 1st delivered value (in `ta-lib` mode) because no `close` to `previous close` comparison is possible. ''' return x._minperiod - 1 + p def _SERIES(x): '''Macro like function which makes clear that one is retrieving the actual underlying series and not something a wrapped version''' return x._series def _MPSERIES(x): '''Macro like function which makes clear that one is retrieving the actual underlying series, sliced starting at the MINPERIOD of the series''' return x._series[x._minperiod - 1:] def _SETVAL(x, idx, val): '''Macro like function which makes clear that one is setting a value in the underlying series''' x._series[idx] = val def _MPSETVAL(x, idx, val): '''Macro like function which makes clear that one is setting a value in the underlying series''' x._series[x._minperiod - 1 + idx] = val
__all__ = ['SEED_AVG', 'SEED_LAST', 'SEED_SUM', 'SEED_NONE', 'SEED_ZERO', 'SEED_ZFILL', '_INCPERIOD', '_DECPERIOD', '_MINIDX', '_SERIES', '_MPSERIES', '_SETVAL', '_MPSETVAL'] seed_avg = 0 seed_last = 1 seed_sum = 2 seed_none = 4 seed_zero = 5 seed_zfill = 6 def _incperiod(x, p=1): """ Forces an increase `p` in the minperiod of object `x`. Example: `ta-lib` calculates `+DM` a period of 1 too early, but calculates the depending `+DI` from the right starting point. Increasing the period, without changing the underlying already calculated `+DM` values, allows the `+DI` values to be right """ x._minperiod += p def _decperiod(x, p=1): """ Forces an increase `p` in the minperiod of object `x`. Example: `ta-lib` calculates `obv` already when the period is `1`, discarding the needed "close" to "previous close" comparison. The only way to take this into account is to decrease the delivery period of the comparison by 1 to start the calculation before (and using a fixed criterion as to what to do in the absence of a valid close to close comparison) """ x._minperiod -= p def _minidx(x, p=0): """ Delivers the index to an array which corresponds to `_minperiod` offset by `p`. This allow direct manipulation of single values in arrays like in the `obv` scenario in which a seed value is needed for the 1st delivered value (in `ta-lib` mode) because no `close` to `previous close` comparison is possible. """ return x._minperiod - 1 + p def _series(x): """Macro like function which makes clear that one is retrieving the actual underlying series and not something a wrapped version""" return x._series def _mpseries(x): """Macro like function which makes clear that one is retrieving the actual underlying series, sliced starting at the MINPERIOD of the series""" return x._series[x._minperiod - 1:] def _setval(x, idx, val): """Macro like function which makes clear that one is setting a value in the underlying series""" x._series[idx] = val def _mpsetval(x, idx, val): """Macro like function which makes clear that one is setting a value in the underlying series""" x._series[x._minperiod - 1 + idx] = val
##Patterns: E0103 def test(): while True: break ##Err: E0103 break for letter in 'Python': if letter == 'h': continue ##Err: E0103 continue
def test(): while True: break break for letter in 'Python': if letter == 'h': continue continue
def checkio(f, g): def call(function, *args, **kwargs): try: return function(*args, **kwargs) except Exception: return None def h(*args, **kwargs): value_f, value_g = call(f, *args, **kwargs), call(g, *args, **kwargs) status = "" if (value_f is None and value_g is None): status = "both_error" elif (value_f is None): status = "f_error" elif (value_g is None): status = "g_error" elif (value_f == value_g): status = "same" else: status = "different" if (value_f is None and value_g is None): return (None, status) elif (value_f is None): return (value_g, status) else: return (value_f, status) return h if __name__ == "__main__": #These "asserts" using only for self-checking and not necessary for auto-testing # (x+y)(x-y)/(x-y) assert checkio(lambda x,y:x+y, lambda x,y:(x**2-y**2)/(x-y))\ (1,3)==(4,"same"), "Function: x+y, first" assert checkio(lambda x,y:x+y, lambda x,y:(x**2-y**2)/(x-y))\ (1,2)==(3,"same"), "Function: x+y, second" assert checkio(lambda x,y:x+y, lambda x,y:(x**2-y**2)/(x-y))\ (1,1.01)==(2.01,"different"), "x+y, third" assert checkio(lambda x,y:x+y, lambda x,y:(x**2-y**2)/(x-y))\ (1,1)==(2,"g_error"), "x+y, fourth" # Remove odds from list f = lambda nums:[x for x in nums if ~x%2] def g(nums): for i in range(len(nums)): if nums[i]%2==1: nums.pop(i) return nums assert checkio(f,g)([2,4,6,8]) == ([2,4,6,8],"same"), "evens, first" assert checkio(f,g)([2,3,4,6,8]) == ([2,4,6,8],"g_error"), "evens, second" # Fizz Buzz assert checkio(lambda n:("Fizz "*(1-n%3) + "Buzz "*(1-n%5))[:-1] or str(n), lambda n:("Fizz"*(n%3==0) + " " + "Buzz"*(n%5==0)).strip())\ (6)==("Fizz","same"), "fizz buzz, first" assert checkio(lambda n:("Fizz "*(1-n%3) + "Buzz "*(1-n%5))[:-1] or str(n), lambda n:("Fizz"*(n%3==0) + " " + "Buzz"*(n%5==0)).strip())\ (30)==("Fizz Buzz","same"), "fizz buzz, second" assert checkio(lambda n:("Fizz "*(1-n%3) + "Buzz "*(1-n%5))[:-1] or str(n), lambda n:("Fizz"*(n%3==0) + " " + "Buzz"*(n%5==0)).strip())\ (7)==("7","different"), "fizz buzz, third"
def checkio(f, g): def call(function, *args, **kwargs): try: return function(*args, **kwargs) except Exception: return None def h(*args, **kwargs): (value_f, value_g) = (call(f, *args, **kwargs), call(g, *args, **kwargs)) status = '' if value_f is None and value_g is None: status = 'both_error' elif value_f is None: status = 'f_error' elif value_g is None: status = 'g_error' elif value_f == value_g: status = 'same' else: status = 'different' if value_f is None and value_g is None: return (None, status) elif value_f is None: return (value_g, status) else: return (value_f, status) return h if __name__ == '__main__': assert checkio(lambda x, y: x + y, lambda x, y: (x ** 2 - y ** 2) / (x - y))(1, 3) == (4, 'same'), 'Function: x+y, first' assert checkio(lambda x, y: x + y, lambda x, y: (x ** 2 - y ** 2) / (x - y))(1, 2) == (3, 'same'), 'Function: x+y, second' assert checkio(lambda x, y: x + y, lambda x, y: (x ** 2 - y ** 2) / (x - y))(1, 1.01) == (2.01, 'different'), 'x+y, third' assert checkio(lambda x, y: x + y, lambda x, y: (x ** 2 - y ** 2) / (x - y))(1, 1) == (2, 'g_error'), 'x+y, fourth' f = lambda nums: [x for x in nums if ~x % 2] def g(nums): for i in range(len(nums)): if nums[i] % 2 == 1: nums.pop(i) return nums assert checkio(f, g)([2, 4, 6, 8]) == ([2, 4, 6, 8], 'same'), 'evens, first' assert checkio(f, g)([2, 3, 4, 6, 8]) == ([2, 4, 6, 8], 'g_error'), 'evens, second' assert checkio(lambda n: ('Fizz ' * (1 - n % 3) + 'Buzz ' * (1 - n % 5))[:-1] or str(n), lambda n: ('Fizz' * (n % 3 == 0) + ' ' + 'Buzz' * (n % 5 == 0)).strip())(6) == ('Fizz', 'same'), 'fizz buzz, first' assert checkio(lambda n: ('Fizz ' * (1 - n % 3) + 'Buzz ' * (1 - n % 5))[:-1] or str(n), lambda n: ('Fizz' * (n % 3 == 0) + ' ' + 'Buzz' * (n % 5 == 0)).strip())(30) == ('Fizz Buzz', 'same'), 'fizz buzz, second' assert checkio(lambda n: ('Fizz ' * (1 - n % 3) + 'Buzz ' * (1 - n % 5))[:-1] or str(n), lambda n: ('Fizz' * (n % 3 == 0) + ' ' + 'Buzz' * (n % 5 == 0)).strip())(7) == ('7', 'different'), 'fizz buzz, third'
# -------------- # Code starts here class_1 = ['Geoffrey Hinton' , 'Andrew Ng' , 'Sebastian Raschka' , 'Yoshua Bengio'] class_2 = ['Hilary Mason' , 'Carla Gentry' , 'Corinna Cortes'] new_class = class_1+class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_class) # Code ends here # -------------- # Code starts here courses = {'Math':65, 'English':70, 'History':80, 'French': 70, 'Science':60} total = sum(courses.values()) print(total) percentage = total/500*100 print(percentage) # Code ends here # -------------- # Code starts here mathematics = {'Geoffrey Hinton': 78, 'Andrew Ng': 95, 'Sebastian Raschka': 65, 'Yoshua Benjio': 50, 'Hilary Mason': 70, 'Corinna Cortes': 60, 'Peter Warden': 75} topper = max(mathematics,key = mathematics.get) print(topper) # Code ends here # -------------- # Given string topper = 'andrew ng' # Code starts here print('-'*20) first_name = topper.split()[0] last_name = topper.split()[1] full_name = f'{last_name} {first_name}' print(full_name) certificate_name = full_name.upper() print(certificate_name) # Code ends here
class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio'] class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes'] new_class = class_1 + class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_class) courses = {'Math': 65, 'English': 70, 'History': 80, 'French': 70, 'Science': 60} total = sum(courses.values()) print(total) percentage = total / 500 * 100 print(percentage) mathematics = {'Geoffrey Hinton': 78, 'Andrew Ng': 95, 'Sebastian Raschka': 65, 'Yoshua Benjio': 50, 'Hilary Mason': 70, 'Corinna Cortes': 60, 'Peter Warden': 75} topper = max(mathematics, key=mathematics.get) print(topper) topper = 'andrew ng' print('-' * 20) first_name = topper.split()[0] last_name = topper.split()[1] full_name = f'{last_name} {first_name}' print(full_name) certificate_name = full_name.upper() print(certificate_name)
N = int(input()) a,b = 1,1 print(0,end=' ') for i in range(1,N-1): if i != N: print(a,end=' ') a,b = b,a+b print(a,end='\n')
n = int(input()) (a, b) = (1, 1) print(0, end=' ') for i in range(1, N - 1): if i != N: print(a, end=' ') (a, b) = (b, a + b) print(a, end='\n')
# This is a dummy file to allow the automatic loading of modules without error on none. def setup(robot_config): return def say(*args): return def mute(): return def unmute(): return def volume(level): return
def setup(robot_config): return def say(*args): return def mute(): return def unmute(): return def volume(level): return
class FeeValidator: def __init__(self, specifier) -> None: super().__init__() self.specifier = specifier def validate(self, fee): failed=False try: if fee != 0 and not 1 <= fee <= 100: failed=True except TypeError: failed=True if failed: raise Exception("Fee for {} cannot be {}. Valid values are 0, [1-100]".format(self.specifier, fee))
class Feevalidator: def __init__(self, specifier) -> None: super().__init__() self.specifier = specifier def validate(self, fee): failed = False try: if fee != 0 and (not 1 <= fee <= 100): failed = True except TypeError: failed = True if failed: raise exception('Fee for {} cannot be {}. Valid values are 0, [1-100]'.format(self.specifier, fee))
INSERT_ONE_BY_BYTE = "insert_one_by_byte" INSERT_ONE_BY_PATH = "insert_one_by_path" INSERT_MANY_BY_BYTE = "insert_many_by_byte" INSERT_MANY_BY_DIR = "insert_many_by_dir" INSERT_MANY_BY_PATHS = "insert_many_by_paths" DELETE_ONE_BY_ID = "delete_one_by_id" DELETE_MANY_BY_IDS = "delete_many_by_ids" DELETE_ALL = "delete_all" UPDATE_ONE_BY_ID = "update_one_by_id" UPDATE_MANY_BY_IDS = "update_many_by_ids" RETRIEVE_ONE = "retrieve_one" RETRIEVE_MANY = "retrieve_many" QUERY_NEAREST_BY_CONTENT = "query_nearest_by_content" QUERY_NEAREST_BY_STYLE = "query_nearest_by_style" QUERY_FARTHEST_BY_CONTENT = "query_farthest_by_content" QUERY_FARTHEST_BY_STYLE = "query_farthest_by_style" QUERY_BY_TAG_ALL = "query_by_tag_all" QUERY_BY_TAG_PARTIAL = "query_by_tag_partial" QUERY_RANGE_BY_CONTENT = "query_range_by_content" QUERY_RANGE_BY_STYLE = "query_range_by_style" BROWSE_BY_RANDOM = "browse_by_random" BROWSE_BY_CLUSTER = "browse_by_cluster"
insert_one_by_byte = 'insert_one_by_byte' insert_one_by_path = 'insert_one_by_path' insert_many_by_byte = 'insert_many_by_byte' insert_many_by_dir = 'insert_many_by_dir' insert_many_by_paths = 'insert_many_by_paths' delete_one_by_id = 'delete_one_by_id' delete_many_by_ids = 'delete_many_by_ids' delete_all = 'delete_all' update_one_by_id = 'update_one_by_id' update_many_by_ids = 'update_many_by_ids' retrieve_one = 'retrieve_one' retrieve_many = 'retrieve_many' query_nearest_by_content = 'query_nearest_by_content' query_nearest_by_style = 'query_nearest_by_style' query_farthest_by_content = 'query_farthest_by_content' query_farthest_by_style = 'query_farthest_by_style' query_by_tag_all = 'query_by_tag_all' query_by_tag_partial = 'query_by_tag_partial' query_range_by_content = 'query_range_by_content' query_range_by_style = 'query_range_by_style' browse_by_random = 'browse_by_random' browse_by_cluster = 'browse_by_cluster'
lista = [] lista_par = [] lista_impar = [] while True: n = (int(input('Digite os numeros: '))) lista.append(n) if n % 2 == 0: lista_par.append(n) else: lista_impar.append(n) res = str(input('Quer continuar [S/N] : ')) if res in 'Nn': break print(f'O numeros da lista fora : {lista}') print(f'O numeros pares foram : {lista_par}') print(f'O numeros impares foram : {lista_impar}')
lista = [] lista_par = [] lista_impar = [] while True: n = int(input('Digite os numeros: ')) lista.append(n) if n % 2 == 0: lista_par.append(n) else: lista_impar.append(n) res = str(input('Quer continuar [S/N] : ')) if res in 'Nn': break print(f'O numeros da lista fora : {lista}') print(f'O numeros pares foram : {lista_par}') print(f'O numeros impares foram : {lista_impar}')
test = [11.0, "Alice has a cat", 12, 4, "5"] print("len(test) = " + str(len(test))) print("test[1] = " + str(test[1])) print("test[3:6] = " + str(test[3:6])) print("test[1:6:2] = " + str(test[1:6:2])) print("test[:6] = " + str(test[:6])) print("test[-2] = " + str(test[-2])) test.append(121) test2 = test + [1, 2, 3] print("len(test2) = " + str(len(test2))) test2[0] = "Lodz" test2[6] = 77 print(test2)
test = [11.0, 'Alice has a cat', 12, 4, '5'] print('len(test) = ' + str(len(test))) print('test[1] = ' + str(test[1])) print('test[3:6] = ' + str(test[3:6])) print('test[1:6:2] = ' + str(test[1:6:2])) print('test[:6] = ' + str(test[:6])) print('test[-2] = ' + str(test[-2])) test.append(121) test2 = test + [1, 2, 3] print('len(test2) = ' + str(len(test2))) test2[0] = 'Lodz' test2[6] = 77 print(test2)
class dotStringProperty_t(object): # no doc aName=None aValueString=None FatherId=None ValueStringIteration=None
class Dotstringproperty_T(object): a_name = None a_value_string = None father_id = None value_string_iteration = None
# pylint: disable=missing-function-docstring, missing-module-docstring/ @toto # pylint: disable=undefined-variable def f(): pass
@toto def f(): pass
x = 50 def func(x): print('x is',x) x = 2 print('Changed local x to',x) func(x) print('x is still',x)
x = 50 def func(x): print('x is', x) x = 2 print('Changed local x to', x) func(x) print('x is still', x)
class Node(): def __init__(self, value="", frequency=0.0): self.frequency = frequency self.value = value self.children = {} self.stop = False def __getitem__(self, key): if key in self.children: return self.children[key] return None def __setitem__(self, key, value): self.children[key] = value def __contains__(self, key): return key in self.children def __str__(self): return self.value def __iter__(self): for key in sorted(self.children.keys()): yield key def __delitem__(self, key): del self.children[key] class Trie: def __init__(self): self.root = Node() def add_word(self, word, frequency): word = word.lower() current_node = self.root for letter in word: if letter not in current_node: current_node[letter] = Node(letter) current_node = current_node[letter] current_node.stop = True current_node.frequency = frequency @staticmethod def get_possible_matches(node, words_list, path): if node.stop: words_list.append((path + node.value, node.frequency)) for letter in node.children: Trie.get_possible_matches(node.children[letter], words_list, path + node.value) def match_suffix(self, word): current_node = self.root for letter in word.lower(): if letter in current_node: current_node = current_node[letter] # word += current_node.value else: return False possible_words = [] self.get_possible_matches(current_node, possible_words, word[:-1]) return possible_words def contains(self, word): current_node = self.root path = "" for letter in word.lower(): if letter not in current_node: return False else: path += letter current_node = current_node[letter] if current_node.stop: return True return False def __contains__(self, key): return self.contains(key) @staticmethod def _print(node, path=""): if node.stop: print(path + node.value, node.frequency) for letter in node.children: Trie._print(node.children[letter], path + node.value) def print_content(self): for letter in self.root.children: self._print(self.root[letter]) if __name__ == "__main__": t = Trie() t.add_word("kaka") t.add_word("kakan") t.add_word("kakor") t.print_content() print("---------------") print(t.contains("kaka"))
class Node: def __init__(self, value='', frequency=0.0): self.frequency = frequency self.value = value self.children = {} self.stop = False def __getitem__(self, key): if key in self.children: return self.children[key] return None def __setitem__(self, key, value): self.children[key] = value def __contains__(self, key): return key in self.children def __str__(self): return self.value def __iter__(self): for key in sorted(self.children.keys()): yield key def __delitem__(self, key): del self.children[key] class Trie: def __init__(self): self.root = node() def add_word(self, word, frequency): word = word.lower() current_node = self.root for letter in word: if letter not in current_node: current_node[letter] = node(letter) current_node = current_node[letter] current_node.stop = True current_node.frequency = frequency @staticmethod def get_possible_matches(node, words_list, path): if node.stop: words_list.append((path + node.value, node.frequency)) for letter in node.children: Trie.get_possible_matches(node.children[letter], words_list, path + node.value) def match_suffix(self, word): current_node = self.root for letter in word.lower(): if letter in current_node: current_node = current_node[letter] else: return False possible_words = [] self.get_possible_matches(current_node, possible_words, word[:-1]) return possible_words def contains(self, word): current_node = self.root path = '' for letter in word.lower(): if letter not in current_node: return False else: path += letter current_node = current_node[letter] if current_node.stop: return True return False def __contains__(self, key): return self.contains(key) @staticmethod def _print(node, path=''): if node.stop: print(path + node.value, node.frequency) for letter in node.children: Trie._print(node.children[letter], path + node.value) def print_content(self): for letter in self.root.children: self._print(self.root[letter]) if __name__ == '__main__': t = trie() t.add_word('kaka') t.add_word('kakan') t.add_word('kakor') t.print_content() print('---------------') print(t.contains('kaka'))
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"PairwiseDistance": "00_distance.ipynb", "pairwise_dist_gram": "00_distance.ipynb", "stackoverflow_pairwise_distance": "00_distance.ipynb", "PairwiseDistance.stackoverflow_pairwise_distance": "00_distance.ipynb", "torch_pairwise_distance": "00_distance.ipynb", "PairwiseDistance.torch_pairwise_distance": "00_distance.ipynb", "measure_execution_time": "00_distance.ipynb", "get_time_stats": "00_distance.ipynb", "DistanceMatrixIndexMapper": "00_distance.ipynb", "Hull": "00_distance.ipynb", "to_2dpositions": "00_distance.ipynb", "Hull.to_2dpositions": "00_distance.ipynb", "plot_atoms_and_hull": "00_distance.ipynb"} modules = ["distance.py"] doc_url = "https://eschmidt42.github.io/md/" git_url = "https://github.com/eschmidt42/md/tree/master/" def custom_doc_links(name): return None
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'PairwiseDistance': '00_distance.ipynb', 'pairwise_dist_gram': '00_distance.ipynb', 'stackoverflow_pairwise_distance': '00_distance.ipynb', 'PairwiseDistance.stackoverflow_pairwise_distance': '00_distance.ipynb', 'torch_pairwise_distance': '00_distance.ipynb', 'PairwiseDistance.torch_pairwise_distance': '00_distance.ipynb', 'measure_execution_time': '00_distance.ipynb', 'get_time_stats': '00_distance.ipynb', 'DistanceMatrixIndexMapper': '00_distance.ipynb', 'Hull': '00_distance.ipynb', 'to_2dpositions': '00_distance.ipynb', 'Hull.to_2dpositions': '00_distance.ipynb', 'plot_atoms_and_hull': '00_distance.ipynb'} modules = ['distance.py'] doc_url = 'https://eschmidt42.github.io/md/' git_url = 'https://github.com/eschmidt42/md/tree/master/' def custom_doc_links(name): return None
class AppUserProfile: types = { 'username': str, 'password': str } def __init__(self): self.username = None # str self.password = None # str
class Appuserprofile: types = {'username': str, 'password': str} def __init__(self): self.username = None self.password = None
class Container: def __init__(self, container=None): if container == None or type(container) != dict: self._container = dict() else: self._container = container def __iter__(self): return iter(self._container.items()) def addObject(self, name, object_:object): self._container[name] = object_ def hasObject(self, name): return self._container.get(name) is not None def getObject(self, name) -> object: return self._container.get(name) def delete(self, name) -> object: return self._container.pop(name) def clearAll(self): self._container.clear()
class Container: def __init__(self, container=None): if container == None or type(container) != dict: self._container = dict() else: self._container = container def __iter__(self): return iter(self._container.items()) def add_object(self, name, object_: object): self._container[name] = object_ def has_object(self, name): return self._container.get(name) is not None def get_object(self, name) -> object: return self._container.get(name) def delete(self, name) -> object: return self._container.pop(name) def clear_all(self): self._container.clear()
class AcousticParam(object): def __init__( self, sampling_rate: int = 24000, pad_second: float = 0, threshold_db: float = None, frame_period: int = 5, order: int = 8, alpha: float = 0.466, f0_floor: float = 71, f0_ceil: float = 800, fft_length: int = 1024, dtype: str = 'float32', ) -> None: self.sampling_rate = sampling_rate self.pad_second = pad_second self.threshold_db = threshold_db self.frame_period = frame_period self.order = order self.alpha = alpha self.f0_floor = f0_floor self.f0_ceil = f0_ceil self.fft_length = fft_length self.dtype = dtype def _asdict(self): return self.__dict__
class Acousticparam(object): def __init__(self, sampling_rate: int=24000, pad_second: float=0, threshold_db: float=None, frame_period: int=5, order: int=8, alpha: float=0.466, f0_floor: float=71, f0_ceil: float=800, fft_length: int=1024, dtype: str='float32') -> None: self.sampling_rate = sampling_rate self.pad_second = pad_second self.threshold_db = threshold_db self.frame_period = frame_period self.order = order self.alpha = alpha self.f0_floor = f0_floor self.f0_ceil = f0_ceil self.fft_length = fft_length self.dtype = dtype def _asdict(self): return self.__dict__
def get_headers(text): list_a = text.split("\n")[1:] list_headers = [] for i in list_a: if not i: break list_headers.append(i.split(": ")) return dict(list_headers)
def get_headers(text): list_a = text.split('\n')[1:] list_headers = [] for i in list_a: if not i: break list_headers.append(i.split(': ')) return dict(list_headers)
#WAP to find, a given number is prime or not num = int(input("enter number")) if num>1: #check for factors for i in range(2,num): if(num / i) == 0: print(num," is not prime number") break else: print(num," is not a prime number")
num = int(input('enter number')) if num > 1: for i in range(2, num): if num / i == 0: print(num, ' is not prime number') break else: print(num, ' is not a prime number')
def Scenario_Generation(): # first restricting the data to April 2020 when we are predicting six weeks out from april 2020 popularity_germany = np.load("./popularity_germany.npy") popularity_germany = np.copy(popularity_germany[:,0:63,:]) # april 20th is the 63rd index in the popularity number # one = np.multiply(np.ones((16,42,6)),popularity_germany[:,62:63,:]) popularity_germany = np.append(popularity_germany,one,axis=1) # bus movement is kept as 0 after march 18 # we keep the flight data same as what was observed on april 20th # there has been no change in the trucj movement pattern (sp we keep as a weekly pattern) # the data contains placeholder for 158 countries (so that we can capture the movement from all the countries) bus_movement = np.load("./bus_movement.npy") truck_movement = np.load("./truck_movement.npy") flight_movement = np.load("./flight_movement.npy") car_movement = np.load("./car_movement.npy") train_movement = np.load("./train_movement.npy") bus_move = bus_movement[:,0:63,:] truck_move = truck_movement[:,0:63,:] flight_move = flight_movement[:,0:63,:] static_car_move = car_movement[:,0:63,:] static_train_move = train_movement[:,0:63,:] one = np.multiply(np.ones((16,42,158)),bus_move[:,62:63,:]) bus_move = np.append(bus_move,one,axis=1) one = np.multiply(np.ones((16,42,158)),truck_move[:,62:63,:]) truck_move = np.append(truck_move,one,axis=1) one = np.multiply(np.ones((16,42,158)),flight_move[:,62:63,:]) flight_move = np.append(flight_move,one,axis=1) one = np.multiply(np.ones((16,42,158)),static_car_move[:,62:63,:]) static_car_move = np.append(static_car_move,one,axis=1) one = np.multiply(np.ones((16,42,158)),static_train_move[:,62:63,:]) static_train_move = np.append(static_train_move,one,axis=1) for t in range(63,63+42): truck_move[:,t,:] = truck_move[:,t-7,:] popularity_o = np.copy(popularity_germany) policy_o = pd.read_csv("./policy.csv") policy_o_life = pd.read_csv("./policy_lift.csv") cols = ['Border Closure', 'Initial business closure', 'Educational facilities closed', 'Non-essential services closed', 'Stay at home order', 'contact restriction', 'retails closed','trend','tmax','frustration'] policy = pd.read_csv("./policy.csv") policy_lift = pd.read_csv("./policy_lift.csv") popularity = np.load("./popularity_germany.npy") weather = pd.read_csv("./weather_predict.csv") trend = pd.read_csv("./trend_predict.csv") # cumulative trend numbers PTV = pd.read_csv("./PTV_predict.csv") # there are 9 scenarios # in first scenario, no change in policy and all policies remain in place # in the next 7 scenarios, we switch off (relax) one of the policy if it was implemented in that respective state # in the last scenario, we relax all the policies (however, we do not show this in paper as it lead to a very sharp rise) # each of these 9 scenarios is tested twice - one when for april 21, 2020 and once for april 28, 2020 for pp in range(9): popularity = np.copy(popularity_o) car_movement = np.copy(static_car_move) train_movement = np.copy(static_train_move) for w in range(2): policy1 = pd.DataFrame.copy(pd.read_csv("./policy.csv") ) policy2 = pd.DataFrame.copy(pd.read_csv("./policy.csv") ) policy3 = pd.DataFrame.copy(pd.read_csv("./policy.csv") ) name = '_P_'+str(pp)+'_W_'+str(w+1) if pp == 0: name = '' # when relaxing a policy, we keep the date very high (1000) so that the return value is 0 (not implemented post april 21 or april 28) elif pp == 8: if w == 0: name = '_P_8_W_1' for xx in range(7): policy1[cols[xx]] = 1000 policy2[cols[xx]] = 1000 policy3[cols[xx]] = 1000 if w == 1: name = '_P_8_W_2' for xx in range(7): policy2[cols[xx]] = 1000 policy3[cols[xx]] = 1000 else: if w == 0: policy1[cols[pp-1]] = 1000 policy2[cols[pp-1]] = 1000 policy3[cols[pp-1]] = 1000 elif w==1: policy2[cols[pp-1]] = 1000 policy3[cols[pp-1]] = 1000 X = [] for j in range(16): # first week for t in range(63,70): c = [] for p in range(7): c.append(int(policy1[cols[p]].iloc[j] <= t+79)) c.append(trend.iloc[t,j+1]) c.append(weather.iloc[t,j+1]) c.append(PTV.iloc[t,1]) X.append(c) # second week for t in range(70,77): c = [] for p in range(7): c.append(int(policy2[cols[p]].iloc[j] <= t+79)) c.append(trend.iloc[t,j+1]) c.append(weather.iloc[t,j+1]) c.append(PTV.iloc[t,1]) X.append(c) # rest of the four weeks for ww in range(4): for t in range(77+7*ww,84+7*ww): c = [] for p in range(7): c.append(int(policy3[cols[p]].iloc[j] <= t+79)) c.append(trend.iloc[t,j+1]) c.append(weather.iloc[t,j+1]) c.append(PTV.iloc[t,1]) X.append(c) x = pd.DataFrame(X,columns=cols) models = RegressionModels() y_pred = models[0].predict(x) y_car = models[1].predict(x) y_train = models[2].predict(x) for j in range(16): for t in range(63,63+42): popularity[j,t,0] = y_pred[42*j+t-63] popularity[j,t,3] = y_car[42*j+t-63] popularity[j,t,4] = y_train[42*j+t-63] wtrain = popularity[:,:,3] wtrain = (wtrain)/100+1 wcars = popularity[:,:,4] wcars = (wcars)/100+1 numbee = 63+42 for i in range(16): car_movement[i] = np.multiply(car_movement[i],wcars[i].reshape([numbee,1])*np.ones([numbee,158])) train_movement[i] = np.multiply(train_movement[i],wtrain[i].reshape([numbee,1])*np.ones([numbee,158])) # the files can be saved #np.save('popularity_germany'+name,popularity) #np.save('train_movement'+name,train_movement) #np.save('car_movement'+name,car_movement) return()
def scenario__generation(): popularity_germany = np.load('./popularity_germany.npy') popularity_germany = np.copy(popularity_germany[:, 0:63, :]) one = np.multiply(np.ones((16, 42, 6)), popularity_germany[:, 62:63, :]) popularity_germany = np.append(popularity_germany, one, axis=1) bus_movement = np.load('./bus_movement.npy') truck_movement = np.load('./truck_movement.npy') flight_movement = np.load('./flight_movement.npy') car_movement = np.load('./car_movement.npy') train_movement = np.load('./train_movement.npy') bus_move = bus_movement[:, 0:63, :] truck_move = truck_movement[:, 0:63, :] flight_move = flight_movement[:, 0:63, :] static_car_move = car_movement[:, 0:63, :] static_train_move = train_movement[:, 0:63, :] one = np.multiply(np.ones((16, 42, 158)), bus_move[:, 62:63, :]) bus_move = np.append(bus_move, one, axis=1) one = np.multiply(np.ones((16, 42, 158)), truck_move[:, 62:63, :]) truck_move = np.append(truck_move, one, axis=1) one = np.multiply(np.ones((16, 42, 158)), flight_move[:, 62:63, :]) flight_move = np.append(flight_move, one, axis=1) one = np.multiply(np.ones((16, 42, 158)), static_car_move[:, 62:63, :]) static_car_move = np.append(static_car_move, one, axis=1) one = np.multiply(np.ones((16, 42, 158)), static_train_move[:, 62:63, :]) static_train_move = np.append(static_train_move, one, axis=1) for t in range(63, 63 + 42): truck_move[:, t, :] = truck_move[:, t - 7, :] popularity_o = np.copy(popularity_germany) policy_o = pd.read_csv('./policy.csv') policy_o_life = pd.read_csv('./policy_lift.csv') cols = ['Border Closure', 'Initial business closure', 'Educational facilities closed', 'Non-essential services closed', 'Stay at home order', 'contact restriction', 'retails closed', 'trend', 'tmax', 'frustration'] policy = pd.read_csv('./policy.csv') policy_lift = pd.read_csv('./policy_lift.csv') popularity = np.load('./popularity_germany.npy') weather = pd.read_csv('./weather_predict.csv') trend = pd.read_csv('./trend_predict.csv') ptv = pd.read_csv('./PTV_predict.csv') for pp in range(9): popularity = np.copy(popularity_o) car_movement = np.copy(static_car_move) train_movement = np.copy(static_train_move) for w in range(2): policy1 = pd.DataFrame.copy(pd.read_csv('./policy.csv')) policy2 = pd.DataFrame.copy(pd.read_csv('./policy.csv')) policy3 = pd.DataFrame.copy(pd.read_csv('./policy.csv')) name = '_P_' + str(pp) + '_W_' + str(w + 1) if pp == 0: name = '' elif pp == 8: if w == 0: name = '_P_8_W_1' for xx in range(7): policy1[cols[xx]] = 1000 policy2[cols[xx]] = 1000 policy3[cols[xx]] = 1000 if w == 1: name = '_P_8_W_2' for xx in range(7): policy2[cols[xx]] = 1000 policy3[cols[xx]] = 1000 elif w == 0: policy1[cols[pp - 1]] = 1000 policy2[cols[pp - 1]] = 1000 policy3[cols[pp - 1]] = 1000 elif w == 1: policy2[cols[pp - 1]] = 1000 policy3[cols[pp - 1]] = 1000 x = [] for j in range(16): for t in range(63, 70): c = [] for p in range(7): c.append(int(policy1[cols[p]].iloc[j] <= t + 79)) c.append(trend.iloc[t, j + 1]) c.append(weather.iloc[t, j + 1]) c.append(PTV.iloc[t, 1]) X.append(c) for t in range(70, 77): c = [] for p in range(7): c.append(int(policy2[cols[p]].iloc[j] <= t + 79)) c.append(trend.iloc[t, j + 1]) c.append(weather.iloc[t, j + 1]) c.append(PTV.iloc[t, 1]) X.append(c) for ww in range(4): for t in range(77 + 7 * ww, 84 + 7 * ww): c = [] for p in range(7): c.append(int(policy3[cols[p]].iloc[j] <= t + 79)) c.append(trend.iloc[t, j + 1]) c.append(weather.iloc[t, j + 1]) c.append(PTV.iloc[t, 1]) X.append(c) x = pd.DataFrame(X, columns=cols) models = regression_models() y_pred = models[0].predict(x) y_car = models[1].predict(x) y_train = models[2].predict(x) for j in range(16): for t in range(63, 63 + 42): popularity[j, t, 0] = y_pred[42 * j + t - 63] popularity[j, t, 3] = y_car[42 * j + t - 63] popularity[j, t, 4] = y_train[42 * j + t - 63] wtrain = popularity[:, :, 3] wtrain = wtrain / 100 + 1 wcars = popularity[:, :, 4] wcars = wcars / 100 + 1 numbee = 63 + 42 for i in range(16): car_movement[i] = np.multiply(car_movement[i], wcars[i].reshape([numbee, 1]) * np.ones([numbee, 158])) train_movement[i] = np.multiply(train_movement[i], wtrain[i].reshape([numbee, 1]) * np.ones([numbee, 158])) return ()
# loendur dictionary counter_dict = {} # loe failist ridade kaupa ja loendab dictionarisse erinevad nimed with open('/Users/mikksillaste/Downloads/aima-python/nameslist.txt') as f: line = f.readline() while line: line = line.strip() if line in counter_dict: counter_dict[line] += 1 else: counter_dict[line] = 1 line = f.readline() # loeb failist ridade kaupa ja loendab dictionarisse erinevad kategooriad, mille jaoks on vaja kindlat osa reast [3:-26] counter_dict2 = {} with open('/Users/mikksillaste/Downloads/aima-python/Training_01.txt') as f: line = f.readline() while line: line = line[3:-26] if line in counter_dict2: counter_dict2[line] += 1 else: counter_dict2[line] = 1 line = f.readline() print(counter_dict) print(counter_dict2)
counter_dict = {} with open('/Users/mikksillaste/Downloads/aima-python/nameslist.txt') as f: line = f.readline() while line: line = line.strip() if line in counter_dict: counter_dict[line] += 1 else: counter_dict[line] = 1 line = f.readline() counter_dict2 = {} with open('/Users/mikksillaste/Downloads/aima-python/Training_01.txt') as f: line = f.readline() while line: line = line[3:-26] if line in counter_dict2: counter_dict2[line] += 1 else: counter_dict2[line] = 1 line = f.readline() print(counter_dict) print(counter_dict2)
def eight_is_great(a, b): if a == 8 or b == 8: print(":)") elif (a + b) == 8: print(":)") else: print(":(")
def eight_is_great(a, b): if a == 8 or b == 8: print(':)') elif a + b == 8: print(':)') else: print(':(')
#ChangeRenderSetting.py ##This only use in the maya software render , not in arnold #Three main Node of Maya Render: # ->defaultRenderGlobals, defaultRenderQuality and defaultResolution # ->those are separate nodes in maya ''' import maya.cmds as cmds #Function : getRenderGlobals() #Usage : get the Value of Render Globals and print it def getRenderGlobals() : render_glob = "defaultRenderGlobals" list_Attr = cmds.listAttr(render_glob,r = True,s = True) #loop the list print 'defaultRenderSetting As follows :' for attr in list_Attr: get_attr_name = "%s.%s"%(render_glob, attr) print "setAttr %s %s"%(get_attr_name, cmds.getAttr(get_attr_name)) #Function : getRenderResolution() #Usage : get the Value of Render Resolution and print it def getRenderResolution() : resolu_list = "defaultResolution" list_Attr = cmds.listAttr(resolu_list,r = True , s = True) print 'defaultResolution As follows :' for attr in list_Attr: get_attr_name = "%s.%s"%(resolu_list, attr) print "setAttr %s %s"%(get_attr_name, cmds.getAttr(get_attr_name)) #defaultRenderGlobals.startFrame = 2.0 #Function : startEndFrame #Usage : to change the Global value(startFrame,endFrame) of the Render #use for set the render startFrame,endFrame,byframe #Example : startEndFrame(3.0,7.0) def startEndFrame(startTime,endTime) : cmds.setAttr("defaultRenderGlobals.startFrame",startTime) cmds.setAttr("defaultRenderGlobals.endFrame",endTime) #Function : setWidthAndHeight #Usage : to change the Resolution value(width,height) of the Render #Example : setWidthAndHeight(960,540) def setWidthAndHeight(width,height) : cmds.setAttr("defaultResolution.width",width) cmds.setAttr("defaultResolution.height",height) '''
""" import maya.cmds as cmds #Function : getRenderGlobals() #Usage : get the Value of Render Globals and print it def getRenderGlobals() : render_glob = "defaultRenderGlobals" list_Attr = cmds.listAttr(render_glob,r = True,s = True) #loop the list print 'defaultRenderSetting As follows :' for attr in list_Attr: get_attr_name = "%s.%s"%(render_glob, attr) print "setAttr %s %s"%(get_attr_name, cmds.getAttr(get_attr_name)) #Function : getRenderResolution() #Usage : get the Value of Render Resolution and print it def getRenderResolution() : resolu_list = "defaultResolution" list_Attr = cmds.listAttr(resolu_list,r = True , s = True) print 'defaultResolution As follows :' for attr in list_Attr: get_attr_name = "%s.%s"%(resolu_list, attr) print "setAttr %s %s"%(get_attr_name, cmds.getAttr(get_attr_name)) #defaultRenderGlobals.startFrame = 2.0 #Function : startEndFrame #Usage : to change the Global value(startFrame,endFrame) of the Render #use for set the render startFrame,endFrame,byframe #Example : startEndFrame(3.0,7.0) def startEndFrame(startTime,endTime) : cmds.setAttr("defaultRenderGlobals.startFrame",startTime) cmds.setAttr("defaultRenderGlobals.endFrame",endTime) #Function : setWidthAndHeight #Usage : to change the Resolution value(width,height) of the Render #Example : setWidthAndHeight(960,540) def setWidthAndHeight(width,height) : cmds.setAttr("defaultResolution.width",width) cmds.setAttr("defaultResolution.height",height) """
x = int(input()) y = int(input()) if (2 * y + 1 - x) % (y - x + 1) == 0: print("YES") else: print("NO")
x = int(input()) y = int(input()) if (2 * y + 1 - x) % (y - x + 1) == 0: print('YES') else: print('NO')
class Solution: def longestPalindrome(self, s: str) -> str: result = '' pal_s = set(s) if len(pal_s) == 1: return s for ind_c in range(len(s)): pal = '' ind_l = ind_c ind_r = ind_c + 1 while ind_l > -1 and ind_r < len(s): if s[ind_l] == s[ind_r]: pal = s[ind_l] + pal + s[ind_r] ind_l -= 1 ind_r += 1 else: break if len(result) < len(pal): result = pal pal = s[ind_c] ind_l = ind_c - 1 ind_r = ind_c + 1 while ind_l > -1 and ind_r < len(s): if s[ind_l] == s[ind_r]: pal = s[ind_l] + pal + s[ind_r] ind_l -= 1 ind_r += 1 else: break if len(result) < len(pal): result = pal return result
class Solution: def longest_palindrome(self, s: str) -> str: result = '' pal_s = set(s) if len(pal_s) == 1: return s for ind_c in range(len(s)): pal = '' ind_l = ind_c ind_r = ind_c + 1 while ind_l > -1 and ind_r < len(s): if s[ind_l] == s[ind_r]: pal = s[ind_l] + pal + s[ind_r] ind_l -= 1 ind_r += 1 else: break if len(result) < len(pal): result = pal pal = s[ind_c] ind_l = ind_c - 1 ind_r = ind_c + 1 while ind_l > -1 and ind_r < len(s): if s[ind_l] == s[ind_r]: pal = s[ind_l] + pal + s[ind_r] ind_l -= 1 ind_r += 1 else: break if len(result) < len(pal): result = pal return result