content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class MidasConfig(object): def __init__(self, linked: bool): self.linked = linked IS_DEBUG = True
class Midasconfig(object): def __init__(self, linked: bool): self.linked = linked is_debug = True
# Python program showing # a use of input() val = input("Enter your value: ") print(val) # Program to check input # type in Python num = input("Enter number :") print(num) name1 = input("Enter name : ") print(name1) # Printing type of input value print("type of number", type(num)) print("type of name", type(name1))
val = input('Enter your value: ') print(val) num = input('Enter number :') print(num) name1 = input('Enter name : ') print(name1) print('type of number', type(num)) print('type of name', type(name1))
#!/usr/bin/env python3 """Implements disjoint-set data structures (so-called union-find data structures). Verification: [Union Find](https://judge.yosupo.jp/submission/11774) """ class UnionFind(object): """A simple implementation of disjoint-set data structures. """ def __init__(self, number_of_nodes): """Create a disjoint-data structure with `number_of_nodes` nodes. """ self.par = list(range(number_of_nodes)) self.rank = [0] * number_of_nodes def root(self, node): """Returns the root of node #`node`. """ if self.par[node] == node: return node else: r = self.root(self.par[node]) self.par[node] = r return r def in_the_same_set(self, node1, node2): """See if the given two nodes #`node1` and #`node2` are in the same set. """ return self.root(node1) == self.root(node2) def unite(self, node1, node2): """Unite the set containing node #`node1` and the another set containing node #`node2`. """ x = self.root(node1) y = self.root(node2) if x != y: if self.rank[x] < self.rank[y]: x, y = y, x self.par[y] = x if self.rank[x] == self.rank[y]: self.rank[x] += 1
"""Implements disjoint-set data structures (so-called union-find data structures). Verification: [Union Find](https://judge.yosupo.jp/submission/11774) """ class Unionfind(object): """A simple implementation of disjoint-set data structures. """ def __init__(self, number_of_nodes): """Create a disjoint-data structure with `number_of_nodes` nodes. """ self.par = list(range(number_of_nodes)) self.rank = [0] * number_of_nodes def root(self, node): """Returns the root of node #`node`. """ if self.par[node] == node: return node else: r = self.root(self.par[node]) self.par[node] = r return r def in_the_same_set(self, node1, node2): """See if the given two nodes #`node1` and #`node2` are in the same set. """ return self.root(node1) == self.root(node2) def unite(self, node1, node2): """Unite the set containing node #`node1` and the another set containing node #`node2`. """ x = self.root(node1) y = self.root(node2) if x != y: if self.rank[x] < self.rank[y]: (x, y) = (y, x) self.par[y] = x if self.rank[x] == self.rank[y]: self.rank[x] += 1
listOfIntegers = [1, 2, 3, 4, 5, 6] for integer in listOfIntegers: if (integer % 2 == 0): print (integer) print ("All done.")
list_of_integers = [1, 2, 3, 4, 5, 6] for integer in listOfIntegers: if integer % 2 == 0: print(integer) print('All done.')
TYPES = ['exact', 'ava', 'like', 'text'] PER_PAGE_MAX = 50 DBS = ['dehkhoda', 'moein', 'amid', 'motaradef', 'farhangestan', 'sareh', 'ganjvajeh', 'wiki', 'slang', 'quran', 'name', 'thesis', 'isfahani', 'bakhtiari', 'tehrani', 'dezfuli', 'gonabadi', 'mazani'] ERROR_CODES = { "400": "failed to parse parameters", "401": "invalid token has been used", "403": "this token is banned from vajehyab", "404": "word is not found in vajehyab databases", "405": "unknown HTTP method used to send data", "500": "server has failed to respond", "503": "server is down", }
types = ['exact', 'ava', 'like', 'text'] per_page_max = 50 dbs = ['dehkhoda', 'moein', 'amid', 'motaradef', 'farhangestan', 'sareh', 'ganjvajeh', 'wiki', 'slang', 'quran', 'name', 'thesis', 'isfahani', 'bakhtiari', 'tehrani', 'dezfuli', 'gonabadi', 'mazani'] error_codes = {'400': 'failed to parse parameters', '401': 'invalid token has been used', '403': 'this token is banned from vajehyab', '404': 'word is not found in vajehyab databases', '405': 'unknown HTTP method used to send data', '500': 'server has failed to respond', '503': 'server is down'}
# Script: software_sales # Description: A software company sells a package that retails for $99. # This program asks the user to enter the number of packages purchased. The program # should then display the amount of the discount (if any) and the total amount of the # purchase after the discount. # Programmer: William Kpabitey Kwabla # Date: 26.06.16 # Declaring discount percentage as Global constants. DISCOUNT1 = 50 DISCOUNT2 = 40 DISCOUNT3 = 30 DISCOUNT4 = 20 # Defining the main function. def main(): # Displaying what the program does to the user. print("A software company sells a package that retails for $99.") print("This program asks the user to enter the number of packages purchased. The program") print("should then display the amount of the discount (if any) and the total amount of the") print("purchase after the discount.") print("") # Asking user for the number of packages purchased. number_of_packages = int(input("Please Enter the number of packages purchased: ")) print("**************************************************************************") # Displaying the discount and the total amount of the purcahse after the discount. if number_of_packages >= 100: total_amount = (DISCOUNT1/100) * 99 print("The total amount of discount is",DISCOUNT1,"%.") print("The total amount of purchase after discount is $",format(total_amount,".1f")) elif number_of_packages >= 50: total_amount = (DISCOUNT2/100) * 99 print("The total amount of discount is",DISCOUNT2,"%.") print("The total amount of purchase after discount is $",format(total_amount,".1f")) elif number_of_packages >= 20: total_amount = (DISCOUNT3/100) * 99 print("The total amount of discount is",DISCOUNT3,"%.") print("The total amount of purchase after discount is $",format(total_amount,".1f")) else: total_amount = (DISCOUNT4/100) * 99 print("The total amount of discount is",DISCOUNT4,"%.") print("The total amount of purchase after discount is $",format(total_amount,".1f")) # Calling the main function to execute program. main()
discount1 = 50 discount2 = 40 discount3 = 30 discount4 = 20 def main(): print('A software company sells a package that retails for $99.') print('This program asks the user to enter the number of packages purchased. The program') print('should then display the amount of the discount (if any) and the total amount of the') print('purchase after the discount.') print('') number_of_packages = int(input('Please Enter the number of packages purchased: ')) print('**************************************************************************') if number_of_packages >= 100: total_amount = DISCOUNT1 / 100 * 99 print('The total amount of discount is', DISCOUNT1, '%.') print('The total amount of purchase after discount is $', format(total_amount, '.1f')) elif number_of_packages >= 50: total_amount = DISCOUNT2 / 100 * 99 print('The total amount of discount is', DISCOUNT2, '%.') print('The total amount of purchase after discount is $', format(total_amount, '.1f')) elif number_of_packages >= 20: total_amount = DISCOUNT3 / 100 * 99 print('The total amount of discount is', DISCOUNT3, '%.') print('The total amount of purchase after discount is $', format(total_amount, '.1f')) else: total_amount = DISCOUNT4 / 100 * 99 print('The total amount of discount is', DISCOUNT4, '%.') print('The total amount of purchase after discount is $', format(total_amount, '.1f')) main()
# https://app.codesignal.com/arcade/code-arcade/lab-of-transformations/dB9drnfWzpiWznESA/ def alphanumericLess(s1, s2): tokens_1 = list(re.findall(r"[0-9]+|[a-z]", s1)) tokens_2 = list(re.findall(r"[0-9]+|[a-z]", s2)) idx = 0 # Tie breakers, if all compared values are the same then the first # differing amount of leading zeros in a number will resolve it. t_1_zeros = 0 t_2_zeros = 0 while idx < len(tokens_1) and idx < len(tokens_2): token_1, token_2 = tokens_1[idx], tokens_2[idx] # If both are numeric if token_1.isdigit() and token_2.isdigit(): if int(token_1) < int(token_2): return True if int(token_1) > int(token_2): return False if t_1_zeros == 0 and t_2_zeros == 0: # Store leading zeros but preserving only the first # found. Whenever anything is stored there will stop # storing new leading zeros. t_1_zeros = sum([x == "0" for x in token_1]) t_2_zeros = sum([x == "0" for x in token_2]) # If both are string elif token_1.isalpha() and token_2.isalpha(): if token_1 < token_2: return True if token_1 > token_2: return False # If both are mixed... elif token_1 != token_2: # In mixed comparisson, digits come before letters. return token_1 < token_2 idx += 1 # If it was practically equal, return the one with the most # leading zeros as being "less". if t_1_zeros != 0 or t_2_zeros != 0: return t_1_zeros > t_2_zeros # If the leading zeros were equal too, then check if the first # string was the one completely exhausted to reach this point. # If both are equal then the first one is not strictly less. first_is_less = idx < len(tokens_2) return first_is_less
def alphanumeric_less(s1, s2): tokens_1 = list(re.findall('[0-9]+|[a-z]', s1)) tokens_2 = list(re.findall('[0-9]+|[a-z]', s2)) idx = 0 t_1_zeros = 0 t_2_zeros = 0 while idx < len(tokens_1) and idx < len(tokens_2): (token_1, token_2) = (tokens_1[idx], tokens_2[idx]) if token_1.isdigit() and token_2.isdigit(): if int(token_1) < int(token_2): return True if int(token_1) > int(token_2): return False if t_1_zeros == 0 and t_2_zeros == 0: t_1_zeros = sum([x == '0' for x in token_1]) t_2_zeros = sum([x == '0' for x in token_2]) elif token_1.isalpha() and token_2.isalpha(): if token_1 < token_2: return True if token_1 > token_2: return False elif token_1 != token_2: return token_1 < token_2 idx += 1 if t_1_zeros != 0 or t_2_zeros != 0: return t_1_zeros > t_2_zeros first_is_less = idx < len(tokens_2) return first_is_less
""" *Pixel* A pixel is a color in point space. """ class Pixel( Point, Color, ): pass
""" *Pixel* A pixel is a color in point space. """ class Pixel(Point, Color): pass
# coding:utf-8 def redprint(str): print("\033[1;31m {0}\033[0m".format(str)) def greenprint(str): print("\033[1;32m {0}\033[0m".format(str)) def blueprint(str): print("\033[1;34m {0}\033[0m".format(str)) def yellowprint(str): print("\033[1;33m {0}\033[0m".format(str))
def redprint(str): print('\x1b[1;31m {0}\x1b[0m'.format(str)) def greenprint(str): print('\x1b[1;32m {0}\x1b[0m'.format(str)) def blueprint(str): print('\x1b[1;34m {0}\x1b[0m'.format(str)) def yellowprint(str): print('\x1b[1;33m {0}\x1b[0m'.format(str))
"""Settings for the ``cmsplugin_blog`` app.""" JQUERY_JS = 'https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js' JQUERY_UI_JS = 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js' JQUERY_UI_CSS = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/themes/smoothness/jquery-ui.css'
"""Settings for the ``cmsplugin_blog`` app.""" jquery_js = 'https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js' jquery_ui_js = 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js' jquery_ui_css = 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/themes/smoothness/jquery-ui.css'
# ----------------------------------------------------- # Trust Game # Licensed under the MIT License # Written by Ye Liu (ye-liu at whu.edu.cn) # ----------------------------------------------------- cfg = { # Initial number of coins the user has 'initial_coins': 100, # Number of total rounds 'num_rounds': 10, # Multiplier for the money recieved by the trustee 'multiplier': 3, # Agent Settings 'agent': { # Whether to use the same gender as user 'use_same_gender': True, # Whether to use the same ethnic as user 'use_same_ethnic': True, # The potential means of yield rates of agents 'means': [-0.8, -0.4, 0, 0.4, 0.8], # The potential variances of yield rates of agents 'variances': [1, 1.5, 2], } }
cfg = {'initial_coins': 100, 'num_rounds': 10, 'multiplier': 3, 'agent': {'use_same_gender': True, 'use_same_ethnic': True, 'means': [-0.8, -0.4, 0, 0.4, 0.8], 'variances': [1, 1.5, 2]}}
class Piece: def __init__(self, t, s): self.t = t self.blocks = [] rows = s.split('\n') for i in range(len(rows)): for j in range(len(rows[i])): if rows[i][j] == '+': self.blocks.append((i, j)) def get_color(t, active=False): return ['#00ffff', '#0000ff', '#ffa500', '#ffff00', '#00ff00', '#800080', '#ff0000'][t]
class Piece: def __init__(self, t, s): self.t = t self.blocks = [] rows = s.split('\n') for i in range(len(rows)): for j in range(len(rows[i])): if rows[i][j] == '+': self.blocks.append((i, j)) def get_color(t, active=False): return ['#00ffff', '#0000ff', '#ffa500', '#ffff00', '#00ff00', '#800080', '#ff0000'][t]
# Enter your code here. Read input from STDIN. Print output to STDOUT def getMean(list): sum = 0 for i in list: sum += i mean = float(sum) / len(list) return mean def getMedian(list): median = 0.0 list.sort() if (len(list) % 2 == 0): median = float(list[len(list)//2 - 1] + list[len(list)//2]) / 2 else: median = list[(len(list)-1)/2] return median def getMode(list): mode = 0 count, max = 0, 0 list.sort() current = 0 for i in list: if (i == current): count += 1 else: count = 1 current = i if (count > max): max = count mode = i return mode size = int(input()) a = list(map(int, input().split())) print(getMean(a)) print(getMedian(a)) print(getMode(a))
def get_mean(list): sum = 0 for i in list: sum += i mean = float(sum) / len(list) return mean def get_median(list): median = 0.0 list.sort() if len(list) % 2 == 0: median = float(list[len(list) // 2 - 1] + list[len(list) // 2]) / 2 else: median = list[(len(list) - 1) / 2] return median def get_mode(list): mode = 0 (count, max) = (0, 0) list.sort() current = 0 for i in list: if i == current: count += 1 else: count = 1 current = i if count > max: max = count mode = i return mode size = int(input()) a = list(map(int, input().split())) print(get_mean(a)) print(get_median(a)) print(get_mode(a))
# -*- coding: utf-8 -*- """ Created on Sun Jan 3 09:43:06 2021 @author: SethHarden """ # SLICING ------------------------------------------------ x = 'computer' #[start : end : step] print(x[1:6:2]) print(x[1:4]) #1 - 4 print(x[3:]) #3 - end print(x[:5]) #0 - 5 print(x[-1]) #gets from right side print(x[:-2]) #from 0 until the last 2 print('-----------------------------------------') # ADDING / CONCATENATING # STRING x = 'horse' + 'shoe' print(x) # LIST y = ['pig', 'cow'] + ['horse'] #TUPLE z = ('DoubleDz', 'Seth', 'Aroosh') + ('RickD',) + ('Anshul',) #NEEDS THE COMMA , !!! print(z) print('-----------------------------------------') # CHECKING MEMBERSHIP x = 'bug' print ('u' in x) # LIST
""" Created on Sun Jan 3 09:43:06 2021 @author: SethHarden """ x = 'computer' print(x[1:6:2]) print(x[1:4]) print(x[3:]) print(x[:5]) print(x[-1]) print(x[:-2]) print('-----------------------------------------') x = 'horse' + 'shoe' print(x) y = ['pig', 'cow'] + ['horse'] z = ('DoubleDz', 'Seth', 'Aroosh') + ('RickD',) + ('Anshul',) print(z) print('-----------------------------------------') x = 'bug' print('u' in x)
# Enumerated constants for voice tokens. SMART, STUPID, ORCISH, ELVEN, DRACONIAN, DWARVEN, GREEK, KITTEH, GNOMIC, \ HURTHISH = list(range( 10))
(smart, stupid, orcish, elven, draconian, dwarven, greek, kitteh, gnomic, hurthish) = list(range(10))
{ 'model_dir': '{this_dir}/model_data/', 'out_dir': 'output/masif_peptides/shape_only/', 'feat_mask': [1.0, 1.0, 0.0, 0.0, 0.0], }
{'model_dir': '{this_dir}/model_data/', 'out_dir': 'output/masif_peptides/shape_only/', 'feat_mask': [1.0, 1.0, 0.0, 0.0, 0.0]}
#!/usr/bin/python3 # -*- coding:utf-8 -*- # Project: http://plankton-toolbox.org # Copyright (c) 2010-2018 SMHI, Swedish Meteorological and Hydrological Institute # License: MIT License (see LICENSE.txt or http://opensource.org/licenses/mit). # import toolbox_utils # import plankton_core class DataImportUtils(object): """ """ def __init__(self): """ """ def cleanup_scientific_name_cf(self, scientific_name, species_flag): """ """ new_scientific_name = scientific_name new_species_flag = species_flag # Remove 'cf.' if ' cf. '.upper() in (' ' + new_scientific_name + ' ').upper(): parts = new_scientific_name.split(' ') # parts = map(str.strip, parts) # Remove white characters. parts = [str.strip(x) for x in parts] # Remove white characters. speciesname = '' for part in parts: if part not in ['cf.', 'CF.', 'cf', 'CF']: speciesname += part + ' ' # new_scientific_name = speciesname.strip() # if len(new_species_flag) > 0: new_species_flag = 'cf., ' + new_species_flag else: new_species_flag = 'cf.' # return new_scientific_name, new_species_flag def cleanup_scientific_name_sp(self, scientific_name, species_flag): """ """ new_scientific_name = scientific_name new_species_flag = species_flag # Remove 'sp.' if (' sp.'.upper() in (new_scientific_name + ' ').upper()) or \ (' sp '.upper() in (new_scientific_name + ' ').upper()): parts = new_scientific_name.split(' ') # parts = map(str.strip, parts) # Remove white characters. parts = [str.strip(x) for x in parts] # Remove white characters. speciesname = '' for part in parts: if part not in ['sp.', 'SP.', 'sp', 'SP']: speciesname += part + ' ' # new_scientific_name = speciesname.strip() # if len(new_species_flag) > 0: new_species_flag = 'sp., ' + new_species_flag else: new_species_flag = 'sp.' # return new_scientific_name, new_species_flag def cleanup_scientific_name_spp(self, scientific_name, species_flag): """ """ new_scientific_name = scientific_name new_species_flag = species_flag # Remove 'spp.' if (' spp.'.upper() in (new_scientific_name + ' ').upper()) or \ (' spp '.upper() in (new_scientific_name + ' ').upper()): parts = new_scientific_name.split(' ') # parts = map(str.strip, parts) # Remove white characters. parts = [str.strip(x) for x in parts] # Remove white characters. speciesname = '' for part in parts: if part not in ['spp.', 'SPP.', 'spp', 'SPP']: speciesname += part + ' ' # new_scientific_name = speciesname.strip() # if len(new_species_flag) > 0: new_species_flag = 'spp., ' + new_species_flag else: new_species_flag = 'spp.' # return new_scientific_name, new_species_flag
class Dataimportutils(object): """ """ def __init__(self): """ """ def cleanup_scientific_name_cf(self, scientific_name, species_flag): """ """ new_scientific_name = scientific_name new_species_flag = species_flag if ' cf. '.upper() in (' ' + new_scientific_name + ' ').upper(): parts = new_scientific_name.split(' ') parts = [str.strip(x) for x in parts] speciesname = '' for part in parts: if part not in ['cf.', 'CF.', 'cf', 'CF']: speciesname += part + ' ' new_scientific_name = speciesname.strip() if len(new_species_flag) > 0: new_species_flag = 'cf., ' + new_species_flag else: new_species_flag = 'cf.' return (new_scientific_name, new_species_flag) def cleanup_scientific_name_sp(self, scientific_name, species_flag): """ """ new_scientific_name = scientific_name new_species_flag = species_flag if ' sp.'.upper() in (new_scientific_name + ' ').upper() or ' sp '.upper() in (new_scientific_name + ' ').upper(): parts = new_scientific_name.split(' ') parts = [str.strip(x) for x in parts] speciesname = '' for part in parts: if part not in ['sp.', 'SP.', 'sp', 'SP']: speciesname += part + ' ' new_scientific_name = speciesname.strip() if len(new_species_flag) > 0: new_species_flag = 'sp., ' + new_species_flag else: new_species_flag = 'sp.' return (new_scientific_name, new_species_flag) def cleanup_scientific_name_spp(self, scientific_name, species_flag): """ """ new_scientific_name = scientific_name new_species_flag = species_flag if ' spp.'.upper() in (new_scientific_name + ' ').upper() or ' spp '.upper() in (new_scientific_name + ' ').upper(): parts = new_scientific_name.split(' ') parts = [str.strip(x) for x in parts] speciesname = '' for part in parts: if part not in ['spp.', 'SPP.', 'spp', 'SPP']: speciesname += part + ' ' new_scientific_name = speciesname.strip() if len(new_species_flag) > 0: new_species_flag = 'spp., ' + new_species_flag else: new_species_flag = 'spp.' return (new_scientific_name, new_species_flag)
def to_rna(dna_strand): rna_dict = { 'C':'G', 'G':'C', 'T':'A', 'A':'U' } ret = '' for char in dna_strand: ret += rna_dict[char] return ret
def to_rna(dna_strand): rna_dict = {'C': 'G', 'G': 'C', 'T': 'A', 'A': 'U'} ret = '' for char in dna_strand: ret += rna_dict[char] return ret
class Subtraction: print('Test Subtraction class') def __init__(self, x, y): self.x = x self.y = y print('This is Subtraction function and result of your numbers is : ', x-y)
class Subtraction: print('Test Subtraction class') def __init__(self, x, y): self.x = x self.y = y print('This is Subtraction function and result of your numbers is : ', x - y)
# number = input('Enter a Number') # w, x, y, z = 5, 10, 10, 20 # if w > x: # print('x equals y') # elif w < y: # print('Second Condition') # elif x == y: # print('Third Condition') # else: # print('Everything is False') # username = 'qaidjohar' # password = 'qwerty' # if not 5 == 5: # if (username == 'qaidjohar' and password == 'qwerty'): # print('You are logged in') # print(f'Welcome {username}') # print('xxsdsds') # else: # print('Invalid Username/Passowrd') # else: # print('5 is not equal') # From 1 to 8: You have to Pay 500 # From 8 to 50: You have to Pay 800 # Above 50: You have to Pay 300 # Input: Enter Your Age print("****Welcome To QJ Amusement Park****") age = int(input("Enter You Age: ")) # if age <= 8: # print('Your ticket is Rs.500') # elif age > 8 and age <= 50: # print('Your ticket is Rs.800') # else: # print('Your ticket is Rs. 300') if age <= 8: print('Your ticket is Rs.500') elif age <= 50: print('Your ticket is Rs.800') else: print('Your ticket is Rs. 300')
print('****Welcome To QJ Amusement Park****') age = int(input('Enter You Age: ')) if age <= 8: print('Your ticket is Rs.500') elif age <= 50: print('Your ticket is Rs.800') else: print('Your ticket is Rs. 300')
paths = \ [dict(steering_angle = -20, target_angle = -20, coords = \ [[0, 53, 91, 97], [0, 64, 97, 107], [15, 76, 107, 119], [33, 86, 119, 132], [47, 95, 132, 146], [59, 102, 146, 160], [69, 108, 160, 175], [76, 112, 175, 190]]), dict(steering_angle = -15, target_angle = -15, coords = \ [[0, 52, 34, 54], [15, 67, 54, 73], [33, 79, 73, 93], [47, 89, 93, 112], [58, 97, 112, 132], [67, 104, 132, 151], [75, 109, 151, 171], [80, 112, 171, 190]]), dict(steering_angle = -7, target_angle = -5, coords = \ [[49, 83, 2, 26], [57, 90, 26, 49], [64, 95, 49, 73], [70, 100, 73, 96], [75, 105, 96, 120], [79, 108, 120, 143], [83, 111, 143, 167], [85, 112, 167, 190]]), dict(steering_angle = 0, target_angle = 0, coords = \ [[88, 112, 2, 26], [88, 112, 26, 49], [88, 112, 49, 73], [88, 112, 73, 96], [88, 112, 96, 120], [88, 112, 120, 143], [88, 112, 143, 167], [88, 112, 167, 190]]), dict(steering_angle = 7, target_angle = 5, coords = \ [[117, 151, 2, 26], [110, 143, 26, 49], [105, 136, 49, 73], [100, 130, 73, 96], [95, 125, 96, 120], [92, 121, 120, 143], [90, 117, 143, 167], [88, 115, 167, 190]]), dict(steering_angle = 15, target_angle = 15, coords = \ [[148, 200, 34, 54], [133, 185, 54, 73], [121, 168, 73, 93], [111, 153, 93, 112], [103, 142, 112, 132], [96, 133, 132, 151], [91, 125, 151, 171], [88, 120, 171, 190]]), dict(steering_angle = 20, target_angle = 20, coords = \ [[147, 200, 91, 97], [136, 200, 97, 107], [124, 186, 107, 119], [114, 167, 119, 132], [105, 153, 132, 146], [98, 141, 146, 160], [92, 131, 160, 175], [88, 124, 175, 190]])]
paths = [dict(steering_angle=-20, target_angle=-20, coords=[[0, 53, 91, 97], [0, 64, 97, 107], [15, 76, 107, 119], [33, 86, 119, 132], [47, 95, 132, 146], [59, 102, 146, 160], [69, 108, 160, 175], [76, 112, 175, 190]]), dict(steering_angle=-15, target_angle=-15, coords=[[0, 52, 34, 54], [15, 67, 54, 73], [33, 79, 73, 93], [47, 89, 93, 112], [58, 97, 112, 132], [67, 104, 132, 151], [75, 109, 151, 171], [80, 112, 171, 190]]), dict(steering_angle=-7, target_angle=-5, coords=[[49, 83, 2, 26], [57, 90, 26, 49], [64, 95, 49, 73], [70, 100, 73, 96], [75, 105, 96, 120], [79, 108, 120, 143], [83, 111, 143, 167], [85, 112, 167, 190]]), dict(steering_angle=0, target_angle=0, coords=[[88, 112, 2, 26], [88, 112, 26, 49], [88, 112, 49, 73], [88, 112, 73, 96], [88, 112, 96, 120], [88, 112, 120, 143], [88, 112, 143, 167], [88, 112, 167, 190]]), dict(steering_angle=7, target_angle=5, coords=[[117, 151, 2, 26], [110, 143, 26, 49], [105, 136, 49, 73], [100, 130, 73, 96], [95, 125, 96, 120], [92, 121, 120, 143], [90, 117, 143, 167], [88, 115, 167, 190]]), dict(steering_angle=15, target_angle=15, coords=[[148, 200, 34, 54], [133, 185, 54, 73], [121, 168, 73, 93], [111, 153, 93, 112], [103, 142, 112, 132], [96, 133, 132, 151], [91, 125, 151, 171], [88, 120, 171, 190]]), dict(steering_angle=20, target_angle=20, coords=[[147, 200, 91, 97], [136, 200, 97, 107], [124, 186, 107, 119], [114, 167, 119, 132], [105, 153, 132, 146], [98, 141, 146, 160], [92, 131, 160, 175], [88, 124, 175, 190]])]
tests = int(input()) for _ in range(tests): data = [float(num) for num in input().split()] sum = 2*data[0]+3*data[1]+5*data[2] print("%0.1f" % (sum/10))
tests = int(input()) for _ in range(tests): data = [float(num) for num in input().split()] sum = 2 * data[0] + 3 * data[1] + 5 * data[2] print('%0.1f' % (sum / 10))
# Append at the end of /etc/mailman/mm_cfg.py DEFAULT_ARCHIVE = Off DEFAULT_REPLY_GOES_TO_LIST = 1 DEFAULT_SUBSCRIBE_POLICY = 3 DEFAULT_MAX_NUM_RECIPIENTS = 30 DEFAULT_MAX_MESSAGE_SIZE = 10000 # KB
default_archive = Off default_reply_goes_to_list = 1 default_subscribe_policy = 3 default_max_num_recipients = 30 default_max_message_size = 10000
class Palindrome: def __init__(self, word, start, end): self.word = word self.start = int(start / 2) self.end = int(end / 2) def __str__(self): return self.word + " " + str(self.start) + " " + str(self.end) + "\n"
class Palindrome: def __init__(self, word, start, end): self.word = word self.start = int(start / 2) self.end = int(end / 2) def __str__(self): return self.word + ' ' + str(self.start) + ' ' + str(self.end) + '\n'
# -*- coding: utf-8 -*- dictTempoMusica = dict({"W":1,"H":1/2,"Q":1/4,"E":1/8,"S":1/16,"T":1/32,"X":1/64}) listSeqCompasso = list(map(str, input().split("/"))) while listSeqCompasso[0] != "*": listSeqCompasso.pop(0) listSeqCompasso.pop(-1) qntCompassoDuracaoCorreta = 0 for compasso in listSeqCompasso: duracaoCompasso = 0 for tempo in compasso: duracaoCompasso += dictTempoMusica[tempo] if duracaoCompasso == 1: qntCompassoDuracaoCorreta += 1 print(qntCompassoDuracaoCorreta) listSeqCompasso = list(map(str, input().split("/")))
dict_tempo_musica = dict({'W': 1, 'H': 1 / 2, 'Q': 1 / 4, 'E': 1 / 8, 'S': 1 / 16, 'T': 1 / 32, 'X': 1 / 64}) list_seq_compasso = list(map(str, input().split('/'))) while listSeqCompasso[0] != '*': listSeqCompasso.pop(0) listSeqCompasso.pop(-1) qnt_compasso_duracao_correta = 0 for compasso in listSeqCompasso: duracao_compasso = 0 for tempo in compasso: duracao_compasso += dictTempoMusica[tempo] if duracaoCompasso == 1: qnt_compasso_duracao_correta += 1 print(qntCompassoDuracaoCorreta) list_seq_compasso = list(map(str, input().split('/')))
def decode(message): first_4 = message[:4] first = add_ordinals(message[0], message[-1]) second = add_ordinals(message[1], message[0]) third = add_ordinals(message[2], message[1]) fourth = add_ordinals(message[3], message[2]) fifth = add_ordinals(message[-4], message[-5]) sixth = add_ordinals(message[-3], message[-4]) seventh = add_ordinals(message[-2], message[-3]) eight = add_ordinals(message[-1], message[-2]) new_message = "" new_message += convert_to_char(first) new_message += convert_to_char(second) new_message += convert_to_char(third) new_message += convert_to_char(fourth) new_message += convert_to_char(fifth) new_message += convert_to_char(sixth) new_message += convert_to_char(seventh) new_message += convert_to_char(eight) return new_message def add_ordinals(ord1, ord2): sum = ord(ord1) + ord(ord2) while sum < 97: sum += ord(ord2) return sum def convert_to_char(num): while num > 122: num -= 26 return chr(num) def main(): message = input() sig = input() decoded = decode(message) if decoded == sig: print(f"{sig} equals {sig}") print("Gru") else: print(f"{decoded} does not equal {sig}") print("Not Gru") if __name__ == "__main__": main()
def decode(message): first_4 = message[:4] first = add_ordinals(message[0], message[-1]) second = add_ordinals(message[1], message[0]) third = add_ordinals(message[2], message[1]) fourth = add_ordinals(message[3], message[2]) fifth = add_ordinals(message[-4], message[-5]) sixth = add_ordinals(message[-3], message[-4]) seventh = add_ordinals(message[-2], message[-3]) eight = add_ordinals(message[-1], message[-2]) new_message = '' new_message += convert_to_char(first) new_message += convert_to_char(second) new_message += convert_to_char(third) new_message += convert_to_char(fourth) new_message += convert_to_char(fifth) new_message += convert_to_char(sixth) new_message += convert_to_char(seventh) new_message += convert_to_char(eight) return new_message def add_ordinals(ord1, ord2): sum = ord(ord1) + ord(ord2) while sum < 97: sum += ord(ord2) return sum def convert_to_char(num): while num > 122: num -= 26 return chr(num) def main(): message = input() sig = input() decoded = decode(message) if decoded == sig: print(f'{sig} equals {sig}') print('Gru') else: print(f'{decoded} does not equal {sig}') print('Not Gru') if __name__ == '__main__': main()
_empty = [] _simple = [1, 2, 3] _complex = [{"value": 1}, {"value": 2}, {"value": 3}] _locations = [ ("Scotland", "Edinburgh", "Branch1", 20000), ("Scotland", "Glasgow", "Branch1", 12500), ("Scotland", "Glasgow", "Branch2", 12000), ("Wales", "Cardiff", "Branch1", 29700), ("Wales", "Cardiff", "Branch2", 30000), ("Wales", "Bangor", "Branch1", 12800), ("England", "London", "Branch1", 90000), ("England", "London", "Branch2", 80000), ("England", "London", "Branch3", 70000), ("England", "Manchester", "Branch1", 45600), ("England", "Manchester", "Branch2", 50000), ("England", "Liverpool", "Branch1", 29700), ("England", "Liverpool", "Branch2", 25000), ]
_empty = [] _simple = [1, 2, 3] _complex = [{'value': 1}, {'value': 2}, {'value': 3}] _locations = [('Scotland', 'Edinburgh', 'Branch1', 20000), ('Scotland', 'Glasgow', 'Branch1', 12500), ('Scotland', 'Glasgow', 'Branch2', 12000), ('Wales', 'Cardiff', 'Branch1', 29700), ('Wales', 'Cardiff', 'Branch2', 30000), ('Wales', 'Bangor', 'Branch1', 12800), ('England', 'London', 'Branch1', 90000), ('England', 'London', 'Branch2', 80000), ('England', 'London', 'Branch3', 70000), ('England', 'Manchester', 'Branch1', 45600), ('England', 'Manchester', 'Branch2', 50000), ('England', 'Liverpool', 'Branch1', 29700), ('England', 'Liverpool', 'Branch2', 25000)]
def hamming_distance(x: int, y: int): """ Calculate the number of bits that are different between 2 numbers. Args: x: first integer to calculate distance on Y: second integer to calculate distance on Returns: An integer representing the number of bits that are different in the two args. """ # xor numbers to get diff bits as 1's xor = x ^ y # count the 1's in integer return hamming_weight(xor) def hamming_weight(x: int): """ Count the number of on bits in an integer. Args: x: the number to count on bits Returns: Integer representing the number of bits that are on (1). """ count = 0 while x: # bitwise AND number with itself minus 1 x &= x - 1 count += 1 return count
def hamming_distance(x: int, y: int): """ Calculate the number of bits that are different between 2 numbers. Args: x: first integer to calculate distance on Y: second integer to calculate distance on Returns: An integer representing the number of bits that are different in the two args. """ xor = x ^ y return hamming_weight(xor) def hamming_weight(x: int): """ Count the number of on bits in an integer. Args: x: the number to count on bits Returns: Integer representing the number of bits that are on (1). """ count = 0 while x: x &= x - 1 count += 1 return count
""" Objective 14 - Perform basic dictionary operations """ """ Add "Herb" to the phonebook with the number 7653420789. Remove "Bill" from the phonebook. """ phonebook = { "Abe": 4569874321, "Bill": 7659803241, "Barry": 6573214789 } # YOUR CODE HERE phonebook['Herb'] = 7653420789 del phonebook['Bill'] # Should print Herb is in the phonebook. if "Herb" in phonebook: print("Herb is in the phonebook.") # Should print Bill is not in the phonebook. if "Bill" not in phonebook: print("Bill is not in the phonebook.")
""" Objective 14 - Perform basic dictionary operations """ '\nAdd "Herb" to the phonebook with the number 7653420789.\nRemove "Bill" from the phonebook.\n' phonebook = {'Abe': 4569874321, 'Bill': 7659803241, 'Barry': 6573214789} phonebook['Herb'] = 7653420789 del phonebook['Bill'] if 'Herb' in phonebook: print('Herb is in the phonebook.') if 'Bill' not in phonebook: print('Bill is not in the phonebook.')
MYSQL_DB = 'edxapp' MYSQL_USER = 'root' MYSQL_PSWD = '' MONGO_DB = 'edxapp' MONGO_DISCUSSION_DB = 'cs_comments_service_development'
mysql_db = 'edxapp' mysql_user = 'root' mysql_pswd = '' mongo_db = 'edxapp' mongo_discussion_db = 'cs_comments_service_development'
# coding: utf-8 class DataBatch: def __init__(self, torch_module): self._data = [] self._label = [] self.torch_module = torch_module def append_data(self, new_data): self._data.append(self.__as_tensor(new_data)) def append_label(self, new_label): self._label.append(self.__as_tensor(new_label)) def __as_tensor(self, in_data): return self.torch_module.from_numpy(in_data) @property def data(self): return self._data @property def label(self): return self._label
class Databatch: def __init__(self, torch_module): self._data = [] self._label = [] self.torch_module = torch_module def append_data(self, new_data): self._data.append(self.__as_tensor(new_data)) def append_label(self, new_label): self._label.append(self.__as_tensor(new_label)) def __as_tensor(self, in_data): return self.torch_module.from_numpy(in_data) @property def data(self): return self._data @property def label(self): return self._label
""" Problem: Given an integer n, return the length of the longest consecutive run of 1s in its binary representation. For example, given 156, you should return 3. """ def get_longest_chain_of_1s(num: int) -> int: num = bin(num)[2:] chain_max = 0 chain_curr = 0 for char in num: if char == "1": chain_curr += 1 else: chain_max = max(chain_max, chain_curr) chain_curr = 0 return max(chain_max, chain_curr) if __name__ == "__main__": print(get_longest_chain_of_1s(15)) print(get_longest_chain_of_1s(156)) """ SPECS: TIME COMPLEXITY: O(log(n)) SPACE COMPLEXITY: O(1) [there are log2(n) digits in the binary representation of any number n] """
""" Problem: Given an integer n, return the length of the longest consecutive run of 1s in its binary representation. For example, given 156, you should return 3. """ def get_longest_chain_of_1s(num: int) -> int: num = bin(num)[2:] chain_max = 0 chain_curr = 0 for char in num: if char == '1': chain_curr += 1 else: chain_max = max(chain_max, chain_curr) chain_curr = 0 return max(chain_max, chain_curr) if __name__ == '__main__': print(get_longest_chain_of_1s(15)) print(get_longest_chain_of_1s(156)) '\nSPECS:\n\nTIME COMPLEXITY: O(log(n))\nSPACE COMPLEXITY: O(1)\n[there are log2(n) digits in the binary representation of any number n]\n'
input = """ p cnf 3 4 -1 2 3 0 1 -2 0 1 -3 0 -1 -2 0 """ output = """ SAT """
input = '\np cnf 3 4\n-1 2 3 0\n1 -2 0\n1 -3 0\n-1 -2 0\n' output = '\nSAT\n'
"""A programe which will find all such numers between 1000 and 3000 such that each digit of the number is an even number""" #num1=0 #num2=0 #num3=0 #num4=0 #real=0 #lresult=[] #def even(num,num1,num2,num3,real): # if (num%2==0) and (num1%2==0) and (num2%2==0) and (num3%2==0): # lresult.append(real) #for value in range(1000,3001): # real=value # while(value!=0): # num1=value%10 # value=value/10 # num2=value%10 # value=value/10 # num3=value%10 # value=value/10 # num4=value # even(num1,num2,num3,num4,real) #print(lresult) """v is a list containig numbers. write code to find and print the highest two values in v. If the list contains only one number, print only that number. If the list is empty, print nothing . For example v=[7,3,1,5,10,6] output,l=[7,10]""" #v=[7,3,1,5,10,6] #maxvalue=v[0] #secmax=maxvalue #for value in v: # if value >= maxvalue: # secmax=maxvalue # maxvalue=value # else: # continue #print(secmax,maxvalue) """Write a programe that takes two different lists as inouts and returns the smallest value that appears in both lists. example l1=[1,3,8,12,12,15,20] l2=[7,9,10,11,15,30,35] l3=[2,4,5,13,16,17,23,25] then print smallest_in_common(l1,l2) should output 15 print smallest_in_common(l1,l3) should output None""" #def smallest_in_common(s1,s2): # s4=s1.intersection(s2) # small=0 # for value in s4: # small=value # break # for x in s4: # if x < small: # small=x # else: # continue # print(small) #l1=[1,3,8,12,12,15,20] #l2=[7,9,10,11,15,30,35] #l3=[2,4,5,13,16,17,23,25] #s1=set(l1) #s2=set(l2) #s3=set(l3) #smallest_in_common(s1,s2) #smallest_in_common(s1,s3) """Python code that takes a list of numbeers, and outputs the positive values that are in v in incresing order, if there are no positive values, then the output should be none. for example l=[17,-5,15,-3,12,-5,0,12,22,-1] then the output of the code'[12,12,15,17,22]""" #l=[17,-5,15,-3,12,-5,0,12,22,-1] #l2=[] #l.sort() #print(l) #for value in l: # if value>0: # l2.append(value) #print(l2) """given a list of test scores, where the maximum score is 100,write cod that prints the nmber of scrores that are in the range 0-9,10-19,20-29,....80-89,90-100.For example given the list of scores [12,90,10,52,56,76,92,83,39,77,73,70,80] the output should be : (0,9):0,(10,19):1,(20,29):0,(30,39):1,(40,49):0,(50,59):2,(60,69):0,(70,79):4, (80,89):2,(90,100):3""" #l=[12,90,10,52,56,76,92,83,39,77,73,70,80] #key1=0 #key2=0 #key3=0 #key4=0 #key5=0 #key6=0 #key7=0 #key8=0 #key9=0 #key10=0 #for value in l: # if value <=9: # key1=key1+1 # elif value <=19: # key2=key2+1 # elif value<19: # key3=key3+1 # elif value <39: # key4=key4+1 # elif value <=49: # key5=key5+1 # elif value <=59: # key6=key6+1 # elif value <=69: # key7=key7+1 # elif value <=79: # key8=key8+1 # elif value <=89: # key9=key9+1 # else: # key10=key10+1 #d={(0,9):key1,(10,19):key2,(20,29):key3,(30,39):key4,(40,49):key5,(50,59):key6,(60,69):key7,(70,79):key8,(80,89):key9,(90,100):key10} #print(d) """A Programe to read elements in a matrix and check whether the matrix is identity matrix or not . Identity matrix is a special square matrix whose diagonal elements is equal to 1 and other elements are 0 Input elements in atrix [[1,0,0], [0,1,0], [0,0,1]] output Its an identity matrix""" #l=[[1,0,0],[0,1,0],[0,0,1]] #l2=[] #for value in l: # for val in value: # l2.append(val) #l3=l2[::4] #if sum(l3)==sum(l2): # print("given matrix is an identity matrix") ''' Practice Question on dictionaries in Python: ------------------------------------------- 1) Given a dictionary that associates the names of states with a list of the names of cities that appear in it, write a program that creates a new dictionary that associates the name of a city with the list of states that it appears in. As an example, if the first dictionary is states = {'New Hampshire': ['Concord', 'Hanover'], 'Massachusetts': ['Boston', 'Concord', 'Springfield'], 'Illinois': ['Chicago', 'Springfield', 'Peoria']} cities = {'Hanover': ['New Hampshire'], 'Chicago': ['Illinois'],'Boston': ['Massachusetts'], 'Peoria': ['Illinois'],'Concord': ['New Hampshire', 'Massachusetts'],Springfield': ['Massachusetts', 'Illinois']} ''' ''' states = {'New Hampshire': ['Concord', 'Hanover'], 'Massachusetts': ['Boston', 'Concord', 'Springfield'], 'Illinois': ['Chicago', 'Springfield', 'Peoria']} cities = {} for k,v in states.items(): for idx in v: if idx in cities.keys(): cities[idx].append(k) else: cities.setdefault(idx,[k]) print(cities) '''
"""A programe which will find all such numers between 1000 and 3000 such that each digit of the number is an even number""" 'v is a list containig numbers. write code to find and print the highest two values \nin v. If the list contains only one number, print only that number. If the list is empty,\nprint nothing .\nFor example\nv=[7,3,1,5,10,6]\noutput,l=[7,10]' 'Write a programe that takes two different lists as inouts and returns the smallest value that appears in both lists.\nexample \nl1=[1,3,8,12,12,15,20]\nl2=[7,9,10,11,15,30,35]\nl3=[2,4,5,13,16,17,23,25]\nthen\nprint smallest_in_common(l1,l2) should output 15\nprint smallest_in_common(l1,l3) should output None' "Python code that takes a list of numbeers, and outputs the positive values that\nare in v in incresing order, if there are no positive values, then the output should\nbe none. for example l=[17,-5,15,-3,12,-5,0,12,22,-1]\nthen the output of the code'[12,12,15,17,22]" 'given a list of test scores, where the maximum score is 100,write cod that prints\nthe nmber of scrores that are in the range 0-9,10-19,20-29,....80-89,90-100.For \nexample given the list of scores\n[12,90,10,52,56,76,92,83,39,77,73,70,80]\n \n the output should be :\n (0,9):0,(10,19):1,(20,29):0,(30,39):1,(40,49):0,(50,59):2,(60,69):0,(70,79):4,\n (80,89):2,(90,100):3' 'A Programe to read elements in a matrix and check whether the matrix is \nidentity matrix or not .\nIdentity matrix is a special square matrix whose diagonal elements is equal to 1 and\nother elements are 0\nInput elements in atrix \n[[1,0,0],\n[0,1,0],\n[0,0,1]]\n\noutput\nIts an identity matrix' "\nPractice Question on dictionaries in Python:\n-------------------------------------------\n1) Given a dictionary that associates the names of states with a list of the names of cities that appear in it,\nwrite a program that creates a new dictionary that associates the name of a city with the list of states that it appears in.\nAs an example, if the first dictionary is \n\nstates = {'New Hampshire': ['Concord', 'Hanover'],\n'Massachusetts': ['Boston', 'Concord', 'Springfield'],\n'Illinois': ['Chicago', 'Springfield', 'Peoria']}\n\ncities = {'Hanover': ['New Hampshire'],\n'Chicago': ['Illinois'],'Boston': ['Massachusetts'],\n'Peoria': ['Illinois'],'Concord': ['New Hampshire', 'Massachusetts'],Springfield': ['Massachusetts', 'Illinois']}\n" "\nstates = {'New Hampshire': ['Concord', 'Hanover'],\n'Massachusetts': ['Boston', 'Concord', 'Springfield'],\n'Illinois': ['Chicago', 'Springfield', 'Peoria']}\n\ncities = {}\n\nfor k,v in states.items():\n for idx in v:\n if idx in cities.keys():\n cities[idx].append(k)\n else:\n cities.setdefault(idx,[k])\nprint(cities)\n"
def find(A): low = 0 high = len(A) - 1 while low < high: mid = (low + high) // 2 if A[mid] > A[high]: low = mid + 1 elif A[mid] <= A[high]: high = mid return low A = [4, 5, 6, 7, 1, 2, 3] idx = find(A) print(A[idx])
def find(A): low = 0 high = len(A) - 1 while low < high: mid = (low + high) // 2 if A[mid] > A[high]: low = mid + 1 elif A[mid] <= A[high]: high = mid return low a = [4, 5, 6, 7, 1, 2, 3] idx = find(A) print(A[idx])
class ladder: def __init__(self): self.start=0 self.end=0
class Ladder: def __init__(self): self.start = 0 self.end = 0
#$Id: embed_pythonLib.py,v 1.3 2010/10/05 19:24:18 jrb Exp $ def generate(env, **kw): if not kw.get('depsOnly',0): env.Tool('addLibrary', library = ['embed_python']) if env['PLATFORM'] == 'posix': env.AppendUnique(LINKFLAGS = ['-rdynamic']) if env['PLATFORM'] == "win32" and env.get('CONTAINERNAME','') == 'GlastRelease': env.Tool('findPkgPath', package = 'embed_python') env.Tool('addLibrary', library = env['pythonLibs']) # No need for incsOnly section def exists(env): return 1
def generate(env, **kw): if not kw.get('depsOnly', 0): env.Tool('addLibrary', library=['embed_python']) if env['PLATFORM'] == 'posix': env.AppendUnique(LINKFLAGS=['-rdynamic']) if env['PLATFORM'] == 'win32' and env.get('CONTAINERNAME', '') == 'GlastRelease': env.Tool('findPkgPath', package='embed_python') env.Tool('addLibrary', library=env['pythonLibs']) def exists(env): return 1
class Solution: def letterCasePermutation(self, s: str) -> List[str]: """ Time complexity O(N!) - factorial time need to generate all permutations Space complexity O(N!) Approach: Using BFS generate new permutations by append one more char to all previous generated permutations """ permutations = [] if not s: return permutations q = deque([""]) while q: curr_string = q.popleft() n = len(curr_string) if n == len(s): permutations.append(curr_string) continue q.append(curr_string + s[n]) if s[n].isalpha(): q.append(curr_string + s[n].swapcase()) return permutations
class Solution: def letter_case_permutation(self, s: str) -> List[str]: """ Time complexity O(N!) - factorial time need to generate all permutations Space complexity O(N!) Approach: Using BFS generate new permutations by append one more char to all previous generated permutations """ permutations = [] if not s: return permutations q = deque(['']) while q: curr_string = q.popleft() n = len(curr_string) if n == len(s): permutations.append(curr_string) continue q.append(curr_string + s[n]) if s[n].isalpha(): q.append(curr_string + s[n].swapcase()) return permutations
# -*- coding: utf-8 -*- # Copyright by BlueWhale. All Rights Reserved. class ValidateError(ValueError): def __init__(self, val, msg: str, *args): super().__init__(val, msg, *args) self.__val = val self.__msg = msg @property def val(self): return self.__val @property def msg(self): return self.__msg class FieldSetError(RuntimeError): def __init__(self, field_name: str, val, msg: str, *args): super().__init__(field_name, val, msg, *args) self.__field_name = field_name self.__val = val self.__msg = msg @property def field_name(self): return self.__field_name @property def val(self): return self.__val @property def msg(self): return self.__msg
class Validateerror(ValueError): def __init__(self, val, msg: str, *args): super().__init__(val, msg, *args) self.__val = val self.__msg = msg @property def val(self): return self.__val @property def msg(self): return self.__msg class Fieldseterror(RuntimeError): def __init__(self, field_name: str, val, msg: str, *args): super().__init__(field_name, val, msg, *args) self.__field_name = field_name self.__val = val self.__msg = msg @property def field_name(self): return self.__field_name @property def val(self): return self.__val @property def msg(self): return self.__msg
# V0 class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def str2tree(self, s): """ :type s: str :rtype: TreeNode """ def str2treeHelper(s, i): start = i if s[i] == '-': i += 1 while i < len(s) and s[i].isdigit(): i += 1 node = TreeNode(int(s[start:i])) if i < len(s) and s[i] == '(': i += 1 node.left, i = str2treeHelper(s, i) i += 1 if i < len(s) and s[i] == '(': i += 1 node.right, i = str2treeHelper(s, i) i += 1 return node, i return str2treeHelper(s, 0)[0] if s else None # V0' class Solution(object): def str2tree(self, s): """ :type s: str :rtype: TreeNode """ if not s: return None n = '' while s and s[0] not in ('(', ')'): n += s[0] s = s[1:] node = TreeNode(int(n)) left, right = self.divide(s) node.left = self.str2tree(left[1:-1]) node.right = self.str2tree(right[1:-1]) return node def divide(self, s): part, deg = '', 0 while s: if s[0] == '(': deg += 1 elif s[0] == ')': deg += -1 else: deg += 0 part += s[0] s = s[1:] if deg == 0: break return part, s # V1 # http://bookshadow.com/weblog/2017/03/12/leetcode-construct-binary-tree-from-string/ # https://blog.csdn.net/magicbean2/article/details/78850694 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def str2tree(self, s): """ :type s: str :rtype: TreeNode """ if not s: return None n = '' while s and s[0] not in ('(', ')'): n += s[0] s = s[1:] node = TreeNode(int(n)) left, right = self.divide(s) node.left = self.str2tree(left[1:-1]) node.right = self.str2tree(right[1:-1]) return node def divide(self, s): part, deg = '', 0 while s: deg += {'(' : 1, ')' : -1}.get(s[0], 0) part += s[0] s = s[1:] if deg == 0: break return part, s ### Test case : dev # V1' # https://www.jiuzhang.com/solution/construct-binary-tree-from-string/#tag-highlight-lang-python # IDEA : RECURSION class Solution: """ @param s: a string @return: return a TreeNode """ def str2tree(self, s): self.idx = 0 self.len = len(s) if(self.len == 0): return None root = self.dfs(s) return root def dfs(self, s): if(self.idx >= self.len): return None sig, k = 1, 0 if(s[self.idx] == '-'): sig = -1 self.idx += 1 while(self.idx < self.len and s[self.idx] >= '0' and s[self.idx] <= '9'): k = k * 10 + ord(s[self.idx]) - ord('0') self.idx += 1 root = TreeNode(sig * k) if(self.idx >= self.len or s[self.idx] == ')'): self.idx += 1 return root self.idx += 1 root.left = self.dfs(s) if(self.idx >= self.len or s[self.idx] == ')'): self.idx += 1 return root self.idx += 1 root.right = self.dfs(s) if(self.idx >= self.len or s[self.idx] == ')'): self.idx += 1 return root return root # V1'' # https://www.geeksforgeeks.org/construct-binary-tree-string-bracket-representation/ # Python3 program to conStruct a # binary tree from the given String # Helper class that allocates a new node class newNode: def __init__(self, data): self.data = data self.left = self.right = None # This funtcion is here just to test def preOrder(node): if (node == None): return print(node.data, end = " ") preOrder(node.left) preOrder(node.right) # function to return the index of # close parenthesis def findIndex(Str, si, ei): if (si > ei): return -1 # Inbuilt stack s = [] for i in range(si, ei + 1): # if open parenthesis, push it if (Str[i] == '('): s.append(Str[i]) # if close parenthesis elif (Str[i] == ')'): if (s[-1] == '('): s.pop(-1) # if stack is empty, this is # the required index if len(s) == 0: return i # if not found return -1 return -1 # function to conStruct tree from String def treeFromString(Str, si, ei): # Base case if (si > ei): return None # new root root = newNode(ord(Str[si]) - ord('0')) index = -1 # if next char is '(' find the # index of its complement ')' if (si + 1 <= ei and Str[si + 1] == '('): index = findIndex(Str, si + 1, ei) # if index found if (index != -1): # call for left subtree root.left = treeFromString(Str, si + 2, index - 1) # call for right subtree root.right = treeFromString(Str, index + 2, ei - 1) return root # V2 # https://github.com/kamyu104/LeetCode-Solutions/blob/master/Python/construct-binary-tree-from-string.py # Time: O(n) # Space: O(h) class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def str2tree(self, s): """ :type s: str :rtype: TreeNode """ def str2treeHelper(s, i): start = i if s[i] == '-': i += 1 while i < len(s) and s[i].isdigit(): i += 1 node = TreeNode(int(s[start:i])) if i < len(s) and s[i] == '(': i += 1 node.left, i = str2treeHelper(s, i) i += 1 if i < len(s) and s[i] == '(': i += 1 node.right, i = str2treeHelper(s, i) i += 1 return node, i return str2treeHelper(s, 0)[0] if s else None
class Treenode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def str2tree(self, s): """ :type s: str :rtype: TreeNode """ def str2tree_helper(s, i): start = i if s[i] == '-': i += 1 while i < len(s) and s[i].isdigit(): i += 1 node = tree_node(int(s[start:i])) if i < len(s) and s[i] == '(': i += 1 (node.left, i) = str2tree_helper(s, i) i += 1 if i < len(s) and s[i] == '(': i += 1 (node.right, i) = str2tree_helper(s, i) i += 1 return (node, i) return str2tree_helper(s, 0)[0] if s else None class Solution(object): def str2tree(self, s): """ :type s: str :rtype: TreeNode """ if not s: return None n = '' while s and s[0] not in ('(', ')'): n += s[0] s = s[1:] node = tree_node(int(n)) (left, right) = self.divide(s) node.left = self.str2tree(left[1:-1]) node.right = self.str2tree(right[1:-1]) return node def divide(self, s): (part, deg) = ('', 0) while s: if s[0] == '(': deg += 1 elif s[0] == ')': deg += -1 else: deg += 0 part += s[0] s = s[1:] if deg == 0: break return (part, s) class Solution(object): def str2tree(self, s): """ :type s: str :rtype: TreeNode """ if not s: return None n = '' while s and s[0] not in ('(', ')'): n += s[0] s = s[1:] node = tree_node(int(n)) (left, right) = self.divide(s) node.left = self.str2tree(left[1:-1]) node.right = self.str2tree(right[1:-1]) return node def divide(self, s): (part, deg) = ('', 0) while s: deg += {'(': 1, ')': -1}.get(s[0], 0) part += s[0] s = s[1:] if deg == 0: break return (part, s) class Solution: """ @param s: a string @return: return a TreeNode """ def str2tree(self, s): self.idx = 0 self.len = len(s) if self.len == 0: return None root = self.dfs(s) return root def dfs(self, s): if self.idx >= self.len: return None (sig, k) = (1, 0) if s[self.idx] == '-': sig = -1 self.idx += 1 while self.idx < self.len and s[self.idx] >= '0' and (s[self.idx] <= '9'): k = k * 10 + ord(s[self.idx]) - ord('0') self.idx += 1 root = tree_node(sig * k) if self.idx >= self.len or s[self.idx] == ')': self.idx += 1 return root self.idx += 1 root.left = self.dfs(s) if self.idx >= self.len or s[self.idx] == ')': self.idx += 1 return root self.idx += 1 root.right = self.dfs(s) if self.idx >= self.len or s[self.idx] == ')': self.idx += 1 return root return root class Newnode: def __init__(self, data): self.data = data self.left = self.right = None def pre_order(node): if node == None: return print(node.data, end=' ') pre_order(node.left) pre_order(node.right) def find_index(Str, si, ei): if si > ei: return -1 s = [] for i in range(si, ei + 1): if Str[i] == '(': s.append(Str[i]) elif Str[i] == ')': if s[-1] == '(': s.pop(-1) if len(s) == 0: return i return -1 def tree_from_string(Str, si, ei): if si > ei: return None root = new_node(ord(Str[si]) - ord('0')) index = -1 if si + 1 <= ei and Str[si + 1] == '(': index = find_index(Str, si + 1, ei) if index != -1: root.left = tree_from_string(Str, si + 2, index - 1) root.right = tree_from_string(Str, index + 2, ei - 1) return root class Treenode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def str2tree(self, s): """ :type s: str :rtype: TreeNode """ def str2tree_helper(s, i): start = i if s[i] == '-': i += 1 while i < len(s) and s[i].isdigit(): i += 1 node = tree_node(int(s[start:i])) if i < len(s) and s[i] == '(': i += 1 (node.left, i) = str2tree_helper(s, i) i += 1 if i < len(s) and s[i] == '(': i += 1 (node.right, i) = str2tree_helper(s, i) i += 1 return (node, i) return str2tree_helper(s, 0)[0] if s else None
def setup(): #this is your canvas size size(1000,1000) #fill(34,45,56,23) #background(192, 64, 0) stroke(255) colorMode(RGB) strokeWeight(1) #rect(150,150,150,150) def draw(): x=mouseX y=mouseY ix=width-x iy=height-y px=pmouseX py=pmouseY background(0,0,0) #rect(150,150,150,150) strokeWeight(5) line(x,y,ix,iy) #line(x,y,px,py) strokeWeight(120) point(40,x) if (mousePressed == True): if (mouseButton == LEFT): fill(196,195,106,255) #box(200,500,500) strokeWeight(0) rectMode(CENTER) rect(height/2,width/2,ix,100) strokeWeight(0) fill(144,135,145) rectMode(CORNERS) rect(mouseX-10,iy-10,width/2,height/2) fill(155,211,211) rectMode(CORNER) rect(mouseX,mouseY,50,50) fill(205,126,145) ellipseMode(CORNER) ellipse(px,py,35,35) #colorMode(RGB,100,100,100,100) fill(80,98,173,188) ellipseMode(CORNERS) ellipse(x*.75,y*.75,35,35) frameRate(12) println(str(mouseX)+"."+str(mouseY)) println(pmouseX-mouseX) print("why is it there?") if (x>500): fill(255,160) rect(0,0,x,height) else: fill(255,160) rect(0,0,width-ix,height) if ((x>250) and (x<500) and (y>500) and (y<1000)): fill(255) rect(250,500,250,500) fill(245,147,188) rectMode(CORNER) rect(mouseX,mouseY,50,50) if ((x>0) and (x<250) and (y>500) and (y<1000)): fill(255) rect(0,500,250,500) fill(20,126,145) ellipseMode(CORNER) ellipse(px,py,35,35) if (mousePressed and (x>500)): background(255,255,255) fill(200) rectMode(CENTER) rect(width/2,height/2,500,500) #colorMode(RGB,100,100,100,100) ellipseMode(CORNERS) fill(170,170,170,255) strokeWeight(4) ellipse(width/2-125,height/2-125,width/2-75,height/2-75) ellipse(width/2+75,height/2-125,width/2+125,height/2-75) a = width/2 b = height/2 strokeWeight(7) noFill() curve(a-125,1.4*b-125,a-50,1.4*b-95,a+50,1.4*b-95,a+125,1.4*b-125)
def setup(): size(1000, 1000) stroke(255) color_mode(RGB) stroke_weight(1) def draw(): x = mouseX y = mouseY ix = width - x iy = height - y px = pmouseX py = pmouseY background(0, 0, 0) stroke_weight(5) line(x, y, ix, iy) stroke_weight(120) point(40, x) if mousePressed == True: if mouseButton == LEFT: fill(196, 195, 106, 255) stroke_weight(0) rect_mode(CENTER) rect(height / 2, width / 2, ix, 100) stroke_weight(0) fill(144, 135, 145) rect_mode(CORNERS) rect(mouseX - 10, iy - 10, width / 2, height / 2) fill(155, 211, 211) rect_mode(CORNER) rect(mouseX, mouseY, 50, 50) fill(205, 126, 145) ellipse_mode(CORNER) ellipse(px, py, 35, 35) fill(80, 98, 173, 188) ellipse_mode(CORNERS) ellipse(x * 0.75, y * 0.75, 35, 35) frame_rate(12) println(str(mouseX) + '.' + str(mouseY)) println(pmouseX - mouseX) print('why is it there?') if x > 500: fill(255, 160) rect(0, 0, x, height) else: fill(255, 160) rect(0, 0, width - ix, height) if x > 250 and x < 500 and (y > 500) and (y < 1000): fill(255) rect(250, 500, 250, 500) fill(245, 147, 188) rect_mode(CORNER) rect(mouseX, mouseY, 50, 50) if x > 0 and x < 250 and (y > 500) and (y < 1000): fill(255) rect(0, 500, 250, 500) fill(20, 126, 145) ellipse_mode(CORNER) ellipse(px, py, 35, 35) if mousePressed and x > 500: background(255, 255, 255) fill(200) rect_mode(CENTER) rect(width / 2, height / 2, 500, 500) ellipse_mode(CORNERS) fill(170, 170, 170, 255) stroke_weight(4) ellipse(width / 2 - 125, height / 2 - 125, width / 2 - 75, height / 2 - 75) ellipse(width / 2 + 75, height / 2 - 125, width / 2 + 125, height / 2 - 75) a = width / 2 b = height / 2 stroke_weight(7) no_fill() curve(a - 125, 1.4 * b - 125, a - 50, 1.4 * b - 95, a + 50, 1.4 * b - 95, a + 125, 1.4 * b - 125)
def binary_search(coll, elem): low = 0 high = len(coll) - 1 while low <= high: middle = (low + high) // 2 guess = coll[middle] if guess == elem: return middle if guess > elem: high = middle - 1 else: low = middle + 1 return None print(binary_search([1, 3, 5, 7, 9], 0)) print(binary_search([1, 3, 5, 7, 9], 7))
def binary_search(coll, elem): low = 0 high = len(coll) - 1 while low <= high: middle = (low + high) // 2 guess = coll[middle] if guess == elem: return middle if guess > elem: high = middle - 1 else: low = middle + 1 return None print(binary_search([1, 3, 5, 7, 9], 0)) print(binary_search([1, 3, 5, 7, 9], 7))
# Time Complexity => O(n^2 + log n) ; log n for sorting class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: output = [] nums.sort() for i in range(len(nums)-2): if i>0 and nums[i]==nums[i-1]: continue j = i+1 k = len(nums)-1 while j<k: temp = nums[i] + nums[j] + nums[k] if temp == 0: output.append([nums[i],nums[j],nums[k]]) while j<k and nums[j]==nums[j+1]: j+=1 while j<k and nums[k]==nums[k-1]: k-=1 j+=1 k-=1 elif temp>0: k-=1 else: j+=1 return output
class Solution: def three_sum(self, nums: List[int]) -> List[List[int]]: output = [] nums.sort() for i in range(len(nums) - 2): if i > 0 and nums[i] == nums[i - 1]: continue j = i + 1 k = len(nums) - 1 while j < k: temp = nums[i] + nums[j] + nums[k] if temp == 0: output.append([nums[i], nums[j], nums[k]]) while j < k and nums[j] == nums[j + 1]: j += 1 while j < k and nums[k] == nums[k - 1]: k -= 1 j += 1 k -= 1 elif temp > 0: k -= 1 else: j += 1 return output
# input 3 number and calculate middle number def Middle_3Num_Calc(a, b, c): if a >= b: if b >= c: return b elif a <= c: return a else: return c elif a > c: return a elif b > c: return c else: return b def Middle_3Num_Calc_ver2(a, b, c): if (b >= a and c <= a) or (b <= a and c >= a): return a elif (a > b and c < b) or (a < b and c > b): return b return c print('Calculate middle number') a = int(input('Num a: ')) b = int(input('Num b: ')) c = int(input('Num c: ')) print(f'Middle Num is {Middle_3Num_Calc(a, b, c)}.')
def middle_3_num__calc(a, b, c): if a >= b: if b >= c: return b elif a <= c: return a else: return c elif a > c: return a elif b > c: return c else: return b def middle_3_num__calc_ver2(a, b, c): if b >= a and c <= a or (b <= a and c >= a): return a elif a > b and c < b or (a < b and c > b): return b return c print('Calculate middle number') a = int(input('Num a: ')) b = int(input('Num b: ')) c = int(input('Num c: ')) print(f'Middle Num is {middle_3_num__calc(a, b, c)}.')
# -*- coding: utf-8 -*- class Null(object): def __init__(self, *args, **kwargs): return None def __call__(self, *args, **kwargs): return self def __getattr__(self, name): return self def __setattr__(self, name, value): return self def __delattr__(self, name): return self def __repr__(self): return "<Null>" def __str__(self): return "Null"
class Null(object): def __init__(self, *args, **kwargs): return None def __call__(self, *args, **kwargs): return self def __getattr__(self, name): return self def __setattr__(self, name, value): return self def __delattr__(self, name): return self def __repr__(self): return '<Null>' def __str__(self): return 'Null'
batch_size = 32 epochs = 200 lr = 0.01 momentum = 0.9 no_cuda =False cuda_id = '0' seed = 1 log_interval = 10 l2_decay = 5e-4 class_num = 31 param = 0.3 bottle_neck = True root_path = "/data/zhuyc/OFFICE31/" source_name = "dslr" target_name = "amazon"
batch_size = 32 epochs = 200 lr = 0.01 momentum = 0.9 no_cuda = False cuda_id = '0' seed = 1 log_interval = 10 l2_decay = 0.0005 class_num = 31 param = 0.3 bottle_neck = True root_path = '/data/zhuyc/OFFICE31/' source_name = 'dslr' target_name = 'amazon'
def solution(record): Change = "Change" entry = {"Enter": " entered .", "Leave": " left." } recs = [] for r in record: r = r.split(" ") recs.append(r) # Change user id for all record first. for r in recs: uid = "" nickname = "" if (Change in r): uid = r[1] nickname = r[2] for r in recs: if (uid in r): r[2] = nickname # Create user data db - {"uid": "nickname"} user_db = {} for r in recs: user_db[r[1]] = r[-1] answer = [] for r in recs: if (Change not in r): message = "" message = f"{user_db[r[1]]}{entry[r[0]]}" answer.append(message) print(message) return answer
def solution(record): change = 'Change' entry = {'Enter': ' entered .', 'Leave': ' left.'} recs = [] for r in record: r = r.split(' ') recs.append(r) for r in recs: uid = '' nickname = '' if Change in r: uid = r[1] nickname = r[2] for r in recs: if uid in r: r[2] = nickname user_db = {} for r in recs: user_db[r[1]] = r[-1] answer = [] for r in recs: if Change not in r: message = '' message = f'{user_db[r[1]]}{entry[r[0]]}' answer.append(message) print(message) return answer
with open("input4.txt") as f: raw = f.read() pp = raw.split("\n\n") ppd = list() for p in pp: p = p.replace("\n", " ") p = p.strip() if not p: continue pairs = p.split(" ") ppd.append({s.split(":")[0]: s.split(":")[1] for s in pairs}) def isvalid(p): if not {"byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"}.issubset(ks): return False print(p) if not len(p["byr"]) == 4: return False if not (1920 <= int(p["byr"]) <= 2002): return False if not (2010 <= int(p["iyr"]) <= 2020): return False if not (2020 <= int(p["eyr"]) <= 2030): return False if p["hgt"].endswith("cm"): num = p["hgt"].split("cm")[0] if not 150 <= int(num) <= 193: return False elif p["hgt"].endswith("in"): num = p["hgt"].split("in")[0] if not (59 <= int(num) <= 76): return False else: return False if not p["hcl"].startswith("#"): return False if not len(p["hcl"]) == 7: return False for c in p["hcl"][1:]: if not c in "abcdef0123456789": return False if not p["ecl"] in ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]: return False if not len(p["pid"]) == 9: return False for c in p["pid"]: if not c in "0123456789": return False return True ok = 0 for p in ppd: ks = set(p.keys()) if isvalid(p): ok += 1 print(ok)
with open('input4.txt') as f: raw = f.read() pp = raw.split('\n\n') ppd = list() for p in pp: p = p.replace('\n', ' ') p = p.strip() if not p: continue pairs = p.split(' ') ppd.append({s.split(':')[0]: s.split(':')[1] for s in pairs}) def isvalid(p): if not {'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'}.issubset(ks): return False print(p) if not len(p['byr']) == 4: return False if not 1920 <= int(p['byr']) <= 2002: return False if not 2010 <= int(p['iyr']) <= 2020: return False if not 2020 <= int(p['eyr']) <= 2030: return False if p['hgt'].endswith('cm'): num = p['hgt'].split('cm')[0] if not 150 <= int(num) <= 193: return False elif p['hgt'].endswith('in'): num = p['hgt'].split('in')[0] if not 59 <= int(num) <= 76: return False else: return False if not p['hcl'].startswith('#'): return False if not len(p['hcl']) == 7: return False for c in p['hcl'][1:]: if not c in 'abcdef0123456789': return False if not p['ecl'] in ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth']: return False if not len(p['pid']) == 9: return False for c in p['pid']: if not c in '0123456789': return False return True ok = 0 for p in ppd: ks = set(p.keys()) if isvalid(p): ok += 1 print(ok)
class Block(object): def __init__(self, block): self.block = block def get_block(self): return self.block def set_block(self, new_block): self.block = new_block
class Block(object): def __init__(self, block): self.block = block def get_block(self): return self.block def set_block(self, new_block): self.block = new_block
# Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Sick Beard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Sick Beard. If not, see <http://www.gnu.org/licenses/>. # all regexes are case insensitive ep_regexes = [ ('standard_repeat', # Show.Name.S01E02.S01E03.Source.Quality.Etc-Group # Show Name - S01E02 - S01E03 - S01E04 - Ep Name ''' ^(?P<series_name>.+?)[. _-]+ # Show_Name and separator s(?P<season_num>\d+)[. _-]* # S01 and optional separator e(?P<ep_num>\d+) # E02 and separator ([. _-]+s(?P=season_num)[. _-]* # S01 and optional separator e(?P<extra_ep_num>\d+))+ # E03/etc and separator [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc- ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group '''), ('fov_repeat', # Show.Name.1x02.1x03.Source.Quality.Etc-Group # Show Name - 1x02 - 1x03 - 1x04 - Ep Name ''' ^(?P<series_name>.+?)[. _-]+ # Show_Name and separator (?P<season_num>\d+)x # 1x (?P<ep_num>\d+) # 02 and separator ([. _-]+(?P=season_num)x # 1x (?P<extra_ep_num>\d+))+ # 03/etc and separator [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc- ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group '''), ('standard', # Show.Name.S01E02.Source.Quality.Etc-Group # Show Name - S01E02 - My Ep Name # Show.Name.S01.E03.My.Ep.Name # Show.Name.S01E02E03.Source.Quality.Etc-Group # Show Name - S01E02-03 - My Ep Name # Show.Name.S01.E02.E03 ''' ^((?P<series_name>.+?)[. _-]+)? # Show_Name and separator s(?P<season_num>\d+)[. _-]* # S01 and optional separator e(?P<ep_num>\d+) # E02 and separator (([. _-]*e|-)(?P<extra_ep_num>\d+))* # additional E03/etc [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc- ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group '''), ('fov', # Show_Name.1x02.Source_Quality_Etc-Group # Show Name - 1x02 - My Ep Name # Show_Name.1x02x03x04.Source_Quality_Etc-Group # Show Name - 1x02-03-04 - My Ep Name ''' ^((?P<series_name>.+?)[. _-]+)? # Show_Name and separator (?P<season_num>\d+)x # 1x (?P<ep_num>\d+) # 02 and separator (([. _-]*x|-)(?P<extra_ep_num>\d+))* # additional x03/etc [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc- ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group '''), ('scene_date_format', # Show.Name.2010.11.23.Source.Quality.Etc-Group # Show Name - 2010-11-23 - Ep Name ''' ^((?P<series_name>.+?)[. _-]+)? # Show_Name and separator (?P<air_year>\d{4})[. _-]+ # 2010 and separator (?P<air_month>\d{2})[. _-]+ # 11 and separator (?P<air_day>\d{2}) # 23 and separator [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc- ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group '''), ('stupid', # tpz-abc102 ''' (?P<release_group>.+?)-\w+?[\. ]? # tpz-abc (?P<season_num>\d{1,2}) # 1 (?P<ep_num>\d{2})$ # 02 '''), ('bare', # Show.Name.102.Source.Quality.Etc-Group ''' ^(?P<series_name>.+?)[. _-]+ # Show_Name and separator (?P<season_num>\d{1,2}) # 1 (?P<ep_num>\d{2}) # 02 and separator ([. _-]+(?P<extra_info>(?!\d{3}[. _-]+)[^-]+) # Source_Quality_Etc- (-(?P<release_group>.+))?)?$ # Group '''), ('verbose', # Show Name Season 1 Episode 2 Ep Name ''' ^(?P<series_name>.+?)[. _-]+ # Show Name and separator season[. _-]+ # season and separator (?P<season_num>\d+)[. _-]+ # 1 episode[. _-]+ # episode and separator (?P<ep_num>\d+)[. _-]+ # 02 and separator (?P<extra_info>.+)$ # Source_Quality_Etc- '''), ('season_only', # Show.Name.S01.Source.Quality.Etc-Group ''' ^((?P<series_name>.+?)[. _-]+)? # Show_Name and separator s(eason[. _-])? # S01/Season 01 (?P<season_num>\d+)[. _-]* # S01 and optional separator [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc- ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group ''' ), ('no_season_general', # Show.Name.E23.Test # Show.Name.Part.3.Source.Quality.Etc-Group # Show.Name.Part.1.and.Part.2.Blah-Group # Show Name Episode 3 and 4 ''' ^((?P<series_name>.+?)[. _-]+)? # Show_Name and separator (e(p(isode)?)?|part|pt)[. _-]? # e, ep, episode, or part (?P<ep_num>(\d+|[ivx]+)) # first ep num ([. _-]+((and|&|to)[. _-]+)? # and/&/to joiner ((e(p(isode)?)?|part|pt)[. _-]?)? # e, ep, episode, or part (?P<extra_ep_num>(\d+|[ivx]+)))* # second ep num [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc- ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group ''' ), ('no_season', # Show Name - 01 - Ep Name # 01 - Ep Name ''' ^((?P<series_name>.+?)[. _-]+)? # Show_Name and separator (?P<ep_num>\d{2}) # 02 [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc- ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group ''' ), ]
ep_regexes = [('standard_repeat', '\n ^(?P<series_name>.+?)[. _-]+ # Show_Name and separator\n s(?P<season_num>\\d+)[. _-]* # S01 and optional separator\n e(?P<ep_num>\\d+) # E02 and separator\n ([. _-]+s(?P=season_num)[. _-]* # S01 and optional separator\n e(?P<extra_ep_num>\\d+))+ # E03/etc and separator\n [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc-\n ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group\n '), ('fov_repeat', '\n ^(?P<series_name>.+?)[. _-]+ # Show_Name and separator\n (?P<season_num>\\d+)x # 1x\n (?P<ep_num>\\d+) # 02 and separator\n ([. _-]+(?P=season_num)x # 1x\n (?P<extra_ep_num>\\d+))+ # 03/etc and separator\n [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc-\n ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group\n '), ('standard', '\n ^((?P<series_name>.+?)[. _-]+)? # Show_Name and separator\n s(?P<season_num>\\d+)[. _-]* # S01 and optional separator\n e(?P<ep_num>\\d+) # E02 and separator\n (([. _-]*e|-)(?P<extra_ep_num>\\d+))* # additional E03/etc\n [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc-\n ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group\n '), ('fov', '\n ^((?P<series_name>.+?)[. _-]+)? # Show_Name and separator\n (?P<season_num>\\d+)x # 1x\n (?P<ep_num>\\d+) # 02 and separator\n (([. _-]*x|-)(?P<extra_ep_num>\\d+))* # additional x03/etc\n [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc-\n ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group\n '), ('scene_date_format', '\n ^((?P<series_name>.+?)[. _-]+)? # Show_Name and separator\n (?P<air_year>\\d{4})[. _-]+ # 2010 and separator\n (?P<air_month>\\d{2})[. _-]+ # 11 and separator\n (?P<air_day>\\d{2}) # 23 and separator\n [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc-\n ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group\n '), ('stupid', '\n (?P<release_group>.+?)-\\w+?[\\. ]? # tpz-abc\n (?P<season_num>\\d{1,2}) # 1\n (?P<ep_num>\\d{2})$ # 02\n '), ('bare', '\n ^(?P<series_name>.+?)[. _-]+ # Show_Name and separator\n (?P<season_num>\\d{1,2}) # 1\n (?P<ep_num>\\d{2}) # 02 and separator\n ([. _-]+(?P<extra_info>(?!\\d{3}[. _-]+)[^-]+) # Source_Quality_Etc-\n (-(?P<release_group>.+))?)?$ # Group\n '), ('verbose', '\n ^(?P<series_name>.+?)[. _-]+ # Show Name and separator\n season[. _-]+ # season and separator\n (?P<season_num>\\d+)[. _-]+ # 1\n episode[. _-]+ # episode and separator\n (?P<ep_num>\\d+)[. _-]+ # 02 and separator\n (?P<extra_info>.+)$ # Source_Quality_Etc-\n '), ('season_only', '\n ^((?P<series_name>.+?)[. _-]+)? # Show_Name and separator\n s(eason[. _-])? # S01/Season 01\n (?P<season_num>\\d+)[. _-]* # S01 and optional separator\n [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc-\n ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group\n '), ('no_season_general', '\n ^((?P<series_name>.+?)[. _-]+)? # Show_Name and separator\n (e(p(isode)?)?|part|pt)[. _-]? # e, ep, episode, or part\n (?P<ep_num>(\\d+|[ivx]+)) # first ep num\n ([. _-]+((and|&|to)[. _-]+)? # and/&/to joiner\n ((e(p(isode)?)?|part|pt)[. _-]?)? # e, ep, episode, or part\n (?P<extra_ep_num>(\\d+|[ivx]+)))* # second ep num\n [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc-\n ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group\n '), ('no_season', '\n ^((?P<series_name>.+?)[. _-]+)? # Show_Name and separator\n (?P<ep_num>\\d{2}) # 02\n [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc-\n ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group\n ')]
''' Problem 48 @author: Kevin Ji ''' def self_power_with_mod(number, mod): product = 1 for _ in range(number): product *= number product %= mod return product MOD = 10000000000 number = 0 for power in range(1, 1000 + 1): number += self_power_with_mod(power, MOD) number %= MOD print(number)
""" Problem 48 @author: Kevin Ji """ def self_power_with_mod(number, mod): product = 1 for _ in range(number): product *= number product %= mod return product mod = 10000000000 number = 0 for power in range(1, 1000 + 1): number += self_power_with_mod(power, MOD) number %= MOD print(number)
# Code for demo_03 def captureInfoCam(): GPIO.setwarnings(False) # Ignore warning for now GPIO.setmode(GPIO.BOARD) # Use physical pin numbering subprocess.call(['fswebcam -r 640x480 --no-banner /home/pi/Desktop/image.jpg', '-1'], shell=True) #Azure face_uri = "https://raspberrycp.cognitiveservices.azure.com/vision/v1.0/analyze?visualFeatures=Faces&language=en" pathToFileInDisk = r'/home/pi/Desktop/image.jpg' with open( pathToFileInDisk, 'rb' ) as f: data = f.read() headers = { "Content-Type": "application/octet-stream" ,'Ocp-Apim-Subscription-Key': '7e9cfbb244204fb994babd6111235269'} try: response = requests.post(face_uri, headers=headers, data=data) faces = response.json() #pprint(faces) age = faces['faces'][0].get('age') gender = faces['faces'][0].get('gender') datosUsuario = [age, gender] except requests.exceptions.ConnectionError: return None except IndexError: return None else: return datosUsuario
def capture_info_cam(): GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) subprocess.call(['fswebcam -r 640x480 --no-banner /home/pi/Desktop/image.jpg', '-1'], shell=True) face_uri = 'https://raspberrycp.cognitiveservices.azure.com/vision/v1.0/analyze?visualFeatures=Faces&language=en' path_to_file_in_disk = '/home/pi/Desktop/image.jpg' with open(pathToFileInDisk, 'rb') as f: data = f.read() headers = {'Content-Type': 'application/octet-stream', 'Ocp-Apim-Subscription-Key': '7e9cfbb244204fb994babd6111235269'} try: response = requests.post(face_uri, headers=headers, data=data) faces = response.json() age = faces['faces'][0].get('age') gender = faces['faces'][0].get('gender') datos_usuario = [age, gender] except requests.exceptions.ConnectionError: return None except IndexError: return None else: return datosUsuario
wagons = int(input()) wagons_list = [0 for _ in range(wagons)] command = input().split() while "End" not in command: if "add" in command: wagons_list[-1] += int(command[1]) elif "insert" in command: wagons_list[int(command[1])] += int(command[2]) elif "leave" in command: wagons_list[int(command[1])] -= int(command[2]) command = input().split() print(wagons_list)
wagons = int(input()) wagons_list = [0 for _ in range(wagons)] command = input().split() while 'End' not in command: if 'add' in command: wagons_list[-1] += int(command[1]) elif 'insert' in command: wagons_list[int(command[1])] += int(command[2]) elif 'leave' in command: wagons_list[int(command[1])] -= int(command[2]) command = input().split() print(wagons_list)
# Copyright (C) 2019-2020 Petr Pavlu <setup@dagobah.cz> # SPDX-License-Identifier: MIT """StorePass exceptions.""" class StorePassException(Exception): """Base StorePass exception.""" class ModelException(StorePassException): """Exception when working with a model.""" class StorageException(StorePassException): """Base storage exception.""" class StorageReadException(StorageException): """Error reading a password database.""" class StorageWriteException(StorageException): """Error writing a password database."""
"""StorePass exceptions.""" class Storepassexception(Exception): """Base StorePass exception.""" class Modelexception(StorePassException): """Exception when working with a model.""" class Storageexception(StorePassException): """Base storage exception.""" class Storagereadexception(StorageException): """Error reading a password database.""" class Storagewriteexception(StorageException): """Error writing a password database."""
class Solution(object): def average(self, salary): """ :type salary: List[int] :rtype: float """ # Runtime: 24 ms # Memory: 13.4 MB # In Python 2, you need to convert the divisor/dividend into float in order to get a float answer return (sum(salary) - min(salary) - max(salary)) / float(len(salary) - 2)
class Solution(object): def average(self, salary): """ :type salary: List[int] :rtype: float """ return (sum(salary) - min(salary) - max(salary)) / float(len(salary) - 2)
# -------------- ##File path for the file file_path def read_file(path): file = open(file_path, 'r') sentence = file.readline() file.close() return sentence sample_message = read_file(file_path) # -------------- #Code starts here #Function to fuse message def fuse_msg(message_a,message_b): #Integer division of two numbers quot=(int(message_b)//int(message_a)) #Returning the quotient in string format return str(quot) #Calling the function to read file message_1=read_file(file_path_1) print(message_1) #Calling the function to read file message_2=read_file(file_path_2) print(message_2) #Calling the function 'fuse_msg' secret_msg_1=fuse_msg(message_1,message_2) #Printing the secret message print(secret_msg_1) #Code ends here with open(file_path, "rb") as fp: print(fp.read()) with open(file_path_1, "rb") as fp: print(fp.read()) with open(file_path_2, "rb") as fp: print(fp.read()) # -------------- #Code starts here #Code starts here message_3 = read_file(file_path_3) print(message_3) def substitute_msg(message_c): if(message_c == 'Red'): sub = 'Army General' elif(message_c == 'Green'): sub = 'Data Scientist' elif(message_c == 'Blue'): sub = 'Marine Biologist' return sub secret_msg_2 = substitute_msg(message_3) print(secret_msg_2) # -------------- # File path for message 4 and message 5 file_path_4 file_path_5 message_4 = read_file(file_path_4) message_5 = read_file(file_path_5) def compare_msg(message_d, message_e): a_list = message_d.split() b_list = message_e.split() c_list = [i for i in a_list if i not in b_list] final_msg = " ".join(c_list) return(final_msg) secret_msg_3 = compare_msg(message_4, message_5) print(secret_msg_3) # -------------- #Code starts here file_path_6 message_6 = read_file(file_path_6) print(message_6) def extract_msg(message_f): a_list = message_f.split() even_word = lambda x: len(x)%2==0 b_list = filter(even_word, a_list) final_msg = " ".join(b_list) return final_msg secret_msg_4 = extract_msg(message_6) print(secret_msg_4) # -------------- message_parts=[secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2] final_path= user_data_dir + 'secret_msg.txt' secret_msg = " ".join(message_parts) print(user_data_dir) def write_file(secret_msg, path): f = open(path, 'a+') f.write(secret_msg) f.close() write_file(secret_msg, final_path) print(secret_msg)
file_path def read_file(path): file = open(file_path, 'r') sentence = file.readline() file.close() return sentence sample_message = read_file(file_path) def fuse_msg(message_a, message_b): quot = int(message_b) // int(message_a) return str(quot) message_1 = read_file(file_path_1) print(message_1) message_2 = read_file(file_path_2) print(message_2) secret_msg_1 = fuse_msg(message_1, message_2) print(secret_msg_1) with open(file_path, 'rb') as fp: print(fp.read()) with open(file_path_1, 'rb') as fp: print(fp.read()) with open(file_path_2, 'rb') as fp: print(fp.read()) message_3 = read_file(file_path_3) print(message_3) def substitute_msg(message_c): if message_c == 'Red': sub = 'Army General' elif message_c == 'Green': sub = 'Data Scientist' elif message_c == 'Blue': sub = 'Marine Biologist' return sub secret_msg_2 = substitute_msg(message_3) print(secret_msg_2) file_path_4 file_path_5 message_4 = read_file(file_path_4) message_5 = read_file(file_path_5) def compare_msg(message_d, message_e): a_list = message_d.split() b_list = message_e.split() c_list = [i for i in a_list if i not in b_list] final_msg = ' '.join(c_list) return final_msg secret_msg_3 = compare_msg(message_4, message_5) print(secret_msg_3) file_path_6 message_6 = read_file(file_path_6) print(message_6) def extract_msg(message_f): a_list = message_f.split() even_word = lambda x: len(x) % 2 == 0 b_list = filter(even_word, a_list) final_msg = ' '.join(b_list) return final_msg secret_msg_4 = extract_msg(message_6) print(secret_msg_4) message_parts = [secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2] final_path = user_data_dir + 'secret_msg.txt' secret_msg = ' '.join(message_parts) print(user_data_dir) def write_file(secret_msg, path): f = open(path, 'a+') f.write(secret_msg) f.close() write_file(secret_msg, final_path) print(secret_msg)
class Solution: def partitionLabels(self, string): """O(N) time | O(1) space""" chars = {} for i, char in enumerate(string): if char in chars: chars[char][1] = i else: chars[char] = [i, i] partitions = [] i = prev = 0 while i < len(string): char = string[i] i = chars[char][1] while char: for c, pos in chars.items(): if pos[0] <= i and pos[1] > i: i = pos[1] else: char = None partitions.append(i - prev + 1) i += 1 prev = i return partitions # Even better, idea from: # https://leetcode.com/problems/partition-labels/discuss/298474/Python-two-pointer-solution-with-explanation class Solution: def partitionLabels(self, string): """O(N) time | O(1) space""" chars = {c:i for i,c in enumerate(string)} left = right = 0 partitions = [] for i, char in enumerate(string): right = max(right, chars[char]) if i == right: partitions.append(right - left + 1) left = right + 1 return partitions
class Solution: def partition_labels(self, string): """O(N) time | O(1) space""" chars = {} for (i, char) in enumerate(string): if char in chars: chars[char][1] = i else: chars[char] = [i, i] partitions = [] i = prev = 0 while i < len(string): char = string[i] i = chars[char][1] while char: for (c, pos) in chars.items(): if pos[0] <= i and pos[1] > i: i = pos[1] else: char = None partitions.append(i - prev + 1) i += 1 prev = i return partitions class Solution: def partition_labels(self, string): """O(N) time | O(1) space""" chars = {c: i for (i, c) in enumerate(string)} left = right = 0 partitions = [] for (i, char) in enumerate(string): right = max(right, chars[char]) if i == right: partitions.append(right - left + 1) left = right + 1 return partitions
# 3.uzdevums my_name = str(input('Enter sentence ')) words = my_name.split() rev_list = [word[::-1] for word in words] rev_string=" ".join(rev_list) result=rev_string.capitalize() print(result) print(" ".join([w[::-1] for w in my_name.split()]).capitalize())
my_name = str(input('Enter sentence ')) words = my_name.split() rev_list = [word[::-1] for word in words] rev_string = ' '.join(rev_list) result = rev_string.capitalize() print(result) print(' '.join([w[::-1] for w in my_name.split()]).capitalize())
# def math(num1, num2, operation='add'): # if(operation == "mult"): # return num1 * num2 # if(operation == "div"): # return num1 / num2 # if(operation == "sub"): # return num1 - num2 # if(operation == "add"): # return num1 + num2 # else: # print("not a valid opreation") # num1 = int(input("input number1:")) # num2 = int(input("input number2:")) # operation = input("write the opreation :add,sub,mult,div:") # val = math(num1, num2, operation) # print(val) # num1 and num2 are parameters # def add(num1, num2): # return num1 + num2 # 100 and 20 are arguments # x = add(100, 20) # print(x) def multiply(num1, num2): return num1 * num2 y = multiply(10, 20) print(y)
def multiply(num1, num2): return num1 * num2 y = multiply(10, 20) print(y)
""" Control Flow II - SOLUTION """ # Write a Python program that prints all the numbers from 0 to 6 except 3 and 6. Note : Use 'continue' statement. for i in range(6): if (i == 3 or i ==6): continue print(i,end=' ') print("\n")
""" Control Flow II - SOLUTION """ for i in range(6): if i == 3 or i == 6: continue print(i, end=' ') print('\n')
""" Euclidean algorithm (greatest common divisor (GCD)) """ def euclidean(a, b): while a != 0 and b != 0: if a > b: a = a % b else: b = b % a gcd = a or b return gcd def test_euclidean(): """ Tests """ assert(euclidean(30, 18) == 6) assert(euclidean(10, 10) == 10) assert(euclidean(0, 0) == 0) if __name__ == '__main__': print('GCD for 30 and 18 is ', euclidean(30, 18))
""" Euclidean algorithm (greatest common divisor (GCD)) """ def euclidean(a, b): while a != 0 and b != 0: if a > b: a = a % b else: b = b % a gcd = a or b return gcd def test_euclidean(): """ Tests """ assert euclidean(30, 18) == 6 assert euclidean(10, 10) == 10 assert euclidean(0, 0) == 0 if __name__ == '__main__': print('GCD for 30 and 18 is ', euclidean(30, 18))
def binary_search(arr, target): low, high = 0, len(arr)-1 while low < high: mid = (low + high)/2 if arr[mid] == target: return mid elif arr[mid] > target: high = mid - 1 else: low = mid + 1 try: if arr[high] == target: return high else: return -1 except IndexError as e: return -1
def binary_search(arr, target): (low, high) = (0, len(arr) - 1) while low < high: mid = (low + high) / 2 if arr[mid] == target: return mid elif arr[mid] > target: high = mid - 1 else: low = mid + 1 try: if arr[high] == target: return high else: return -1 except IndexError as e: return -1
MOD_ID = 'id' MOD_RGB = 'rgb' MOD_SS_DENSE = 'semseg_dense' MOD_SS_CLICKS = 'semseg_clicks' MOD_SS_SCRIBBLES = 'semseg_scribbles' MOD_VALIDITY = 'validity_mask' SPLIT_TRAIN = 'train' SPLIT_VALID = 'val' MODE_INTERP = { MOD_ID: None, MOD_RGB: 'bilinear', MOD_SS_DENSE: 'nearest', MOD_SS_CLICKS: 'sparse', MOD_SS_SCRIBBLES: 'sparse', MOD_VALIDITY: 'nearest', }
mod_id = 'id' mod_rgb = 'rgb' mod_ss_dense = 'semseg_dense' mod_ss_clicks = 'semseg_clicks' mod_ss_scribbles = 'semseg_scribbles' mod_validity = 'validity_mask' split_train = 'train' split_valid = 'val' mode_interp = {MOD_ID: None, MOD_RGB: 'bilinear', MOD_SS_DENSE: 'nearest', MOD_SS_CLICKS: 'sparse', MOD_SS_SCRIBBLES: 'sparse', MOD_VALIDITY: 'nearest'}
nmbr = 3 if nmbr % 2 == 0: print("%d is even" % nmbr) elif nmbr == 0: print("%d is zero" % nmbr) else: print("%d is odd" % nmbr) free = "free"; print("I am free") if free == "free" else print("I am not free") # Nested Conditions nmbr = 4 if nmbr % 2 == 0: if nmbr % 4 == 0: print("I can pass all the condititions!") if nmbr > 0 and nmbr % 1 == 0: print("Vow I can pass here too!")
nmbr = 3 if nmbr % 2 == 0: print('%d is even' % nmbr) elif nmbr == 0: print('%d is zero' % nmbr) else: print('%d is odd' % nmbr) free = 'free' print('I am free') if free == 'free' else print('I am not free') nmbr = 4 if nmbr % 2 == 0: if nmbr % 4 == 0: print('I can pass all the condititions!') if nmbr > 0 and nmbr % 1 == 0: print('Vow I can pass here too!')
class Book: """ Model for Book object """ def __init__(self, title, author): self.title = title self.author = author self.bookmark = None self.read = False def setBookmark(self, page): """ Sets bookmark attribute of a book to given page """ self.bookmark = page def read(self): """ Changes read status of a book """ self.read = True
class Book: """ Model for Book object """ def __init__(self, title, author): self.title = title self.author = author self.bookmark = None self.read = False def set_bookmark(self, page): """ Sets bookmark attribute of a book to given page """ self.bookmark = page def read(self): """ Changes read status of a book """ self.read = True
class Node: def __init__(self, key): self.left = None self.right = None self.val = key def insert(root, key): if root is None: return Node(key) else: if root.val == key: return root elif root.val < key: root.right = insert(root.right, key) else: root.left = insert(root.left, key) return root def inorder(root): if root: inorder(root.left) print(root.val) inorder(root.right) if __name__ == "__main__": """ from timeit import timeit r = Node(50) r = insert(r, 30) r = insert(r, 20) r = insert(r, 40) r = insert(r, 70) r = insert(r, 60) r = insert(r, 80) print(timeit(lambda: inorder(r), number=10000)) # 0.4426064440012851 """
class Node: def __init__(self, key): self.left = None self.right = None self.val = key def insert(root, key): if root is None: return node(key) elif root.val == key: return root elif root.val < key: root.right = insert(root.right, key) else: root.left = insert(root.left, key) return root def inorder(root): if root: inorder(root.left) print(root.val) inorder(root.right) if __name__ == '__main__': '\n from timeit import timeit\n\n r = Node(50)\n r = insert(r, 30)\n r = insert(r, 20)\n r = insert(r, 40)\n r = insert(r, 70)\n r = insert(r, 60)\n r = insert(r, 80)\n\n print(timeit(lambda: inorder(r), number=10000)) # 0.4426064440012851\n '
#!/usr/bin/python3 """ Part of speech tagging in python using Hidden Markov Model. POS tagging using Hidden Markov model (Viterbi algorithm) """ __author__ = "Sunil" __copyright__ = "Copyright (c) 2017 Sunil" __license__ = "MIT License" __email__ = "suba5417@colorado.edu" __version__ = "0.1" class PennTreebank(object): """ Dictionary of all tags in the Penn tree bank. Can be used to look up penn tree bank codeword to human understandable Parts of speech """ tagset = defaultdict ( lambda: '#unknown#', { "CC" : "Coordinating conjunction", "CD" : "Cardinal number", "DT" : "Determiner", "EX" : "Existential there", "FW" : "Foreign word", "IN" : "Preposition or subordinating conjunction", "JJ" : "Adjective", "JJR" : "Adjective, comparative", "JJS" : "Adjective, superlative", "LS" : "List item marker", "MD" : "Modal", "NN" : "Noun, singular or mass", "NNS" : "Noun, plural", "NNP" : "Proper noun, singular", "NNPS" : "Proper noun, plural", "PDT" : "Predeterminer", "POS" : "Possessive ending", "PRP" : "Personal pronoun", "PRP$" : "Possessive pronoun", "RB" : "Adverb", "RBR" : "Adverb, comparative", "RBS" : "Adverb, superlative", "RP" : "Particle", "SYM" : "Symbol", "TO" : "to", "UH" : "Interjection", "VB" : "Verb, base form", "VBD" : "Verb, past tense", "VBG" : "Verb, gerund or present participle", "VBN" : "Verb, past participle", "VBP" : "Verb, non-3rd person singular present", "VBZ" : "Verb, 3rd person singular present", "WDT" : "Wh-determiner", "WP" : "Wh-pronoun", "WP$" : "Possessive wh-pronoun", "WRB" : "Wh-adverb" } ) @classmethod def lookup(cls, codedTag): """ look up coded tag and return human understanable POS. No exception hanlding required because of defaultdict """ return cls.tagset[codedTag]
""" Part of speech tagging in python using Hidden Markov Model. POS tagging using Hidden Markov model (Viterbi algorithm) """ __author__ = 'Sunil' __copyright__ = 'Copyright (c) 2017 Sunil' __license__ = 'MIT License' __email__ = 'suba5417@colorado.edu' __version__ = '0.1' class Penntreebank(object): """ Dictionary of all tags in the Penn tree bank. Can be used to look up penn tree bank codeword to human understandable Parts of speech """ tagset = defaultdict(lambda : '#unknown#', {'CC': 'Coordinating conjunction', 'CD': 'Cardinal number', 'DT': 'Determiner', 'EX': 'Existential there', 'FW': 'Foreign word', 'IN': 'Preposition or subordinating conjunction', 'JJ': 'Adjective', 'JJR': 'Adjective, comparative', 'JJS': 'Adjective, superlative', 'LS': 'List item marker', 'MD': 'Modal', 'NN': 'Noun, singular or mass', 'NNS': 'Noun, plural', 'NNP': 'Proper noun, singular', 'NNPS': 'Proper noun, plural', 'PDT': 'Predeterminer', 'POS': 'Possessive ending', 'PRP': 'Personal pronoun', 'PRP$': 'Possessive pronoun', 'RB': 'Adverb', 'RBR': 'Adverb, comparative', 'RBS': 'Adverb, superlative', 'RP': 'Particle', 'SYM': 'Symbol', 'TO': 'to', 'UH': 'Interjection', 'VB': 'Verb, base form', 'VBD': 'Verb, past tense', 'VBG': 'Verb, gerund or present participle', 'VBN': 'Verb, past participle', 'VBP': 'Verb, non-3rd person singular present', 'VBZ': 'Verb, 3rd person singular present', 'WDT': 'Wh-determiner', 'WP': 'Wh-pronoun', 'WP$': 'Possessive wh-pronoun', 'WRB': 'Wh-adverb'}) @classmethod def lookup(cls, codedTag): """ look up coded tag and return human understanable POS. No exception hanlding required because of defaultdict """ return cls.tagset[codedTag]
DEBUG = True SECRET_KEY = 'topsecret' #SQLALCHEMY_DATABASE_URI = 'postgresql://yazhu:root@localhost/matcha' # SQLALCHEMY_DATABASE_URI = 'postgresql://jchung:@localhost/matcha' SQLALCHEMY_DATABASE_URI = 'postgresql://root:1234@localhost/matcha' SQLALCHEMY_TRACK_MODIFICATIONS = False ACCOUNT_ACTIVATION = False ROOT_URL = 'localhost:5000' REDIRECT_HTTP = False
debug = True secret_key = 'topsecret' sqlalchemy_database_uri = 'postgresql://root:1234@localhost/matcha' sqlalchemy_track_modifications = False account_activation = False root_url = 'localhost:5000' redirect_http = False
"""Defines a node for link-based data structures""" class Node: """A node in the linked list""" def __init__(self, next=None, data=None): self.next = next self.data = data def __eq__(self, other): return self.data == other.data def __repr__(self): return repr(self.data)
"""Defines a node for link-based data structures""" class Node: """A node in the linked list""" def __init__(self, next=None, data=None): self.next = next self.data = data def __eq__(self, other): return self.data == other.data def __repr__(self): return repr(self.data)
PURCHASE_NO_CLIENT_STATE = 0 PURCHASE_WAITING_STATE = 1 PURCHASE_PLAYAGAIN_STATE = 2 PURCHASE_EXIT_STATE = 3 PURCHASE_DISCONNECTED_STATE = 4 PURCHASE_UNREPORTED_STATE = 10 PURCHASE_REPORTED_STATE = 11 PURCHASE_CANTREPORT_STATE = 12 PURCHASE_COUNTDOWN_TIME = 120
purchase_no_client_state = 0 purchase_waiting_state = 1 purchase_playagain_state = 2 purchase_exit_state = 3 purchase_disconnected_state = 4 purchase_unreported_state = 10 purchase_reported_state = 11 purchase_cantreport_state = 12 purchase_countdown_time = 120
# 14. Write a program in Python to calculate the volume of a sphere rad=int(input("Enter radius of the sphere: ")) vol=(4/3)*3.14*(rad**3) print("Volume of the sphere= ",vol)
rad = int(input('Enter radius of the sphere: ')) vol = 4 / 3 * 3.14 * rad ** 3 print('Volume of the sphere= ', vol)
''' Created on Aug 10, 2017 @author: Itai Agmon ''' class ReportElementType(): REGULAR = "regular" LINK = "lnk" IMAGE = "img" HTML = "html" STEP = "step" START_LEVEL = "startLevel" STOP_LEVEL = "stopLevel" class ReportElementStatus(): SUCCESS = "success" WARNING = "warning" FAILURE = "failure" ERROR = "error" class ReportElement(object): def __init__(self): self.parent = None self.title = "" self.message = "" self.status = ReportElementStatus.SUCCESS self.time = "" self.element_type = ReportElementType.REGULAR def set_status(self, status): if status != ReportElementStatus.ERROR and \ status != ReportElementStatus.FAILURE and \ status != ReportElementStatus.WARNING and \ status != ReportElementStatus.SUCCESS: raise ValueError("Illegal status %s" % status) if status == ReportElementStatus.ERROR: self.status = status elif status == ReportElementStatus.FAILURE: if self.status != ReportElementStatus.ERROR: self.status = status elif status == ReportElementStatus.WARNING: if self.status != ReportElementStatus.ERROR and self.status != ReportElementStatus.FAILURE: self.status = status def set_type(self, element_type): if element_type != ReportElementType.REGULAR and \ element_type != ReportElementType.LINK and \ element_type != ReportElementType.IMAGE and \ element_type != ReportElementType.HTML and \ element_type != ReportElementType.STEP and \ element_type != ReportElementType.START_LEVEL and \ element_type != ReportElementType.STOP_LEVEL: raise ValueError("Illegal element type %s" % element_type) self.element_type = element_type def dict(self): d = {} d["title"] = self.title d["message"] = self.message d["status"] = self.status d["time"] = self.time d["status"] = str(self.status) d["type"] = str(self.element_type) return d class TestDetails(object): def __init__(self, uid): self.uid = uid self.report_elements = [] self.level_elements_stack = [] self.execution_properties = {} def add_element(self, element): if type(element) is not ReportElement: raise TypeError("Can only add report elements") element.parent = self if element.element_type is None: element.element_type = ReportElementType.REGULAR self.report_elements.append(element) if element.element_type == ReportElementType.START_LEVEL: self.level_elements_stack.append(element) elif element.element_type == ReportElementType.STOP_LEVEL: self.level_elements_stack.pop() if element.status != ReportElementStatus.SUCCESS: for e in self.level_elements_stack: e.set_status(element.status) def dict(self): d = {} d["uid"] = self.uid d["reportElements"] = [] for element in self.report_elements: d["reportElements"].append(element.dict()) return d
""" Created on Aug 10, 2017 @author: Itai Agmon """ class Reportelementtype: regular = 'regular' link = 'lnk' image = 'img' html = 'html' step = 'step' start_level = 'startLevel' stop_level = 'stopLevel' class Reportelementstatus: success = 'success' warning = 'warning' failure = 'failure' error = 'error' class Reportelement(object): def __init__(self): self.parent = None self.title = '' self.message = '' self.status = ReportElementStatus.SUCCESS self.time = '' self.element_type = ReportElementType.REGULAR def set_status(self, status): if status != ReportElementStatus.ERROR and status != ReportElementStatus.FAILURE and (status != ReportElementStatus.WARNING) and (status != ReportElementStatus.SUCCESS): raise value_error('Illegal status %s' % status) if status == ReportElementStatus.ERROR: self.status = status elif status == ReportElementStatus.FAILURE: if self.status != ReportElementStatus.ERROR: self.status = status elif status == ReportElementStatus.WARNING: if self.status != ReportElementStatus.ERROR and self.status != ReportElementStatus.FAILURE: self.status = status def set_type(self, element_type): if element_type != ReportElementType.REGULAR and element_type != ReportElementType.LINK and (element_type != ReportElementType.IMAGE) and (element_type != ReportElementType.HTML) and (element_type != ReportElementType.STEP) and (element_type != ReportElementType.START_LEVEL) and (element_type != ReportElementType.STOP_LEVEL): raise value_error('Illegal element type %s' % element_type) self.element_type = element_type def dict(self): d = {} d['title'] = self.title d['message'] = self.message d['status'] = self.status d['time'] = self.time d['status'] = str(self.status) d['type'] = str(self.element_type) return d class Testdetails(object): def __init__(self, uid): self.uid = uid self.report_elements = [] self.level_elements_stack = [] self.execution_properties = {} def add_element(self, element): if type(element) is not ReportElement: raise type_error('Can only add report elements') element.parent = self if element.element_type is None: element.element_type = ReportElementType.REGULAR self.report_elements.append(element) if element.element_type == ReportElementType.START_LEVEL: self.level_elements_stack.append(element) elif element.element_type == ReportElementType.STOP_LEVEL: self.level_elements_stack.pop() if element.status != ReportElementStatus.SUCCESS: for e in self.level_elements_stack: e.set_status(element.status) def dict(self): d = {} d['uid'] = self.uid d['reportElements'] = [] for element in self.report_elements: d['reportElements'].append(element.dict()) return d
{ "targets": [ { "target_name": "strings", "sources": ["main.cpp"], "cflags": ["-Wall", "-Wextra", "-ansi", "-O3"], "include_dirs" : ["<!(node -e \"require('nan')\")"] } ] }
{'targets': [{'target_name': 'strings', 'sources': ['main.cpp'], 'cflags': ['-Wall', '-Wextra', '-ansi', '-O3'], 'include_dirs': ['<!(node -e "require(\'nan\')")']}]}
class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: anagrams = {} for str in strs: key = ''.join(sorted(str)) if key not in anagrams: anagrams[key] = [] anagrams[key].append(str) return list(anagrams.values())
class Solution: def group_anagrams(self, strs: List[str]) -> List[List[str]]: anagrams = {} for str in strs: key = ''.join(sorted(str)) if key not in anagrams: anagrams[key] = [] anagrams[key].append(str) return list(anagrams.values())
class Car: # Class-level wheels = 4 def __init__(self, manufacturer: str, model: str, color: str, mileage: int): # Instance-level self.manufacturer = manufacturer self.model = model self.color = color self.mileage = mileage # Method def add_mileage(self, miles: int) -> str: self.mileage += miles print(f"The car has {miles} miles on it.") my_car = Car("Audi", "R8", "Blue", 1000) print(f"I just bought a {my_car.color} {my_car.manufacturer} {my_car.model}") print(f"My new car's mileage is {my_car.mileage}") print("Adding 500 miles to my car...") my_car.add_mileage(500) print(f"My new car's mileage is {my_car.mileage}")
class Car: wheels = 4 def __init__(self, manufacturer: str, model: str, color: str, mileage: int): self.manufacturer = manufacturer self.model = model self.color = color self.mileage = mileage def add_mileage(self, miles: int) -> str: self.mileage += miles print(f'The car has {miles} miles on it.') my_car = car('Audi', 'R8', 'Blue', 1000) print(f'I just bought a {my_car.color} {my_car.manufacturer} {my_car.model}') print(f"My new car's mileage is {my_car.mileage}") print('Adding 500 miles to my car...') my_car.add_mileage(500) print(f"My new car's mileage is {my_car.mileage}")
def gcd(a, b): while b != 0: a, b = b, a % b return a def lcm(a, b, g): return a * b // g A, B = (int(term) for term in input().split()) g = gcd(A, B) print(g) print(lcm(A, B, g))
def gcd(a, b): while b != 0: (a, b) = (b, a % b) return a def lcm(a, b, g): return a * b // g (a, b) = (int(term) for term in input().split()) g = gcd(A, B) print(g) print(lcm(A, B, g))
def solution(a, b): answer = 0 for x,y in zip(a,b): answer+=x*y return answer
def solution(a, b): answer = 0 for (x, y) in zip(a, b): answer += x * y return answer
AVAILABLE_OPTIONS = [('doc_m2m_prob_threshold', 'Probability threshold for showing document to mass2motif links'), ('doc_m2m_overlap_threshold', 'Threshold on overlap score for showing document to mass2motif links'), ('log_peakset_intensities', 'Whether or not to log the peakset intensities (true,false)'), # ('peakset_matching_tolerance', 'Tolerance to use when matching peaksets'), ('heatmap_minimum_display_count', 'Minimum number of instances in a peakset to display it in the heatmap'), # ('default_doc_m2m_score', # 'Default score to use when extracting document <-> mass2motif matches. Use either "probability" or "overlap_score", or "both"'), ('heatmap_normalisation','how to normalise the rows in the heatmap: none, standard, max')]
available_options = [('doc_m2m_prob_threshold', 'Probability threshold for showing document to mass2motif links'), ('doc_m2m_overlap_threshold', 'Threshold on overlap score for showing document to mass2motif links'), ('log_peakset_intensities', 'Whether or not to log the peakset intensities (true,false)'), ('heatmap_minimum_display_count', 'Minimum number of instances in a peakset to display it in the heatmap'), ('heatmap_normalisation', 'how to normalise the rows in the heatmap: none, standard, max')]
phi, d, t, coll = input().split() phi = float(phi) phi_1 = phi - 0.01 phi_2 = phi + 0.01 print(str(phi) + " " + "0.00001" + " " + "0.1 " + str(t) + " 10 20")
(phi, d, t, coll) = input().split() phi = float(phi) phi_1 = phi - 0.01 phi_2 = phi + 0.01 print(str(phi) + ' ' + '0.00001' + ' ' + '0.1 ' + str(t) + ' 10 20')
class usuario(object): def __init__(self, nombre, apellido, edad, genero): self.nombre = nombre self.apellido = apellido self.edad = edad self.genero = genero def descripcion_usuario(self): print("Nombre: " + self.nombre.title() + "\nApellido: " + self.apellido.title() + "\nEdad: " + str(self.edad) + "\nGenero: " + self.genero) def greet_usuario(self): print("Bienvenido: " + self.nombre.title() + " " + self.apellido.title()) class privilegios(object): def __init__(self): self.privilegios = [] def obtener_privilegios(self, *list_privilegios): self.privilegios = list_privilegios def imprime_privilegios(self): print("Los Privilegios del Admin son: ") for priv in self.privilegios: print("- " + priv) class admin(usuario): def __init__(self, nombre, apellido, edad, genero): super(admin, self).__init__(nombre, apellido, edad, genero) self.privilegios = privilegios() administrador_n = admin('Rosa', 'Sanchez', 18, 'F') print(administrador_n.descripcion_usuario()) administrador_n.privilegios.obtener_privilegios('Puede Agregar Publicaciones', 'Puede Eliminar Publicaciones') administrador_n.privilegios.imprime_privilegios()
class Usuario(object): def __init__(self, nombre, apellido, edad, genero): self.nombre = nombre self.apellido = apellido self.edad = edad self.genero = genero def descripcion_usuario(self): print('Nombre: ' + self.nombre.title() + '\nApellido: ' + self.apellido.title() + '\nEdad: ' + str(self.edad) + '\nGenero: ' + self.genero) def greet_usuario(self): print('Bienvenido: ' + self.nombre.title() + ' ' + self.apellido.title()) class Privilegios(object): def __init__(self): self.privilegios = [] def obtener_privilegios(self, *list_privilegios): self.privilegios = list_privilegios def imprime_privilegios(self): print('Los Privilegios del Admin son: ') for priv in self.privilegios: print('- ' + priv) class Admin(usuario): def __init__(self, nombre, apellido, edad, genero): super(admin, self).__init__(nombre, apellido, edad, genero) self.privilegios = privilegios() administrador_n = admin('Rosa', 'Sanchez', 18, 'F') print(administrador_n.descripcion_usuario()) administrador_n.privilegios.obtener_privilegios('Puede Agregar Publicaciones', 'Puede Eliminar Publicaciones') administrador_n.privilegios.imprime_privilegios()
# Ley d'Hondt def hondt(votes, n): """ Ley d'Hondt; coefficient: c_i = V_i / (s_i + 1) V_i = total number of votes obtained by party i s_i = number of seats assigned to party i (initially 0) """ s = [0] * len(votes) for i in range(n): c = [v[j] / (s[j] + 1) for j in range(len(s))] s[c.index(max(c))] += 1 return s # Example v = [340000, 280000, 160000, 60000, 15000] # votes for each party n = 155 # number of seats print(hondt(v, n))
def hondt(votes, n): """ Ley d'Hondt; coefficient: c_i = V_i / (s_i + 1) V_i = total number of votes obtained by party i s_i = number of seats assigned to party i (initially 0) """ s = [0] * len(votes) for i in range(n): c = [v[j] / (s[j] + 1) for j in range(len(s))] s[c.index(max(c))] += 1 return s v = [340000, 280000, 160000, 60000, 15000] n = 155 print(hondt(v, n))
class Class1(object): def __init__(self): pass def test1(self): return 5 class Class2(object): def test1(self): return 6 class Class3(object): def test1(self, x): return self.test2(x)-1 def test2(self, x): return 2*x a = Class1() print(a.test1()) a = Class2() print(a.test1()) a = Class3() print(a.test1(3)) print(a.test2(3))
class Class1(object): def __init__(self): pass def test1(self): return 5 class Class2(object): def test1(self): return 6 class Class3(object): def test1(self, x): return self.test2(x) - 1 def test2(self, x): return 2 * x a = class1() print(a.test1()) a = class2() print(a.test1()) a = class3() print(a.test1(3)) print(a.test2(3))
# -*- coding: utf-8 -*- """ sphinxpapyrus ~~~~~~~~~~~~~ Sphinx extensions. :copyright: Copyright 2018 by nakandev. :license: MIT, see LICENSE for details. """ __import__('pkg_resources').declare_namespace(__name__)
""" sphinxpapyrus ~~~~~~~~~~~~~ Sphinx extensions. :copyright: Copyright 2018 by nakandev. :license: MIT, see LICENSE for details. """ __import__('pkg_resources').declare_namespace(__name__)
class Tee: def __init__(self, f, f_tee): self.f = f self.f_tee = f_tee def read(self, nbytes): buf = self.f.read(nbytes) self.f_tee.write(buf) return buf def write(self, buf): self.f_tee.write(buf) self.f.write(buf) def flush(self): self.f.flush()
class Tee: def __init__(self, f, f_tee): self.f = f self.f_tee = f_tee def read(self, nbytes): buf = self.f.read(nbytes) self.f_tee.write(buf) return buf def write(self, buf): self.f_tee.write(buf) self.f.write(buf) def flush(self): self.f.flush()
''' This is all the calculation for the main window '''
""" This is all the calculation for the main window """
__title__ = 'lottus' __description__ = 'An ussd library that will save you time' __version__ = '0.0.4' __author__ = 'Benjamim Chambule' __author_email__ = 'benchambule@gmail.com' __license__ = 'MIT' __copyright__ = 'Copyright 2021 Benjamim Chambule'
__title__ = 'lottus' __description__ = 'An ussd library that will save you time' __version__ = '0.0.4' __author__ = 'Benjamim Chambule' __author_email__ = 'benchambule@gmail.com' __license__ = 'MIT' __copyright__ = 'Copyright 2021 Benjamim Chambule'
extra_annotations = \ { 'ai': [ 'artificial intelligence', 'machine learning', 'statistical learning', 'statistical model', 'supervised model', 'unsupervised model', 'computer vision', 'image analysis', 'object recognistion', 'object detection', 'image segmentation', 'deep learning', 'cognitive computing', 'neural network', 'classification model', 'regression model', 'classifier', 'reinforcment learning' ], 'tech': [ 'digital health', 'ehealth', 'digital medicine', 'mhealth', 'digital healthcare', 'digital biomarker', 'telemedicine' ], 'medicine': [ 'health occupations', 'health occupation', 'health professions', 'health profession', 'profession, health', 'professions, health', 'health occup', 'medicine', 'medical specialities', 'medical speciality', 'speciality, medical', 'specialities, medical', 'specialties, medical', 'medical specialty', 'specialty, medical', 'medical specialties', 'med specialties', 'med specialty', 'specialty med', 'specialties med', 'med specialities', 'specialities med', 'addiction psychiatry', 'psychiatry, addiction', 'addiction medicine', 'medicine, addiction', 'adolescent medicine', 'medicine, adolescent', 'hebiatrics', 'ephebiatrics', 'med adolescent', 'adolescent med', 'aerospace medicine', 'medicine, aerospace', 'med aerospace', 'aerospace med', 'aviation medicine', 'medicine, aviation', 'med aviation', 'aviation med', 'medicine, space', 'space medicine', 'med space', 'space med', 'allergy specialty', 'specialty, allergy', 'allergy and immunology', 'allergy, immunology', 'immunology, allergy', 'allergy immunology', 'immunology allergy', 'immunology and allergy', 'allergy immunol', 'immunol allergy', 'immunology', 'immunol', 'immunochemistry', 'immunochem', 'anesthesiology', 'anesthesiol', 'bariatric medicine', 'medicine, bariatric', 'behavioral medicine', 'medicine, behavioral', 'med behavioral', 'behavioral med', 'health psychology', 'health psychologies', 'psychologies, health', 'psychology, health', 'health psychol', 'psychol health', 'clinical medicine', 'medicine, clinical', 'clin med', 'med clin', 'evidence-based medicine', 'evidence based medicine', 'medicine, evidence based', 'medicine, evidence-based', 'evidence based med', 'med evidence based', 'precision medicine', 'medicine, precision', 'p health', 'p-health', 'p-healths', 'personalized medicine', 'medicine, personalized', 'individualized medicine', 'medicine, individualized', 'community medicine', 'medicine, community', 'med community', 'community med', 'dermatology', 'dermatol', 'disaster medicine', 'medicine, disaster', 'emergency medicine', 'medicine, emergency', 'med emergency', 'emergency med', 'emergency medicine, pediatric', 'medicine, pediatric emergency', 'pediatric emergency medicine', 'forensic medicine', 'medicine, forensic', 'med forensic', 'forensic med', 'medicine, legal', 'legal medicine', 'legal med', 'med legal', 'forensic genetics', 'genetics, forensic', 'genetic, forensic', 'forensic genetic', 'forensic pathology', 'pathology, forensic', 'forensic pathol', 'pathol forensic', 'general practice', 'practice, general', 'family practice', 'family practices', 'practices, family', 'practice, family', 'genetics, medical', 'medical genetics', 'med genet', 'genet med', 'geography, medical', 'medical geography', 'geomedicine', 'nosogeography', 'geogr med', 'med geogr', 'topography, medical', 'medical topography', 'med topogr', 'topogr med', 'geriatrics', 'gerontology', 'gerontol', 'international health problems', 'health problem, international', 'international health problem', 'problem, international health', 'health problems, international', 'problems, international health', 'world health', 'health, world', 'worldwide health', 'health, worldwide', 'healths, international', 'international healths', 'international health', 'health, international', 'global health', 'health, global', 'hospital medicine', 'medicine, hospital', 'integrative medicine', 'medicine, integrative', 'internal medicine', 'medicine, internal', 'internal med', 'med internal', 'cardiology', 'cardiol', 'vascular medicine', 'medicine, vascular', 'angiology', 'cardiovascular disease specialty', 'disease specialty, cardiovascular', 'specialty, cardiovascular disease', 'endocrinology', 'endocrinol', 'endocrinology and metabolism specialty', 'metabolism and endocrinology specialty', 'gastroenterology', 'gastroenterol', 'hepatology', 'hepatol', 'hematology', 'hematol', 'infectious disease medicine', 'disease medicine, infectious', 'medicine, infectious disease', 'infectious diseases specialty', 'infectious disease specialties', 'infectious disease specialty', 'infectious diseases specialties', 'specialties, infectious diseases', 'specialties, infectious disease', 'specialty, infectious disease', 'diseases specialty, infectious', 'specialty, infectious diseases', 'medical oncology', 'oncology, medical', 'med oncol', 'oncol med', 'clinical oncology', 'oncology, clinical', 'nephrology', 'nephrol', 'pulmonary medicine', 'medicine, pulmonary', 'pneumology', 'pneumonology', 'pulmonology', 'med pulm', 'pulm med', 'pneumonol', 'pneumol', 'pulmonol', 'respiratory medicine', 'medicine, respiratory', 'rheumatology', 'rheumatol', 'sleep medicine specialty', 'medicine specialties, sleep', 'sleep medicine specialties', 'specialties, sleep medicine', 'medicine specialty, sleep', 'specialty, sleep medicine', 'military medicine', 'medicine, military', 'med military', 'military med', 'molecular medicine', 'medicines, molecular', 'molecular medicines', 'medicine, molecular', 'naval medicine', 'medicine, naval', 'nautical medicine', 'medicine, nautical', 'med nautical', 'nautical med', 'med naval', 'naval med', 'submarine medicine', 'medicine, submarine', 'med submarine', 'submarine med', 'neurology', 'neurol', 'neuropathologist', 'neuropathologists', 'neuropathology', 'neuropathologies', 'neurotology', 'neuro-otology', 'neuro otology', 'otoneurology', 'osteopathic medicine', 'medicine, osteopathic', 'med osteopathic', 'osteopathic med', 'osteopathic manipulative medicine', 'manipulative medicine, osteopathic', 'medicine, osteopathic manipulative', 'palliative medicine', 'medicine, palliative', 'palliative care medicine', 'medicine, palliative care', 'med palliative', 'palliative med', 'pathology', 'pathologies', 'pathol', 'forensic pathology', 'pathology, forensic', 'forensic pathol', 'pathol forensic', 'neuropathologist', 'neuropathologists', 'neuropathology', 'neuropathologies', 'pathology, clinical', 'clinical pathology', 'clin pathol', 'pathol clin', 'pathology, molecular', 'molecular pathologies', 'pathologies, molecular', 'molecular pathology', 'molecular diagnostics', 'diagnostic, molecular', 'molecular diagnostic', 'diagnostics, molecular', 'diagnostic molecular pathology', 'diagnostic molecular pathologies', 'molecular pathologies, diagnostic', 'pathologies, diagnostic molecular', 'molecular pathology, diagnostic', 'pathology, diagnostic molecular', 'pathology, surgical', 'surgical pathology', 'pathol surg', 'surg pathol', 'telepathology', 'telepathol', 'pediatrics', 'neonatology', 'neonatol', 'emergency medicine, pediatric', 'medicine, pediatric emergency', 'pediatric emergency medicine', 'perinatology', 'perinatol', 'perioperative medicine', 'medicine, perioperative', 'physical and rehabilitation medicine', 'physical medicine and rehabilitation', 'physical medicine', 'medicine, physical', 'physiatry', 'physiatrics', 'med physical', 'physical med', 'habilitation', 'rehabilitation', 'rehabil', 'psychiatrist', 'psychiatrists', 'psychiatry', 'adolescent psychiatry', 'psychiatry, adolescent', 'biological psychiatry', 'psychiatry, biological', 'biologic psychiatry', 'psychiatry, biologic', 'psychiatry biol', 'biol psychiatry', 'child psychiatry', 'psychiatry, child', 'community psychiatry', 'psychiatry, community', 'social psychiatry', 'psychiatry, social', 'forensic psychiatry', 'psychiatry, forensic', 'jurisprudence, psychiatric', 'psychiatric jurisprudence', 'geriatric psychiatry', 'psychiatry, geriatric', 'psychogeriatrics', 'military psychiatry', 'psychiatry, military', 'neuropsychiatry', 'environment, preventive medicine and public health', 'environment, preventive medicine & public health', 'envir prev med public health', 'public health', 'health, public', 'community health', 'health, community', 'epidemiology', 'epidemiol', 'preventive medicine', 'medicine, preventive', 'preventative medicine', 'medicine, preventative', 'med prev', 'prev med', 'preventive care', 'care, preventive', 'preventative care', 'care, preventative', 'radiology', 'radiol', 'atomic medicine', 'medicine, atomic', 'nuclear medicine', 'medicine, nuclear', 'med atomic', 'atomic med', 'med nuclear', 'nuclear med', 'radiology, nuclear', 'nuclear radiology', 'nuclear radiol', 'radiol nuclear', 'therapeutic radiology', 'radiology, therapeutic', 'radiol ther', 'ther radiol', 'radiation oncology', 'oncology, radiation', 'oncol rad', 'rad oncol', 'radiology, interventional', 'interventional radiology', 'interventional radiol', 'radiol interventional', 'regenerative medicine', 'regenerative medicines', 'medicines, regenerative', 'medicine, regenerative', 'regenerative med', 'reproductive medicine', 'medicine, reproductive', 'med reproductive', 'reproductive med', 'andrology', 'androl', 'gynecology', 'gynecol', 'social medicine', 'medicine, social', 'med social', 'social med', 'specialties, surgical', 'surgical specialties', 'specialties surg', 'surg specialties', 'colon and rectal surgery specialty', 'surgery specialty, colon and rectal', 'colorectal surgery', 'surgery, colorectal', 'surg specialty colon rectal', 'colon rectal surg specialty', 'colorectal surg', 'surg colorectal', 'colon surgery specialty', 'specialty, colon surgery', 'surgery specialty, colon', 'specialty colon surg', 'surg specialty colon', 'colon surg specialty', 'proctology', 'rectal surgery specialty', 'specialty, rectal surgery', 'surgery specialty, rectal', 'rectal surg specialty', 'specialty rectal surg', 'surg specialty rectal', 'proctol', 'surgery', 'general surgery', 'surgery, general', 'surg', 'gynecology', 'gynecol', 'neurosurgery', 'neurosurgeries', 'neurosurg', 'obstetrics', 'ophthalmology', 'ophthalmol', 'orthognathic surgery', 'orthognathic surgeries', 'surgeries, orthognathic', 'surgery, orthognathic', 'orthopedics', 'otolaryngology', 'otorhinolaryngology', 'otolaryngol', 'otorhinolaryngol', 'otology', 'otol', 'laryngology', 'surgery, plastic', 'plastic surgery', 'plastic surg', 'surg plastic', 'surgery, cosmetic', 'cosmetic surgery', 'surg cosmetic', 'cosmetic surg', 'esthetic surgery', 'esthetic surgeries', 'surgeries, esthetic', 'surgery, esthetic', 'esthetic surg', 'surg esthetic', 'surgical oncology', 'oncology, surgical', 'thoracic surgery', 'surgery, thoracic', 'surg thoracic', 'thoracic surg', 'surgery, cardiac', 'cardiac surgery', 'heart surgery', 'surgery, heart', 'surg cardiac', 'cardiac surg', 'surg heart', 'heart surg', 'traumatology', 'traumatol', 'surgical traumatology', 'traumatology, surgical', 'urology', 'urol', 'sports medicine', 'medicine, sport', 'sport medicine', 'medicine, sports', 'med sports', 'med sport', 'sport med', 'sports med', 'sports nutritional sciences', 'nutritional science, sports', 'science, sports nutritional', 'sports nutritional science', 'nutritional sciences, sports', 'sciences, sports nutritional', 'sports nutrition sciences', 'nutrition science, sports', 'science, sports nutrition', 'sports nutrition science', 'nutrition sciences, sports', 'sciences, sports nutrition', 'exercise nutritional sciences', 'exercise nutritional science', 'nutritional science, exercise', 'science, exercise nutritional', 'nutritional sciences, exercise', 'sciences, exercise nutritional', 'veterinary sports medicine', 'sports medicines, veterinary', 'medicine, sports veterinary', 'medicine, veterinary sports', 'sports medicine, veterinary', 'sports veterinary medicine', 'veterinary medicine, sports', 'telemedicine', 'telemed', 'telehealth', 'ehealth', 'mobile health', 'health, mobile', 'mhealth', 'telepathology', 'telepathol', 'teleradiology', 'teleradiol', 'telerehabilitation', 'remote rehabilitation', 'rehabilitations, remote', 'remote rehabilitations', 'rehabilitation, remote', 'telerehabilitations', 'virtual rehabilitation', 'rehabilitations, virtual', 'virtual rehabilitations', 'rehabilitation, virtual', 'tele-rehabilitation', 'tele rehabilitation', 'tele-rehabilitations', 'theranostic nanomedicine', 'nanomedicines, theranostic', 'theranostic nanomedicines', 'nanomedicine, theranostic', 'theranostics', 'theranostic', 'emporiatrics', 'travel medicine', 'medicine, travel', 'medicine, emporiatric', 'emporiatric medicine', 'tropical medicine', 'medicine, tropical', 'med tropical', 'tropical med', 'vaccinology', 'venereology', 'venereol', 'wilderness medicine', 'medicine, wilderness' ], }
extra_annotations = {'ai': ['artificial intelligence', 'machine learning', 'statistical learning', 'statistical model', 'supervised model', 'unsupervised model', 'computer vision', 'image analysis', 'object recognistion', 'object detection', 'image segmentation', 'deep learning', 'cognitive computing', 'neural network', 'classification model', 'regression model', 'classifier', 'reinforcment learning'], 'tech': ['digital health', 'ehealth', 'digital medicine', 'mhealth', 'digital healthcare', 'digital biomarker', 'telemedicine'], 'medicine': ['health occupations', 'health occupation', 'health professions', 'health profession', 'profession, health', 'professions, health', 'health occup', 'medicine', 'medical specialities', 'medical speciality', 'speciality, medical', 'specialities, medical', 'specialties, medical', 'medical specialty', 'specialty, medical', 'medical specialties', 'med specialties', 'med specialty', 'specialty med', 'specialties med', 'med specialities', 'specialities med', 'addiction psychiatry', 'psychiatry, addiction', 'addiction medicine', 'medicine, addiction', 'adolescent medicine', 'medicine, adolescent', 'hebiatrics', 'ephebiatrics', 'med adolescent', 'adolescent med', 'aerospace medicine', 'medicine, aerospace', 'med aerospace', 'aerospace med', 'aviation medicine', 'medicine, aviation', 'med aviation', 'aviation med', 'medicine, space', 'space medicine', 'med space', 'space med', 'allergy specialty', 'specialty, allergy', 'allergy and immunology', 'allergy, immunology', 'immunology, allergy', 'allergy immunology', 'immunology allergy', 'immunology and allergy', 'allergy immunol', 'immunol allergy', 'immunology', 'immunol', 'immunochemistry', 'immunochem', 'anesthesiology', 'anesthesiol', 'bariatric medicine', 'medicine, bariatric', 'behavioral medicine', 'medicine, behavioral', 'med behavioral', 'behavioral med', 'health psychology', 'health psychologies', 'psychologies, health', 'psychology, health', 'health psychol', 'psychol health', 'clinical medicine', 'medicine, clinical', 'clin med', 'med clin', 'evidence-based medicine', 'evidence based medicine', 'medicine, evidence based', 'medicine, evidence-based', 'evidence based med', 'med evidence based', 'precision medicine', 'medicine, precision', 'p health', 'p-health', 'p-healths', 'personalized medicine', 'medicine, personalized', 'individualized medicine', 'medicine, individualized', 'community medicine', 'medicine, community', 'med community', 'community med', 'dermatology', 'dermatol', 'disaster medicine', 'medicine, disaster', 'emergency medicine', 'medicine, emergency', 'med emergency', 'emergency med', 'emergency medicine, pediatric', 'medicine, pediatric emergency', 'pediatric emergency medicine', 'forensic medicine', 'medicine, forensic', 'med forensic', 'forensic med', 'medicine, legal', 'legal medicine', 'legal med', 'med legal', 'forensic genetics', 'genetics, forensic', 'genetic, forensic', 'forensic genetic', 'forensic pathology', 'pathology, forensic', 'forensic pathol', 'pathol forensic', 'general practice', 'practice, general', 'family practice', 'family practices', 'practices, family', 'practice, family', 'genetics, medical', 'medical genetics', 'med genet', 'genet med', 'geography, medical', 'medical geography', 'geomedicine', 'nosogeography', 'geogr med', 'med geogr', 'topography, medical', 'medical topography', 'med topogr', 'topogr med', 'geriatrics', 'gerontology', 'gerontol', 'international health problems', 'health problem, international', 'international health problem', 'problem, international health', 'health problems, international', 'problems, international health', 'world health', 'health, world', 'worldwide health', 'health, worldwide', 'healths, international', 'international healths', 'international health', 'health, international', 'global health', 'health, global', 'hospital medicine', 'medicine, hospital', 'integrative medicine', 'medicine, integrative', 'internal medicine', 'medicine, internal', 'internal med', 'med internal', 'cardiology', 'cardiol', 'vascular medicine', 'medicine, vascular', 'angiology', 'cardiovascular disease specialty', 'disease specialty, cardiovascular', 'specialty, cardiovascular disease', 'endocrinology', 'endocrinol', 'endocrinology and metabolism specialty', 'metabolism and endocrinology specialty', 'gastroenterology', 'gastroenterol', 'hepatology', 'hepatol', 'hematology', 'hematol', 'infectious disease medicine', 'disease medicine, infectious', 'medicine, infectious disease', 'infectious diseases specialty', 'infectious disease specialties', 'infectious disease specialty', 'infectious diseases specialties', 'specialties, infectious diseases', 'specialties, infectious disease', 'specialty, infectious disease', 'diseases specialty, infectious', 'specialty, infectious diseases', 'medical oncology', 'oncology, medical', 'med oncol', 'oncol med', 'clinical oncology', 'oncology, clinical', 'nephrology', 'nephrol', 'pulmonary medicine', 'medicine, pulmonary', 'pneumology', 'pneumonology', 'pulmonology', 'med pulm', 'pulm med', 'pneumonol', 'pneumol', 'pulmonol', 'respiratory medicine', 'medicine, respiratory', 'rheumatology', 'rheumatol', 'sleep medicine specialty', 'medicine specialties, sleep', 'sleep medicine specialties', 'specialties, sleep medicine', 'medicine specialty, sleep', 'specialty, sleep medicine', 'military medicine', 'medicine, military', 'med military', 'military med', 'molecular medicine', 'medicines, molecular', 'molecular medicines', 'medicine, molecular', 'naval medicine', 'medicine, naval', 'nautical medicine', 'medicine, nautical', 'med nautical', 'nautical med', 'med naval', 'naval med', 'submarine medicine', 'medicine, submarine', 'med submarine', 'submarine med', 'neurology', 'neurol', 'neuropathologist', 'neuropathologists', 'neuropathology', 'neuropathologies', 'neurotology', 'neuro-otology', 'neuro otology', 'otoneurology', 'osteopathic medicine', 'medicine, osteopathic', 'med osteopathic', 'osteopathic med', 'osteopathic manipulative medicine', 'manipulative medicine, osteopathic', 'medicine, osteopathic manipulative', 'palliative medicine', 'medicine, palliative', 'palliative care medicine', 'medicine, palliative care', 'med palliative', 'palliative med', 'pathology', 'pathologies', 'pathol', 'forensic pathology', 'pathology, forensic', 'forensic pathol', 'pathol forensic', 'neuropathologist', 'neuropathologists', 'neuropathology', 'neuropathologies', 'pathology, clinical', 'clinical pathology', 'clin pathol', 'pathol clin', 'pathology, molecular', 'molecular pathologies', 'pathologies, molecular', 'molecular pathology', 'molecular diagnostics', 'diagnostic, molecular', 'molecular diagnostic', 'diagnostics, molecular', 'diagnostic molecular pathology', 'diagnostic molecular pathologies', 'molecular pathologies, diagnostic', 'pathologies, diagnostic molecular', 'molecular pathology, diagnostic', 'pathology, diagnostic molecular', 'pathology, surgical', 'surgical pathology', 'pathol surg', 'surg pathol', 'telepathology', 'telepathol', 'pediatrics', 'neonatology', 'neonatol', 'emergency medicine, pediatric', 'medicine, pediatric emergency', 'pediatric emergency medicine', 'perinatology', 'perinatol', 'perioperative medicine', 'medicine, perioperative', 'physical and rehabilitation medicine', 'physical medicine and rehabilitation', 'physical medicine', 'medicine, physical', 'physiatry', 'physiatrics', 'med physical', 'physical med', 'habilitation', 'rehabilitation', 'rehabil', 'psychiatrist', 'psychiatrists', 'psychiatry', 'adolescent psychiatry', 'psychiatry, adolescent', 'biological psychiatry', 'psychiatry, biological', 'biologic psychiatry', 'psychiatry, biologic', 'psychiatry biol', 'biol psychiatry', 'child psychiatry', 'psychiatry, child', 'community psychiatry', 'psychiatry, community', 'social psychiatry', 'psychiatry, social', 'forensic psychiatry', 'psychiatry, forensic', 'jurisprudence, psychiatric', 'psychiatric jurisprudence', 'geriatric psychiatry', 'psychiatry, geriatric', 'psychogeriatrics', 'military psychiatry', 'psychiatry, military', 'neuropsychiatry', 'environment, preventive medicine and public health', 'environment, preventive medicine & public health', 'envir prev med public health', 'public health', 'health, public', 'community health', 'health, community', 'epidemiology', 'epidemiol', 'preventive medicine', 'medicine, preventive', 'preventative medicine', 'medicine, preventative', 'med prev', 'prev med', 'preventive care', 'care, preventive', 'preventative care', 'care, preventative', 'radiology', 'radiol', 'atomic medicine', 'medicine, atomic', 'nuclear medicine', 'medicine, nuclear', 'med atomic', 'atomic med', 'med nuclear', 'nuclear med', 'radiology, nuclear', 'nuclear radiology', 'nuclear radiol', 'radiol nuclear', 'therapeutic radiology', 'radiology, therapeutic', 'radiol ther', 'ther radiol', 'radiation oncology', 'oncology, radiation', 'oncol rad', 'rad oncol', 'radiology, interventional', 'interventional radiology', 'interventional radiol', 'radiol interventional', 'regenerative medicine', 'regenerative medicines', 'medicines, regenerative', 'medicine, regenerative', 'regenerative med', 'reproductive medicine', 'medicine, reproductive', 'med reproductive', 'reproductive med', 'andrology', 'androl', 'gynecology', 'gynecol', 'social medicine', 'medicine, social', 'med social', 'social med', 'specialties, surgical', 'surgical specialties', 'specialties surg', 'surg specialties', 'colon and rectal surgery specialty', 'surgery specialty, colon and rectal', 'colorectal surgery', 'surgery, colorectal', 'surg specialty colon rectal', 'colon rectal surg specialty', 'colorectal surg', 'surg colorectal', 'colon surgery specialty', 'specialty, colon surgery', 'surgery specialty, colon', 'specialty colon surg', 'surg specialty colon', 'colon surg specialty', 'proctology', 'rectal surgery specialty', 'specialty, rectal surgery', 'surgery specialty, rectal', 'rectal surg specialty', 'specialty rectal surg', 'surg specialty rectal', 'proctol', 'surgery', 'general surgery', 'surgery, general', 'surg', 'gynecology', 'gynecol', 'neurosurgery', 'neurosurgeries', 'neurosurg', 'obstetrics', 'ophthalmology', 'ophthalmol', 'orthognathic surgery', 'orthognathic surgeries', 'surgeries, orthognathic', 'surgery, orthognathic', 'orthopedics', 'otolaryngology', 'otorhinolaryngology', 'otolaryngol', 'otorhinolaryngol', 'otology', 'otol', 'laryngology', 'surgery, plastic', 'plastic surgery', 'plastic surg', 'surg plastic', 'surgery, cosmetic', 'cosmetic surgery', 'surg cosmetic', 'cosmetic surg', 'esthetic surgery', 'esthetic surgeries', 'surgeries, esthetic', 'surgery, esthetic', 'esthetic surg', 'surg esthetic', 'surgical oncology', 'oncology, surgical', 'thoracic surgery', 'surgery, thoracic', 'surg thoracic', 'thoracic surg', 'surgery, cardiac', 'cardiac surgery', 'heart surgery', 'surgery, heart', 'surg cardiac', 'cardiac surg', 'surg heart', 'heart surg', 'traumatology', 'traumatol', 'surgical traumatology', 'traumatology, surgical', 'urology', 'urol', 'sports medicine', 'medicine, sport', 'sport medicine', 'medicine, sports', 'med sports', 'med sport', 'sport med', 'sports med', 'sports nutritional sciences', 'nutritional science, sports', 'science, sports nutritional', 'sports nutritional science', 'nutritional sciences, sports', 'sciences, sports nutritional', 'sports nutrition sciences', 'nutrition science, sports', 'science, sports nutrition', 'sports nutrition science', 'nutrition sciences, sports', 'sciences, sports nutrition', 'exercise nutritional sciences', 'exercise nutritional science', 'nutritional science, exercise', 'science, exercise nutritional', 'nutritional sciences, exercise', 'sciences, exercise nutritional', 'veterinary sports medicine', 'sports medicines, veterinary', 'medicine, sports veterinary', 'medicine, veterinary sports', 'sports medicine, veterinary', 'sports veterinary medicine', 'veterinary medicine, sports', 'telemedicine', 'telemed', 'telehealth', 'ehealth', 'mobile health', 'health, mobile', 'mhealth', 'telepathology', 'telepathol', 'teleradiology', 'teleradiol', 'telerehabilitation', 'remote rehabilitation', 'rehabilitations, remote', 'remote rehabilitations', 'rehabilitation, remote', 'telerehabilitations', 'virtual rehabilitation', 'rehabilitations, virtual', 'virtual rehabilitations', 'rehabilitation, virtual', 'tele-rehabilitation', 'tele rehabilitation', 'tele-rehabilitations', 'theranostic nanomedicine', 'nanomedicines, theranostic', 'theranostic nanomedicines', 'nanomedicine, theranostic', 'theranostics', 'theranostic', 'emporiatrics', 'travel medicine', 'medicine, travel', 'medicine, emporiatric', 'emporiatric medicine', 'tropical medicine', 'medicine, tropical', 'med tropical', 'tropical med', 'vaccinology', 'venereology', 'venereol', 'wilderness medicine', 'medicine, wilderness']}
num = int(input()) numdict = { 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine' } print(numdict.get(num, 'number too big'))
num = int(input()) numdict = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine'} print(numdict.get(num, 'number too big'))
# -*- coding: utf-8 -*- class FormFactory(type): """This is the factory required to gather every Form components""" def __init__(cls, name, bases, dct): cls.datas={} for k,v in dct.items(): if k[0]!="_": cls.datas[k]=v return type.__init__(cls, name, bases, dct) class Form(object): def __init__(self, action="", method="post", **kw): """You have to provide the form's action, the form's method and some additional parameters. You can put any type of form's parameter expect "class" which must be written "class_" """ self.errors={} self.values={} self.action=action self.method=method self.parameters="" for k,v in kw.items(): if k=="class_": self.parameters+=' class="%s"' % (v) else: self.parameters+=' %s="%s"' % (k, v) self.submit_text="" def submit(self, buttons): """Generate self.submit_text parameters must be a list of (value, name, params). params is here a string sample: <fieldset class="submit"> <input type="submit" value="send" name="bt1"/> <input type="submit" value="cancel" name="bt1"/> <fieldset> """ res='<fieldset class="submit">' for value, name, params in buttons: res+='<input type="submit" value="%s" name="%s" %s/>' % (value, name, params) res+="</fieldset>" self.submit_text=res def render_error(self, name): """generate a list of error messages. sample: <ul class="errorlist"> <li><rong value</li> </ul> """ err="""<ul class="errorlist">""" for error in self.errors[name]: err+="<li>%s</li>" % error err+="</ul>" return "<div>%s</div>" % err def render_form(self, form_fields): """Generate the html's form with all fields provided and the self.submit_text previously generated. This is the main method to generate the form. Parameter is a list of field's names you want to see in the form. """ res='<form action="%s" method="%s" %s>\n' % (self.action, self.method, self.parameters) res+="<fieldset>\n<ol>\n" for name in form_fields: obj=self.datas[name] if self.errors.has_key(name): res+= '<li class="error">' errormsg=self.render_error(name)+"\n" else: res+= "<li>" errormsg=None value=self.values.get(name, "") res+= obj.render(name, value) if errormsg: res+=errormsg res+= "</li>\n" res+="</ol>\n</fieldset>\n" res+=self.submit_text res+="</form>\n" return res def validate(self, input_values, form_fields): """Validate the data provided in the 1st parameter (a dictionary) agains the fields provided in the 2nd parameter (a list). and store the values in self.values This is an important medthod that allow you to generate self.values. self.values is the actual result of the form. """ self.errors={} for name in form_fields: obj=self.datas[name] if input_values.has_key(name): data=input_values[name] else: data="" err=obj.isvalid(data) if err: self.errors[name]=err else: self.values[name]=data def render_list(self, records): """Generate a table with a list of possible values associated with this form. 1st parameter must be a list of dictionary. The first column of the generated table will receive the hyperlink: /admin/edit/<table name>/<record id> to the real form """ res="""<table class="tablesorter">\n<thead>\n<tr>""" for name in self._html_list: res+="<th>%s</th>" % name res+="</tr>\n</thead>\n<tbody>" i=1 for data in records: if i%2==0: class_="odd" else: class_="even" res+='<tr class="%s">' % class_ j=1 for name in self._html_list: obj=self.datas[name] if j==1: pk_path=[] for key in self._dbkey: pk_path.append(unicode(data[key])) res+="""<td %s><a href="/admin/edit/%s/%s">%s</a></td>""" % (obj.list_attrs,self.__class__.__name__, "/".join(pk_path),unicode(data[name] or "")) else: res+="<td %s>%s</td>" % (obj.list_attrs, unicode(data[name] or "")) j+=1 res+="</tr>\n" i+=1 res+="\n</tbody>\n</table>" return res
class Formfactory(type): """This is the factory required to gather every Form components""" def __init__(cls, name, bases, dct): cls.datas = {} for (k, v) in dct.items(): if k[0] != '_': cls.datas[k] = v return type.__init__(cls, name, bases, dct) class Form(object): def __init__(self, action='', method='post', **kw): """You have to provide the form's action, the form's method and some additional parameters. You can put any type of form's parameter expect "class" which must be written "class_" """ self.errors = {} self.values = {} self.action = action self.method = method self.parameters = '' for (k, v) in kw.items(): if k == 'class_': self.parameters += ' class="%s"' % v else: self.parameters += ' %s="%s"' % (k, v) self.submit_text = '' def submit(self, buttons): """Generate self.submit_text parameters must be a list of (value, name, params). params is here a string sample: <fieldset class="submit"> <input type="submit" value="send" name="bt1"/> <input type="submit" value="cancel" name="bt1"/> <fieldset> """ res = '<fieldset class="submit">' for (value, name, params) in buttons: res += '<input type="submit" value="%s" name="%s" %s/>' % (value, name, params) res += '</fieldset>' self.submit_text = res def render_error(self, name): """generate a list of error messages. sample: <ul class="errorlist"> <li><rong value</li> </ul> """ err = '<ul class="errorlist">' for error in self.errors[name]: err += '<li>%s</li>' % error err += '</ul>' return '<div>%s</div>' % err def render_form(self, form_fields): """Generate the html's form with all fields provided and the self.submit_text previously generated. This is the main method to generate the form. Parameter is a list of field's names you want to see in the form. """ res = '<form action="%s" method="%s" %s>\n' % (self.action, self.method, self.parameters) res += '<fieldset>\n<ol>\n' for name in form_fields: obj = self.datas[name] if self.errors.has_key(name): res += '<li class="error">' errormsg = self.render_error(name) + '\n' else: res += '<li>' errormsg = None value = self.values.get(name, '') res += obj.render(name, value) if errormsg: res += errormsg res += '</li>\n' res += '</ol>\n</fieldset>\n' res += self.submit_text res += '</form>\n' return res def validate(self, input_values, form_fields): """Validate the data provided in the 1st parameter (a dictionary) agains the fields provided in the 2nd parameter (a list). and store the values in self.values This is an important medthod that allow you to generate self.values. self.values is the actual result of the form. """ self.errors = {} for name in form_fields: obj = self.datas[name] if input_values.has_key(name): data = input_values[name] else: data = '' err = obj.isvalid(data) if err: self.errors[name] = err else: self.values[name] = data def render_list(self, records): """Generate a table with a list of possible values associated with this form. 1st parameter must be a list of dictionary. The first column of the generated table will receive the hyperlink: /admin/edit/<table name>/<record id> to the real form """ res = '<table class="tablesorter">\n<thead>\n<tr>' for name in self._html_list: res += '<th>%s</th>' % name res += '</tr>\n</thead>\n<tbody>' i = 1 for data in records: if i % 2 == 0: class_ = 'odd' else: class_ = 'even' res += '<tr class="%s">' % class_ j = 1 for name in self._html_list: obj = self.datas[name] if j == 1: pk_path = [] for key in self._dbkey: pk_path.append(unicode(data[key])) res += '<td %s><a href="/admin/edit/%s/%s">%s</a></td>' % (obj.list_attrs, self.__class__.__name__, '/'.join(pk_path), unicode(data[name] or '')) else: res += '<td %s>%s</td>' % (obj.list_attrs, unicode(data[name] or '')) j += 1 res += '</tr>\n' i += 1 res += '\n</tbody>\n</table>' return res
class Rational: def __init__(self, p, q): self.numerator = p self.denominator = q def __mul__(self, other): return Rational( self.numerator * other.numerator, self.denominator * other.denominator ) def __str__(self): return f"{self.numerator}/{self.denominator}" r0 = Rational(1, 2) print(r0) r1 = Rational(1, 3) print(r1) r2 = r0 * r1 print(r2)
class Rational: def __init__(self, p, q): self.numerator = p self.denominator = q def __mul__(self, other): return rational(self.numerator * other.numerator, self.denominator * other.denominator) def __str__(self): return f'{self.numerator}/{self.denominator}' r0 = rational(1, 2) print(r0) r1 = rational(1, 3) print(r1) r2 = r0 * r1 print(r2)
# -*- coding: utf-8 -*- db.define_table('Device', Field('device_id', 'string'), Field('device_name', 'string'), Field('model', 'string'), Field('location', 'string') ) db.Device.device_id.requires = [IS_NOT_EMPTY(),IS_NOT_IN_DB(db, 'Device.device_id')] db.Device.device_name.requires = IS_NOT_EMPTY() db.define_table('User_Device', Field('user_ref_id', 'reference auth_user'), Field('device_ref_id', 'reference Device')) db.define_table('Direction', Field('direction_type', label='Direction'), format="%(direction_type)s") db.define_table('Control_Instruction', Field('device_ref_id', 'reference Device'), Field('onoff_flag', 'boolean', notnull=True, label='Motor ON/OFF', comment='* Check for ON & Uncheck for OFF'), Field('volt_flag', 'string', label='Voltage'), Field('curr_flag', 'string', label='Current'), Field('rot_flag', 'string', label='Rotation', comment='* Insert only integer value [revolution per minute]'), Field('dir_flag', 'reference Direction', label='Direction', requires = IS_IN_DB(db, db.Direction.id,'%(direction_type)s')), Field('freq_flag', 'string', label='Frequency'), Field('off_flag', 'boolean', notnull=True, label='Off') ) db.define_table('Changes', Field('device_ref_id', 'reference Device'), Field('change_flag', 'string') ) db.define_table('Status', Field('device_ref_id', 'reference Device'), Field('created', 'datetime'), Field('last_ping','datetime', requires=IS_NOT_EMPTY()), Field('server_time','datetime', requires=IS_NOT_EMPTY())) db.define_table('Device_States', Field('device_ref_id', 'reference Device'), Field('on_or_off', 'boolean', notnull=True, label='ON/OFF'), Field('voltage', 'string'), Field('current', 'string'), Field('rotation', 'string'), Field('direction', 'reference Direction', requires = IS_IN_DB(db, db.Direction.id,'%(direction_type)s')), Field('frequency', 'string'), Field('off', 'boolean', notnull=True, label='OFF'))
db.define_table('Device', field('device_id', 'string'), field('device_name', 'string'), field('model', 'string'), field('location', 'string')) db.Device.device_id.requires = [is_not_empty(), is_not_in_db(db, 'Device.device_id')] db.Device.device_name.requires = is_not_empty() db.define_table('User_Device', field('user_ref_id', 'reference auth_user'), field('device_ref_id', 'reference Device')) db.define_table('Direction', field('direction_type', label='Direction'), format='%(direction_type)s') db.define_table('Control_Instruction', field('device_ref_id', 'reference Device'), field('onoff_flag', 'boolean', notnull=True, label='Motor ON/OFF', comment='* Check for ON & Uncheck for OFF'), field('volt_flag', 'string', label='Voltage'), field('curr_flag', 'string', label='Current'), field('rot_flag', 'string', label='Rotation', comment='* Insert only integer value [revolution per minute]'), field('dir_flag', 'reference Direction', label='Direction', requires=is_in_db(db, db.Direction.id, '%(direction_type)s')), field('freq_flag', 'string', label='Frequency'), field('off_flag', 'boolean', notnull=True, label='Off')) db.define_table('Changes', field('device_ref_id', 'reference Device'), field('change_flag', 'string')) db.define_table('Status', field('device_ref_id', 'reference Device'), field('created', 'datetime'), field('last_ping', 'datetime', requires=is_not_empty()), field('server_time', 'datetime', requires=is_not_empty())) db.define_table('Device_States', field('device_ref_id', 'reference Device'), field('on_or_off', 'boolean', notnull=True, label='ON/OFF'), field('voltage', 'string'), field('current', 'string'), field('rotation', 'string'), field('direction', 'reference Direction', requires=is_in_db(db, db.Direction.id, '%(direction_type)s')), field('frequency', 'string'), field('off', 'boolean', notnull=True, label='OFF'))
lista = [1753, 1858, 1860, 1978, 1758, 1847, 2010, 1679, 1222, 1723, 1592, 1992, 1865, 1635, 1692, 1653, 1485, 848, 1301, 1818, 1872, 1883, 1464, 2002, 1736, 1821, 1851, 1299, 1627, 1698, 1713, 1676, 1673, 1448, 1939, 1506, 1896, 1710, 1677, 1894, 1645, 1454, 1972, 1687, 265, 1923, 1666, 1761, 1386, 2006, 1463, 1759, 1460, 1722, 1670, 1731, 1732, 1976, 1564, 1380, 1981, 1998, 1912, 1479, 1500, 167, 1904, 1689, 1810, 1675, 1811, 1671, 1535, 1624, 1638, 1848, 1646, 1795, 1717, 1803, 1867, 1794, 1774, 1245, 1915, 1601, 1656, 1472, 1700, 1887, 1869, 1876, 1561, 1743, 1900, 1574, 1400, 1950, 1893, 1576, 1903, 1747, 1560, 1445, 1652, 633, 1970, 1812, 1807, 1788, 1948, 1588, 1639, 1719, 1680, 1773, 1890, 1347, 1344, 1456, 1691, 1842, 1585, 1953, 410, 1791, 485, 1412, 1994, 1799, 1955, 1554, 1661, 1708, 1824, 1553, 1993, 1911, 1515, 1545, 856, 1685, 1982, 1954, 1480, 1709, 1428, 1829, 1606, 1613, 1941, 1483, 1513, 1664, 1801, 1720, 1984, 1575, 1805, 1833, 1418, 1882, 1746, 483, 1674, 1467, 1453, 523, 1414, 1800, 1403, 1946, 1868, 1520, 1861, 1580, 1995, 1960, 1625, 1411, 1558, 1817, 1854, 1617, 1478, 735, 1593, 1778, 1809, 1584, 1438, 1845, 1712, 1655, 1990, 1578, 1703, 1895, 1765, 1572] def find_two_2020(lista): result = None for i in lista: for j in lista: if i + j == 2020: result = i * j return result def find_three_2020(lista): result = None for i in lista: for j in lista: for k in lista: if j + i + k == 2020: result = j * i * k return result result = find_three_2020(lista) print(result) def find_sum(lista, num): for i in lista: need = abs(i-num) if need in lista: return [i, need] lista = [1, 2, 4, 9, 5, 4] print(find_sum(lista, 8))
lista = [1753, 1858, 1860, 1978, 1758, 1847, 2010, 1679, 1222, 1723, 1592, 1992, 1865, 1635, 1692, 1653, 1485, 848, 1301, 1818, 1872, 1883, 1464, 2002, 1736, 1821, 1851, 1299, 1627, 1698, 1713, 1676, 1673, 1448, 1939, 1506, 1896, 1710, 1677, 1894, 1645, 1454, 1972, 1687, 265, 1923, 1666, 1761, 1386, 2006, 1463, 1759, 1460, 1722, 1670, 1731, 1732, 1976, 1564, 1380, 1981, 1998, 1912, 1479, 1500, 167, 1904, 1689, 1810, 1675, 1811, 1671, 1535, 1624, 1638, 1848, 1646, 1795, 1717, 1803, 1867, 1794, 1774, 1245, 1915, 1601, 1656, 1472, 1700, 1887, 1869, 1876, 1561, 1743, 1900, 1574, 1400, 1950, 1893, 1576, 1903, 1747, 1560, 1445, 1652, 633, 1970, 1812, 1807, 1788, 1948, 1588, 1639, 1719, 1680, 1773, 1890, 1347, 1344, 1456, 1691, 1842, 1585, 1953, 410, 1791, 485, 1412, 1994, 1799, 1955, 1554, 1661, 1708, 1824, 1553, 1993, 1911, 1515, 1545, 856, 1685, 1982, 1954, 1480, 1709, 1428, 1829, 1606, 1613, 1941, 1483, 1513, 1664, 1801, 1720, 1984, 1575, 1805, 1833, 1418, 1882, 1746, 483, 1674, 1467, 1453, 523, 1414, 1800, 1403, 1946, 1868, 1520, 1861, 1580, 1995, 1960, 1625, 1411, 1558, 1817, 1854, 1617, 1478, 735, 1593, 1778, 1809, 1584, 1438, 1845, 1712, 1655, 1990, 1578, 1703, 1895, 1765, 1572] def find_two_2020(lista): result = None for i in lista: for j in lista: if i + j == 2020: result = i * j return result def find_three_2020(lista): result = None for i in lista: for j in lista: for k in lista: if j + i + k == 2020: result = j * i * k return result result = find_three_2020(lista) print(result) def find_sum(lista, num): for i in lista: need = abs(i - num) if need in lista: return [i, need] lista = [1, 2, 4, 9, 5, 4] print(find_sum(lista, 8))
class helloworld: def hello(self): print("This is my first task !") def run(): helloworld().hello()
class Helloworld: def hello(self): print('This is my first task !') def run(): helloworld().hello()
# dp class Solution: def lengthOfLIS(self, nums: 'List[int]') -> 'int': if len(nums) < 2: return len(nums) dp = [1] * (len(nums) + 1) for i in range(1, len(nums)): for j in range(0, i): if nums[i] > nums[j]: dp[i] = max(dp[i], dp[j] + 1) return max(dp)
class Solution: def length_of_lis(self, nums: 'List[int]') -> 'int': if len(nums) < 2: return len(nums) dp = [1] * (len(nums) + 1) for i in range(1, len(nums)): for j in range(0, i): if nums[i] > nums[j]: dp[i] = max(dp[i], dp[j] + 1) return max(dp)
class Configuration: """ Configuration file for Twitter Sentiment """ def __init__(self): self.color = "#00A8E0" self.total_gauge_color = "#FF0102" self.image_path = "static/icon.jpeg" self.default_model = "twitter_sentiment_model" self.title = "Twitter Sentiment" self.subtitle = "Searches twitter hashtags and sentiment analysis" self.icon = "UpgradeAnalysis" self.boxes = { "banner": "1 1 -1 1", "logo": "11 1 -1 1", "navbar": "4 1 -1 1", "search_click": "11 2 2 1", "search_tab": "1 2 10 1", "credentials": "-1 -1 -1 -1" } self.tweet_row_indexes = ['3', '9', '15', '21', '27'] self.tweet_column_indexes = ['1', '4', '7', '10'] self.max_tweet_count = 12 self.default_search_text = 'AI' self.ask_for_access_text = "Apply for access : <a href=\"https://developer.twitter.com/en/apply-for-access\" " \ "target='_blank'\">Visit developer.twitter.com!</a>" self.popularity_terms = {'neg': 'Negative', 'neu': 'Neutral', 'pos': 'Positive', 'compound': 'Compound'}
class Configuration: """ Configuration file for Twitter Sentiment """ def __init__(self): self.color = '#00A8E0' self.total_gauge_color = '#FF0102' self.image_path = 'static/icon.jpeg' self.default_model = 'twitter_sentiment_model' self.title = 'Twitter Sentiment' self.subtitle = 'Searches twitter hashtags and sentiment analysis' self.icon = 'UpgradeAnalysis' self.boxes = {'banner': '1 1 -1 1', 'logo': '11 1 -1 1', 'navbar': '4 1 -1 1', 'search_click': '11 2 2 1', 'search_tab': '1 2 10 1', 'credentials': '-1 -1 -1 -1'} self.tweet_row_indexes = ['3', '9', '15', '21', '27'] self.tweet_column_indexes = ['1', '4', '7', '10'] self.max_tweet_count = 12 self.default_search_text = 'AI' self.ask_for_access_text = 'Apply for access : <a href="https://developer.twitter.com/en/apply-for-access" target=\'_blank\'">Visit developer.twitter.com!</a>' self.popularity_terms = {'neg': 'Negative', 'neu': 'Neutral', 'pos': 'Positive', 'compound': 'Compound'}
# -*- coding: utf-8 -*- """ Created on Wed Jun 3 17:48:06 2020 @author: Fernando """ # A = [14,13,12,11,10,9,8,7,6,5,4,3,2,1] A = [3,2,1] B = [] C = [] count = 0 def towers_of_hanoi(A,B,C,n): global count if n == 1: disk = A.pop() C.append(disk) count +=1 else: towers_of_hanoi(A,C,B,n-1) print(f'First call {A,B,C}') towers_of_hanoi(A,B,C,1) print(f'Second call {A,B,C}') towers_of_hanoi(B,A,C,n-1) print(f'Third call {A,B,C}') return count towers_of_hanoi(A,B,C,3)
""" Created on Wed Jun 3 17:48:06 2020 @author: Fernando """ a = [3, 2, 1] b = [] c = [] count = 0 def towers_of_hanoi(A, B, C, n): global count if n == 1: disk = A.pop() C.append(disk) count += 1 else: towers_of_hanoi(A, C, B, n - 1) print(f'First call {(A, B, C)}') towers_of_hanoi(A, B, C, 1) print(f'Second call {(A, B, C)}') towers_of_hanoi(B, A, C, n - 1) print(f'Third call {(A, B, C)}') return count towers_of_hanoi(A, B, C, 3)
def test_udp_header_with_counter(api, b2b_raw_config, utils): """ Configure a raw udp flow with, - Non-default Counter Pattern values of src and dst Port address, length, checksum - 100 frames of 74B size each - 10% line rate Validate, - tx/rx frame count is as expected - all captured frames have expected src and dst Port address """ api.set_config(api.config()) flow = b2b_raw_config.flows[0] packets = 100 size = 74 flow.packet.ethernet().ipv4().udp() eth, ip, udp = flow.packet[0], flow.packet[1], flow.packet[2] eth.src.value = "00:0c:29:1d:10:67" eth.dst.value = "00:0c:29:1d:10:71" ip.src.value = "10.10.10.1" ip.dst.value = "10.10.10.2" udp.src_port.increment.start = 5000 udp.src_port.increment.step = 2 udp.src_port.increment.count = 10 udp.dst_port.decrement.start = 6000 udp.dst_port.decrement.step = 2 udp.dst_port.decrement.count = 10 flow.duration.fixed_packets.packets = packets flow.size.fixed = size flow.rate.percentage = 10 flow.metrics.enable = True utils.start_traffic(api, b2b_raw_config) utils.wait_for( lambda: results_ok(api, size, packets, utils), "stats to be as expected", ) captures_ok(api, b2b_raw_config, size, utils) def results_ok(api, size, packets, utils): """ Returns true if stats are as expected, false otherwise. """ port_results, flow_results = utils.get_all_stats(api) frames_ok = utils.total_frames_ok(port_results, flow_results, packets) bytes_ok = utils.total_bytes_ok(port_results, flow_results, packets * size) return frames_ok and bytes_ok def captures_ok(api, cfg, size, utils): """ Returns normally if patterns in captured packets are as expected. """ src = [src_port for src_port in range(5000, 5020, 2)] dst = [dst_port for dst_port in range(6000, 5980, -2)] cap_dict = utils.get_all_captures(api, cfg) assert len(cap_dict) == 1 for k in cap_dict: i = 0 j = 0 for packet in cap_dict[k]: assert utils.to_hex(packet[34:36]) == hex(src[i]) assert utils.to_hex(packet[36:38]) == hex(dst[i]) assert len(packet) == size i = (i + 1) % 10 j = (j + 1) % 2
def test_udp_header_with_counter(api, b2b_raw_config, utils): """ Configure a raw udp flow with, - Non-default Counter Pattern values of src and dst Port address, length, checksum - 100 frames of 74B size each - 10% line rate Validate, - tx/rx frame count is as expected - all captured frames have expected src and dst Port address """ api.set_config(api.config()) flow = b2b_raw_config.flows[0] packets = 100 size = 74 flow.packet.ethernet().ipv4().udp() (eth, ip, udp) = (flow.packet[0], flow.packet[1], flow.packet[2]) eth.src.value = '00:0c:29:1d:10:67' eth.dst.value = '00:0c:29:1d:10:71' ip.src.value = '10.10.10.1' ip.dst.value = '10.10.10.2' udp.src_port.increment.start = 5000 udp.src_port.increment.step = 2 udp.src_port.increment.count = 10 udp.dst_port.decrement.start = 6000 udp.dst_port.decrement.step = 2 udp.dst_port.decrement.count = 10 flow.duration.fixed_packets.packets = packets flow.size.fixed = size flow.rate.percentage = 10 flow.metrics.enable = True utils.start_traffic(api, b2b_raw_config) utils.wait_for(lambda : results_ok(api, size, packets, utils), 'stats to be as expected') captures_ok(api, b2b_raw_config, size, utils) def results_ok(api, size, packets, utils): """ Returns true if stats are as expected, false otherwise. """ (port_results, flow_results) = utils.get_all_stats(api) frames_ok = utils.total_frames_ok(port_results, flow_results, packets) bytes_ok = utils.total_bytes_ok(port_results, flow_results, packets * size) return frames_ok and bytes_ok def captures_ok(api, cfg, size, utils): """ Returns normally if patterns in captured packets are as expected. """ src = [src_port for src_port in range(5000, 5020, 2)] dst = [dst_port for dst_port in range(6000, 5980, -2)] cap_dict = utils.get_all_captures(api, cfg) assert len(cap_dict) == 1 for k in cap_dict: i = 0 j = 0 for packet in cap_dict[k]: assert utils.to_hex(packet[34:36]) == hex(src[i]) assert utils.to_hex(packet[36:38]) == hex(dst[i]) assert len(packet) == size i = (i + 1) % 10 j = (j + 1) % 2
''' Dict with attr access to keys. Usage: pip install adict from adict import adict d = adict(a=1) assert d.a == d['a'] == 1 See all features, including ajson() in adict.py:test(). adict version 0.1.7 Copyright (C) 2013-2015 by Denis Ryzhkov <denisr@denisr.com> MIT License, see http://opensource.org/licenses/MIT ''' #### adict class adict(dict): def __getattr__(self, name): try: return self[name] except KeyError: raise self.__attr_error(name) def __setattr__(self, name, value): self[name] = value def __delattr__(self, name): try: del self[name] except KeyError: raise self.__attr_error(name) def __attr_error(self, name): return AttributeError("type object '{subclass_name}' has no attribute '{attr_name}'".format(subclass_name=type(self).__name__, attr_name=name)) def copy(self): return adict(self) #### ajson def ajson(item): return ( adict((name, ajson(value)) for name, value in item.iteritems()) if isinstance(item, dict) else [ajson(value) for value in item] if isinstance(item, list) else item ) #### test def test(): d = adict(a=1) # Create from names and values. assert d == adict(dict(a=1)) # Create from dict. assert d.a == d['a'] == 1 # Get by attr and by key. d.b = 2 # Set by attr. assert d.b == d['b'] == 2 d['c'] = 3 # Set by key. assert d.c == d['c'] == 3 d.update(copy=3) # Set reserved name by update(). d['copy'] = 3 # Set reserved name by key. assert d['copy'] == 3 # Get reserved name by key. assert isinstance(d.copy(), adict) # copy() is adict too. assert d.copy().a == d.a == 1 # Really. assert d.copy() is not d # But not the same object. del d.a # Delete by attr. assert 'a' not in d # Check membership. try: d.a # Exception on get, has no attribute 'a'. raise Exception('AttributeError expected') except AttributeError as e: # Exception is of correct type. assert str(e) == "type object 'adict' has no attribute 'a'" # And correct message. try: del d.a # Exception on delele, has no attribute 'a'. raise Exception('AttributeError expected') except AttributeError as e: # Exception is of correct type. assert str(e) == "type object 'adict' has no attribute 'a'" # And correct message. class SubClass(adict): pass try: SubClass().a # Exception in SubClass. except AttributeError as e: # Exception is of correct type. assert str(e) == "type object 'SubClass' has no attribute 'a'" # And correct message. j = ajson({"e": ["f", {"g": "h"}]}) # JSON with all dicts converted to adicts. assert j.e[1].g == 'h' # Get by attr in JSON. print('OK') if __name__ == '__main__': test()
""" Dict with attr access to keys. Usage: pip install adict from adict import adict d = adict(a=1) assert d.a == d['a'] == 1 See all features, including ajson() in adict.py:test(). adict version 0.1.7 Copyright (C) 2013-2015 by Denis Ryzhkov <denisr@denisr.com> MIT License, see http://opensource.org/licenses/MIT """ class Adict(dict): def __getattr__(self, name): try: return self[name] except KeyError: raise self.__attr_error(name) def __setattr__(self, name, value): self[name] = value def __delattr__(self, name): try: del self[name] except KeyError: raise self.__attr_error(name) def __attr_error(self, name): return attribute_error("type object '{subclass_name}' has no attribute '{attr_name}'".format(subclass_name=type(self).__name__, attr_name=name)) def copy(self): return adict(self) def ajson(item): return adict(((name, ajson(value)) for (name, value) in item.iteritems())) if isinstance(item, dict) else [ajson(value) for value in item] if isinstance(item, list) else item def test(): d = adict(a=1) assert d == adict(dict(a=1)) assert d.a == d['a'] == 1 d.b = 2 assert d.b == d['b'] == 2 d['c'] = 3 assert d.c == d['c'] == 3 d.update(copy=3) d['copy'] = 3 assert d['copy'] == 3 assert isinstance(d.copy(), adict) assert d.copy().a == d.a == 1 assert d.copy() is not d del d.a assert 'a' not in d try: d.a raise exception('AttributeError expected') except AttributeError as e: assert str(e) == "type object 'adict' has no attribute 'a'" try: del d.a raise exception('AttributeError expected') except AttributeError as e: assert str(e) == "type object 'adict' has no attribute 'a'" class Subclass(adict): pass try: sub_class().a except AttributeError as e: assert str(e) == "type object 'SubClass' has no attribute 'a'" j = ajson({'e': ['f', {'g': 'h'}]}) assert j.e[1].g == 'h' print('OK') if __name__ == '__main__': test()
while True: n = int(input()) if n == 0: break x, y = [int(g) for g in str(input()).split()] for j in range(n): a, b = [int(g) for g in str(input()).split()] if a == x or b == y: print('divisa') else: if x < a: if y < b: print('NE') else: print('SE') else: if y < b: print('NO') else: print('SO')
while True: n = int(input()) if n == 0: break (x, y) = [int(g) for g in str(input()).split()] for j in range(n): (a, b) = [int(g) for g in str(input()).split()] if a == x or b == y: print('divisa') elif x < a: if y < b: print('NE') else: print('SE') elif y < b: print('NO') else: print('SO')
""" TW3: Sliced to Order Mohammed Elhaj Sohrab Rajabi Andrew Nalundasan Teamwork exercise 3 code """ # user inputs user_text = input('Enter some text, please: ') start_position = int(input('Slice starting position (zero for beginning): ')) end_position = int(input('Slice ending position (can be negative to count from end): ')) stride = int(input('Stride: ')) print('Your text:', user_text) # step 2: add delimiter '|' slice = '|' + user_text[start_position:end_position:stride] + '|' print('You want to slice it from', start_position, 'to', end_position, 'which is', slice) # step 3: setup prefix and suffix using slicing prefix = '|' + user_text[:start_position:stride] + '|' print('Prefix: ', prefix) suffix = '|' + user_text[end_position::stride] + '|' print('Suffix: ', suffix) # step 4: put it all together print(user_text[:start_position:stride] + '|' + user_text[start_position:end_position:stride] + '|' + user_text[end_position::stride])
""" TW3: Sliced to Order Mohammed Elhaj Sohrab Rajabi Andrew Nalundasan Teamwork exercise 3 code """ user_text = input('Enter some text, please: ') start_position = int(input('Slice starting position (zero for beginning): ')) end_position = int(input('Slice ending position (can be negative to count from end): ')) stride = int(input('Stride: ')) print('Your text:', user_text) slice = '|' + user_text[start_position:end_position:stride] + '|' print('You want to slice it from', start_position, 'to', end_position, 'which is', slice) prefix = '|' + user_text[:start_position:stride] + '|' print('Prefix: ', prefix) suffix = '|' + user_text[end_position::stride] + '|' print('Suffix: ', suffix) print(user_text[:start_position:stride] + '|' + user_text[start_position:end_position:stride] + '|' + user_text[end_position::stride])