content
stringlengths
7
1.05M
# from recipes.decor.tests import test_cases as tcx # pylint: disable-all def test_expose_decor(): @expose.show def foo(a, b=1, *args, c=2, **kws): pass foo(88, 12, 11, c=4, y=1) def test_expose_decor(): @expose.args def foo(a, b=1, *args, c=2, **kws): pass foo(88, 12, 11, c=4, y=1) # # print(i) # # print(sig) # # print(ba) # ba.apply_defaults() # # print(ba) # print(f'{ba!s}'.replace('<BoundArguments ', fun.__qualname__).rstrip('>')) # # print('*'*88) # from IPython import embed # embed(header="Embedded interpreter at 'test_expose.py':32")
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2018 CESAR SINCHIGUANO <cesarsinchiguano@hotmail.es> # # Distributed under terms of the BSD license. """ """ #The Fibonacci sequence is a number sequence where each #number is the sum of the previous two numbers. The first #two numbers are defined as 0 and 1, so the third number is #1 (0 + 1 = 1), the fourth number is 2 (1 + 1 = 2), the #fifth number is 3 (1 + 2 = 3), the sixth number is 5 #(2 + 3 = 5), and so on. # #Below we've started a class called FibSeq. At any time, #FibSeq holds two values from the Fibonacci sequence: #back1 and back2. # #Create a new method inside FibSeq called next_number. The #next_number method should: # # - Calculate and return the next number in the sequence, # based on the previous 2. # - Update back2 with the former value of back1, and update # back1 with the new next item in the sequence. # #This means that consecutive calls to next_number should #yield each consecutive number from the Fibonacci sequence. #Calling next_number 5 times would print 1, 2, 3, 5, and 8. class FibSeq: def __init__(self): self.back1 = 1 self.back2 = 0 def next_number(self): tmp=self.back1+self.back2 self.back2=self.back1 self.back1=tmp return tmp #The code below will test your method. It's not used for #grading, so feel free to change it. As written, it should #print 1, 2, 3, 5, and 8. newFib = FibSeq() print(newFib.next_number()) print(newFib.next_number()) print(newFib.next_number()) print(newFib.next_number()) print(newFib.next_number())
def fill_bin_num(dataframe, feature, bin_feature, bin_size, stat_measure, min_bin=None, max_bin=None, default_val='No'): if min_bin is None: min_bin = dataframe[bin_feature].min() if max_bin is None: max_bin = dataframe[bin_feature].max() new_dataframe = dataframe.copy() df_meancat = pd.DataFrame(columns=['interval', 'stat_measure']) for num_bin, subset in dataframe.groupby(pd.cut(dataframe[bin_feature], np.arange(min_bin, max_bin+bin_size, bin_size), include_lowest=True)): if stat_measure is 'mean': row = [num_bin, subset[feature].mean()] elif stat_measure is 'mode': mode_ar = subset[feature].mode().values if len(mode_ar) > 0: row = [num_bin, mode_ar[0]] else: row = [num_bin, default_val] else: raise Exception('Unknown statistical measure: ' + stat_measure) df_meancat.loc[len(df_meancat)] = row for index, row_df in dataframe[dataframe[feature].isna()].iterrows(): for _, row_meancat in df_meancat.iterrows(): if row_df[bin_feature] in row_meancat['interval']: new_dataframe.at[index, feature] = row_meancat['stat_measure'] return new_dataframe def make_dummy_cols(dataframe, column, prefix, drop_dummy): dummy = pd.get_dummies(dataframe[column], prefix=prefix) dummy = dummy.drop(columns=prefix+'_'+drop_dummy) dataframe = pd.concat([dataframe, dummy], axis=1) dataframe = dataframe.drop(columns=column) return dataframe def cleaning(dataframe_raw): dataframe = dataframe_raw.copy() dataframe = dataframe.set_index('ID') dataframe.loc[(dataframe['Age']<=13) & (dataframe['Education'].isna()), 'Education'] = 'Lower School/Kindergarten' dataframe.loc[(dataframe['Age']==14) & (dataframe['Education'].isna()), 'Education'] = '8th Grade' dataframe.loc[(dataframe['Age']<=17) & (dataframe['Education'].isna()), 'Education'] = '9 - 11th Grade' dataframe.loc[(dataframe['Age']<=21) & (dataframe['Education'].isna()), 'Education'] = 'High School' dataframe['Education'] = dataframe['Education'].fillna('Some College') dataframe.loc[(dataframe['Age']<=20) & (dataframe['MaritalStatus'].isna()), 'MaritalStatus'] = 'NeverMarried' dataframe.at[dataframe['MaritalStatus'].isna(), 'MaritalStatus'] = fill_bin_num(dataframe, 'MaritalStatus', 'Age', 5, 'mode',20) dataframe = dataframe.drop(columns=['HHIncome']) dataframe.loc[dataframe['HHIncomeMid'].isna(), 'HHIncomeMid'] = dataframe['HHIncomeMid'].mean() dataframe.loc[dataframe['Poverty'].isna(), 'Poverty'] = dataframe['Poverty'].mean() dataframe.loc[dataframe['HomeRooms'].isna(), 'HomeRooms'] = dataframe['HomeRooms'].mean() dataframe.loc[dataframe['HomeOwn'].isna(), 'HomeOwn'] = dataframe['HomeOwn'].mode().values[0] dataframe.loc[(dataframe['Work'].isna()) & (dataframe['Education'].isna()) & (dataframe['Age']<=20), 'Work'] = 'NotWorking' dataframe.loc[dataframe['Work'].isna(), 'Work'] = dataframe['Work'].mode().values[0] dataframe = fill_bin_num(dataframe, 'Weight', 'Age', 2, 'mean') dataframe = dataframe.drop(columns=['HeadCirc']) for index, row in dataframe.iterrows(): if np.isnan(row['Height']) and not np.isnan(row['Length']): dataframe.at[index, 'Height'] = row['Length'] dataframe = fill_bin_num(dataframe, 'Height', 'Age', 2, 'mean') dataframe = dataframe.drop(columns=['Length']) for index, row in dataframe[dataframe['BMI'].isna()].iterrows(): dataframe.at[index, 'BMI'] = row['Weight'] / ((row['Height']/100)**2) dataframe = dataframe.drop(columns='BMICatUnder20yrs') dataframe = dataframe.drop(columns='BMI_WHO') dataframe = fill_bin_num(dataframe, 'Pulse', 'Age', 10, 'mean') dataframe.loc[(dataframe['Age']<10) & (dataframe['BPSysAve'].isna()), 'BPSysAve'] = 105 dataframe = fill_bin_num(dataframe, 'BPSysAve', 'Age', 5, 'mean', 10) dataframe.loc[(dataframe['Age']<10) & (dataframe['BPDiaAve'].isna()), 'BPDiaAve'] = 60 dataframe = fill_bin_num(dataframe, 'BPDiaAve', 'Age', 5, 'mean', 10) dataframe = dataframe.drop(columns='BPSys1') dataframe = dataframe.drop(columns='BPDia1') dataframe = dataframe.drop(columns='BPSys2') dataframe = dataframe.drop(columns='BPDia2') dataframe = dataframe.drop(columns='BPSys3') dataframe = dataframe.drop(columns='BPDia3') dataframe = dataframe.drop(columns=['Testosterone']) dataframe.loc[(dataframe['Age']<10) & (dataframe['DirectChol'].isna()), 'DirectChol'] = 0 dataframe = fill_bin_num(dataframe, 'DirectChol', 'Age', 5, 'mean', 10) dataframe.loc[(dataframe['Age']<10) & (dataframe['TotChol'].isna()), 'TotChol'] = 0 dataframe = fill_bin_num(dataframe, 'TotChol', 'Age', 5, 'mean', 10) dataframe = dataframe.drop(columns=['UrineVol1']) dataframe = dataframe.drop(columns=['UrineFlow1']) dataframe = dataframe.drop(columns=['UrineVol2']) dataframe = dataframe.drop(columns=['UrineFlow2']) dataframe['Diabetes'] = dataframe['Diabetes'].fillna('No') dataframe['DiabetesAge'] = dataframe['DiabetesAge'].fillna(0) dataframe.loc[(dataframe['Age']<=12) & (dataframe['HealthGen'].isna()), 'HealthGen'] = 'Good' dataframe = fill_bin_num(dataframe, 'HealthGen', 'Age', 5, 'mode', 10) dataframe.loc[(dataframe['Age']<=12) & (dataframe['DaysMentHlthBad'].isna()), 'DaysMentHlthBad'] = 0 dataframe = fill_bin_num(dataframe, 'DaysMentHlthBad', 'Age', 5, 'mean', 10) dataframe.loc[(dataframe['Age']<=15) & (dataframe['LittleInterest'].isna()), 'LittleInterest'] = 'None' dataframe = fill_bin_num(dataframe, 'LittleInterest', 'Age', 5, 'mode', 15) dataframe.loc[(dataframe['Age']<=12) & (dataframe['DaysMentHlthBad'].isna()), 'DaysMentHlthBad'] = 0 dataframe = fill_bin_num(dataframe, 'DaysMentHlthBad', 'Age', 5, 'mean', 10) for index, row in dataframe.iterrows(): if np.isnan(row['nBabies']) and not np.isnan(row['nPregnancies']): dataframe.at[index, 'nBabies'] = row['nPregnancies'] dataframe['nBabies'] = dataframe['nBabies'].fillna(0) dataframe['nPregnancies'] = dataframe['nPregnancies'].fillna(0) dataframe['Age1stBaby'] = dataframe['Age1stBaby'].fillna(0) dataframe.loc[(dataframe['Age']==0) & (dataframe['SleepHrsNight'].isna()), 'SleepHrsNight'] = 14 dataframe.loc[(dataframe['Age']<=2) & (dataframe['SleepHrsNight'].isna()), 'SleepHrsNight'] = 12 dataframe.loc[(dataframe['Age']<=5) & (dataframe['SleepHrsNight'].isna()), 'SleepHrsNight'] = 10 dataframe.loc[(dataframe['Age']<=10) & (dataframe['SleepHrsNight'].isna()), 'SleepHrsNight'] = 9 dataframe.loc[(dataframe['Age']<=15) & (dataframe['SleepHrsNight'].isna()), 'SleepHrsNight'] = 8 dataframe['SleepHrsNight'] = dataframe['SleepHrsNight'].fillna(dataframe_raw['SleepHrsNight'].mean()) dataframe['SleepTrouble'] = dataframe['SleepTrouble'].fillna('No') dataframe.loc[(dataframe['Age']<=4) & (dataframe['PhysActive'].isna()), 'PhysActive'] = 'No' dataframe = fill_bin_num(dataframe, 'PhysActive', 'Age', 2, 'mode', 16) dataframe['PhysActive'] = dataframe['PhysActive'].fillna('Yes') # Big assumption here. All kids between 4 and 16 are physically active dataframe = dataframe.drop(columns=['PhysActiveDays']) dataframe = dataframe.drop(columns=['TVHrsDay']) dataframe = dataframe.drop(columns=['TVHrsDayChild']) dataframe = dataframe.drop(columns=['CompHrsDay']) dataframe = dataframe.drop(columns=['CompHrsDayChild']) dataframe.loc[(dataframe['Age']<18) & (dataframe['Alcohol12PlusYr'].isna()), 'Alcohol12PlusYr'] = 'No' dataframe = fill_bin_num(dataframe, 'Alcohol12PlusYr', 'Age', 5, 'mode', 18) dataframe.loc[(dataframe['Age']<18) & (dataframe['AlcoholDay'].isna()), 'AlcoholDay'] = 0 dataframe = fill_bin_num(dataframe, 'AlcoholDay', 'Age', 5, 'mean', 18) dataframe.loc[(dataframe['Age']<18) & (dataframe['AlcoholYear'].isna()), 'AlcoholYear'] = 0 dataframe = fill_bin_num(dataframe, 'AlcoholYear', 'Age', 5, 'mean', 18) dataframe.loc[(dataframe['Age']<20) & (dataframe['SmokeNow'].isna()), 'SmokeNow'] = 'No' dataframe = fill_bin_num(dataframe, 'SmokeNow', 'Age', 5, 'mode', 20) dataframe['Smoke100'] = dataframe['Smoke100'].fillna('No') dataframe['Smoke100n'] = dataframe['Smoke100n'].fillna('No') dataframe.loc[(dataframe['SmokeNow']=='No') & (dataframe['SmokeAge'].isna()), 'SmokeAge'] = 0 dataframe = fill_bin_num(dataframe, 'SmokeAge', 'Age', 5, 'mean', 20) dataframe.loc[(dataframe['Age']<18) & (dataframe['Marijuana'].isna()), 'Marijuana'] = 'No' dataframe.loc[(dataframe['Marijuana'].isna()) & (dataframe['SmokeNow']=='No'), 'Marijuana'] = 'No' dataframe = fill_bin_num(dataframe, 'Marijuana', 'Age', 5, 'mode', 20) dataframe.loc[(dataframe['Marijuana']=='No') & (dataframe['AgeFirstMarij'].isna()), 'AgeFirstMarij'] = 0 dataframe = fill_bin_num(dataframe, 'AgeFirstMarij', 'Age', 5, 'mean', 20) dataframe.loc[(dataframe['Marijuana']=='No') & (dataframe['RegularMarij'].isna()), 'RegularMarij'] = 'No' dataframe = fill_bin_num(dataframe, 'RegularMarij', 'Age', 5, 'mode', 20) dataframe.loc[(dataframe['RegularMarij']=='No') & (dataframe['AgeRegMarij'].isna()), 'AgeRegMarij'] = 0 dataframe = fill_bin_num(dataframe, 'AgeRegMarij', 'Age', 5, 'mean', 20) dataframe.loc[(dataframe['Age']<18) & (dataframe['HardDrugs'].isna()), 'HardDrugs'] = 'No' dataframe = fill_bin_num(dataframe, 'HardDrugs', 'Age', 5, 'mode', 18) mode_sex_age = dataframe['SexAge'].mode()[0] dataframe.loc[(dataframe['Age']<=mode_sex_age) & (dataframe['SexEver'].isna()), 'SexEver'] = 'No' dataframe['SexEver'] = dataframe['SexEver'].fillna('Yes') dataframe.loc[(dataframe['SexEver']=='No') & (dataframe['SexAge'].isna()), 'SexAge'] = 0 dataframe.loc[(dataframe['SexAge'].isna() & (dataframe['Age']<mode_sex_age)), 'SexAge'] = dataframe.loc[(dataframe['SexAge'].isna() & (dataframe['Age']<mode_sex_age)), 'Age'] dataframe['SexAge'] = dataframe['SexAge'].fillna(mode_sex_age) dataframe.loc[(dataframe['SexEver']=='No') & (dataframe['SexNumPartnLife'].isna()), 'SexNumPartnLife'] = 0 dataframe = fill_bin_num(dataframe, 'SexNumPartnLife', 'Age', 5, 'mean') dataframe['SexNumPartnLife'] = dataframe_raw.loc[(dataframe_raw['Age'] >= 60) & (dataframe_raw['Age'] <= 70), 'SexNumPartnLife'].mode()[0] # Missing values for the elderly. Assumed that lifetime sex partners do not increase after 60. dataframe.loc[(dataframe['SexEver']=='No') & (dataframe['SexNumPartYear'].isna()), 'SexNumPartYear'] = 0 dataframe = fill_bin_num(dataframe, 'SexNumPartYear', 'Age', 10, 'mean') dataframe['SexNumPartYear'] = dataframe['SexNumPartYear'].fillna(0) dataframe = dataframe.drop(columns=['SameSex']) dataframe = dataframe.drop(columns=['SexOrientation']) dataframe['PregnantNow'] = dataframe['PregnantNow'].fillna('No') # Making dummy variables dataframe['male'] = 1*(dataframe['Gender'] == 'male') dataframe = dataframe.drop(columns=['Gender']) dataframe['white'] = np.where(dataframe['Race1'] == 'white',1,0) dataframe = dataframe.drop(columns=['Race1']) dataframe = make_dummy_cols(dataframe, 'Education', 'education', '8th Grade') dataframe = make_dummy_cols(dataframe, 'MaritalStatus', 'maritalstatus', 'Separated') dataframe = make_dummy_cols(dataframe, 'HomeOwn', 'homeown', 'Other') dataframe = make_dummy_cols(dataframe, 'Work', 'work', 'Looking') dataframe['Diabetes'] = np.where(dataframe['Diabetes'] == 'Yes',1,0) dataframe = make_dummy_cols(dataframe, 'HealthGen', 'healthgen', 'Poor') dataframe = make_dummy_cols(dataframe, 'LittleInterest', 'littleinterest', 'None') dataframe = make_dummy_cols(dataframe, 'Depressed', 'depressed', 'None') dataframe['SleepTrouble'] = np.where(dataframe['SleepTrouble'] == 'Yes',1,0) dataframe['PhysActive'] = np.where(dataframe['PhysActive'] == 'Yes',1,0) dataframe['Alcohol12PlusYr'] = np.where(dataframe['Alcohol12PlusYr'] == 'Yes',1,0) dataframe['SmokeNow'] = np.where(dataframe['SmokeNow'] == 'Yes',1,0) dataframe['Smoke100'] = np.where(dataframe['Smoke100'] == 'Yes',1,0) dataframe['Smoke100n'] = np.where(dataframe['Smoke100n'] == 'Yes',1,0) dataframe['Marijuana'] = np.where(dataframe['Marijuana'] == 'Yes',1,0) dataframe['RegularMarij'] = np.where(dataframe['RegularMarij'] == 'Yes',1,0) dataframe['HardDrugs'] = np.where(dataframe['HardDrugs'] == 'Yes',1,0) dataframe['SexEver'] = np.where(dataframe['SexEver'] == 'Yes',1,0) dataframe['PregnantNow'] = np.where(dataframe['PregnantNow'] == 'Yes',1,0) return dataframe
def main(): num = int(input("introduce un numero:")) for x in range (1,num): print(x, end=",") else: print(num, end="")
''' Mysql Table Create Queries ''' tables = [ # master_config Table ''' CREATE TABLE IF NOT EXISTS master_config ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, author VARCHAR(20) NOT NULL, PRIMARY KEY(id) ); ''', ''' CREATE TABLE IF NOT EXISTS user ( id VARCHAR(200) NOT NULL, pw VARCHAR(200) NOT NULL, PRIMARY KEY(id) ); ''', ]
class Person: ''' 这是一个 Person类 实例属性: None: 没有任何东西 ''' print('--------') print(Person.__doc__) print('--------') Person.__doc__ = "三扥东方" print(Person.__doc__) print('--------')
x,y = map(int,input().split()) if x+y < 10: print(x+y) else: print("error")
class Address(object): ADDRESS_UTIM = 0 ADDRESS_UHOST = 1 ADDRESS_DEVICE = 2 ADDRESS_PLATFORM = 3
s = "a quick {0} brown fox {2} jumped over {1} the lazy dog"; x = 100; y = 200; z = 300; t = s.format(x,y,z); print(t);
def uncollapse(s): for n in ['zero','one','two','three','four','five','six','seven','eight','nine']: s=s.replace(n,n+' ') return s[:-1] def G(s): for n in ['zero','one','two','three','four','five','six','seven','eight','nine']: s=s.replace(n,n+' ') return s[:-1]
"""This file defines the unified tensor framework interface required by DGL unit testing, other than the ones used in the framework itself. """ ############################################################################### # Tensor, data type and context interfaces def cuda(): """Context object for CUDA.""" pass def is_cuda_available(): """Check whether CUDA is available.""" pass ############################################################################### # Tensor functions on feature data # -------------------------------- # These functions are performance critical, so it's better to have efficient # implementation in each framework. def array_equal(a, b): """Check whether the two tensors are *exactly* equal.""" pass def allclose(a, b, rtol=1e-4, atol=1e-4): """Check whether the two tensors are numerically close to each other.""" pass def randn(shape): """Generate a tensor with elements from standard normal distribution.""" pass def full(shape, fill_value, dtype, ctx): pass def narrow_row_set(x, start, stop, new): """Set a slice of the given tensor to a new value.""" pass def sparse_to_numpy(x): """Convert a sparse tensor to a numpy array.""" pass def clone(x): pass def reduce_sum(x): """Sums all the elements into a single scalar.""" pass def softmax(x, dim): """Softmax Operation on Tensors""" pass def spmm(x, y): """Sparse dense matrix multiply""" pass def add(a, b): """Compute a + b""" pass def sub(a, b): """Compute a - b""" pass def mul(a, b): """Compute a * b""" pass def div(a, b): """Compute a / b""" pass def sum(x, dim, keepdims=False): """Computes the sum of array elements over given axes""" pass def max(x, dim): """Computes the max of array elements over given axes""" pass def min(x, dim): """Computes the min of array elements over given axes""" pass def prod(x, dim): """Computes the prod of array elements over given axes""" pass def matmul(a, b): """Compute Matrix Multiplication between a and b""" pass def dot(a, b): """Compute Dot between a and b""" pass ############################################################################### # Tensor functions used *only* on index tensor # ---------------- # These operators are light-weighted, so it is acceptable to fallback to # numpy operators if currently missing in the framework. Ideally in the future, # DGL should contain all the operations on index, so this set of operators # should be gradually removed. ############################################################################### # Other interfaces # ---------------- # These are not related to tensors. Some of them are temporary workarounds that # should be included in DGL in the future.
# based on https://nlp.stanford.edu/software/dependencies_manual.pdf DEPENDENCY_DEFINITONS = { 'acomp': 'adjectival_complement', 'advcl': 'adverbial_clause_modifier', 'advmod': 'adverb_modifier', 'agent': 'agent', 'amod': 'adjectival_modifier', 'appos': 'appositional_modifier', 'aux': 'auxiliary', 'auxpass': 'passive_auxiliary', 'cc': 'coordination', 'ccomp': 'clausal_complement', 'conj': 'conjunct', 'cop': 'copula', 'csubj': 'clausal_subject', 'csubjpass': 'clausal_passive_subject', 'dep': 'dependent', 'det': 'determiner', 'discourse': 'discourse_element', 'dobj': 'direct_object', 'expl': 'expletive', 'goeswith': 'goes_with', 'iobj': 'indirect_object', 'mark': 'marker', 'mwe': 'multiword_expression', 'neg': 'negation_modifier', 'nn': 'noun_compound_modifier', 'npadvmod': 'noun_phrase_as_adverbial_modifier', 'nsubj': 'nominal_subject', 'nsubjpass': 'passive_nominal_subject', 'num': 'numeric_modifier', 'nummod': 'numeric_modifier', 'number': 'element_of_compound_number', 'parataxis': 'parataxis', 'pcomp': 'prepositional_complement', 'pobj': 'preposition_object', 'poss': 'possession_modifier', 'possessive': 'possessive_modifier', 'preconj': 'preconjunct', 'predet': 'predeterminer', 'prep': 'prepositional_modifier', 'prepc': 'prepositional_clausal_modifier', 'prt': 'phrasal_verb_particle', 'punct': 'punctuation', 'quantmod': 'quantifier_phrase_modifier', 'rcmod': 'relative_clause_modifier', 'ref': 'referent', 'root': 'root', 'tmod': 'temporal_modifier', 'vmod': 'reduced_nonfinite_verbal_modifier', 'xcomp': 'open_clausal_complement', 'xsubj': 'controlling_subject', 'attr': 'attributive', 'relcl': 'relative_clause_modifier', 'intj': 'interjection' }
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def sumOfLeftLeaves(self, root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 sum = 0 if root.left is not None and root.left.left is None and root.left.right is None: sum = root.left.val return sum + self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right) if __name__ == '__main__': solution = Solution() node = TreeNode(3) node.left = TreeNode(9) node.right = TreeNode(20) node.right.left = TreeNode(15) node.right.right = TreeNode(7) print(solution.sumOfLeftLeaves(node)) else: pass
'''Exercício Python 072: Crie um programa que tenha uma dupla totalmente preenchida com uma contagem por extenso, de zero até vinte. Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostrá-lo por extenso.''' #---------------------------------------------------- tupla20 = ('zero','um', 'dois','três','quatro','cinco','seis','sete','oito','nove','dez','onze','doze','treze','quartoze','quinze','dezesseis','dezessete','dezoito','dezenove','vinte') print('-'*40) while True: numero = int(input('Digite um número entre 0 e 20. >>> ')) if 0 <= numero <=20: print(f'Você digitou o número "{tupla20[numero]}".') resp = str(input('Quer continuar? [S/N] ')).strip().upper()[0] print('-'*40) while resp not in 'SN': resp = str(input('Quer continuar? [S/N] ')).strip().upper()[0] if resp == 'N': break else: print('Tente novamente. ', end = '') print('Saindo do programa...')
"""The functional module implements various functional needed for reinforcement learning calculations. Exposed functions: * :py:func:`loss.entropy` * :py:func:`loss.policy_gradient` * :py:func:`vtrace.from_logits` """
class GH_GrasshopperLibraryInfo(GH_AssemblyInfo): """ GH_GrasshopperLibraryInfo() """ AuthorContact=property(lambda self: object(),lambda self,v: None,lambda self: None) """Get: AuthorContact(self: GH_GrasshopperLibraryInfo) -> str """ AuthorName=property(lambda self: object(),lambda self,v: None,lambda self: None) """Get: AuthorName(self: GH_GrasshopperLibraryInfo) -> str """ Description=property(lambda self: object(),lambda self,v: None,lambda self: None) """Get: Description(self: GH_GrasshopperLibraryInfo) -> str """ Icon=property(lambda self: object(),lambda self,v: None,lambda self: None) """Get: Icon(self: GH_GrasshopperLibraryInfo) -> Bitmap """ Id=property(lambda self: object(),lambda self,v: None,lambda self: None) """Get: Id(self: GH_GrasshopperLibraryInfo) -> Guid """ License=property(lambda self: object(),lambda self,v: None,lambda self: None) """Get: License(self: GH_GrasshopperLibraryInfo) -> GH_LibraryLicense """ Name=property(lambda self: object(),lambda self,v: None,lambda self: None) """Get: Name(self: GH_GrasshopperLibraryInfo) -> str """ Version=property(lambda self: object(),lambda self,v: None,lambda self: None) """Get: Version(self: GH_GrasshopperLibraryInfo) -> str """
class Solution: def reverse(self, x: int) -> int: s = '' if x < 0: s += '-' x *= -1 else: s += '0' while x > 0: tmp = x % 10 s += str(tmp) x = x // 10 res = int(s) if res > 2**31 - 1 or res < - 2**31: return 0 else: return res if __name__ == '__main__': s = Solution() print(s.reverse(1534236469))
#!/usr/bin/env python # encoding: utf-8 """ surrounded_regions.py Created by Shengwei on 2014-07-15. """ # https://oj.leetcode.com/problems/surrounded-regions/ # tags: hard, matrix, bfs """ Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region. For example, X X X X X O O X X X O X X O X X After running your function, the board should be: X X X X X X X X X X X X X O X X """ # https://oj.leetcode.com/discuss/6454/dp-bfs-solution-o-n # http://blog.shengwei.li/leetcode-surrounded-regions/ def flip(board, row, col, value): char_array = list(board[row]) char_array[col] = value board[row] = ''.join(char_array) def mark_escaped(board, row, col, marker): bfs = [(row, col)] while bfs: row, col = bfs.pop(0) if row >= 0 and row < len(board) and col >= 0 and col < len(board[row]): if board[row][col] == 'O' and marker[row][col] != -1: marker[row][col] = -1 bfs.append((row, col - 1)) bfs.append((row, col + 1)) bfs.append((row - 1, col)) bfs.append((row + 1, col)) class Solution: # @param board, a 2D array # Capture all regions by modifying the input board in-place. # Do not return any value. def solve(self, board): if len(board) < 3 or len(board[0]) < 3: return marker = [[0] * m for _ in xrange(n)] for i in xrange(0, len(board)): mark_escaped(board, i, 0, marker) mark_escaped(board, i, len(board[i]) - 1, marker) for j in xrange(0, len(board[0])): mark_escaped(board, 0, j, marker) mark_escaped(board, len(board) - 1, j, marker) for i in xrange(1, len(board) - 1): for j in xrange(1, len(board[i]) - 1): if marker[i][j] != -1 and board[i][j] == 'O': flip(board, i, j, 'X')
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param headA: the first list @param headB: the second list @return: a ListNode """ def getIntersectionNode(self, headA, headB): # write your code here if not headA or not headB: return None # Find last ListNode a = headA while a.next: a = a.next a.next = headB # Fast - Slow pointers haveIntersection = False slow, fast = headA, headA while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: haveIntersection = True break if haveIntersection: third = headA while third != slow: third = third.next slow = slow.next return slow return None
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: result = ListNode(0) curr = result carry = 0 while l1 or l2: x = l1.val if l1 else 0 y = l2.val if l2 else 0 value = carry + x + y carry = value // 10 curr.next = ListNode(value % 10) curr = curr.next l1 = l1.next if l1 else None l2 = l2.next if l2 else None if carry > 0: curr.next = ListNode(carry) return result.next
string = "PATTERN" strlen = len(string) for x in range(0, strlen): print(string[0:strlen-x])
# 姓名 names = ['singi', 'lily', 'sam'] print(names[0]) print(names[1]) print(names[2])
#Donal Maher # Check if one number divides by another def sleep_in(weekday, vacation): if (weekday and vacation == False): return False else: return True result = sleep_in(False, False) print("The result is {} ".format(result))
def calc(n1 ,op ,n2): result = 0 if op == '+': result = n1 + n2 elif op == '-': result = n1 - n2 elif op == '*': result = n1 * n2 elif op == '/': result = n1 / n2 else: result = 0 return result num1 = input('Input num1...') num2 = input('Input num2...') op = input('Input op...') data = calc(int(num1), op , int(num2)) print(data)
n = int(input()) L = list(map(int,input().split())) ans = 1 c = L[0] cnt = 1 for i in L[1:]: if c <= i: cnt+=1 c = i ans = max(ans,cnt) else: cnt = 1 c = i c = L[0] cnt = 1 for i in L[1:]: if c >= i: cnt+=1 c = i ans = max(ans,cnt) else: cnt = 1 c = i print(ans)
""" 백준 2525번 : 오븐 시계 """ a, b = map(int, input().split()) c = int(input()) b = b + c mock = b // 60 b = b % 60 a = mock + a if a >= 24: a = a - 24 print(a, b)
# -*- coding: utf-8 -*- class Config(object): def __init__(self, bucket, root): self.bucket = bucket self.root = root
def find_best_investment(arr): if len(arr) < 2: return None, None current_min = arr[0] current_max_profit = -float("inf") result = (None, None) for item in arr[1:]: current_profit = item - current_min if current_profit > current_max_profit: current_max_profit = current_profit result = (current_min, item) if item < current_min: current_min = item return result if __name__ == '__main__': print(find_best_investment([1, 2, -1, 4, 5, 6, 7]))
def returnValues(z): results = [(x, y) for x in range(z) for y in range(z) if x + y == 5 if x > y] return results print(returnValues(10))
# This file is used on sr restored train set (which includes dev segments) tagged with their segment headers # It splits the set into the dev and train sets using the header information dev_path = 'dev/text' # stores dev segment information restored_sr = 'train/text_restored_by_inference_version2_with_timing' # restored full train + dev segments with headers save_dev = open('../../data/sr_restored_split_by_inference_version2/dev', 'a') save_train = open('../../data/sr_restored_split_by_inference_version2/train','a') def convert_word(text): t = text.strip() if t == '': return '' # get first punctuation for i in range(len(t)): if t[i] == ',': return t[:i] + "\t" + "COMMA" elif t[i]== '.': return t[:i] + "\t" + "PERIOD" elif t[i] == '?': return t[:i] + "\t" + "QUESTION" return t + "\t" + "O" def get_dev_headers(file_path): ''' takes in data file processed by sr which labels lines by their id (swXXXXX) returns the number of unique files in that data file ''' data_file = open(file_path, "r", encoding="utf-8") lines = data_file.readlines() lines = list(map(lambda x: x.split(" ")[0], lines)) lines = list(dict.fromkeys(lines)) lines.sort() return set(lines) dev_headers = get_dev_headers(dev_path) data_file = open(restored_sr, "r", encoding="utf-8") lines = data_file.readlines() for l in lines: line = l.split(' ', 1) segment_header = line[0] segment_text = line[1] segment = segment_text.split(' ') word_list = list(map(convert_word, segment)) if segment_header in dev_headers: save_dev.write('\n'.join(word_list)) save_dev.write('\n') else: save_train.write('\n'.join(word_list)) save_train.write('\n')
"""FrequencyEstimator.py Estimate frequencies of items in a data stream. D. Eppstein, Feb 2016.""" class FrequencyEstimator: """Estimate frequencies of a stream of items to a specified accuracy (e.g. accuracy=0.1 means within 10% of actual frequency) using only O(1/accuracy) bytes of memory.""" def __init__(self, accuracy): self._counts = {} self._howmany = int(1./accuracy) self._total = 0 def __iadd__(self, key): """FrequencyEstimator += key counts another copy of the key. This operation takes amortized constant time, but the worst-case time may be O(1/accuracy).""" self._total += 1 if key in self._counts: self._counts[key] += 1 # Already there, increment its counter. elif len(self._counts) < self._howmany: self._counts[key] = 1 # We have room to add it, so do. else: # We need to make some room, by decrementing all the counters # and clearing out the keys that this reduces to zero. # This happens on at most 1/(howmany+1) of the calls to add(), # so we have enough (amortized) time to loop over all keys. # # One complication is that we can't loop over and modify # the keys in the dict at the same time, without wasting # space making a second list of keys, so instead we build # a linked list of keys to eliminate within the dict itself. # # As a side note, we should not immediately use the space to # add the new key. It is not necessary, and makes the data # structure less accurate by increasing the potential # rate of decrements from 1/(howmany+1) to 1/howmany. # anchor = linkchain = object() # nonce sentinel for key in self._counts: self._counts[key] -= 1 if self._counts[key] == 0: self._counts[key] = linkchain linkchain = key while linkchain != anchor: victim, linkchain = linkchain, self._counts[linkchain] del self._counts[victim] return self def __iter__(self): """iter(FrequencyEstimator) loops through the most frequent keys.""" return iter(self._counts) def __getitem__(self, key): """FrequencyEstimator[key] estimates the frequency of the key.""" if key not in self._counts: return 0 return self._counts[key]*1.0/self._total
async with pyryver.Ryver("organization_name", "username", "password") as ryver: await ryver.load_chats() a_user = ryver.get_user(username="tylertian123") a_forum = ryver.get_groupchat(display_name="Off-Topic")
# tests require to import from Faiss module # so thus require PYTHONPATH # the other option would be installing via requirements # but that would always be a different version # only required for CI. DO NOT add real tests here, but in top-level integration def test_dummy(): pass
numbers = [int(n) for n in input().split(", ")] count_of_beggars = int(input()) collected = [] index = 0 for i in range(count_of_beggars): current_list = [] for index in range(0, len(numbers) + 1, count_of_beggars): index += i if index < len(numbers): current_list.append(numbers[index]) collected.append(sum(current_list)) print(collected) # nums_str = input().split(', ') # count = int(input()) # # nums = [] # # for num in nums_str: # nums.append(int(num)) # # result_sum = [0] * count # # for i in range(len(nums)): # index = i % count # result_sum[index] += nums[i] # # print(result_sum)
# list comprehension is an elegant way to creats list based on exesting list # We can use this one liner comprehensioner for dictnory ans sets also. #l1 = [3,5,6,7,8,90,12,34,67,0] ''' # For addind even in l2 l2 =[] for item in l1: if item%2 == 0: l2.append(item) print(l2) ''' ''' # Shortcut to write the same: l2 = [item for item in l1 if item < 8] l3 = [item for item in l1 if item%2 ==0] # creating a list for print(l2) print(l3) ''' # print a reaptated element from both list. l4 = ['am' , 'em' , 'fcgh' , 'em' , 'em'] l5 = ['am', 'f' , 'em' , 'rg' , 'em'] flist = [item for item in l4+l5 if item == 'em'] #print(flist) #print(flist.count('em')) a= [4,6,8,5,4,4,4] b = [4,5,6,4,5,4] c = [i for i in a+b if i==4] print(c) print(c.count(4))
''' Created on Apr 11, 2017 tutorial: https://www.youtube.com/watch?v=nefopNkZmB4&list=PL6gx4Cwl9DGAcbMi1sH6oAMk4JHw91mC_&index=3 modules: https://www.youtube.com/watch?v=sKYiQLRe254 @author: halil ''' class BayesianFilter(object): ''' classdocs ''' def __init__(self): ''' Constructor ''' print ("hello bayesian filter!")
#Функция вычисления чисел Фибоначчи def fib(n): if n == 1 or n == 2: return 1 return (fib(n-1) + fib(n-2)) print(fib(int(input()))) fib(0) fib(1) fib(9)
""" This is one solution to the cash machine challenge. It will be good to re run this when they start to do OOP and see how subtly different the code is. I have got around the local scope of the subroutines by declaring thst I will be using the global variables at the start of the subroutines. This is not the only way you can get around this. You can also use parameters and return values. The code loads the account number, pin and balance from the file each time it runs the menu and saves them back to the file each time the balance is changed. """ accNo = "" pin = "" balance = 1000 loggedIn = False def saveData(): fileName = "user.txt" try: fout = open(fileName, "w") except OSError: print("Cannot open", fileName) else: user = accNo + "," + pin + "," + str(balance) userCode = "" for letter in user: userCode = userCode + chr(ord(letter)+10) fout.write(userCode + "\n") fout.close() print("Success!") def getData(): global accNo, pin, balance, loggedIn fileName = "user.txt" try: my_file = open(fileName, "r") except OSError: print("Cannot open", fileName) else: fileRead = my_file.readlines() userDecode = "" for line in fileRead: for letter in line: userDecode = userDecode + chr(ord(letter)-10) userDetails = userDecode.split(",") accNo = userDetails[0] pin = userDetails[1] balance = userDetails[2] # when the balance is read from the file it has the \n new line # character included. This must be removed before you can cast it # to a float. balance = balance[:-1] print(balance) try: balance = float(balance) except ValueError: print("There has been an error loading the balance.") print(userDecode, userDetails) # menu is an array of option that are printed out # the return value is the option number as a string. def menu(): menuList = ["1. Login", "2. Logout", "3. Display Account Balance", "4. Withdraw Funds", "5. Deposit Funds", "6. Exit"] for i in menuList: print(i) choice = input("\nEnter the number of your option: ") return choice def optionOne(): aNumber = input("Enter your account Number: ") apin = input("Enter your pin number: ") if aNumber == accNo: if apin == pin: return True else: print("Pin is incorrect.") optionOne() else: print("Account Number is incorrect.") optionOne() def optionTwo(): print("You have logged out") return False def optionthree(): print("Your balance is:", balance) def optionfour(): global balance print("Please enter the withdrawal amount:") try: amount = float(input()) except ValueError: print("Please enter a valid number.") optionfour() else: if balance >= amount: balance = round(balance - amount, 2) saveData() else: print("Sorry you don't have enough money!") def optionfive(): global balance print("Please enter the deposit amount:") try: amount = float(input()) except ValueError: print("Please enter a valid number.") optionfive() else: balance = round(balance + amount, 2) saveData() def main(): global loggedIn exitApp = False while not exitApp: getData() option = menu() if option == "1": loggedIn = optionOne() elif option == "2": loggedIn = optionTwo() elif option == "3": if loggedIn: optionthree() else: print("You must be logged in to view your balance.") elif option == "4": if loggedIn: optionfour() else: print("You must be logged in to withdraw funds.") elif option == "5": if loggedIn: optionfive() else: print("You must be logged in to deposit funds.") elif option == "6": exitApp = True main()
rpc_impl_rename = "_rpc_impl_name" def impl_name(name: str): """ 允许 RPC 服务的定义跟实现使用不同名称的类型 :param name: :return: """ def wrap(cls): setattr(cls, rpc_impl_rename, name) return cls return wrap
"""Simplest possible f-string with one string variable.""" name = "Peter" print(f"Hello {name}")
rules = {} appearances = {} original = input() input() while True: try: l, r = input().split(" -> ") except: break rules[l] = r appearances[l] = 0 for i in range(len(original)-1): a = original[i] b = original[i+1] appearances[a+b] += 1 def polymerization(d): new = {x: 0 for x in rules} singular = {x: 0 for x in rules.values()} for ((a, b), c) in rules.items(): new[a+c] += d[a+b] new[c+b] += d[a+b] singular[c] += d[a+b] singular[a] += d[a+b] #last letter of the word is a K (not not counted above) singular["K"] += 1 return new, singular for i in range(40): (appearances, sing) = polymerization(appearances) counts = [(v, k) for (k, v) in sing.items()] counts.sort() print(counts[-1][0] - counts[0][0])
#opens the file data2.txt and prints all the lines in it that contain the the word “lol” #in any mixture of upper and lower case f = open("data2.txt") text = f.read() lines = text.split("\n") print(lines) for i in range(len(lines)): if ((lines[i].lower()).find("lol") != -1): print(lines[i]) def dict_to_str(d): '''Return a str containing each key and value in dict d. Keys and values are separated by a comma. Key-value pairs separated by a newline character from each other''' new_str = "" for key, value in d.items(): new_str += (str(key) + ", ") new_str += (str(value) + "\n") return new_str d = {"CAN": 80, "USA": 75, "GER": 88} print(dict_to_str(d)) def dict_to_str_sorted(d): """Return a str containing each key and value in dict d. Keys and values are separated by a comma. Key-value pairs are separated by a newline character from each other, and are sorted in ascending order by key. For example, dict_to_str_sorted({1:2, 0:3, 10:5}) should return "0, 3\n1, 2\n10, 5". The keys in the string must be sorted in ascending order.""" c = "" L = [] for key, value in d.items(): a = str(key) + ", " + str(value) + "\n" L.append(a) b = sorted(L) for i in range(len(L)): c += str(b[i]) return c d = {1:30, 4:5, 2:6, -3:7} #Create a Python dictionary whose keys are words, and whose values are lists of phones. f2 = open("cmudict-0.7b.txt") text = f2.read() lines = text.split("\n") phone_dict = {} for i in range(len(lines)): key_value = lines[i].split(" ") phones = key_value[1].split(" ") phone_dict[key_value[0]] = phones f3 = open("cmudict-0.7b.phones.txt") text = f3.read() lines = text.split("\n") vowel_dict = {} for i in range(len(lines)): key_value = lines[i].split("\t") vowel_dict[key_value[0]] = key_value[1] print(vowel_dict) #takes in a word and returns the number of vowels in that word def vowels_calc(word, dictp, dictv): word = word.upper() phones = dictp[word] vowels = 0 for i in range(len(phones)): phones[i] = phones[i].replace("0", "") phones[i] = phones[i].replace("1", "") phones[i] = phones[i].replace("2", "") for key, value in dictv.items(): if (key == phones[i]): if (value == "vowel"): vowels += 1 return vowels #evaluates the Flesch-Kincaid Readability Grade level of a text. def FK_grade(text, dictp, dictv): text += " " sentences = text.split(". ") del sentences[-1] words = [] num_syll = 0 num_words = 0 for i in range(len(sentences)): words.append(sentences[i].split(" ")) for j in range(len(words[i])): num_words += 1 num_syll += num_vowels(words[i][j], dictp, dictv) num_sentences = len(sentences) return (0.39*(num_words/num_sentences) + 11.8*(num_syll/num_words) - 15.59) # Test case FK_grade("Hi. My name is Joao. This is a nondescript sentence. I am merely testing the grade of my lexicon.", phone_dict, vowel_dict)
class AccountManagement: """ All Account requests allow managing the authenticated user's account or are in some way connected to account management. """ def __init__(self, resolve): self.resolve = resolve def get_account_information(self): """ Returns the account details of the authenticated user. :return: Response Object - Account """ request_method = 'GET' resource_url = '/account' return self.resolve(request_method, resource_url) def change_vacation_status(self, on_vacation: bool, cancel_orders: bool = False, relist_items: bool = False): """ Updates the vacation status of the user. :param on_vacation: Boolean flag if the user is on vacation or not :param cancel_orders: Boolean flag to cancel open orders, resp. request cancellation for open orders :param relist_items: Boolean flag to relist items for canceled orders; only applies if cancelOrders is also provided and set to true for all orders, that are effectively canceled :return: Response Object - Account """ request_method = 'PUT' resource_url = f'/account/vacation' params = { 'onVacation': 'true' if on_vacation else 'false', 'cancelOrders': 'true' if cancel_orders else 'false', 'relistItems': 'true' if relist_items else 'false' } return self.resolve(request_method, resource_url, params=params) def change_display_language(self, new_language: int): """ Updates the display language of the authenticated user. :param new_language: 1: English, 2: French, 3: German, 4: Spanish, 5: English :return: Response Object - Account """ if not isinstance(new_language, int) or new_language < 1 or new_language > 5: raise ValueError('The new language must be a number between 1 and 5.') request_method = 'PUT' resource_url = '/account/language' params = {'idDisplayLanguage': new_language} return self.resolve(request_method, resource_url, params=params) def get_message_overview(self): """ Returns the message thread overview of the authenticated user. :return: Response Object - Message Thread """ request_method = 'GET' resource_url = '/account/messages' return self.resolve(request_method, resource_url) def get_messages_from(self, other_user_id: int): """ Returns the message thread with a specified other user. :param other_user_id: ID of the other user (as integer) :return: Response Object - Message Thread """ if not isinstance(other_user_id, int): raise ValueError('The user id must be an integer.') request_method = 'GET' resource_url = f'/account/messages/{other_user_id}' return self.resolve(request_method, resource_url) def get_message_from(self, other_user_id: int, message_id: str): """ Returns a specified message with a specified other user. :param other_user_id: ID of the other user (as integer) :param message_id: ID of the message (as string) :return: Response Object - Message Thread """ if not isinstance(other_user_id, int): raise ValueError('The user id must be an integer.') if not isinstance(message_id, str): raise ValueError('The message id must be a (hex) string.') request_method = 'GET' resource_url = f'/account/messages/{other_user_id}/{message_id}' return self.resolve(request_method, resource_url) def send_message(self, other_user_id: int, message: str): """ Creates a new message sent to a specified other user. :param other_user_id: ID of the other user (as integer) :param message: Text of the message to send. Use '\n' for newline. :return: Response Object - Message Thread (With only the message just sent) """ if not isinstance(other_user_id, int): raise ValueError('The user id must be an integer.') request_method = 'POST' resource_url = f'/account/messages/{other_user_id}' data = {'message': message} return self.resolve(request_method, resource_url, data=data) def delete_message(self, other_user_id: int, message_id: str): """ Deletes a specified message to a specified other user. The message will be delete just for you, it is still visible to the other user. :param other_user_id: ID of the other user (as integer) :param message_id: ID of the message (as string) :return: Empty """ if not isinstance(other_user_id, int): raise ValueError('The user id must be an integer.') if not isinstance(message_id, str): raise ValueError('The message id must be a (hex) string.') request_method = 'DELETE' resource_url = f'/account/messages/{other_user_id}/{message_id}' return self.resolve(request_method, resource_url) def delete_messages_from(self, other_user_id: int): """ Deletes a complete message thread to a specified other user. :param other_user_id: ID of the other user (as integer) :return: Empty """ if not isinstance(other_user_id, int): raise ValueError('The user id must be an integer.') request_method = 'DELETE' resource_url = f'/account/messages/{other_user_id}' return self.resolve(request_method, resource_url) def get_unread_messages(self): """ Returns all unread messages. This request returns only messages where the authenticated user is the receiver. Note: As of Jan 2020 there is a confirmed issue with this method on the MKM backend resulting in a Bad Request (400) status code for some users. :return: Response Object - Message """ request_method = 'GET' resource_url = '/account/messages/find' params = {'unread': 'true'} return self.resolve(request_method, resource_url, params=params) def get_messages_between(self, start_date: str, end_date: str = None): """ Returns all messages between the start and end date. If the end date is omitted, the current date is assumed. The safest format to use is the ISO 8601 representation: E.g. 2017-12-08T14:41:12+0100 (YYYY-MM-DDTHH:MM:SS+HHMM) for 8th of December, 2017, 14:41:12 CET Be aware that the colon (:) in time representations is a reserved character and needs to be percent encoded. Note: As of Jan 2020 there is a confirmed issue with this method on the MKM backend resulting in a Bad Request (400) status code for some users. :param start_date: The earliest date to get messages :param end_date: The lastest date to get messages (current date if omitted) :return: Response Object - Message """ request_method = 'GET' resource_url = '/account/messages/find' params = {'startDate': start_date} if end_date is not None: params['endDate'] = end_date return self.resolve(request_method, resource_url, params=params) def redeem_coupon(self, coupon_code): """ Redeems one coupon. :param coupon_code: Code of the coupon to redeem :return: Response Object - Account plus CodeRedemption """ request_method = 'POST' resource_url = f'/account/coupon' data = {'couponCode': coupon_code} return self.resolve(request_method, resource_url, data=data)
#Potrebno je da izračunate ukupno vrijeme leta za nadolazeće putovanje. #Letite iz Los Angelesa do Sydney-a čija udaljenost iznosi 7425 milja. Avion leti prosječnom brzinom od 550 milja po satu. #Izračunajte i ispišite ukupno vrijeme leta u satima #HINT: Rezultat bi trebao biti float udaljenost = 7425 #milja prosjecna_brzina = 550 #milja/h # v = s/t (s - pređeni put ; t - vrijeme ; v - brzina kretanja) t = s/v vrijeme = udaljenost / prosjecna_brzina print(vrijeme)
n, m = map(int, input().split()) res = [] for _ in range(m): res.append(int(input())) res.sort() price, ans = 0,0 for i in range(m): result = min(m-i, n) if ans < res[i] * result: price = res[i] ans = res[i] * result print(price, ans)
# Crie um programa que leia nome, sexo e idade de várias pessoas, guardando os dados de cada pessoa em um dicionário e todos os dicionários em uma lista. No final, mostre: # A) Quantas pessoas foram cadastradas # B) A média de idade # C) Uma lista com as mulheres # D) Uma lista de pessoas com idade acima da média pessoa = dict() todas_pessoas = list() while True: pessoa['nome'] = str(input('Nome: ')) pessoa['sexo'] = str(input('Sexo [M/F]: ')).upper().strip()[0] while pessoa['sexo'] not in 'MF': pessoa['sexo'] = str(input('Inválido, tente novamente [M/F]: ')).upper().strip()[0] pessoa['idade'] = int(input('Idade: ')) todas_pessoas.append(pessoa) pessoa = dict() continuar = str(input('Quer continuar? [S/N]: ')).upper().strip()[0] while continuar not in 'SN': continuar = str(input('Inválido, quer continuar? [S/N]: ')).upper().strip()[0] if continuar == 'N': break print(f'Foram {len(todas_pessoas)} pessoas cadastradas') print('A média de idade foi de ', end='') idade_total = 0 for x in range(0, len(todas_pessoas)): idade_total += todas_pessoas[x]['idade'] media_idade = idade_total / len(todas_pessoas) print(f'{media_idade:.2f}') print('As mulheres cadastradas foram ', end='') for y in range(0, len(todas_pessoas)): if todas_pessoas[y]['sexo'] == 'F': print(todas_pessoas[y]['nome'], end=' ') print('\nAs pessoas com idade acima da média são ', end='') for z in range(0, len(todas_pessoas)): if todas_pessoas[z]['idade'] > media_idade: print(todas_pessoas[z]['nome'])
n1 = float(input('Digite sua primeira nota: ')) n2 = float(input('Digite sua segunda nota: ')) média = (n1+n2) / 2 if média < 5.0: print('sua média é {}, você está \033[1;31mReprovado\033[m'.format(média)) elif média < 7.0: print('Sua média é {}, você está em \033[1;32mRecuperação\033[m'.format(média)) else: print('Sua média é {}, \n\033[1;35mParabéns!!! Você está APROVADO!\033[m'.format(média))
__version__ = "0.3.1" __logo__ = [ " _ _", "| | _____ | |__ _ __ __ _", "| |/ / _ \\| '_ \\| '__/ _` |", "| < (_) | |_) | | | (_| |", "|_|\\_\\___/|_.__/|_| \\__,_|", " " ]
def _RELIC__word_list_prep(): file = open('stopwords.txt') new_file = open('stopwords_new.txt', 'w') for line in file: if line.strip(): new_file.write(line) file.close() new_file.close()
# There are a total of n courses you have to take, labeled from 0 to n - 1. # Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] # Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses? # For example: # 2, [[1,0]] # There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible. # 2, [[1,0],[0,1]] # There are a total of 2 courses to take. To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible. # Note: # The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented. # You may assume that there are no duplicate edges in the input prerequisites. class Solution(object): def canFinish(self, numCourses, prerequisites): """ O(V+E) :type numCourses: int :type prerequisites: List[List[int]] :rtype: bool """ zero_indegree = [] indegree = {} outdegree = {} # save the indegree and outdegree for i, j in prerequisites: if i not in indegree: indegree[i] = set() if j not in outdegree: outdegree[j] = set() indegree[i].add(j) outdegree[j].add(i) # find zero indegree in the graph for i in range(numCourses): if i not in indegree: zero_indegree.append(i) while zero_indegree: prerequest = zero_indegree.pop(0) if prerequest in outdegree: for course in outdegree[prerequest]: indegree[course].remove(prerequest) # empty if not indegree[course]: zero_indegree.append(course) del (outdegree[prerequest]) # check out degree if outdegree: return False return True def canFinish(self, n, pres): oud = [[] for _ in range(n)] # indegree ind = [0] * n # outdegree for succ,pre in pres: ind[succ] += 1 oud[pre].append(succ) dq = [] for i in range(n): if ind[i] == 0: dq.append(i) count = 0 while dq: pre_course = dq.pop(0) count += 1 for succ in oud[pre_course]: ind[succ] -= 1 if ind[succ] == 0: dq.append(succ) return count == n
""" Web server settings """ # 433 MHz Outlet Codes ----------------------------------------------------------------------------- rfcodes = {'1': {'on': '21811', 'off': '21820'}, '2': {'on': '21955', 'off': '21964'}, '3': {'on': '22275', 'off': '22284'}, '4': {'on': '23811', 'off': '23820'}, '5': {'on': '29955', 'off': '29964'}, '6': {'on': '10000', 'off': '10010'}, '7': {'on': '11000', 'off': '11010'}, '8': {'on': '12000', 'off': '12010'}, '9': {'on': '13000', 'off': '13010'}} # 433 MHz transmission settings -------------------------------------------------------------------- codesend = {'pin': '0', # Set pin number (GPIO: 17 | Pin #: 13) 'length': '189', # Set pulse length 'exec': './codesend'} # Set codesend script path (should be in rfoutlet) # LED settings ------------------------------------------------------------------------------------- led_settings = {'on': 24, # Green LED GPIO 'off': 23, # Red LED GPIO 'num': 2, # Number of times to blink 'speed': 0.15, # Speed of blink (s) 'blink': False} # Blink when outlets are switched # Weather settings --------------------------------------------------------------------------------- weather_settings = {'city': 'pittsburgh', 'state': 'PA', 'unit': 'C', 'precision': 1} # Bus API settings --------------------------------------------------------------------------------- pgh_api_key = "LMJrK9vutafSVnViFmFvjaXvY" bus_stops = {'id': [8245, 3144, 8192], 'name': ['Summerlea', 'Bellefonte', 'Graham'], 'max_prd': 1} # --------------------------------------------------------------------------------------------------
# acutal is the list of actual labels, pred is the list of predicted labels. # sensitive is the column of sensitive attribute, target_group is s in S = s # positive_pred is the favorable result in prediction task. e.g. get approved for a loan def calibration_pos(actual,pred,sensitive,target_group,positive_pred): tot_pred_pos = 0 act_pos = 0 for act, pred_val, sens in zip(actual, pred,sensitive): # the case S != s if sens != target_group: continue else: # Yhat = 1 if pred_val == positive_pred: tot_pred_pos += 1 # the case both Yhat = 1 and Y = 1 if act == positive_pred: act_pos +=1 if act_pos == 0 and tot_pred_pos ==0: return 1 if tot_pred_pos == 0: return 0 return act_pos/tot_pred_pos
# Problem Link: https://www.hackerrank.com/contests/projecteuler/challenges/euler013/problem sum = 0 for _ in range(int(input())): sum += int(input()) print(str(sum)[:10])
# -*- coding: utf-8 -*- # # -- General configuration ------------------------------------- source_suffix = ".rst" master_doc = "index" project = u"Sphinx theme for dynamic html presentation style" copyright = u"2012-2021, Sphinx-users.jp" version = "0.5.0" # -- Options for HTML output ----------------------------------- extensions = [ "sphinxjp.themes.impressjs", ] html_theme = "impressjs" html_use_index = False
"""Custom mail app exceptions""" class MultiEmailValidationError(Exception): """ General exception for failures while validating multiple emails """ def __init__(self, invalid_emails, msg=None): """ Args: invalid_emails (set of str): All email addresses that failed validation msg (str): A custom exception message """ self.invalid_emails = invalid_emails super().__init__(msg)
operators = { '+': (lambda a, b: a + b), '-': (lambda a, b: a - b), '*': (lambda a, b: a * b), '/': (lambda a, b: a / b), '**': (lambda a, b: a ** b), '^': (lambda a, b: a ** b) } priorities = { '+': 1, '-': 1, '*': 2, '/': 2, '**': 3, '^': 3 } op_chars = {char for op in operators for char in op} def evaluate(expression): infix = _parse_tokens(expression.replace(' ', '')) postfix = _postfix(infix) stack = [] for token in postfix: if _is_number(token): stack.append(ExpressionNode(token)) if token in operators: t1, t2 = stack.pop(), stack.pop() node = ExpressionNode(token) node.left, node.right = t1, t2 stack.append(node) return stack.pop().result() class ExpressionNode: def __init__(self, value): self.value = value self.left = None self.right = None def result(self): if _is_number(self.value): return _to_number(self.value) else: return operators[self.value]( self.right.result(), self.left.result()) def _postfix(tokens): stack = ['('] tokens.append(')') postfix = [] for token in tokens: if _is_number(token): postfix.append(token) elif token == '(': stack.append('(') elif token == ')': while stack[-1] != '(': postfix.append(stack.pop()) stack.pop() else: while _priority(token) <= _priority(stack[-1]): postfix.append(stack.pop()) stack.append(token) return postfix def _priority(token): if token in priorities: return priorities[token] return 0 def _parse_tokens(exp): tokens = [] next_token = "" pos = 0 while pos < len(exp): if _is_number(exp[pos]): next_token, pos = _read_next_value(exp, pos) elif exp[pos] in op_chars: next_token, pos = _read_next_operator(exp, pos) elif exp[pos] in ('(', ')'): next_token = exp[pos] else: raise ValueError("Unrecognized character at position " + str(pos)) tokens.append(next_token) pos += 1 return tokens def _read_next_value(exp, pos): token = "" while pos < len(exp) and (_is_number(exp[pos]) or exp[pos] == '.'): token += exp[pos] pos += 1 return token, pos - 1 def _read_next_operator(exp, pos): token = "" while (pos < len(exp) and exp[pos] in op_chars): token += exp[pos] pos += 1 return token, pos - 1 def _to_number(str): try: return int(str) except ValueError: return float(str) def _is_number(str): try: complex(str) return True except ValueError: return False
states = ["Washington", "Oregon", "California"] for x in states: print(x) print("Washington" in states) print("Tennessee" in states) print("Washington" not in states) states2 = ["Arizona", "Ohio", "Louisiana"] best_states = states + states2 print(best_states) print(best_states[1:3]) print(best_states[:2]) print(best_states[4:])
#!/usr/local/bin/python # -*- coding: utf-8 -*- ## # Calculates and display a restaurant bill with tax and tips # @author: rafael magalhaes # Tax Rate in percent TAX = 8/100 # Tip percentage TIP = 18/100 # Getting the meal value print("Welcome to grand total restaurant app.") meal_value = float(input("How much was the ordered total meal: ")) # calculate and display the grand total amount tax_value = meal_value * TAX tip_value = meal_value * TIP grand_total = meal_value + tax_value + tip_value print("\n\nGreat Meal! Your meal and total amount is:\n") print("${:10,.2f} - Net meal ordered value".format(meal_value)) print("${:10,.2f} - State TAX of meal".format(tax_value)) print("${:10,.2f} - Suggested TIP of the meal".format(tip_value)) print("---------------------") print("${:10,.2f} - Grand TOTAL\n".format(grand_total))
# Topics topics = { # Letter A "Amor post mortem" : ["Love beyond death.", "The nature of love is eternal, a bond that goes beyond physical death."] , "Amor bonus" : ["Good love.", "The nature of love is good."] , "Amor ferus" : ["Fiery love.", "A negative nature of the physical love, reference to passionate, rough sex."] , "Amor mixtus" : ["Mix love.", "The complex nature of love when the physical and spiritual parts merge."] # Letter B , "Beatus ille" : ["Blissful thee.", "A praise to the simple life, farm and rural instead of the hustle of the modern life."] # Letter C , "Carpe diem" : ["Seize the day.", "To enjoy the present and not worry about the future; to live in the moment."] , "Collige virgo rosas" : ["Grab the roses, virgin.", "The irrecoverable nature of youth and beauty; an invitation to enjoy love (represented in the symbol of a rose) before time takes away our youth."] , "Contempus mundi" : ["Contempt to the world.", "Contempt to the world and the terrenal life, nothing but a valley of pain and tears."] # Letter D , "Descriptio puellae" : ["Description of a young girl.", "Description of a young girl in a descendant order, head, neck, chest, ..."] , "Dum vivimus, vivamus" : ["While we're alive, we live.", "The idea of life as something transient and inalienable, hence an invitation to enjoy and seize it."] # Letter F , "Fugit irreparabile tempus" : ["Time passes irredeemably.", "The idea of time as something that cannot be recovered, life itself is fleeting and transient."] , "Furor amoris" : ["Passionate love.", "The idea of love as a disease that negates all reason and logic."] # Letter H , "Homo viator" : ["Traveling man.", "The idea of the living man as an itinerant being, consider your existence as a journey through life."] # Letter I , "Ignis amoris" : ["The fire of love.", "The idea of love as a fire that burns inside you."] # Letter L , "Locus amoenus" : ["A nice scene.", "The mythical nature of the ideal scene described by its bucolic elements, almost always related to love."] # Letter M , "Memento mori" : ["Reminder of your death.", "Death is certain, the end of everyone's life, a reminder to never forget."] , "Militia est vita hominis super terra" : ["The life of men on this earth is a struggle.", "The idea of life as a military thing, a field of war against everyone; society, other men, love, destiny, ..."] , "Militia species amor est" : ["Love is a struggle.", "The idea of love as a struggle between the two lovers."] # Letter O , "Omnia mors aequat" : ["Death sets everyone equal.", "Death as an equality force, it doesn't care about hierarchy, richness or power; upon its arrival all humans are the same."] , "Oculos Sicarii" : ["Murdering eyes.", "The idea of a stare that would kill you if it could."] # Letter P , "Peregrinatio vitae" : ["Life as a journey.", "The idea of life as a journey, a road which where the man must walk through."] # Letter Q , "Quodomo fabula, sic vita" : ["Life is like theater.", "The idea that life is a play with the man itself as protagonist."] , "Quotidie morimur" : ["We die every day.", "Life has a determined time, by each moment that passes we're closer to the end of our journey which is death."] # Letter R , "Recusatio" : ["Rejection.", "Reject others values and actions."] , "Religio amoris" : ["Worship love.", "Love is a cult which man is bound to serve, as such we must free ourselves from it."] , "Ruit hora" : ["Time runs.", "By nature time is fleeting, hence life is too. As such we're running towards our inevitable death."] # Letter S , "Sic transit gloria mundi" : ["Glory is mundane and it passes by.", "Fortune, glory and reputation are all fleeting, death takes everything away."] , "Somnium, imago mortis" : ["Sleep, an image of death.", "When a man sleeps it's as though he was dead."] # Letter T , "Theatrum mundi" : ["The world, a theater.", "The idea of the world and life as a play, think of them as different dramatic scenarios in which actors -mankind- represent their lives on an already written play."] # Letter U , "Ubi sunt" : ["Where are they?", "The idea of the unkown, beyond death nothing is certain."] # Letter V , "Vanitas vanitatis" : ["Vanity of vanities.", "Looks are decieving, human ambitions are vain, thus they should be rejected."] , "Varium et mutabile semper femina" : ["Wayward and unsettled, women are.", "Women have a wayward nature, they change and never settle."] , "Venatus amoris" : ["The hunt for love.", "Love is presented as a hunt, where one hunts for its lover."] , "Vita flumen" : ["Life is a river.", "Existence is a river that always goes foward, never stopping, until it reaches the sea. Death."] , "Vita somnium" : ["Life is a dream.", "Life is irreal, strange and fleeting, much like a dream."] } first_word = [] for phrase in topics: templo = phrase.split(" ",1)[0].lower() tempup = phrase.split(" ",1)[0].capitalize() first_word.append(templo) first_word.append(tempup)
def xfail(fun, excp): flag = False try: fun() except excp: flag = True assert flag
# 立方 cube = [v**3 for v in range(1, 11)] for v in cube: print(v)
def reverse_words(text): # 7 kyu reverse = [] words = text.split(' ') for word in words: reverse.append(word[::-1]) return ' '.join(reverse) t = "This is an example!" print(reverse_words(t))
with open('p11_grid.txt', 'r') as file: lines = file.readlines() n = [] for line in lines: a = line.split(' ') b = [] for i in a: b.append(int(i)) n.append(b) N = 0 for i in range(20): for j in range(20): horizontal, vertical, diag1, diag2 = 0, 0, 0, 0 if j < 17: horizontal = n[i][j]*n[i][j+1]*n[i][j+2]*n[i][j+3] if horizontal > N: N = horizontal if i < 17: vertical = n[i][j]*n[i+1][j]*n[i+2][j]*n[i+3][j] if vertical > N: N = vertical if i < 17 and j < 17: diag1 = n[i][j]*n[i+1][j+1]*n[i+2][j+2]*n[i+3][j+3] if diag1 > N: N = diag1 if i > 3 and j < 17: diag2 = n[i-1][j]*n[i-2][j+1]*n[i-3][j+2]*n[i-4][j+3] if diag2 > N: N = diag2 print(N)
""" Problem 11 ----------- In the 20×20 grid below, four numbers along a diagonal line have been marked in red. [moved to data/011.txt] The product of these numbers is 26 × 63 × 78 × 14 = 1788696. What is the greatest product of four adjacent numbersin the same direction (up, down, left, right, or diagonally) in the 20×20 grid? """ with open('data/011.txt', 'rt') as f: lines = [s.strip() for s in f] grid = [line.split(' ') for line in lines] grid = [[int(num) for num in line] for line in grid] f.closed max_prod = 0 for y in range(17): for x in range(17): prod = max( grid[y][x] * grid[y][x+1] * grid[y][x+2] * grid[y][x+3], grid[y][x] * grid[y+1][x] * grid[y+2][x] * grid[y+3][x], grid[y][x] * grid[y+1][x+1] * grid[y+2][x+2] * grid[y+3][x+3], grid[y][x+3] * grid[y+1][x+2] * grid[y+2][x+1] * grid[y+3][x] ) if prod > max_prod: max_prod = prod print(max_prod)
class BST: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right class TreeInfo: def __init__(self, numberOfNodesVisited, latestVisitedNodeValue): self.numberOfNodesVisited = numberOfNodesVisited self.latestVisitedNodeValue = latestVisitedNodeValue # O(h + k) time | O(h) space, where h is the height/depth and k the kth largest element. def findKthLargestValueInBst(tree, k): # To solve this problem, what we do is to traverse from right - visit - left. And when we reach a visit element we add a counter and # keep track of it's value. We will add +1 every time until counter = k. We create a DS to store the treeInfo value treeInfo = TreeInfo(0, -1) reverseInOrderTraverse(tree, k, treeInfo) return treeInfo.latestVisitedNodeValue def reverseInOrderTraverse(node, k, treeInfo): # base case, when the node is none or the number of nodes visited is equal to k, we simply return until # find Kth largest value, where we return the latest visited node value. if node == None or treeInfo.numberOfNodesVisited >= k: return # reverse in order: right - visited - left reverseInOrderTraverse(node.right, k, treeInfo) if treeInfo.numberOfNodesVisited < k: treeInfo.numberOfNodesVisited += 1 treeInfo.latestVisitedNodeValue = node.value # if numberOfNodesVisited is less than k, we want to return; but if is equal to k we don't want, we want to inmediately return # otherwise it will update the value reverseInOrderTraverse(node.left, k, treeInfo)
class ObjectA: """first type of object to be matched when running the gale-shapley algorithm""" def __init__(self, name: str): self.name = name def __repr__(self): return self.name class ObjectB: """second type of object to be matched when running the gale-shapley algorithm""" def __init__(self, name: str): self.name = name def __repr__(self): return self.name def gale_shapley(preferences_a: dict[ObjectA, list[ObjectB]], preferences_b: dict[ObjectB, list[ObjectA]]) -> \ dict[ObjectA, ObjectB]: """computes a stable matching given a two lists of objects and the preferences :param preferences_a: dictionary with all objects_a and the list of their preferences :param preferences_b: dictionary with all objects_b and the list of their preferences :return: dictionary of the stable matching from objects_b to objects_a """ matching_a = {} matching_b = {} unmatched_a = list(preferences_a.keys()) while unmatched_a: new_a = unmatched_a[0] if not preferences_a[new_a]: unmatched_a.remove(new_a) continue potential_b = preferences_a[new_a].pop(0) if potential_b in matching_a.values(): current_a = matching_b[potential_b] if preferences_b[potential_b].index(new_a) > preferences_b[potential_b].index(current_a): continue matching_a.pop(current_a) unmatched_a.append(current_a) matching_a[new_a] = potential_b matching_b[potential_b] = new_a unmatched_a.remove(new_a) return matching_a
class Solution: def mostCommonWord(self, paragraph, banned): """ :type paragraph: str :type banned: List[str] :rtype: str """ return collections.Counter(word for word in re.sub("[!?',;.]", " ", paragraph).lower().split() if word not in banned).most_common(1)[0][0]
#encoding=utf-8 #人类能理解的版本 dataset = [16,9,21,3,13,14,23,6,4,11,3,15,99,8,22] for i in range(len(dataset)-1,0,-1): print("-------",dataset[0:i+1],len(dataset),i) #for index in range(int(len(dataset)/2),0,-1): for index in range(int((i+1)/2),0,-1): print(index) p_index = index l_child_index = p_index *2 - 1 r_child_index = p_index *2 print("l index",l_child_index,'r index',r_child_index) p_node = dataset[p_index-1] left_child = dataset[l_child_index] if p_node < left_child: # switch p_node with left child dataset[p_index - 1], dataset[l_child_index] = left_child, p_node # redefine p_node after the switch ,need call this val below p_node = dataset[p_index - 1] if r_child_index < len(dataset[0:i+1]): #avoid right out of list index range #if r_child_index < len(dataset[0:i]): #avoid right out of list index range #print(left_child) right_child = dataset[r_child_index] print(p_index,p_node,left_child,right_child) # if p_node < left_child: #switch p_node with left child # dataset[p_index - 1] , dataset[l_child_index] = left_child,p_node # # redefine p_node after the switch ,need call this val below # p_node = dataset[p_index - 1] # if p_node < right_child: #swith p_node with right child dataset[p_index - 1] , dataset[r_child_index] = right_child,p_node # redefine p_node after the switch ,need call this val below p_node = dataset[p_index - 1] else: print("p node [%s] has no right child" % p_node) #最后这个列表的第一值就是最大堆的值,把这个最大值放到列表最后一个, 把神剩余的列表再调整为最大堆 print("switch i index", i, dataset[0], dataset[i] ) print("before switch",dataset[0:i+1]) dataset[0],dataset[i] = dataset[i],dataset[0] print(dataset)
def compute(data): lines = data.split('\n') pairs = { '(':')', '[':']', '{':'}', '<':'>', } p1_scores = { ')':3, ']':57, '}':1197, '>':25137, } p2_scores = { ')':1, ']':2, '}':3, '>':4, } p1_score = 0 p2_score = [] for l in lines: stack = [] corrupt = False for c in l: if c in pairs.keys(): stack.append(c) elif c in pairs.values(): m = stack.pop() if pairs[m] != c: # print(f'corrupted: {l}') # print(f"{m} doesn't match {c} expected {pairs[m]}") p1_score += p1_scores[c] corrupt = True break if len(stack) > 0 and not corrupt: print(stack) # complete the braces - inverse of the stack: stack.reverse() completion_cost = 0 for c in stack: completion_cost = completion_cost * 5 completion_cost += p2_scores[pairs[c]] print(f'completion score for {l} is {completion_cost} from {stack}') p2_score.append(completion_cost) p2_score.sort() print(f'p1 = {p1_score}') middle = int(len(p2_score)/2) print(p2_score) print(f'middle of {len(p2_score)} is {middle}') print(f'p2 = {p2_score[middle]}') test_data = """[({(<(())[]>[[{[]{<()<>> [(()[<>])]({[<{<<[]>>( {([(<{}[<>[]}>{[]{[(<()> (((({<>}<{<{<>}{[]{[]{} [[<[([]))<([[{}[[()]]] [{[{({}]{}}([{[{{{}}([] {<[[]]>}<{[{[{[]{()[[[] [<(<(<(<{}))><([]([]() <{([([[(<>()){}]>(<<{{ <{([{{}}[<[[[<>{}]]]>[]]""" real_data = """{[[<{(<{[{{[{[[]{}]{<>{}}}({<>()}{{}{}})]}{({[<>{}]({}[])})[{[{}[]](()<>)}<[{}{}]{()<>}>]}}]<(({{{(){}}{[][] <<<({((<{<([([<>{}]<{}<>>]{<{}<>>({}<>)}])>}{({(([()[]]{[]()})({{}<>}<(){}>))[(<<><>>[()[]]){{()[]}< <<<[(({{(([[[[<><>][<><>]]]([[{}{}](<><>)][(<>[]){[]()}])])([[(<{}<>>(()[]))(<[][]>)]]{{<[[]{}]{< ({({([{{[[[{(<(){}><[]{}>)}]]][(<<([()[]](()[]))>[[[{}[]]{[]<>}](<()>[()<>]]]>(<(({}<>){<>[]}){<[]()>}>{[{( [([{(<[<<[({<[()<>][{}]>({{}{}})}({[<>{}][()()]}[([][]){()[]}]))]>>]>)<<[((([[{{()()}(<>{})}[(<>( {[[{<[[[[([[{[()[]]<[]()>}<({}())<[]<>>>]({<{}[]>}<<{}<>>>)](([(<>{}){[][]}]<[(){}]({}{})>)[((()){[]})<{{} {{<<((({(<[({<<>[]><{}{}>}((<>[])([]())))[((()[]){[]{}})]]{<([{}[]]<<>[]>)(({}[]}{[][]})><<([][])([][])>>} ([[(<({[[{[{<[<><>]({}())>}](<[[{}[]](<><>)]{{()<>}[{}]}>{((<><>]<()()>)([(){}]<()>)})}{[<{({}())<<><>>}[(() (<((([[<<[<[{[()[]][[]{}]}{([]<>){[]{}}}]>]>>{{([[({<>()}(<>{}))]<{(()<>)([])}([<>{}}{{}()})> (<({{<(<{[{<{[(){}][<>{}]}{[[][]]{<>{}}}>}<(([[][]][<>()])[[{}{}][{}()]])>]}>{{{([<(()())> (<[{<<(<<<((<[<>[]]>)({[[]<>]}<({}<>)([][])>))[{<[[]()](<>())>{<[]<>><{}()>}}(<<{}<>>(<>[] <[[(((([[(<[{((){})<{}<>>}{({}<>><{}<>>}]([{<>()}([]<>)]<{()()}({}[])>)>)]{{({([{}<>])(<<>() <({<(<{[{<<[[[{}[]][()[]]](<()()><()>)]>>[(((([]<>){(){}})<{{}()}({}())>)[<[[]()]{<>[]}><[()[]][<>()]>])[(<<< ([[[{(<<<([[[<<>[]>]]{<([]<>){[]{}}><<[]>({}<>)>}]<(<<{}<>>([])><{<>[]}<{}<>>>)([{[]()}<<> <({<<(<{(<<(({[]<>}{{}{}})(<<>[]><<>[]>))(<<<><>><[]{}>>{[()[]][()[]]})>>){{<{([{}()]{<>()}){<[][]>({}<>)}} (([{{(<[([([([[]()]({}))<<[][]><{}()>>][[[{}<>][<>{}]]]){[{[[][]]<{}{}>}<<()<>>(<>())>]}])<{{[(({})<[]()>){[< {(<<[<{<<{(([[()<>]{<>[]}]{[{}{}]{<>()}})<([[][]]{[]<>}){(()<>)<[]<>>}>)[[{{[]}}]]}<{{((<>)<{}>){ <{<{<{{[<{{<<<<>[]>{()[]}>><[<<>()>{{}[]}]<[{}]{[]()}>>}}>[[{(((<>{}]({}()))<<{}()>[[]()]>)}]{{({[<>() <[[<<([{([{{[[()()]<{}<>>][{{}()}<()()>]}({([]<>)<<>[]>}{[[][]][()[]]})}[((<{}{}><()[]>){<<>()>((){} <<{([[{[<{[<([()()]{()<>}>[<[]<>>[[]<>]]>{{[{}{}][()<>]}<[[]{}][{}{}]>}]<((({}<>)<<><>>){{<><>}[()<>]})> [[[[[{({((([<[<>{}]<{}()>>[<{}[]>[[]{}]]]{{{()<>}<{}[]>>([()()]{{}()})})))}[{{[({<{}[]>}<[[]()]>)( {[[<[([{((<[<[{}[]][<><>]>({{}{}}[{}{}])]{{({}{}){{}[]}><[{}[]]([]())>}>[{<{()<>}([]())>}]))(<[([[()][[][]] [(({[((<{<{<<[[]<>]<{}[]>>>{[<[]{}>[[]{}]]{((){})<[]>}}}<<<{{}{}}<<>()>>{<<>[]>([]{})}>>>}{[{{{<[]()>(()<>)}< {[[[{<([{[<{([<>()]{<>[])){<<><>>([]<>)}}<{[(){}]<()<>>}>>([[<()<>>((){})]][<<[]{}><()()>>(<[ [{(<{[({[{[{{(<>{})({}{})}<(<>[])>}([<()<>>[()<>]]{(()<>)<{}()>})]{([{{}{}}(()<>)][{()()>])[<<[][]>(<>[])> [[{[{([<<<<([{[][]}{<>()}]([[]<>]<<>[]>))<{[<>()][<>{}]}[((){})]>><[[<{}<>>([]())]]>><<{{(() <{[<<[[[<{{[<<[]{}>[()<>]><{()()}<()[]>>][[[<>{}][[]()]][<<>>{{}[]}]]}{<<<[]()>({}<>)>>(<[[]()]{<>[]} {(([({{<(<<[(({}{})[()[]])<<{}{}>(()[])>](([()[]]<{}()>){{<><>}<[][]>})>((<{()()}[{}()]>[{<>()} <(({(([[<[{[{<{}>(())}{<{}[]>[<>[]]}]{<{()}><<()()>[{}{}]>}}]({<<<()[]>{()<>}>>}[[{(<>){[]}}((()) {{<{<<(([[[{{[{}{}]{<>[]}}}{[<{}<>>[{}<>]]{{[][]}{[]]}}]({<([][])[<>]>{(()())<<><>>}}([([][]){{}()}]<{()[]}{[ [<<<<<[{<{{({[[]()](<>())}{{[]{}}([][])})}(<<[{}{}]({}<>)>[<<>>{()}]>)>({[(<[][]>{{}[]})][[(()())<(){}>]{<()< {({<<([[(<(([(()[])]{{{}<>)((){})}))[([<(){}>[<>()]]{{<><>}})<({<>{}}(<>[]))>]>({[{([]()){(){ <{[<(<{[(<<{(({}[])(<>()))}[{<[]<>><()[]>}<<{}{}>(<>{})>]>{{{<{}<>>[{}()]}}[<<()()}>(([]{})([] {<[(([{{{[(<<[{}()]>{(<>())[[]{}]}>){{[{{}[]}{()<>}]{(()<>)<<><>>}}}]}{(<[([[]][{}[]])]>)[[((<{}[]})[ ([[[({({{[<<[<[]<>><()>]>{([<><>])(<<><>><<>()>)}>[(([[][]]{()<>}>)([{(){}}({}<>)])]][(<<{{}{}}{() {([({[{{{[(<<<<><>>([][])>[<[]<>>[()<>]]>)[[(<()[]>)(<<>()>[()<>])]({<[][]>{[][]}}[<()()>[<>[]]])]](<<{<<><> <((({{<[[({[(([]<>)[[]<>])]{{<{}>{[]<>}}(([][])[()[]])}}{[{<()<>>[()[]]}{{[]<>}{[]()}}]}){([{{{}{}}[( {<<[[{[<(([[{([][])[<>()]}<{<><>}>](<<[][]>[[]{}]>[{<>}{{}<>}])]{<([()<>]<()[]>)(<[][]>(<>[]))>[{[[]< ([{((<[<<([[[{<>()}(<>())]([(){}](<>[]))][[<[]>]]]<{<[{}[]][[][]]>}([<[]()><<>{}>]<{(){}}[{}{}]>)>)>({([ ([{(<<[<{<[[(<[][]>{<><>}){<<>()>}]{({()[]}<<>()>)}][{({(){}}[()()])<[<><>]<<>[]>>}]>}<<[({< {<({[({{<[[({{(){}}<<>[]>}<({}[]){()())>)<{([]{})([]())}>]]>(<{[((<>[]){[]()})<<()<>>({}<>)>]{{{()[]}}} {({[[<(<{[[{<<[]()>[()()]>([<>{}]{<>[]))}<{([]())(()<>)}<<[]><[][]>>>][({<{}><[]()>})[<[()[]][()()]>{<{}<>> {({(((<{<[<(<({}<>)[()()]>{<[]{}><()<>>})[<({}<>)><(<>)<()()>>]>(<(([][])<()<>>)<<<><>>([])>>{(<[]{}> [{{[([<<(<[<({<><>}{[]()})[{<><>}]>{<(()[])><[<><>]>}][<{[{}<>][[]<>]}(([]{}))>[[([])<{}[]>]{<(){}>({}())}]] {[<<((<<[([[([()[]]({}()))(<{}()>{(){}})][((<>[]]{{}{}})((()<>)<<><>>)]]{[<(<>[])<[]>>([<>()]{[] ((({({{<[(((<[<>[]]([]<>)>[<[]{}>{<><>}])<{[<>()][()<>]}{<{}<>>[[]()]}>))<[<{(<><>)<()<>>}>[<[[]<>]<[]{ {<<<{<({([({((<><>)[[][]]){[()<>]{<><>}}}<[{[]<>}[<>[]]][[()<>]{(){}}]>)<[[[[]<>]]((<><>))}(<<()<>><<><>>><[[ (({{[({<{<{[[<<>[]>([][])]{<<>()>{{}()>}]{[<<>[]>[{}{}]][{()()}{[]<>}]}}([({{}[]}{{}()}){(()<>){()<>}} (<([({{{{<[<{{<>[]}{{}}}<[{}{}]<{}{}>>><{{(){}}([]{})}>](<[([]())[()]]>[(<[]<>>[[]{}])])>[{(<[[][]]<{} ((({[{{{([<{{<<><>><[][]>}{({}())<<>{}>}}[{([]())}[<<>()>({}[])]]>{<[<<>[]]<()<>>][[()[]][<>[]]]>[{[[] <(<<[[<{({{[(([][]))([<><>][{}{}])]}})}>]](<([{{[{<{[][]}[{}<>]>([{}()])}]}([{{(())}{{{}{}}<[]{} <([<[{{({[(({({}{})<{}()>}))[[((<><>)<{}>)[[[][]]((){})]]<<<[]()>{()[]}>>]]{<<(<[]<>>[<>{}]){({}())}>>}}{[[ [<<[(({<({{{[{[][]}{(){}}][<()()>]}((<{}{}>>[{{}[]}])}{<[(<>[])[(){}]](<<><>>({}<>))><(({}()) [([{<{(([[[([{{}[]}<(){}>])]<{([[]()][[]<>])([{}{}]([][]))}>]({<<([][]){()<>}>>{([()<>]([])){{{}()}{[][]} {<({[<[(({{({<(){}><[][]>}[{<>()}({})])<[[{}]{<><>}]<<[]{}>([]{})>>}[(({[]<>})([(){}]<()[]>))]}))]><<( {<<[[<[[[((<[<{}<>><<><>>]<({}[])([]{})>>{<{()<>}>{([]{})[()[]]}}>[[<({}<>)([]{})>(<{}()>[[]()])][[<()<>><[] {((({(<{[[[({<<>[]><{}<>>}[{[][]}[<>()]]){([<>()][[]()])({[]<>}{{}<>})}]<<{[{}<>]<{}()>}<(()){(){}}>>{ <[[{<<([<[{{(({}()){[]{}}){{{}[]}{<>()}}}}{<{[<><>]<{}{}>}(({}()){()<>})>(<(<>{})[<>()]>{<<><>>{[][]}} {{([{(((({<{[({}{}){{}{}}]{(<>{})[{}{}]}}[{[()[]][{}()]}{(()[])(()())}]><({(<>[])}((())<[]>))>}<{{{{{}<> ({(([({(<<<((({}[])((){}))((<><>)[[][]]))((<()<>><(){}>){{{}()}(()[])})><([[{}<>][()[]]])(([<> <<<<<{({{([(([{}{}]<{}()>))][<<{<>[]}{<>}>({()<>}{{}()})>[([<><>]{{}()})([[]{}])}]){({[([]<>)<[][]>][{<><> ((<[<<{{<([{{[{}<>]{{}<>}}([[][]]<<>{}>)}{[[[]{}]])]{[<<{}<>>{{}{}}><({}<>)>]([(<><>)[{}()]])})(< <(((<[(((<([[{(){}}<<>()>]]<{<<>{}><(){}>}<{[][]}{[]{}}>>)>{<<{{<><>}{[]<>}}{{<>[]}<[]()>}>[{{{}()}{[]<> {[<{((<<[<<([(()()){{}()}](([]{}){<>()>))>{({((){})({}())}[[()][<><>]])<([{}[]][[]{}])(([]{}){()<>} (<[({[(([[{[[<{}{}><<>{}>][<<>{}>]]([{<>()}<<>{}>]{{[]{}}({}())})}([({{}()}{{}()})][[<<>[]>[<>{}]]{<<>[])}]) {<{(((<([[[<[(<>())[()[]]]<<()[]><{}<>>>>]<{({<>()}(()<>)){<<><>>{{}[]}}}{(<()<>><<>[]>){{[]()}[[]()]}}>][(<[ <<[[<(({{{{<{{[]()}({}<>)}[(<>{}){[]{}}]>[<{[][]}{{}{}}>]}{{(<<>()><{}{}>)[{{}[])[(){}]]}(([()[]][{}[]]){< (<(<<<([{((<[[{}[]]{{}}]<({}<>)<()<>>>})<(<[<>{}]<{}<>>><([]<>)([]<>)>)[{<{}<>>[()()]}[(<>[])] <{(([([[<<([{{<><>}[<><>}}{[{}<>]{{}<>}}]{([[]()]<()[]>)[({}<>){[][]}]})({[((){})<<>[]>][{<>()}[[]<>] <<<{{<{[({<<[[[]][[][]]]({[]()}{{}[]})>>{[({{}<>}{[][]})[[{}()]{[]}]]}}([[[[<>[]]<{}[]>]{[{}{ {<{{([([<{[[{([]<>)[()<>]}][{<()()>}<{{}<>}([]{})>]]{{[{[][]}<{}[]>]([<>()]{{}{}})}{(({}{})(( <{<((<{<{([<((()<>){()[]}){[[]<>](()[])}><(([]()])<[[]()]{{}<>}>>]{({<()><()()>}[[()<>]<<>[]>] [<[{[(<<[(<<<(<>[])[[]]>{<(){}>}><([<>[]]{<>{}})[{<><>}{[]()}]>>{[(<[]<>>)<[{}<>]{<>()}>]{<(()())[[][]]>[ [<<<{[(<<[({{{<>[]}<[]()>}{<<>[]>(<>[]]}})]>>{[[<({([][]){{}()}}[{<>()}({}())])({(()[])(<> [<[[<{<{{{{{<([]())[<>()]><{()<>}[<><>]>}}}}}><<{(([{<[][]>{[]()}}[{[][]}{{}<>}>][(({}())({}()) <[[{{[<{<<[<(<<>[]>)<<()()>{{}[]}>>{<{()<>}[<><>]>[{{}{}}{()}]}]{(<([]<>)({}())>{<[]{}>}){[({}())]{( ({{[(([(<{[[{(()<>)({}())}<({}{}){{}}>](((()())<{}()>)[<{}<>><{}()>])]({{([][])({}<>)}<({}())<[] {[(<[<{[(([<(<[]()><{}()>)<<[][]><()>>>][<<[{}[]]<{}{}>](<<>>{<>[]})>[{(<>())[<>]}<{[]<>}(( [{{(<{{[{<<<<(<><>)>(({}[]))><<[[]{}][<>()]>>>({[({}{}){<>{}}]<[<><>]>})>}<[<{{<{}{}>{<><>}}}>]<( {<{<<{[{<[[[<<{}[]>{()<>}>(<()[]>({}<>))]{<((){})[<><>]><{<>{}}{<>()}>}]({([()[]]{[]()})}([{()()}}<(<>() [<<([(<[<[[([(<>{}){()<>}][<{}()><{}()>])]((([()<>]{()<>})[[<><>]]))][{([{{}{}}]<{<>}[{}()]>)[[{ <[[{([({<<<(<([]<>)<<><>>>[{[]()}<(){}>])>>>({(([[<>{}]([]<>)]{[(){}](()())})([{<>()}([]<>)]))<[{[{}()]{<>[]} <(([{<{[[<({[({}()){{}[]}]{<{}[]>[{}<>]}}[[[{}<>](<><>)][<()()>({}<>)]])<{{[{}<>]{<>[]}}}([[{}[]]<<>{}>])>> {(<[([[[{[<[[<[]()>[{}{}]][<()[]>{[]()}]]>[[[(<>[]){<>[]}][{<>{}}<()[]>]]]](<{{([]())[()()]]<[{}[]][[]( [([[[<<<{({[[{[][]}<()[]>]][{{[]()}([]<>)}({()<>})]))[<{<[<>{}]{[]{}}>({<>{}}[()()])}><<([<>[]]{{}[]})[<[][] {(({({<{([[[[<[]{}>(<>{})]{({}())(()<>)}]]<{{<[]()>(()())}{([][])}}<{[[][]]<()<>>}{(<>{})({} [{{<[{(<{({<[{[]<>}[[]()]][[{}<>]{{}()}]>(<[()()]>([{}[]]{(){}}))}{{{({}<>)<<><>>}({[]<>)<{}>)}})([<({ (<[{{{{<(<[<{{()()}{[]{}}}<([]{}){<>()}>>[({{}<>}{{}[]})]][[({{}()}(<>[])){<[][]>[<>()]}]]>]>{[( [{<(<<{[<(<[<({}[])({}{})>]{<{{}()}<<><>>>{<{}{}>(()())}}>)>][({<[[<(){}>(<>())](({}{}){{}()} {([[{<{<{(([<([]<>)[<>]>{(<>[]){<>[]}}][<[(){}]{{}()}>((<>[]))])<({[()<>](()[])}){<[()<>]{<>{}}>{([])<() <[{[{(<<({[((<[]{}>{[]{}})([()[]]<(){}>))<{<<>[]>[{}]}{<{}<>>{()}}>]{{{(<>())}(({}<>))}<<{()<>}({}())>([{}< <(<[{{<{{[([{{(){}}<<>{}>}(<(){}>)][[{{}<>}(()<>)]]){([<<>{}>[()()]][{[]()}<{}()>])}]<{([{[]}([][] <[[{<{[<{([<[<[]<>][{}]]<({}{})([])>>]({{(<><>)[[]<>]}<<{}[]>[[]<>]>}))}([<(({()()}{[]<>}))<{<()[]><[]()>}((( ({{{<{([{<[{{[{}<>](<><>)}[[<>()]({}[])]}[[<(){}>({}<>)]<(()())({}())>])>[<<<[[][]][(){}]><([ ((<{[<[[(((<[<<>()>([]())]<(()<>){()[]}>>[<{(){}}{{}}>[[(){}}<[]{}>]])<[[[[][]][{}()]]{[{}()][ (({[[<{({[[[[[<><>]<[]{}>]<(<>{}){[]()}>][(([]<>){()[]})([<>{}]<()<>>)]]]}[[<{<(<><>)<{}[]>>}<<{<> <{({[{(([[{(<(()[])<(){}>>{<{}{}>{<><>}})[<(()())<[]{}>>]}[{{{[]}[()[]]}[<()[]><<>{}>]}{<[<><>]{[] [<[<<{<{{<[(<{(){}}[<>()]><({}<>)<<>{}>))<<<()<>>({}<>)><[<><>][()]>>](({({}()){()()}}<[[]<>]<<>{}>>)<[[[] {<{(<(<[<([{<{{}[]}(()[])>[({}())<[][]>]}<<{()()}[<><>]>>]<{{[[]{}]{<><>}}(({}{})[[]])}({(<>[])<<>{}> {{{[[((<[(<<[[{}()]<[]<>>]{<()[]>}>[<<()()>>([<><>]((){}))]>{<<[{}{}][{}()]>[(()())[<>[]]]>{{ <({<{[{<[<({{[<><>]{<>[]}}<{[]<>}<<><>>]}{{[{}{}]{{}{}}}{<[]<>>{[][]}}})(<({()<>}<{}[]>){([]{}) {<(<<[<{([{[({{}<>}[()()]){(()<>)[{}<>]}]}])}>]{{(<[<<((()())<<>()>)>{([[]{}]((){}))<({}<>)({}< [<(<[[{{[([[<<[]{}>{[]<>}>{(<>[])[{}{}]>]([[[]<>](()())])])([[<{<>{}}(<><>)><({}<>)<()>>][({[]<>} [<{({{[<([{<{[()[]][(){}]}>[([<>[]]{{}})]}<<((()<>}(()()))<[(){}]>>((({}())[{}<>]){({}<>)<<>[]>})>]{<<{<{}[] [[<{<{({(<{<{({}())[{}]}([()[]]{{}()})>}((([{}{}]{()<>})<[<>()]{<>[]}>)[([()<>]<<><>>)[[()[]]{[]}]]]>){([[[ {<(([<<[<{(((<()<>>{{}()})({[]{}}[[]{}]))(([{}[]]{[]<>})<<[]>(<>{})>))}[{{<(<><>]<<>>>}}({[({}[]) [[{{[([<[({[{(<>()}[<>[]]}{{<>{}}<[]{}>}]{{{()[]}([]{})}([()<>]{()<>})}}[<{(<>)<<><>>}{{<>[]}<<>[]>}>({< {{[{{{<([<{<{<{}<>>}{[(){}]{{}()}}><{{[]()}<{}>}>)[[{[{}{}]{()<>}}<(<>{}){[]{}}>][[(()<>)(<>())]({[]<>}[()[] ((<({<{[(<[{[<<>><{}()>][[{}[]>]}{({()<>}[{}[]])[(()())]}][<<{<>{}}<<><>>>[{[][]}{<>()}]>]>[<({({}()){{ [([<<({({[<{(((){}){<>{}})(({}<>))}{<[[]()][{}{}]>{([][])<[][]>}}>]<<(<{<>()}[()[]]>[<(){}>[<>()>])<<[{}(""" compute(real_data)
n = int(input()) count = 0 a_prev, b_prev = -1, 0 for _ in range(n): a, b = map(int, input().split()) start = max(a_prev, b_prev) end = min(a, b) if end >= start: count += end - start + 1 if a_prev == b_prev: count -= 1 a_prev, b_prev = a, b print(count)
# Copyright 2021 by Saithalavi M, saithalavi@gmail.com # All rights reserved. # This file is part of the Nessaid readline Framework, nessaid_readline python package # and is released under the "MIT License Agreement". Please see the LICENSE # file included as part of this package. # # common CR = "\x0d" LF = "\x0a" BACKSPACE = "\x7f" SPACE = "\x20" TAB = "\x09" ESC = "\x1b" INSERT = "\x1b\x5b\x32\x7e" DELETE = "\x1b\x5b\x33\x7e" PAGE_UP = "\x1b\x5b\x35\x7e" PAGE_DOWN = "\x1b\x5b\x36\x7e" HOME = "\x1b\x5b\x48" END = "\x1b\x5b\x46" # cursors UP = "\x1b\x5b\x41" DOWN = "\x1b\x5b\x42" LEFT = "\x1b\x5b\x44" RIGHT = "\x1b\x5b\x43" # CTRL CTRL_A = '\x01' CTRL_B = '\x02' CTRL_C = '\x03' CTRL_D = '\x04' CTRL_E = '\x05' CTRL_F = '\x06' CTRL_G = '\x07' # CTRL_H is '\x08', '\b', BACKSPACE # CTRL_I is '\x09', '\t', TAB # CTRL_J is '\x0a', '\n', LF CTRL_K = '\x0b' CTRL_L = '\x0c' # CTRL_M is '\x0d', '\r', CR CTRL_N = '\x0e' CTRL_O = '\x0f' CTRL_P = '\x10' CTRL_Q = '\x11' CTRL_R = '\x12' CTRL_S = '\x13' CTRL_T = '\x14' CTRL_U = '\x15' CTRL_V = '\x16' CTRL_W = '\x17' CTRL_X = '\x18' CTRL_Y = '\x19' CTRL_Z = '\x1a' # ALT ALT_A = "\x1b" + 'a' ALT_B = "\x1b" + 'b' ALT_C = "\x1b" + 'c' ALT_D = "\x1b" + 'd' ALT_E = "\x1b" + 'e' ALT_F = "\x1b" + 'f' ALT_G = "\x1b" + 'g' ALT_H = "\x1b" + 'h' ALT_I = "\x1b" + 'i' ALT_J = "\x1b" + 'j' ALT_K = "\x1b" + 'k' ALT_L = "\x1b" + 'l' ALT_M = "\x1b" + 'm' ALT_N = "\x1b" + 'n' ALT_O = "\x1b" + 'o' ALT_P = "\x1b" + 'p' ALT_Q = "\x1b" + 'q' ALT_R = "\x1b" + 'r' ALT_S = "\x1b" + 's' ALT_T = "\x1b" + 't' ALT_U = "\x1b" + 'u' ALT_V = "\x1b" + 'v' ALT_W = "\x1b" + 'w' ALT_X = "\x1b" + 'x' ALT_Y = "\x1b" + 'y' ALT_Z = "\x1b" + 'z' # CTRL + ALT CTRL_ALT_A = "\x1b" + CTRL_A CTRL_ALT_B = "\x1b" + CTRL_B CTRL_ALT_C = "\x1b" + CTRL_C CTRL_ALT_D = "\x1b" + CTRL_D CTRL_ALT_E = "\x1b" + CTRL_E CTRL_ALT_F = "\x1b" + CTRL_F CTRL_ALT_G = "\x1b" + CTRL_G CTRL_ALT_H = "\x1b" + '\x08' CTRL_ALT_I = "\x1b" + '\x09' CTRL_ALT_J = "\x1b" + '\x0a' CTRL_ALT_K = "\x1b" + CTRL_K CTRL_ALT_L = "\x1b" + CTRL_L CTRL_ALT_M = "\x1b" + '\x0d' CTRL_ALT_N = "\x1b" + CTRL_N CTRL_ALT_O = "\x1b" + CTRL_O CTRL_ALT_P = "\x1b" + CTRL_P CTRL_ALT_Q = "\x1b" + CTRL_Q CTRL_ALT_R = "\x1b" + CTRL_R CTRL_ALT_S = "\x1b" + CTRL_S CTRL_ALT_T = "\x1b" + CTRL_T CTRL_ALT_U = "\x1b" + CTRL_U CTRL_ALT_V = "\x1b" + CTRL_V CTRL_ALT_W = "\x1b" + CTRL_W CTRL_ALT_X = "\x1b" + CTRL_X CTRL_ALT_Y = "\x1b" + CTRL_Y CTRL_ALT_Z = "\x1b" + CTRL_Z CTRL_ALT_DELETE = "\x1b\x5b\x33\x5e" KEY_NAME_MAP = { "cr": CR, "lf": LF, "tab": TAB, "page-up": PAGE_UP, "page-down": PAGE_DOWN, "insert": INSERT, "delete": DELETE, "backspace": BACKSPACE, "home": HOME, "end": END, "left": LEFT, "right": RIGHT, "up": UP, "down": DOWN, "esc": ESC, "escape": ESC, "ctrl-a": CTRL_A, "ctrl-b": CTRL_B, "ctrl-c": CTRL_C, "ctrl-d": CTRL_D, "ctrl-e": CTRL_E, "ctrl-f": CTRL_F, "ctrl-g": CTRL_G, "ctrl-k": CTRL_K, "ctrl-l": CTRL_L, "ctrl-n": CTRL_N, "ctrl-o": CTRL_O, "ctrl-p": CTRL_P, "ctrl-q": CTRL_Q, "ctrl-r": CTRL_R, "ctrl-s": CTRL_S, "ctrl-t": CTRL_T, "ctrl-u": CTRL_U, "ctrl-v": CTRL_V, "ctrl-w": CTRL_W, "ctrl-x": CTRL_X, "ctrl-y": CTRL_Y, "ctrl-z": CTRL_Z, "alt-a": ALT_A, "alt-b": ALT_B, "alt-c": ALT_C, "alt-d": ALT_D, "alt-e": ALT_E, "alt-f": ALT_F, "alt-g": ALT_G, "alt-h": ALT_H, "alt-i": ALT_I, "alt-j": ALT_J, "alt-k": ALT_K, "alt-l": ALT_L, "alt-m": ALT_M, "alt-n": ALT_N, "alt-o": ALT_O, "alt-p": ALT_P, "alt-q": ALT_Q, "alt-r": ALT_R, "alt-s": ALT_S, "alt-t": ALT_T, "alt-u": ALT_U, "alt-v": ALT_V, "alt-w": ALT_W, "alt-x": ALT_X, "alt-y": ALT_Y, "alt-z": ALT_Z, "ctrl-alt-a": CTRL_ALT_A, "ctrl-alt-b": CTRL_ALT_B, "ctrl-alt-c": CTRL_ALT_C, "ctrl-alt-d": CTRL_ALT_D, "ctrl-alt-e": CTRL_ALT_E, "ctrl-alt-f": CTRL_ALT_F, "ctrl-alt-g": CTRL_ALT_G, "ctrl-alt-h": CTRL_ALT_H, "ctrl-alt-i": CTRL_ALT_I, "ctrl-alt-j": CTRL_ALT_J, "ctrl-alt-k": CTRL_ALT_K, "ctrl-alt-l": CTRL_ALT_L, "ctrl-alt-m": CTRL_ALT_M, "ctrl-alt-n": CTRL_ALT_N, "ctrl-alt-o": CTRL_ALT_O, "ctrl-alt-p": CTRL_ALT_P, "ctrl-alt-q": CTRL_ALT_Q, "ctrl-alt-r": CTRL_ALT_R, "ctrl-alt-s": CTRL_ALT_S, "ctrl-alt-t": CTRL_ALT_T, "ctrl-alt-u": CTRL_ALT_U, "ctrl-alt-v": CTRL_ALT_V, "ctrl-alt-w": CTRL_ALT_W, "ctrl-alt-x": CTRL_ALT_X, "ctrl-alt-y": CTRL_ALT_Y, "ctrl-alt-z": CTRL_ALT_Z, "ctrl-alt-delete": CTRL_ALT_DELETE, }
""" Given a binary tree, find the maximum path sum. For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root. For example: Given the below binary tree, 1 / \ 2 3 Return 6. """ # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return an integer def maxPathSum(self, root): self.current_max = float("-inf") self.traverse_tree(root) return self.current_max def traverse_tree(self, root): if root == None: return 0 # calc left max left_max = max(0, self.traverse_tree(root.left)) # calc right max right_max = max(0, self.traverse_tree(root.right)) # update current_max root_max_sum = root.val + left_max + right_max self.current_max = max(self.current_max, root_max_sum) #return the max path sum from this root return max(left_max, right_max) + root.val
"""Ext macros.""" load("@b//:lib2.bzl", "bar") foo = bar
# The contents of this file is free and unencumbered software released into the # public domain. For more information, please refer to <http://unlicense.org/> manga_query = ''' query ($id: Int,$search: String) { Page (perPage: 10) { media (id: $id, type: MANGA,search: $search) { id title { romaji english native } description (asHtml: false) startDate{ year } type format status siteUrl averageScore genres bannerImage } } } '''
# this code will accept an input string and check if it is a plandrome # it will then return true if it is a plaindrome and false if it is not def reverse(str1): if(len(str1) == 0): return str1 else: return reverse(str1[1:]) + str1[0] string = input("Please enter your own String : ") # check for strings str1 = reverse(string) print("String in reverse Order : ", str1) if(string == str1): print("This is a Palindrome String") else: print("This is Not a Palindrome String")
ticket_dict1 = { "pagination": { "object_count": 2, "continuation": None, "page_count": 1, "page_size": 50, "has_more_items": False, "page_number": 1 }, "ticket_classes": [ { "actual_cost": None, "actual_fee": { "display": "$7.72", "currency": "USD", "value": 772, "major_value": "7.72" }, "cost": { "display": "$100.00", "currency": "USD", "value": 10000, "major_value": "100.00" }, "fee": { "display": "$7.72", "currency": "USD", "value": 772, "major_value": "7.72" }, "tax": { "display": "$0.00", "currency": "USD", "value": 0, "major_value": "0.00" }, "resource_uri": "https://www.eventbriteapi.com/v3/events/158717222485/ticket_classes/567567567/", "display_name": "Regular Price", "name": "Regular Price", "description": None, "sorting": 1, "donation": False, "free": False, "minimum_quantity": 1, "maximum_quantity": 10, "maximum_quantity_per_order": 10, "on_sale_status": "AVAILABLE", "has_pdf_ticket": True, "order_confirmation_message": None, "delivery_methods": [ "electronic" ], "category": "admission", "sales_channels": [ "online", "atd" ], "secondary_assignment_enabled": False, "event_id": "12122222111111", "image_id": None, "id": "278648077", "capacity": 300, "quantity_total": 300, "quantity_sold": 0, "sales_start": "2021-06-02T04:00:00Z", "sales_end": "2021-09-03T19:00:00Z", "sales_end_relative": None, "hidden": False, "hidden_currently": False, "include_fee": False, "split_fee": False, "hide_description": True, "hide_sale_dates": False, "auto_hide": False, "payment_constraints": [] }, { "actual_cost": None, "actual_fee": None, "cost": None, "fee": None, "tax": None, "resource_uri": "https://www.eventbriteapi.com/v3/events/158717222485/ticket_classes/678678678/", "display_name": "Super Special Free Admission", "name": "Super Special Free Admission", "description": None, "sorting": 2, "donation": False, "free": True, "minimum_quantity": 1, "maximum_quantity": 1, "maximum_quantity_per_order": 1, "on_sale_status": "AVAILABLE", "has_pdf_ticket": True, "order_confirmation_message": None, "delivery_methods": [ "electronic" ], "category": "admission", "sales_channels": [ "online", "atd" ], "secondary_assignment_enabled": False, "event_id": "12122222111111", "image_id": None, "id": "278648079", "capacity": 50, "quantity_total": 50, "quantity_sold": 0, "sales_start": "2021-06-02T04:00:00Z", "sales_end": "2021-09-03T19:00:00Z", "sales_end_relative": None, "hidden": True, "hidden_currently": True, "include_fee": False, "split_fee": False, "hide_description": True, "hide_sale_dates": False, "auto_hide": False, "payment_constraints": [] } ] } ticket_dict2 = { "pagination": { "object_count": 2, "continuation": None, "page_count": 1, "page_size": 50, "has_more_items": False, "page_number": 1 }, "ticket_classes": [ { "actual_cost": None, "actual_fee": { "display": "$7.72", "currency": "USD", "value": 772, "major_value": "7.72" }, "cost": { "display": "$100.00", "currency": "USD", "value": 10000, "major_value": "100.00" }, "fee": { "display": "$7.72", "currency": "USD", "value": 772, "major_value": "7.72" }, "tax": { "display": "$0.00", "currency": "USD", "value": 0, "major_value": "0.00" }, "resource_uri": "https://www.eventbriteapi.com/v3/events/158717222485/ticket_classes/3255985/", "display_name": "Regular Price", "name": "Regular Price", "description": None, "sorting": 1, "donation": False, "free": False, "minimum_quantity": 1, "maximum_quantity": 10, "maximum_quantity_per_order": 10, "on_sale_status": "AVAILABLE", "has_pdf_ticket": True, "order_confirmation_message": None, "delivery_methods": [ "electronic" ], "category": "admission", "sales_channels": [ "online", "atd" ], "secondary_assignment_enabled": False, "event_id": "2222333332323232", "image_id": None, "id": "278648077", "capacity": 300, "quantity_total": 300, "quantity_sold": 0, "sales_start": "2021-06-02T04:00:00Z", "sales_end": "2021-09-03T19:00:00Z", "sales_end_relative": None, "hidden": False, "hidden_currently": False, "include_fee": False, "split_fee": False, "hide_description": True, "hide_sale_dates": False, "auto_hide": False, "payment_constraints": [] }, { "actual_cost": None, "actual_fee": None, "cost": None, "fee": None, "tax": None, "resource_uri": "https://www.eventbriteapi.com/v3/events/158717222485/ticket_classes/890890890/", "display_name": "Super Special Free Admission", "name": "Super Special Free Admission", "description": None, "sorting": 2, "donation": False, "free": True, "minimum_quantity": 1, "maximum_quantity": 1, "maximum_quantity_per_order": 1, "on_sale_status": "AVAILABLE", "has_pdf_ticket": True, "order_confirmation_message": None, "delivery_methods": [ "electronic" ], "category": "admission", "sales_channels": [ "online", "atd" ], "secondary_assignment_enabled": False, "event_id": "2222333332323232", "image_id": None, "id": "278648079", "capacity": 50, "quantity_total": 50, "quantity_sold": 0, "sales_start": "2021-06-02T04:00:00Z", "sales_end": "2021-09-03T19:00:00Z", "sales_end_relative": None, "hidden": True, "hidden_currently": True, "include_fee": False, "split_fee": False, "hide_description": True, "hide_sale_dates": False, "auto_hide": False, "payment_constraints": [] } ] } ticket_dict3 = { "pagination": { "object_count": 2, "continuation": None, "page_count": 1, "page_size": 50, "has_more_items": False, "page_number": 1 }, "ticket_classes": [ { "actual_cost": None, "actual_fee": { "display": "$7.72", "currency": "USD", "value": 772, "major_value": "7.72" }, "cost": { "display": "$100.00", "currency": "USD", "value": 10000, "major_value": "100.00" }, "fee": { "display": "$7.72", "currency": "USD", "value": 772, "major_value": "7.72" }, "tax": { "display": "$0.00", "currency": "USD", "value": 0, "major_value": "0.00" }, "resource_uri": "https://www.eventbriteapi.com/v3/events/158717222485/ticket_classes/098098098/", "display_name": "Regular Price", "name": "Regular Price", "description": None, "sorting": 1, "donation": False, "free": False, "minimum_quantity": 1, "maximum_quantity": 10, "maximum_quantity_per_order": 10, "on_sale_status": "AVAILABLE", "has_pdf_ticket": True, "order_confirmation_message": None, "delivery_methods": [ "electronic" ], "category": "admission", "sales_channels": [ "online", "atd" ], "secondary_assignment_enabled": False, "event_id": "44454545454545454", "image_id": None, "id": "278648077", "capacity": 300, "quantity_total": 300, "quantity_sold": 0, "sales_start": "2021-06-02T04:00:00Z", "sales_end": "2021-09-03T19:00:00Z", "sales_end_relative": None, "hidden": False, "hidden_currently": False, "include_fee": False, "split_fee": False, "hide_description": True, "hide_sale_dates": False, "auto_hide": False, "payment_constraints": [] }, { "actual_cost": None, "actual_fee": None, "cost": None, "fee": None, "tax": None, "resource_uri": "https://www.eventbriteapi.com/v3/events/158717222485/ticket_classes/987987987/", "display_name": "Super Special Free Admission", "name": "Super Special Free Admission", "description": None, "sorting": 2, "donation": False, "free": True, "minimum_quantity": 1, "maximum_quantity": 1, "maximum_quantity_per_order": 1, "on_sale_status": "AVAILABLE", "has_pdf_ticket": True, "order_confirmation_message": None, "delivery_methods": [ "electronic" ], "category": "admission", "sales_channels": [ "online", "atd" ], "secondary_assignment_enabled": False, "event_id": "44454545454545454", "image_id": None, "id": "278648079", "capacity": 50, "quantity_total": 50, "quantity_sold": 0, "sales_start": "2021-06-02T04:00:00Z", "sales_end": "2021-09-03T19:00:00Z", "sales_end_relative": None, "hidden": True, "hidden_currently": True, "include_fee": False, "split_fee": False, "hide_description": True, "hide_sale_dates": False, "auto_hide": False, "payment_constraints": [] } ] }
# sorting n=7 print(n) arr=[5,1,1,2,10,2,1] arr.sort() for i in arr: print(i,end=' ')
n = int(input()) for _ in range(n): (d, m) = map(int, input().split(' ')) days = list(map(int, input().split(' '))) day_of_week = 0 friday_13s = 0 for month in range(m): for day in range(1, days[month] + 1): if day_of_week == 5 and day == 13: friday_13s += 1 day_of_week = (day_of_week + 1) % 7 print(friday_13s)
class Solution(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'} letters = list(s) start, end = 0, len(letters) - 1 while start < end: while start < end and letters[start] not in vowels: start += 1 while start < end and letters[end] not in vowels: end -= 1 letters[start], letters[end] = letters[end], letters[start] start += 1 end -= 1 return ''.join(letters)
f = open("13.txt", "r") sum = 0 while (1): num = 0 line = f.readline() if line: line = line.strip('\n') for i in range(0, len(line)): num = num * 10 + int(line[i]) sum += num else: break ans = str(sum) for i in range(0, 10): print(ans[i], end = '')
def from_file(input, output, fasta, fai): """ Args: input - A 23andme data file, output - Output VCF file, fasta - An uncompressed reference genome GRCh37 fasta file fai - The fasta index for for the reference """ args = { 'input': input, 'output': output, 'fasta': fasta, 'fai': fai } fai = __load_fai__(args) snps = __load_23andme_data__(args.input) records = __get_vcf_records__(snps, fai, args) __write_vcf__(args.output, records) def __load_fai__(args): index = {} with open(args.fai) as f: for line in f: toks = line.split('\t') chrom = 'chr' + toks[0] if chrom == 'chrMT': chrom = 'chrM' length = int(toks[1]) start = int(toks[2]) linebases = int(toks[3]) linewidth = int(toks[4]) index[chrom] = (start, length, linebases, linewidth) return index def __get_vcf_records__(pos_list, fai, args): with open(args.fasta) as f: def get_alts(ref, genotype): for x in genotype: assert x in 'ACGT' if len(genotype) == 1: if ref in genotype: return [] return [genotype] if ref == genotype[0] and ref == genotype[1]: return [] if ref == genotype[0]: return [genotype[1]] if ref == genotype[1]: return [genotype[0]] return [genotype[0], genotype[1]] for (rsid, chrom, pos, genotype) in pos_list: start, _, linebases, linewidth = fai[chrom] n_lines = int(pos / linebases) n_bases = pos % linebases n_bytes = start + n_lines * linewidth + n_bases f.seek(n_bytes) ref = f.read(1) alts = get_alts(ref, genotype) pos = str(pos + 1) diploid = len(genotype) == 2 assert ref not in alts assert len(alts) <= 2 if diploid: if len(alts) == 2: if alts[0] == alts[1]: yield (chrom, pos, rsid, ref, alts[0], '.', '.', '.', 'GT', '1/1') else: yield (chrom, pos, rsid, ref, alts[0], '.', '.', '.', 'GT', '1/2') yield (chrom, pos, rsid, ref, alts[1], '.', '.', '.', 'GT', '2/1') elif len(alts) == 1: yield (chrom, pos, rsid, ref, alts[0], '.', '.', '.', 'GT', '0/1') elif len(alts) == 1: yield (chrom, pos, rsid, ref, alts[0], '.', '.', '.', 'GT', '1') def __load_23andme_data__(input): with open(input) as f: for line in f: if line.startswith('#'): continue if line.strip(): rsid, chrom, pos, genotype = line.strip().split('\t') if chrom == 'MT': chrom = 'M' chrom = 'chr' + chrom if genotype != '--': skip = False for x in genotype: if x not in 'ACTG': skip = True if not skip: yield rsid, chrom, int(pos) - 1, genotype # subtract one because positions are 1-based indices def __write_vcf_header__(f): f.write( """##fileformat=VCFv4.2 ##source=23andme_to_vcf ##reference=GRCh37 ##FORMAT=<ID=GT,Number=1,Type=String,Description="Genotype"> #CHROM POS ID REF ALT QUAL FILTER INFO FORMAT SAMPLE """) def __write_vcf__(outfile, records): with open(outfile, 'w') as f: __write_vcf_header__(f) for record in records: f.write('\t'.join(record) + '\n')
#!/usr/bin/env python3 def string_to_max_list(s): """Given an input string, convert it to a descendant list of numbers from the length of the string down to 0""" out_list = list(range(len(s) - 1, -1, -1)) return out_list def string_to_min_list(s): out_list = list(range(len(s))) out_list[0], out_list[1] = out_list[1], out_list[0] return out_list def list_to_base10_int(in_list): my_int = 0 base = len(in_list) exp = base - 1 for item in in_list: my_int += item*base**exp exp -= 1 return my_int def main(): t = int(input()) for i in range(1, t + 1): s = input() my_max_int = list_to_base10_int(string_to_max_list(s)) my_min_int = list_to_base10_int(string_to_min_list(s)) my_diff = my_max_int - my_min_int print("Case #{}: {}".format(i, my_diff)) if __name__ == "__main__": main()
def getNewAddress(): pass def pushRawP2PKHTxn(): pass def pushRawP2SHTxn(): pass def pushRawBareP2WPKHTxn(): pass def pushRawBareP2WSHTxn(): pass def pushRawP2SH_P2WPKHTxn(): pass def pushRawP2SH_P2WSHTxn(): pass def getSignedTxn(): pass
def nextPermutation(nums: list[int]) -> None: """ Do not return anything, modify nums in-place instead. """ def reverse(nums, left, right): while left < right: nums[left], nums[right] = nums[right], nums[left] left += 1 right -= 1 if not nums: return a = None for i in range(len(nums) - 2, -1, -1): if nums[i] < nums[i + 1]: a = i break if a is None: reverse(nums, 0, len(nums) - 1) return b = None for i in range(len(nums) - 1, a, -1): if nums[a] < nums[i]: b = i break nums[a], nums[b] = nums[b], nums[a] reverse(nums, a+1, len(nums) - 1)
""" Mercedes Me APIs Author: G. Ravera For more details about this component, please refer to the documentation at https://github.com/xraver/mercedes_me_api/ """ # Software Name & Version NAME = "Mercedes Me API" DOMAIN = "mercedesmeapi" VERSION = "0.8" # Software Parameters TOKEN_FILE = ".mercedesme_token" CREDENTIALS_FILE = ".mercedesme_credentials" RESOURCES_FILE = ".mercedesme_resources" # Mercedes me Application Parameters REDIRECT_URL = "https://localhost" SCOPE = "mb:vehicle:mbdata:fuelstatus%20mb:vehicle:mbdata:vehiclestatus%20mb:vehicle:mbdata:vehiclelock%20mb:vehicle:mbdata:evstatus%20offline_access" URL_RES_PREFIX = "https://api.mercedes-benz.com/vehicledata/v2" # File Parameters CONF_CLIENT_ID = "CLIENT_ID" CONF_CLIENT_SECRET = "CLIENT_SECRET" CONF_VEHICLE_ID = "VEHICLE_ID"
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2019-12-29 15:17 albert_models_google = { 'albert_base_zh': 'https://storage.googleapis.com/albert_models/albert_base_zh.tar.gz', 'albert_large_zh': 'https://storage.googleapis.com/albert_models/albert_large_zh.tar.gz', 'albert_xlarge_zh': 'https://storage.googleapis.com/albert_models/albert_xlarge_zh.tar.gz', 'albert_xxlarge_zh': 'https://storage.googleapis.com/albert_models/albert_xxlarge_zh.tar.gz', }
# -*- coding:utf-8; -*- class Solution: """思路:关键是理解高位设置以后,其后的数字应该排列为最小的数值这一点。 1. 倒序寻找第一个破坏升序的数nums[pos]。为什么这样查找,因为最大的那个数字排序肯定是倒序的。时间复杂度O(n),例如 [2,4,3,1] 中2 破坏了升序。 2. 然后在遍历过的数里寻找第一个比nums[pos]大数字nums[i],时间复杂度O(n),该数字是3。 3. 交换nums[pos]和nums[i],这里交换2和3,新序列是[3,4,2,1] 4. 将pos后面的数字改为升序,这是因为高位重新设置后,其后的数字应该排列成最小的数值。 """ def nextPermutation(self, nums): pos = len(nums) - 1 while pos > 0 and nums[pos - 1] >= nums[pos]: pos -= 1 if pos > 0: i = len(nums) - 1 while i > pos - 1 and nums[i] <= nums[pos - 1]: i -= 1 nums[pos - 1], nums[i] = nums[i], nums[pos - 1] i = pos j = len(nums) - 1 while i < j: nums[i], nums[j] = nums[j], nums[i] i += 1 j -= 1 if __name__ == "__main__": nums = [5, 1, 1] s = Solution() s.nextPermutation(nums) print(nums)
class Solution(object): def getMoneyAmount(self, n): """ :type n: int :rtype: int """ cache = [[0] * (n + 1) for _ in xrange(n + 1)] def dc(cache, start, end): if start >= end: return 0 if cache[start][end] != 0: return cache[start][end] minV = float("inf") for i in range(start, end + 1): left = dc(cache, start, i - 1) right = dc(cache, i + 1, end) minV = min(minV, max(left, right) + i) if minV != float("inf"): cache[start][end] = minV return cache[start][end] dc(cache, 1, n) return cache[1][n]
AWR_CONFIGS = { "Ant-v2": { "actor_net_layers": [128, 64], "actor_stepsize": 0.00005, "actor_momentum": 0.9, "actor_init_output_scale": 0.01, "actor_batch_size": 256, "actor_steps": 1000, "action_std": 0.2, "critic_net_layers": [128, 64], "critic_stepsize": 0.01, "critic_momentum": 0.9, "critic_batch_size": 256, "critic_steps": 200, "discount": 0.99, "samples_per_iter": 2048, "replay_buffer_size": 50000, "normalizer_samples": 300000, "weight_clip": 20, "td_lambda": 0.95, "temp": 1.0, }, "HalfCheetah-v2": { "actor_net_layers": [128, 64], "actor_stepsize": 0.00005, "actor_momentum": 0.9, "actor_init_output_scale": 0.01, "actor_batch_size": 256, "actor_steps": 1000, "action_std": 0.4, "critic_net_layers": [128, 64], "critic_stepsize": 0.01, "critic_momentum": 0.9, "critic_batch_size": 256, "critic_steps": 200, "discount": 0.99, "samples_per_iter": 2048, "replay_buffer_size": 50000, "normalizer_samples": 300000, "weight_clip": 20, "td_lambda": 0.95, "temp": 1.0, }, "Hopper-v2": { "actor_net_layers": [128, 64], "actor_stepsize": 0.0001, "actor_momentum": 0.9, "actor_init_output_scale": 0.01, "actor_batch_size": 256, "actor_steps": 1000, "action_std": 0.4, "critic_net_layers": [128, 64], "critic_stepsize": 0.01, "critic_momentum": 0.9, "critic_batch_size": 256, "critic_steps": 200, "discount": 0.99, "samples_per_iter": 2048, "replay_buffer_size": 50000, "normalizer_samples": 300000, "weight_clip": 20, "td_lambda": 0.95, "temp": 1.0, }, "Humanoid-v2": { "actor_net_layers": [128, 64], "actor_stepsize": 0.00001, "actor_momentum": 0.9, "actor_init_output_scale": 0.01, "actor_batch_size": 256, "actor_steps": 1000, "action_std": 0.4, "critic_net_layers": [128, 64], "critic_stepsize": 0.01, "critic_momentum": 0.9, "critic_batch_size": 256, "critic_steps": 200, "discount": 0.99, "samples_per_iter": 2048, "replay_buffer_size": 50000, "normalizer_samples": 300000, "weight_clip": 20, "td_lambda": 0.95, "temp": 1.0, }, "LunarLander-v2": { "actor_net_layers": [128, 64], "actor_stepsize": 0.0005, "actor_momentum": 0.9, "actor_init_output_scale": 0.01, "actor_batch_size": 256, "actor_steps": 1000, "action_l2_weight": 0.001, "critic_net_layers": [128, 64], "critic_stepsize": 0.01, "critic_momentum": 0.9, "critic_batch_size": 256, "critic_steps": 200, "discount": 0.99, "samples_per_iter": 2048, "replay_buffer_size": 50000, "normalizer_samples": 100000, "weight_clip": 20, "td_lambda": 0.95, "temp": 1.0, }, "LunarLanderContinuous-v2": { "actor_net_layers": [128, 64], "actor_stepsize": 0.0001, "actor_momentum": 0.9, "actor_init_output_scale": 0.01, "actor_batch_size": 256, "actor_steps": 1000, "action_std": 0.2, "critic_net_layers": [128, 64], "critic_stepsize": 0.01, "critic_momentum": 0.9, "critic_batch_size": 256, "critic_steps": 200, "discount": 0.99, "samples_per_iter": 2048, "replay_buffer_size": 50000, "normalizer_samples": 300000, "weight_clip": 20, "td_lambda": 0.95, "temp": 1.0, }, "Reacher-v2": { "actor_net_layers": [128, 64], "actor_stepsize": 0.0001, "actor_momentum": 0.9, "actor_init_output_scale": 0.01, "actor_batch_size": 256, "actor_steps": 1000, "action_std": 0.2, "critic_net_layers": [128, 64], "critic_stepsize": 0.01, "critic_momentum": 0.9, "critic_batch_size": 256, "critic_steps": 200, "discount": 0.99, "samples_per_iter": 2048, "replay_buffer_size": 50000, "normalizer_samples": 300000, "weight_clip": 20, "td_lambda": 0.95, "temp": 1.0, }, "Walker2d-v2": { "actor_net_layers": [128, 64], "actor_stepsize": 0.000025, "actor_momentum": 0.9, "actor_init_output_scale": 0.01, "actor_batch_size": 256, "actor_steps": 1000, "action_std": 0.4, "critic_net_layers": [128, 64], "critic_stepsize": 0.01, "critic_momentum": 0.9, "critic_batch_size": 256, "critic_steps": 200, "discount": 0.99, "samples_per_iter": 2048, "replay_buffer_size": 50000, "normalizer_samples": 300000, "weight_clip": 20, "td_lambda": 0.95, "temp": 1.0, } }
""" Custom exceptions for runpandas """ class InvalidFileError(Exception): def __init__(self, msg): message = "It doesn't like a valid %s file!" % (msg) super().__init__(message) class RequiredColumnError(Exception): def __init__(self, column, cls=None): if cls is None: message = "{!r} column not found".format(column) else: message = "{!r} column should be of type {!s}".format(column, cls) super().__init__(message)
#!/usr/bin/python # -*- coding:utf-8 -*- __author__ = 'exchris' """ 204.计数质数 统计所以小于非负整数n的质数的数量 输入:10 输出: 4 解释:小于10的质数一共有4个,它们是2,3,5,7 """ class Solution: def countPrimes(self, n): if n < 3: return 0 prime = [1] * n prime[0] = prime[1] = 0 for i in range(2, int(n ** 0.5) + 1): if prime[i] == 1: prime[i * i:n:i] = [0] * len(prime[i * i:n:i]) return sum(prime) def countPrimes1(self, n): flag, sum = False, 0 for i in range(2, n): for j in range(2, int(i**0.5)+1): if i % j == 0: flag = True break if flag == 0: print(i) sum += 1 else: flag = False print(sum) s = Solution() s1 = s.countPrimes1(10) print(s1)
# 给定两个字符串 text1 和 text2,返回这两个字符串的最长公共子序列。 # # 一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。 # 例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。两个字符串的「公共子序列」是这两个字符串所共同拥有的子序列。 # # 若这两个字符串没有公共子序列,则返回 0。 # #   # # 示例 1: # # 输入:text1 = "abcde", text2 = "ace" # 输出:3 # 解释:最长公共子序列是 "ace",它的长度为 3。 # 示例 2: # # 输入:text1 = "abc", text2 = "abc" # 输出:3 # 解释:最长公共子序列是 "abc",它的长度为 3。 # 示例 3: # # 输入:text1 = "abc", text2 = "def" # 输出:0 # 解释:两个字符串没有公共子序列,返回 0。 #   # # 提示: # # 1 <= text1.length <= 1000 # 1 <= text2.length <= 1000 # 输入的字符串只含有小写英文字符。 # # 来源:力扣(LeetCode) # 链接:https://leetcode-cn.com/problems/longest-common-subsequence # 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: m = len(text1) n = len(text2) if m == 0 or n == 0: return 0 dp = [[0] * n for _ in range(m)] for i in range(m): for j in range(n): if text1[i] == text2[j]: dp[i][j] = (dp[i - 1][j - 1] + 1) if i > 0 and j > 0 else 1 else: dp[i][j] = max(dp[i - 1][j] if i > 0 else 0, dp[i][j - 1] if j > 0 else 0) return max(dp[-1]) if __name__ == '__main__': s = Solution() assert s.longestCommonSubsequence("abcde", "ace") == 3 assert s.longestCommonSubsequence("abc", "abc") == 3 assert s.longestCommonSubsequence("abc", "def") == 0 assert s.longestCommonSubsequence("abcef", "adef") == 3
class MonoMacPackage (Package): def __init__ (self): self.pkgconfig_version = '1.0' self.maccore_tag = '0b71453' self.maccore_source_dir_name = 'mono-maccore-0b71453' self.monomac_tag = 'ae428c7' self.monomac_source_dir_name = 'mono-monomac-ae428c7' Package.__init__ (self, 'monomac', self.monomac_tag) self.sources = [ 'https://github.com/mono/maccore/tarball/%{maccore_tag}', 'https://github.com/mono/monomac/tarball/%{monomac_tag}' ] def prep (self): self.sh ('tar xf "%{sources[0]}"') self.sh ('tar xf "%{sources[1]}"') self.sh ('mv %{maccore_source_dir_name} maccore') self.sh ('mv %{monomac_source_dir_name} monomac') self.cd ('monomac/src') def build (self): self.sh ('make') def install (self): self.sh ('mkdir -p %{prefix}/lib/monomac') self.sh ('mkdir -p %{prefix}/share/pkgconfig') self.sh ('echo "Libraries=%{prefix}/lib/monomac/MonoMac.dll\n\nName: MonoMac\nDescription: Mono Mac bindings\nVersion:%{pkgconfig_version}\nLibs: -r:%{prefix}/lib/monomac/MonoMac.dll" > %{prefix}/share/pkgconfig/monomac.pc') self.sh ('cp MonoMac.dll %{prefix}/lib/monomac') MonoMacPackage ()
# flake8: noqa # Disable all security c.NotebookApp.token = "" c.NotebookApp.password = "" c.NotebookApp.open_browser = True c.NotebookApp.ip = "localhost"
"""STATES""" ON = "ON" OFF = "OFF"
"""Message type identifiers for Connections.""" MESSAGE_FAMILY = "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/credential-issuance/0.1" CREDENTIAL_OFFER = f"{MESSAGE_FAMILY}/credential-offer" CREDENTIAL_REQUEST = f"{MESSAGE_FAMILY}/credential-request" CREDENTIAL_ISSUE = f"{MESSAGE_FAMILY}/credential-issue" MESSAGE_TYPES = { CREDENTIAL_OFFER: ( "aries_cloudagent.messaging.credentials.messages." + "credential_offer.CredentialOffer" ), CREDENTIAL_REQUEST: ( "aries_cloudagent.messaging.credentials.messages." + "credential_request.CredentialRequest" ), CREDENTIAL_ISSUE: ( "aries_cloudagent.messaging.credentials.messages." + "credential_issue.CredentialIssue" ), }
# -*- coding: utf-8 -*- def comp_mass_magnets(self): """Compute the mass of the hole magnets Parameters ---------- self : HoleM50 A HoleM50 object Returns ------- Mmag: float mass of the 2 Magnets [kg] """ M = 0 # magnet_0 and magnet_1 can have different materials if self.magnet_0: M += self.H3 * self.W4 * self.magnet_0.Lmag * self.magnet_0.mat_type.struct.rho if self.magnet_1: M += self.H3 * self.W4 * self.magnet_1.Lmag * self.magnet_1.mat_type.struct.rho return M
A, B = map(int, input().split()) if A > 8 or B > 8: print(":(") else: print("Yay!")
class PointObject(RhinoObject): # no doc def DuplicatePointGeometry(self): """ DuplicatePointGeometry(self: PointObject) -> Point """ pass PointGeometry = property( lambda self: object(), lambda self, v: None, lambda self: None ) """Get: PointGeometry(self: PointObject) -> Point """
playlist_list = [['MIT 8.01SC Classical Mechanics, Fall 2016', 'https://www.youtube.com/playlist?list=PLUl4u3cNGP61qDex7XslwNJ-xxxEFzMNV'], ['How We Teach MIT 8.13-14 Experimental Physics I & II “Junior Lab”, Fall 2016 - Spring 2017','https://www.youtube.com/playlist?list=PLUl4u3cNGP6393Jj6WMmNd1_pOs0UDq2R'], ['MIT 18.06SC Linear Algebra, Fall 2011','https://www.youtube.com/playlist?list=PL221E2BBF13BECF6C'], ['MIT 8.03SC Physics III Vibrations and Waves, Fall 2016','https://www.youtube.com/playlist?list=PLUl4u3cNGP61R5sPDPKVfcFlu95wSs2Kx'], ['MIT 6.S095 Programming for the Puzzled, January IAP 2018','https://www.youtube.com/playlist?list=PLUl4u3cNGP62QumaaZtCCjkID-NgqrleA'], ['MIT RES.6-012 Introduction to Probability, Spring 2018','https://www.youtube.com/playlist?list=PLUl4u3cNGP60hI9ATjSFgLZpbNJ7myAg6'], ['MIT RES.9-003 Brains, Minds and Machines Summer Course, Summer 2015','https://www.youtube.com/playlist?list=PLUl4u3cNGP61RTZrT3MIAikp2G5EEvTjf'], ['MIT 18.650 Statistics for Applications, Fall 2016','https://www.youtube.com/playlist?list=PLUl4u3cNGP60uVBMaoNERc6knT_MgPKS0'], ['MIT RES.3-003 Learn to Build Your Own Videogame with the Unity Game Engine and Microsoft Kinect, IAP 2017','https://www.youtube.com/playlist?list=PLUl4u3cNGP60ZaGv5SgpIk67YnH1WqCLI'], ['MIT 6.0002 Introduction to Computational Thinking and Data Science, Fall 2016','https://www.youtube.com/playlist?list=PLUl4u3cNGP619EG1wp0kT-7rDE_Az5TNd'], ['MIT 8.334 Statistical Mechanics II, Spring 2014','https://www.youtube.com/playlist?list=PLUl4u3cNGP63HkEHvYaNJiO0UCUmY0Ts7'], ['6.0001 Introduction to Computer Science and Programming in Python. Fall 2016','https://www.youtube.com/playlist?list=PLUl4u3cNGP63WbdFxL8giv4yhgdMGaZNA'], ['MIT Learn Differential Equations','https://www.youtube.com/playlist?list=PLUl4u3cNGP63oTpyxCMLKt_JmB0WtSZfG'], ['MIT 6.034 Artificial Intelligence, Fall 2010','https://www.youtube.com/playlist?list=PLUl4u3cNGP63gFHB6xb-kVBiQHYe_4hSi'], ['MIT 8.821 String Theory and Holographic Duality, Fall 2014','https://www.youtube.com/playlist?list=PLUl4u3cNGP633VWvZh23bP6dG80gW34SU'], ['MIT 8.333 Statistical Mechanics I Statistical Mechanics of Particles, Fall 2013','https://www.youtube.com/playlist?list=PLUl4u3cNGP60gl3fdUTKRrt5t_GPx2sRg'], ['MIT 22.15 Essential Numerical Methods, Fall 2014','https://www.youtube.com/playlist?list=PLUl4u3cNGP63_OOz8w5qDEoqErZ8Hj-fc'], ['MIT 8.421 Atomic and Optical Physics I, Spring 2014','https://www.youtube.com/playlist?list=PLUl4u3cNGP62FPGcyFJkzhqq9c5cHCK32'], ['MIT 2.087 Engineering Mathematics: Linear Algebra and ODEs, Fall 2014','https://www.youtube.com/playlist?list=PLUl4u3cNGP63w3DE9izYp_3fpAdi0Wkga'], ['MIT 8.422 Atomic and Optical Physics II, Spring 2013','https://www.youtube.com/playlist?list=PLUl4u3cNGP62uOSArqLf4vNLiZtgIRm1K'], ['MIT 8.05 Quantum Physics II, Fall 2013','https://www.youtube.com/playlist?list=PLUl4u3cNGP60QlYNsy52fctVBOlk-4lYx'], ['MIT 8.286 The Early Universe, Fall 2013','https://www.youtube.com/playlist?list=PLUl4u3cNGP61Bf9I0WDDriuDqEnywoxra'], ['MIT 6.851 Advanced Data Structures, Spring 2012','https://www.youtube.com/playlist?list=PLUl4u3cNGP61hsJNdULdudlRL493b-XZf'], ['MIT 6.006 Introduction to Algorithms, Fall 2011','https://www.youtube.com/playlist?list=PLUl4u3cNGP61Oq3tWYp6V_F-5jb5L2iHb'], ['MIT 18.03 Differential Equations, Spring 2006','https://www.youtube.com/playlist?list=PLEC88901EBADDD980'], ['MIT 18.03SC Differential Equations, Fall 2011','https://www.youtube.com/playlist?list=PL64BDFBDA2AF24F7E'], ['MIT 18.S997 Introduction to MATLAB Programming Fall 2011','https://www.youtube.com/playlist?list=PLUl4u3cNGP62bMZx9A3DR7V5myByt48CC'], ['6.041 Probabilistic Systems Analysis and Applied Probability','https://www.youtube.com/playlist?list=PLUl4u3cNGP61MdtwGTqZA0MreSaDybji8'], ['MIT 6.262 Discrete Stochastic Processes, Spring 2011','https://www.youtube.com/playlist?list=PLEEF5322B331C1B98'], ['MIT RES.6-006 Video Demonstrations in Lasers and Optics','https://www.youtube.com/playlist?list=PL4E7FAAD67B171EBC'], ['MIT RES.6.007 Signals and Systems, 1987','https://www.youtube.com/playlist?list=PL41692B571DD0AF9B'], ['Highlights of Calculus','https://www.youtube.com/playlist?list=PLBE9407EA64E2C318'], ['MIT Calculus Revisited Multivariable Calculus','https://www.youtube.com/playlist?list=PL1C22D4DED943EF7B'], ['MIT Calculus Revisited Calculus of Complex Variables','https://www.youtube.com/playlist?list=PLD971E94905A70448'], ['MIT 6.042J Mathematics for Computer Science, Fall 2010','https://www.youtube.com/playlist?list=PLB7540DEDD482705B'], ['MIT 6.00SC Introduction to Computer Science and Programming','https://www.youtube.com/playlist?list=PLB2BE3D6CA77BB8F7'], ['MIT Calculus Revisited Single Variable Calculus','https://www.youtube.com/playlist?list=PL3B08AE665AB9002A'], ['MIT RES.6-008 Digital Signal Processing, 1975','https://www.youtube.com/playlist?list=PL8157CA8884571BA2'], ['MIT 18.085 Computational Science & Engineering I, Fall 2008','https://www.youtube.com/playlist?list=PLF706B428FB7BD52C'], ['MIT Linear Finite Element Analysis','https://www.youtube.com/playlist?list=PLD4017FC423EC3EB5'], ['MIT Understanding Lasers and Fiberoptics','https://www.youtube.com/playlist?list=PL6F914D0CF944737A'], ['MIT 2.71 Optics, Spring 2009','https://www.youtube.com/playlist?list=PLEA084AC2DD3CEC09'], ['MIT 3.60 Symmetry, Structure & Tensor Properties of Material','https://www.youtube.com/playlist?list=PL7E7E396BF006E209'], ['MIT 6.172 Performance Engineering of Software Systems','https://www.youtube.com/playlist?list=PLD2AE32F507F10481'], ['MIT Nonlinear Finite Element Analysis','https://www.youtube.com/playlist?list=PL75C727EA9F6A0E8B'], ['MIT 5.80 Small-Molecule Spectroscopy and Dynamics, Fall 2008','https://www.youtube.com/playlist?list=PL683876BE6097A1C2'], ['MIT 16.01 Unified Engineering, Fall 2005','https://www.youtube.com/playlist?list=PLA481C3DD60812502'], ['MIT 6.046J / 18.410J Introduction to Algorithms (SMA 5503)','https://www.youtube.com/playlist?list=PL8B24C31197EC371C'], ['MIT 18.01 Single Variable Calculus, Fall 2006','https://www.youtube.com/playlist?list=PL590CCC2BC5AF3BC1'], ['MIT 18.02 Multivariable Calculus, Fall 2007','https://www.youtube.com/playlist?list=PL4C4C8A7D06566F38'], ['MIT 6.00 Intro to Computer Science & Programming, Fall 2008','https://www.youtube.com/playlist?list=PL4C4720A6F225E074'], ['MIT 6.002 Circuits and Electronics, Spring 2007','https://www.youtube.com/playlist?list=PL9F74AFA03AA06A11'], ['MIT 5.60 Thermodynamics & Kinetics, Spring 2008','https://www.youtube.com/playlist?list=PLA62087102CC93765'], ['MIT Exploring Black Holes General Relativity & Astrophysics','https://www.youtube.com/playlist?list=PL858478F1EC364A2C'], ['MIT 5.74 Introductory Quantum Mechanics II, Spring 2009','https://www.youtube.com/playlist?list=PL21D8ADED13B2D74C'], ['MIT 6.832 Underactuated Robotics, Spring 2009','https://www.youtube.com/playlist?list=PL58F1D0056F04CF8C'], ['MIT 3.320 Atomistic Computer Modeling of Materials','https://www.youtube.com/playlist?list=PL13CB8C2EDA4453ED'], ['MIT 16.885J Aircraft Systems Engineering, Fall 2005','https://www.youtube.com/playlist?list=PL35721A60B7B57386'], ['MIT 6.033 Computer System Engineering, Spring 2005','https://www.youtube.com/playlist?list=PL6535748F59DCA484'], ['MIT 18.085 Computational Science & Engineering I, Fall 2007','https://www.youtube.com/playlist?list=PL51CACD5B1F58C40C'], ['MIT 6.013 Electromagnetics and Applications, Fall 2005','https://www.youtube.com/playlist?list=PL502E7BF2CF94D753'], ['MIT 5.74 Introductory Quantum Mechanics II, Spring 2004','https://www.youtube.com/playlist?list=PL958F66FFE4393435']]