content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Goals: """Represents scenario goals Attributes: conquest (int): 1 conquest unknown1 (int): unknown relics (int): number of relics required unknown2 (int): unknown exploration (int): map exploratino required in % all (int): all conditions mode (int): ? score (int): number of score required time (int): time required (100 = 10yr) """ def __init__(self, conquest=0, unknown1=0, relics=0, unknown2=0, exploration=0, unknown3=0, all=0, mode=0, score=0, time=0): """Initialize scenario goals Args: conquest (int): 1 conquest unknown1 (int): unknown relics (int): number of relics required unknown2 (int): unknown exploration (int): map exploratino required in % all (int): all conditions mode (int): ? score (int): number of score required time (int): time required (100 = 10yr) Todo: describe mode param """ self.conquest = conquest self.unknown1 = unknown2 self.relics = relics self.unknown2 = unknown2 self.exploration = exploration self.unknown3 = unknown3 self.all = all self.mode = mode self.score = score self.time = time def __repr__(self): name = "Goals: \n" part1 = "\tConquest: {}\n\tRelics: {}\n".format( self.conquest, self.relics) part2 = "\tExploration: {}\n\tAllModes: {}\n".format( self.exploration, self.all) part3 = "\tCustomMode: {}\n\tScore: {}\n".format(self.mode, self.time) part4 = "\tTime: {}\n".format(self.time) return name + part1 + part2 + part3 + part4
class Goals: """Represents scenario goals Attributes: conquest (int): 1 conquest unknown1 (int): unknown relics (int): number of relics required unknown2 (int): unknown exploration (int): map exploratino required in % all (int): all conditions mode (int): ? score (int): number of score required time (int): time required (100 = 10yr) """ def __init__(self, conquest=0, unknown1=0, relics=0, unknown2=0, exploration=0, unknown3=0, all=0, mode=0, score=0, time=0): """Initialize scenario goals Args: conquest (int): 1 conquest unknown1 (int): unknown relics (int): number of relics required unknown2 (int): unknown exploration (int): map exploratino required in % all (int): all conditions mode (int): ? score (int): number of score required time (int): time required (100 = 10yr) Todo: describe mode param """ self.conquest = conquest self.unknown1 = unknown2 self.relics = relics self.unknown2 = unknown2 self.exploration = exploration self.unknown3 = unknown3 self.all = all self.mode = mode self.score = score self.time = time def __repr__(self): name = 'Goals: \n' part1 = '\tConquest: {}\n\tRelics: {}\n'.format(self.conquest, self.relics) part2 = '\tExploration: {}\n\tAllModes: {}\n'.format(self.exploration, self.all) part3 = '\tCustomMode: {}\n\tScore: {}\n'.format(self.mode, self.time) part4 = '\tTime: {}\n'.format(self.time) return name + part1 + part2 + part3 + part4
def findLargest(l): lo , hi = 0 , len(l) left , right = l[0] , l[-1] while(lo<hi): mid = (lo + hi)//2 if(left > l[mid]): hi = mid else: lo = mid +1 return l[lo-1]
def find_largest(l): (lo, hi) = (0, len(l)) (left, right) = (l[0], l[-1]) while lo < hi: mid = (lo + hi) // 2 if left > l[mid]: hi = mid else: lo = mid + 1 return l[lo - 1]
def rule(event): # Only check actions creating a new Network ACL entry if event['eventName'] != 'CreateNetworkAclEntry': return False # Check if this new NACL entry is allowing traffic from anywhere return (event['requestParameters']['cidrBlock'] == '0.0.0.0/0' and event['requestParameters']['ruleAction'] == 'allow' and event['requestParameters']['egress'] is False)
def rule(event): if event['eventName'] != 'CreateNetworkAclEntry': return False return event['requestParameters']['cidrBlock'] == '0.0.0.0/0' and event['requestParameters']['ruleAction'] == 'allow' and (event['requestParameters']['egress'] is False)
_base_ = [ './coco_data_pipeline.py' ] model = dict( type='MaskRCNN', backbone=dict( type='efficientnet_b2b', out_indices=(2, 3, 4, 5), frozen_stages=-1, pretrained=True, activation_cfg=dict(type='torch_swish'), norm_cfg=dict(type='BN', requires_grad=True)), neck=dict( type='FPN', in_channels=[24, 48, 120, 352], out_channels=80, num_outs=5), rpn_head=dict( type='RPNHead', in_channels=80, feat_channels=80, anchor_generator=dict( type='AnchorGenerator', scales=[8], ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64]), bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0.0, 0.0, 0.0, 0.0], target_stds=[1.0, 1.0, 1.0, 1.0]), loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), loss_bbox=dict(type='L1Loss', loss_weight=1.0)), roi_head=dict( type='StandardRoIHead', bbox_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0), out_channels=80, featmap_strides=[4, 8, 16, 32]), bbox_head=dict( type='Shared2FCBBoxHead', in_channels=80, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict( type='DeltaXYWHBBoxCoder', target_means=[0.0, 0.0, 0.0, 0.0], target_stds=[0.1, 0.1, 0.2, 0.2]), reg_class_agnostic=False, loss_cls=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='L1Loss', loss_weight=1.0)), mask_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=0), out_channels=80, featmap_strides=[4, 8, 16, 32]), mask_head=dict( type='FCNMaskHead', num_convs=4, in_channels=80, conv_out_channels=80, num_classes=80, loss_mask=dict( type='CrossEntropyLoss', use_mask=True, loss_weight=1.0))), train_cfg=dict( rpn=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.3, min_pos_iou=0.3, match_low_quality=True, ignore_iof_thr=-1, gpu_assign_thr=300), sampler=dict( type='RandomSampler', num=256, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=False), allowed_border=-1, pos_weight=-1, debug=False), rpn_proposal=dict( nms_across_levels=False, nms_pre=2000, nms_post=1000, max_num=1000, nms_thr=0.8, min_bbox_size=0), rcnn=dict( assigner=dict( type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.5, min_pos_iou=0.5, match_low_quality=True, ignore_iof_thr=-1, gpu_assign_thr=300), sampler=dict( type='RandomSampler', num=256, pos_fraction=0.25, neg_pos_ub=-1, add_gt_as_proposals=True), mask_size=28, pos_weight=-1, debug=False)), test_cfg=dict( rpn=dict( nms_across_levels=False, nms_pre=800, nms_post=500, max_num=500, nms_thr=0.8, min_bbox_size=0), rcnn=dict( score_thr=0.05, nms=dict(type='nms', iou_threshold=0.7), max_per_img=500, mask_thr_binary=0.5))) cudnn_benchmark = True evaluation = dict(interval=1, metric='mAP', save_best='mAP', iou_thr=[0.5 , 0.55, 0.6 , 0.65, 0.7 , 0.75, 0.8 , 0.85, 0.9, 0.95]) optimizer = dict(type='SGD', lr=0.015, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=None) lr_config = dict( policy='ReduceLROnPlateau', metric='mAP', patience=5, iteration_patience=300, interval=1, min_lr=0.000001, warmup='linear', warmup_iters=200, warmup_ratio=0.3333333333333333 ) runner = dict(type='EpochRunnerWithCancel', max_epochs=300) checkpoint_config = dict(interval=5) log_config = dict( interval=1, hooks=[ dict(type='TextLoggerHook'), # dict(type='TensorboardLoggerHook'), ]) dist_params = dict(backend='nccl') log_level = 'INFO' load_from = 'https://storage.openvinotoolkit.org/repositories/openvino_training_extensions/models/instance_segmentation/v2/efficientnet_b2b-mask_rcnn-576x576.pth' resume_from = None workflow = [('train', 1)] work_dir = 'output' custom_hooks = [ dict(type='EarlyStoppingHook', patience=10, metric='mAP', interval=1, priority=75, iteration_patience=0), ] fp16 = dict(loss_scale=512.)
_base_ = ['./coco_data_pipeline.py'] model = dict(type='MaskRCNN', backbone=dict(type='efficientnet_b2b', out_indices=(2, 3, 4, 5), frozen_stages=-1, pretrained=True, activation_cfg=dict(type='torch_swish'), norm_cfg=dict(type='BN', requires_grad=True)), neck=dict(type='FPN', in_channels=[24, 48, 120, 352], out_channels=80, num_outs=5), rpn_head=dict(type='RPNHead', in_channels=80, feat_channels=80, anchor_generator=dict(type='AnchorGenerator', scales=[8], ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64]), bbox_coder=dict(type='DeltaXYWHBBoxCoder', target_means=[0.0, 0.0, 0.0, 0.0], target_stds=[1.0, 1.0, 1.0, 1.0]), loss_cls=dict(type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0), loss_bbox=dict(type='L1Loss', loss_weight=1.0)), roi_head=dict(type='StandardRoIHead', bbox_roi_extractor=dict(type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0), out_channels=80, featmap_strides=[4, 8, 16, 32]), bbox_head=dict(type='Shared2FCBBoxHead', in_channels=80, fc_out_channels=1024, roi_feat_size=7, num_classes=80, bbox_coder=dict(type='DeltaXYWHBBoxCoder', target_means=[0.0, 0.0, 0.0, 0.0], target_stds=[0.1, 0.1, 0.2, 0.2]), reg_class_agnostic=False, loss_cls=dict(type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0), loss_bbox=dict(type='L1Loss', loss_weight=1.0)), mask_roi_extractor=dict(type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=14, sampling_ratio=0), out_channels=80, featmap_strides=[4, 8, 16, 32]), mask_head=dict(type='FCNMaskHead', num_convs=4, in_channels=80, conv_out_channels=80, num_classes=80, loss_mask=dict(type='CrossEntropyLoss', use_mask=True, loss_weight=1.0))), train_cfg=dict(rpn=dict(assigner=dict(type='MaxIoUAssigner', pos_iou_thr=0.7, neg_iou_thr=0.3, min_pos_iou=0.3, match_low_quality=True, ignore_iof_thr=-1, gpu_assign_thr=300), sampler=dict(type='RandomSampler', num=256, pos_fraction=0.5, neg_pos_ub=-1, add_gt_as_proposals=False), allowed_border=-1, pos_weight=-1, debug=False), rpn_proposal=dict(nms_across_levels=False, nms_pre=2000, nms_post=1000, max_num=1000, nms_thr=0.8, min_bbox_size=0), rcnn=dict(assigner=dict(type='MaxIoUAssigner', pos_iou_thr=0.5, neg_iou_thr=0.5, min_pos_iou=0.5, match_low_quality=True, ignore_iof_thr=-1, gpu_assign_thr=300), sampler=dict(type='RandomSampler', num=256, pos_fraction=0.25, neg_pos_ub=-1, add_gt_as_proposals=True), mask_size=28, pos_weight=-1, debug=False)), test_cfg=dict(rpn=dict(nms_across_levels=False, nms_pre=800, nms_post=500, max_num=500, nms_thr=0.8, min_bbox_size=0), rcnn=dict(score_thr=0.05, nms=dict(type='nms', iou_threshold=0.7), max_per_img=500, mask_thr_binary=0.5))) cudnn_benchmark = True evaluation = dict(interval=1, metric='mAP', save_best='mAP', iou_thr=[0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95]) optimizer = dict(type='SGD', lr=0.015, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=None) lr_config = dict(policy='ReduceLROnPlateau', metric='mAP', patience=5, iteration_patience=300, interval=1, min_lr=1e-06, warmup='linear', warmup_iters=200, warmup_ratio=0.3333333333333333) runner = dict(type='EpochRunnerWithCancel', max_epochs=300) checkpoint_config = dict(interval=5) log_config = dict(interval=1, hooks=[dict(type='TextLoggerHook')]) dist_params = dict(backend='nccl') log_level = 'INFO' load_from = 'https://storage.openvinotoolkit.org/repositories/openvino_training_extensions/models/instance_segmentation/v2/efficientnet_b2b-mask_rcnn-576x576.pth' resume_from = None workflow = [('train', 1)] work_dir = 'output' custom_hooks = [dict(type='EarlyStoppingHook', patience=10, metric='mAP', interval=1, priority=75, iteration_patience=0)] fp16 = dict(loss_scale=512.0)
class LayoutSettings(object): """ Provides a base class for collecting layout scheme characteristics. """ LayoutEngine=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the current table layout engine. Get: LayoutEngine(self: LayoutSettings) -> LayoutEngine """
class Layoutsettings(object): """ Provides a base class for collecting layout scheme characteristics. """ layout_engine = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets the current table layout engine.\n\n\n\nGet: LayoutEngine(self: LayoutSettings) -> LayoutEngine\n\n\n\n'
def main() -> None: x0, y0 = map(int, input().split()) x1, y1 = map(int, input().split()) x2, y2 = map(int, input().split()) def calc(x0, y0, x1, y1, x2, y2): if y2 == y0: print(x2, y1) else: print(x2, y0) if x0 == x1: calc(x0, y0, x1, y1, x2, y2) elif x1 == x2: calc(x1, y1, x2, y2, x0, y0) else: calc(x2, y2, x0, y0, x1, y1) # if y0 == y1: if __name__ == "__main__": main()
def main() -> None: (x0, y0) = map(int, input().split()) (x1, y1) = map(int, input().split()) (x2, y2) = map(int, input().split()) def calc(x0, y0, x1, y1, x2, y2): if y2 == y0: print(x2, y1) else: print(x2, y0) if x0 == x1: calc(x0, y0, x1, y1, x2, y2) elif x1 == x2: calc(x1, y1, x2, y2, x0, y0) else: calc(x2, y2, x0, y0, x1, y1) if __name__ == '__main__': main()
class FreqStack: def __init__(self): self.fmap = Counter() self.stack = [0] def push(self, x: int) -> None: self.fmap[x] += 1 freq = self.fmap[x] if (freq == len(self.stack)): self.stack.append([x]) else: self.stack[freq].append(x) def pop(self) -> int: top = self.stack[-1] x = top.pop() if (not top): self.stack.pop() self.fmap[x] -= 1 return x
class Freqstack: def __init__(self): self.fmap = counter() self.stack = [0] def push(self, x: int) -> None: self.fmap[x] += 1 freq = self.fmap[x] if freq == len(self.stack): self.stack.append([x]) else: self.stack[freq].append(x) def pop(self) -> int: top = self.stack[-1] x = top.pop() if not top: self.stack.pop() self.fmap[x] -= 1 return x
input_1 = int(input('Ingrese numero 1 = ')) input_2 = int(input('Ingrese numero 2 = ')) for x in range(input_1, input_2): print(x)
input_1 = int(input('Ingrese numero 1 = ')) input_2 = int(input('Ingrese numero 2 = ')) for x in range(input_1, input_2): print(x)
CERTIFICATE = { "type": "service_account", "project_id": "fir-orm-python", "private_key_id": "47246fe582a99774f4daf19fad21b97a09df8c70", "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDMp79d08KEZPrn\nN0xZGULfM/eZwAJ+MytsPQhs+LVSqtx1c/oGHpQC5GiW9xwgnMpEh7xfX5NNjp6x\n0BVP9e7jS1EGcjmZqauCzYzNhnG9fuUdVQv7WmskDuCcl6sVRLjhqbSxC+xTH4pP\n+PcC19NYxqcg3DVnEHG80lXTETZmgudfUPwS92UDZK7bn1mj/skSudg2mXeRDUek\nPUtQcKD92pr2Vd/5/cvUadBKx9/IOUb0UxKPynJFKttg2iWi2oZOSgorszm6j/ms\nt9jCe5tdyyXAFV5L6wPcJ9ZBLSi3VhIwVJbq1BKC/WvbfTiwDJ5+/NifcahfuhOB\nqgH+VyePAgMBAAECggEAUMUPoK83gNr9rw1DA5MVslOnL7X5BeeaBqDb124c2eB3\nG5/HGG0vCyksIhCquDBJH9zWOmnVD/Hurcyq7KDqRChwdPPVydCN0RTgsiiScTBI\nqlfrX6six9tbSFIPglhaAy3gE1PaVEAJbWCb1DJrxgi44x4lsWRrDxOQLboIV1Iz\nEEE/GDXq4u6EoMr0pfm9nduRj+JvOO6/1EYdTkPBzX2j/UgkrY4+tYNC0dBOwjvs\n+kyUAf/Sikmzs/3TnSoGG2savtCnT+ADNYrncUsXLtaMDMX3ejmirFJHYNH7kbGk\nZsA/21wUT94WFb62NIrLOBq1Y+gn+HBLg7Etke1jgQKBgQD74Jshv8Cw/2oHdwre\nO8YDdVq8feY1p2c4ygFuJATvubMyMpA1B97KxCOuFR5YmEI5aMCFaP184EJSNFLB\nVzgs3c4T7cRwWmP9AOZUJ7SKjSC4F6uCk2XjbviFqZ7vdBKo8nbTNbg+x0dQJowE\n3b3vQArNe6z3cE7p/iGCrUYpzwKBgQDQAUaUx8bmSWL37RdQNwRodogem2nWH/Jm\nb4Th3wBfaTxT8OndDNXZSakER1kOLLO1OijfS6QWFa0U1NJM4MERlC69V3v5TeNJ\n5/b15lwgva9WsUB5YwOWrsvO0H4Ywy1WsJUPnZe/YmlpocC8EZAFRr7Wr8D4jEg7\n8/t0aJVWQQKBgQDB0xWN4wFlMydklzbFzTmTb7tjUX7Vyvyjts9i8lTaJQzAlChk\npqnLXyQV0iqIAqLziqicAS8P6YMfvyPvpC6WWBk9PLrtuqE3EHouSF+mPvPutkhF\nMyg03DBiqySjH688U1kdLzmZFcDK7N7S39BJS/8EISf5QXN4nRcseCqGAQKBgQCP\nogHiJR3k0ZJEz3SE0Kj7lbYjJIBt+vuA3sssybfRKrMc58Ql/4IAHIxYxwfo8Ndb\ncoDcyLfTBD7Tnq5lpeHMSL4Jw0p5ed5Un5h6bwr5FOLqA1YZPFUzDRrxgilA4i4B\nqcgU02cBImzWI3saoyoHarXHO/AN8ZjDxZPC66ELwQKBgQDIk+ITDLDRm6lXGiP6\nUaLRs/esyG+iNLlkQBHZtqUV+RIsde0fhpSawCHbuv9rW6hDwhn4Ojc/ml2XB0Mx\nQxkhgLIyxzyFC4AzGYi2D4WWSBpeQZyNvyWBRcLVkI3d0jW7keUPOqBuSnT+qVUw\nxpAgGdUHYiug0D4BTt8SJlyLRA==\n-----END PRIVATE KEY-----\n", "client_email": "firebase-adminsdk-bcynb@fir-orm-python.iam.gserviceaccount.com", "client_id": "103369610968201073713", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://accounts.google.com/o/oauth2/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-bcynb%40fir-orm-python.iam.gserviceaccount.com" } BUCKET_NAME = 'fir-orm-python'
certificate = {'type': 'service_account', 'project_id': 'fir-orm-python', 'private_key_id': '47246fe582a99774f4daf19fad21b97a09df8c70', 'private_key': '-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDMp79d08KEZPrn\nN0xZGULfM/eZwAJ+MytsPQhs+LVSqtx1c/oGHpQC5GiW9xwgnMpEh7xfX5NNjp6x\n0BVP9e7jS1EGcjmZqauCzYzNhnG9fuUdVQv7WmskDuCcl6sVRLjhqbSxC+xTH4pP\n+PcC19NYxqcg3DVnEHG80lXTETZmgudfUPwS92UDZK7bn1mj/skSudg2mXeRDUek\nPUtQcKD92pr2Vd/5/cvUadBKx9/IOUb0UxKPynJFKttg2iWi2oZOSgorszm6j/ms\nt9jCe5tdyyXAFV5L6wPcJ9ZBLSi3VhIwVJbq1BKC/WvbfTiwDJ5+/NifcahfuhOB\nqgH+VyePAgMBAAECggEAUMUPoK83gNr9rw1DA5MVslOnL7X5BeeaBqDb124c2eB3\nG5/HGG0vCyksIhCquDBJH9zWOmnVD/Hurcyq7KDqRChwdPPVydCN0RTgsiiScTBI\nqlfrX6six9tbSFIPglhaAy3gE1PaVEAJbWCb1DJrxgi44x4lsWRrDxOQLboIV1Iz\nEEE/GDXq4u6EoMr0pfm9nduRj+JvOO6/1EYdTkPBzX2j/UgkrY4+tYNC0dBOwjvs\n+kyUAf/Sikmzs/3TnSoGG2savtCnT+ADNYrncUsXLtaMDMX3ejmirFJHYNH7kbGk\nZsA/21wUT94WFb62NIrLOBq1Y+gn+HBLg7Etke1jgQKBgQD74Jshv8Cw/2oHdwre\nO8YDdVq8feY1p2c4ygFuJATvubMyMpA1B97KxCOuFR5YmEI5aMCFaP184EJSNFLB\nVzgs3c4T7cRwWmP9AOZUJ7SKjSC4F6uCk2XjbviFqZ7vdBKo8nbTNbg+x0dQJowE\n3b3vQArNe6z3cE7p/iGCrUYpzwKBgQDQAUaUx8bmSWL37RdQNwRodogem2nWH/Jm\nb4Th3wBfaTxT8OndDNXZSakER1kOLLO1OijfS6QWFa0U1NJM4MERlC69V3v5TeNJ\n5/b15lwgva9WsUB5YwOWrsvO0H4Ywy1WsJUPnZe/YmlpocC8EZAFRr7Wr8D4jEg7\n8/t0aJVWQQKBgQDB0xWN4wFlMydklzbFzTmTb7tjUX7Vyvyjts9i8lTaJQzAlChk\npqnLXyQV0iqIAqLziqicAS8P6YMfvyPvpC6WWBk9PLrtuqE3EHouSF+mPvPutkhF\nMyg03DBiqySjH688U1kdLzmZFcDK7N7S39BJS/8EISf5QXN4nRcseCqGAQKBgQCP\nogHiJR3k0ZJEz3SE0Kj7lbYjJIBt+vuA3sssybfRKrMc58Ql/4IAHIxYxwfo8Ndb\ncoDcyLfTBD7Tnq5lpeHMSL4Jw0p5ed5Un5h6bwr5FOLqA1YZPFUzDRrxgilA4i4B\nqcgU02cBImzWI3saoyoHarXHO/AN8ZjDxZPC66ELwQKBgQDIk+ITDLDRm6lXGiP6\nUaLRs/esyG+iNLlkQBHZtqUV+RIsde0fhpSawCHbuv9rW6hDwhn4Ojc/ml2XB0Mx\nQxkhgLIyxzyFC4AzGYi2D4WWSBpeQZyNvyWBRcLVkI3d0jW7keUPOqBuSnT+qVUw\nxpAgGdUHYiug0D4BTt8SJlyLRA==\n-----END PRIVATE KEY-----\n', 'client_email': 'firebase-adminsdk-bcynb@fir-orm-python.iam.gserviceaccount.com', 'client_id': '103369610968201073713', 'auth_uri': 'https://accounts.google.com/o/oauth2/auth', 'token_uri': 'https://accounts.google.com/o/oauth2/token', 'auth_provider_x509_cert_url': 'https://www.googleapis.com/oauth2/v1/certs', 'client_x509_cert_url': 'https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-bcynb%40fir-orm-python.iam.gserviceaccount.com'} bucket_name = 'fir-orm-python'
MODEL_PATH = { "glove": "phrase-emb-storage/saved_models/glove/", "bert": "bert-base-uncased", "spanbert": "phrase-emb-storage/saved_models/span-bert-model/", "sentbert": "bert-base-nli-stsb-mean-tokens", "phrase-bert": "phrase-emb-storage/saved_models/phrase-bert-model/" } GLOVE_FILE_PATH = 'phrase-emb-storage/cc_glove/glove.840B.300d.txt'
model_path = {'glove': 'phrase-emb-storage/saved_models/glove/', 'bert': 'bert-base-uncased', 'spanbert': 'phrase-emb-storage/saved_models/span-bert-model/', 'sentbert': 'bert-base-nli-stsb-mean-tokens', 'phrase-bert': 'phrase-emb-storage/saved_models/phrase-bert-model/'} glove_file_path = 'phrase-emb-storage/cc_glove/glove.840B.300d.txt'
if __name__ == '__main__': mark = [] for _ in range(int(input())): name = input() score = float(input()) mark.append([name, score]) second_highest = sorted(set([score for name, score in mark]))[1] print('\n'.join(sorted([name for name, score in mark if score == second_highest])))
if __name__ == '__main__': mark = [] for _ in range(int(input())): name = input() score = float(input()) mark.append([name, score]) second_highest = sorted(set([score for (name, score) in mark]))[1] print('\n'.join(sorted([name for (name, score) in mark if score == second_highest])))
""" HackerRank - Algorithms - Implementation Kangaroo """ #!/bin/python3 x1, v1, x2, v2 = input().strip().split(" ") x1, v1, x2, v2 = [int(x1), int(v1), int(x2), int(v2)] if ( v1 != v2 and (x1 - x2) % (v2 - v1) == 0 and (x1 - x2) / (v2 - v1) > 0 ): # Takes care of zero devision print("YES") else: print("NO")
""" HackerRank - Algorithms - Implementation Kangaroo """ (x1, v1, x2, v2) = input().strip().split(' ') (x1, v1, x2, v2) = [int(x1), int(v1), int(x2), int(v2)] if v1 != v2 and (x1 - x2) % (v2 - v1) == 0 and ((x1 - x2) / (v2 - v1) > 0): print('YES') else: print('NO')
# optimizer optimizer = dict(type='Lamb', lr=0.005, weight_decay=0.02) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='CosineAnnealing', min_lr=1.0e-6, warmup='linear', # For ImageNet-1k, 626 iters per epoch, warmup 5 epochs. warmup_iters=5 * 626, warmup_ratio=0.0001) runner = dict(type='EpochBasedRunner', max_epochs=100)
optimizer = dict(type='Lamb', lr=0.005, weight_decay=0.02) optimizer_config = dict(grad_clip=None) lr_config = dict(policy='CosineAnnealing', min_lr=1e-06, warmup='linear', warmup_iters=5 * 626, warmup_ratio=0.0001) runner = dict(type='EpochBasedRunner', max_epochs=100)
""" This module provides functionality to work with images """ def overlay(background_image, foreground_image, x_offset, y_offset): """ Overlays a png image on another image. :param background_image: OpenCv image to be overlaid with foreground image :param foreground_image: OpenCv image to overlay :param x_offset: Position of the overlay in x direction :param y_offset: Position of the overlay in y direction :return: Image with overlay Example: s_img = cv2.imread("foreground.png", -1) l_img = cv2.imread("background.png") img = overlay(l_img, s_img, 50, 50) cv2.imshow("Overlay", img) cv2.waitKey(0) cv2.destroyAllWindows() """ y1, y2 = y_offset, y_offset + foreground_image.shape[0] x1, x2 = x_offset, x_offset + foreground_image.shape[1] alpha_s = foreground_image[:, :, 3] / 255.0 alpha_l = 1.0 - alpha_s for c in range(0, 3): background_image[y1:y2, x1:x2, c] = (alpha_s * foreground_image[:, :, c] + alpha_l * background_image[y1:y2, x1:x2, c]) return background_image
""" This module provides functionality to work with images """ def overlay(background_image, foreground_image, x_offset, y_offset): """ Overlays a png image on another image. :param background_image: OpenCv image to be overlaid with foreground image :param foreground_image: OpenCv image to overlay :param x_offset: Position of the overlay in x direction :param y_offset: Position of the overlay in y direction :return: Image with overlay Example: s_img = cv2.imread("foreground.png", -1) l_img = cv2.imread("background.png") img = overlay(l_img, s_img, 50, 50) cv2.imshow("Overlay", img) cv2.waitKey(0) cv2.destroyAllWindows() """ (y1, y2) = (y_offset, y_offset + foreground_image.shape[0]) (x1, x2) = (x_offset, x_offset + foreground_image.shape[1]) alpha_s = foreground_image[:, :, 3] / 255.0 alpha_l = 1.0 - alpha_s for c in range(0, 3): background_image[y1:y2, x1:x2, c] = alpha_s * foreground_image[:, :, c] + alpha_l * background_image[y1:y2, x1:x2, c] return background_image
{ "targets": [ { "target_name": "ultradb", "sources": [ "src/ultradb.cc" ], "conditions": [ ["OS==\"linux\"", { "cflags_cc": [ "-fpermissive", "-Os" ] }] ] } ] }
{'targets': [{'target_name': 'ultradb', 'sources': ['src/ultradb.cc'], 'conditions': [['OS=="linux"', {'cflags_cc': ['-fpermissive', '-Os']}]]}]}
VBA = \ r""" Function Base64ToStream(b) Dim enc, length, ba, transform, ms Set enc = CreateObject("System.Text.ASCIIEncoding") length = enc.GetByteCount_2(b) Set transform = CreateObject("System.Security.Cryptography.FromBase64Transform") Set ms = CreateObject("System.IO.MemoryStream") ms.Write transform.TransformFinalBlock(enc.GetBytes_4(b), 0, length), 0, ((length / 4) * 3) ms.Position = 0 Set Base64ToStream = ms End Function Sub Run() Dim s, entry_class <tugtug> End Sub Function WebMeter() On Error Resume Next Run End Function """
vba = '\n\n\n\nFunction Base64ToStream(b)\n Dim enc, length, ba, transform, ms\n Set enc = CreateObject("System.Text.ASCIIEncoding")\n length = enc.GetByteCount_2(b)\n Set transform = CreateObject("System.Security.Cryptography.FromBase64Transform")\n Set ms = CreateObject("System.IO.MemoryStream")\n ms.Write transform.TransformFinalBlock(enc.GetBytes_4(b), 0, length), 0, ((length / 4) * 3)\n ms.Position = 0\n Set Base64ToStream = ms\nEnd Function\n\nSub Run()\n Dim s, entry_class\n\n <tugtug>\nEnd Sub\n\nFunction WebMeter()\n On Error Resume Next\n Run\nEnd Function\n\n'
class Solution: def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ s=s.strip() if len(s)==0: return 0 return len((s.split(" "))[-1])
class Solution: def length_of_last_word(self, s): """ :type s: str :rtype: int """ s = s.strip() if len(s) == 0: return 0 return len(s.split(' ')[-1])
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Justin Santa Barbara # All Rights Reserved. # Copyright (c) 2010 Citrix Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Power state is the state we get by calling virt driver on a particular domain. The hypervisor is always considered the authority on the status of a particular VM, and the power_state in the DB should be viewed as a snapshot of the VMs's state in the (recent) past. It can be periodically updated, and should also be updated at the end of a task if the task is supposed to affect power_state. """ # NOTE(maoy): These are *not* virDomainState values from libvirt. # The hex value happens to match virDomainState for backward-compatibility # reasons. NOSTATE = 0x00 RUNNING = 0x01 PAUSED = 0x03 SHUTDOWN = 0x04 # the VM is powered off CRASHED = 0x06 SUSPENDED = 0x07 # TODO(maoy): BUILDING state is only used in bare metal case and should # eventually be removed/cleaned up. NOSTATE is probably enough. BUILDING = 0x09 # TODO(justinsb): Power state really needs to be a proper class, # so that we're not locked into the libvirt status codes and can put mapping # logic here rather than spread throughout the code _STATE_MAP = { NOSTATE: 'pending', RUNNING: 'running', PAUSED: 'paused', SHUTDOWN: 'shutdown', CRASHED: 'crashed', SUSPENDED: 'suspended', BUILDING: 'building', } def name(code): return _STATE_MAP[code] def valid_states(): return _STATE_MAP.keys()
"""Power state is the state we get by calling virt driver on a particular domain. The hypervisor is always considered the authority on the status of a particular VM, and the power_state in the DB should be viewed as a snapshot of the VMs's state in the (recent) past. It can be periodically updated, and should also be updated at the end of a task if the task is supposed to affect power_state. """ nostate = 0 running = 1 paused = 3 shutdown = 4 crashed = 6 suspended = 7 building = 9 _state_map = {NOSTATE: 'pending', RUNNING: 'running', PAUSED: 'paused', SHUTDOWN: 'shutdown', CRASHED: 'crashed', SUSPENDED: 'suspended', BUILDING: 'building'} def name(code): return _STATE_MAP[code] def valid_states(): return _STATE_MAP.keys()
DEBUG = False SQLALCHEMY_DATABASE_URI = 'postgresql:///logging' PORT = 5555 SERVER = 'production' #SSL_KEY = "/path/to/keyfile.key" #SSL_CRT = "/path/to/certfile.crt"
debug = False sqlalchemy_database_uri = 'postgresql:///logging' port = 5555 server = 'production'
# Event: LCCS Python Fundamental Skills Workshop # Date: Dec 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Breakout 6.4 Check digits # Solution to Exercise 1 - extract the ith digit from n # A function to extract digit i from number n def extractDigit(i, n): i = len(n) - i if i < 0: return -1 n = int(n) return (n//pow(10, i))%10 x = input("Enter a number: ") pos = int(input("Enter position of digit to extract: ")) print(extractDigit(pos, x)) # The code snippets below will serve to provide a useful background ''' n = int(input("Enter a 2 digit number: ")) d2 = n%10 # %10 extracts the final digit d1 = n//10 # //10 to remove the final digit print(d1, d2) ''' ''' n = int(input("Enter a 3 digit number: ")) d1 = n%10 # %10 to extract the final digit d2 = (n//10)%10 # //10 to remove the final digit d3 = (n//100) # //100 to remove the final two digits print(d1, d2, d3) ''' ''' n = int(input("Enter a 4 digit number: ")) d1 = n%10 # %10 extracts the final digit d2 = (n//10)%10 # //10 chops off the last digit d3 = (n//100)%10 # //100 chops off the last two digits d4 = (n//1000)%10 # //1000 chops off the last three digits print(d1, d2, d3, d4) ''' ''' n = input("Enter a number: ") numDigits = len(n) n = int(n) d = n%10 # %10 to extract the final digit print(d, end=' ') for count in range(1, numDigits): d = (n//pow(10, count))%10 print(d, end=' ') print("") ''' ''' def extractDigit2(i, n): if i <= 0 or i>= len(n): return -1 return (n[i-1]) n = input("Enter a number: ") print(extractDigit2(0, n)) '''
def extract_digit(i, n): i = len(n) - i if i < 0: return -1 n = int(n) return n // pow(10, i) % 10 x = input('Enter a number: ') pos = int(input('Enter position of digit to extract: ')) print(extract_digit(pos, x)) '\nn = int(input("Enter a 2 digit number: "))\nd2 = n%10 # %10 extracts the final digit\nd1 = n//10 # //10 to remove the final digit\nprint(d1, d2)\n' '\nn = int(input("Enter a 3 digit number: "))\nd1 = n%10 # %10 to extract the final digit\nd2 = (n//10)%10 # //10 to remove the final digit\nd3 = (n//100) # //100 to remove the final two digits\nprint(d1, d2, d3)\n' '\nn = int(input("Enter a 4 digit number: "))\nd1 = n%10 # %10 extracts the final digit\nd2 = (n//10)%10 # //10 chops off the last digit\nd3 = (n//100)%10 # //100 chops off the last two digits\nd4 = (n//1000)%10 # //1000 chops off the last three digits\nprint(d1, d2, d3, d4)\n' '\nn = input("Enter a number: ")\nnumDigits = len(n)\nn = int(n)\n\nd = n%10 # %10 to extract the final digit\nprint(d, end=\' \')\nfor count in range(1, numDigits):\n d = (n//pow(10, count))%10\n print(d, end=\' \') \nprint("")\n' '\ndef extractDigit2(i, n):\n\n if i <= 0 or i>= len(n):\n return -1\n \n return (n[i-1])\n\n\nn = input("Enter a number: ")\nprint(extractDigit2(0, n))\n'
st=input() k=list(st) print(k) def equal(s): n=len(s) sh=0 tr=0 for i in s: if(i=='s'): sh+=1 if(i=='t'): tr+=1 if(sh==tr): return 1 else: return 0 def equal_s_t(st): maxi=0 n=len(st) for i in range(n): for j in range(i,n): if(equal(st[i:j+1]) and maxi<j-i+1): maxi=j-i+1 return maxi print(equal_s_t(st))
st = input() k = list(st) print(k) def equal(s): n = len(s) sh = 0 tr = 0 for i in s: if i == 's': sh += 1 if i == 't': tr += 1 if sh == tr: return 1 else: return 0 def equal_s_t(st): maxi = 0 n = len(st) for i in range(n): for j in range(i, n): if equal(st[i:j + 1]) and maxi < j - i + 1: maxi = j - i + 1 return maxi print(equal_s_t(st))
""" .. module: onacol.base :synopsis: Basic utilities and exception classes. .. moduleauthor:: Josef Nevrly <josef.nevrly@gmail.com> """ class OnacolException(Exception): pass
""" .. module: onacol.base :synopsis: Basic utilities and exception classes. .. moduleauthor:: Josef Nevrly <josef.nevrly@gmail.com> """ class Onacolexception(Exception): pass
def linha(): print() print('=' * 80) print() linha() num = 0 soma = 0 cont = 0 while not num == 999: num = int(input('Valor: ')) if num != 999: soma += num cont += 1 print() print(f'Valores digitados: {cont}') print(f'Soma dos valores: {soma}') linha()
def linha(): print() print('=' * 80) print() linha() num = 0 soma = 0 cont = 0 while not num == 999: num = int(input('Valor: ')) if num != 999: soma += num cont += 1 print() print(f'Valores digitados: {cont}') print(f'Soma dos valores: {soma}') linha()
CDNX_POS_PERMISSIONS = { 'operator': [ 'list_subcategory', 'list_productfinal', 'list_productfinaloption', ], }
cdnx_pos_permissions = {'operator': ['list_subcategory', 'list_productfinal', 'list_productfinaloption']}
#!/usr/bin/env python3 # MIT License # # Copyright (c) 2020 FABRIC Testbed # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # # Author: Komal Thareja (kthare10@renci.org) class ConfigurationMapping: def __init__(self): self.type = None self.class_name = None self.properties = None self.module_name = None def __getstate__(self): state = self.__dict__.copy() return state def __setstate__(self, state): self.__dict__.update(state) def get_module_name(self) -> str: return self.module_name def get_class_name(self) -> str: return self.class_name def get_key(self) -> str: return self.type def get_properties(self) -> dict: return self.properties def set_class_name(self, *, class_name: str): self.class_name = class_name def set_module_name(self, *, module_name: str): self.module_name = module_name def set_key(self, *, key: str): self.type = key def set_properties(self, *, properties: dict): self.properties = properties def __str__(self): return f"resource_type: {self.type} class_name: {self.class_name} module: {self.module_name} " \ f"properties: {self.properties}"
class Configurationmapping: def __init__(self): self.type = None self.class_name = None self.properties = None self.module_name = None def __getstate__(self): state = self.__dict__.copy() return state def __setstate__(self, state): self.__dict__.update(state) def get_module_name(self) -> str: return self.module_name def get_class_name(self) -> str: return self.class_name def get_key(self) -> str: return self.type def get_properties(self) -> dict: return self.properties def set_class_name(self, *, class_name: str): self.class_name = class_name def set_module_name(self, *, module_name: str): self.module_name = module_name def set_key(self, *, key: str): self.type = key def set_properties(self, *, properties: dict): self.properties = properties def __str__(self): return f'resource_type: {self.type} class_name: {self.class_name} module: {self.module_name} properties: {self.properties}'
#!/usr/bin/python3 def multiple_returns(sentence): if len(sentence) == 0: return (0, None) return (len(sentence), sentence[0])
def multiple_returns(sentence): if len(sentence) == 0: return (0, None) return (len(sentence), sentence[0])
#Instructions #Create an empty list named misspelled_words. #Write a for loop that: #iterates over tokenized_story, #uses an if statement that returns True if the current token is not in tokenized_vocabulary and if so, appends the current token to misspelled_words. #Print misspelled_words. #In this code, we're going to explore how to build a basic spell checker. Spell checkers work by comparing each word in a passage of text to a set of correctly spelled words. In this mission, we will learn: #how to work with plain text files to read in a vocabulary of correctly spelled words, #more string methods for working with and processing text data, #how to create functions to make the components of our spell checker more reusable. #In this code, we're going to explore how to customize the functions we write to improve the spell checker we built from the previous mission. As our code becomes more modular and separated into functions, it can often become harder to debug. We'll explore how to debug our code in this mission using the errors the Python interpreter returns. #Recall that our spell checker works by: #reading in a file of correctly spelled words, tokenizing it into a list and assigning it to the variable vocabulary, #reading in, cleaning, and tokenizing the piece of text we want spell checked, #comparing each word (token) in the piece of text with each word in vocabulary and returning the ones that weren't found. #The file dictionary.txt contains a sequence of correctly spelled words, which we'll use to seed the vocabulary. The file story.txt is a piece of text containing some misspelled words. In the following code cell, we added the spell checker we wrote so far from the previous mission. def clean_text(text_string, special_characters): cleaned_string = text_string for string in special_characters: cleaned_string = cleaned_string.replace(string, "") cleaned_string = cleaned_string.lower() return(cleaned_string) def tokenize(text_string, special_characters): cleaned_story = clean_text(text_string, special_characters) story_tokens = cleaned_story.split(" ") return(story_tokens) misspelled_words = [] clean_chars = [",", ".", "'", ";", "\n"] tokenized_story = tokenize(story_string, clean_chars) tokenized_vocabulary = tokenize(vocabulary, clean_chars) for ts in tokenized_story: if ts not in tokenized_vocabulary: misspelled_words.append(ts) print(misspelled_words) #Instructions #Modify the tokenize() function: def tokenize(text_string, special_characters, clean=False): cleaned_story = clean_text(text_string, special_characters) story_tokens = cleaned_story.split(" ") return(story_tokens) clean_chars = [",", ".", "'", ";", "\n"] tokenized_story = [] tokenized_vocabulary = [] misspelled_words = [] #Use an if statement to check if clean is True. If so: #Clean text_string using clean_text and assign the returned string to a variable. #Tokenize this new string variable using the split() method and assign the returned list to a variable. #Return this list. # Answer code def tokenize(text_string, special_characters, clean=False): # If `clean` is `True`. if clean: cleaned_story = clean_text(text_string, special_characters) story_tokens = cleaned_story.split(" ") return(story_tokens) #Outside the if statement, write the code that's executed if clean is False: #Tokenize text_string using the split() method and assign the returned list to a variable. #Return this list. # If `clean` not equal to `True`, no cleaning. story_tokens = text_string.split(" ") return(story_tokens) #Outside the tokenize() function: #Use the tokenize() function to clean and tokenize story_string and assign the result to tokenized_story. #Use the tokenize() function to tokenize vocabulary and assign the result to tokenized_vocabulary. clean_chars = [",", ".", "'", ";", "\n"] tokenized_story = tokenize(story_string, clean_chars, True) tokenized_vocabulary = tokenize(vocabulary, clean_chars) #Finally, loop over in tokenized_story, check if each element is in tokenized_vocabulary, and add to misspelled_words if it isn't. for ts in tokenized_story: if ts not in tokenized_vocabulary: misspelled_words.append(ts)
def clean_text(text_string, special_characters): cleaned_string = text_string for string in special_characters: cleaned_string = cleaned_string.replace(string, '') cleaned_string = cleaned_string.lower() return cleaned_string def tokenize(text_string, special_characters): cleaned_story = clean_text(text_string, special_characters) story_tokens = cleaned_story.split(' ') return story_tokens misspelled_words = [] clean_chars = [',', '.', "'", ';', '\n'] tokenized_story = tokenize(story_string, clean_chars) tokenized_vocabulary = tokenize(vocabulary, clean_chars) for ts in tokenized_story: if ts not in tokenized_vocabulary: misspelled_words.append(ts) print(misspelled_words) def tokenize(text_string, special_characters, clean=False): cleaned_story = clean_text(text_string, special_characters) story_tokens = cleaned_story.split(' ') return story_tokens clean_chars = [',', '.', "'", ';', '\n'] tokenized_story = [] tokenized_vocabulary = [] misspelled_words = [] def tokenize(text_string, special_characters, clean=False): if clean: cleaned_story = clean_text(text_string, special_characters) story_tokens = cleaned_story.split(' ') return story_tokens story_tokens = text_string.split(' ') return story_tokens clean_chars = [',', '.', "'", ';', '\n'] tokenized_story = tokenize(story_string, clean_chars, True) tokenized_vocabulary = tokenize(vocabulary, clean_chars) for ts in tokenized_story: if ts not in tokenized_vocabulary: misspelled_words.append(ts)
# slicing # my_list[start_index:end_index] # my_list[:] # This would be all of the items in my_list # my_list[:5] # This would be the items from index 0 to 4 # my_list[5:] # This would be the items from index 5 to the end of the list # guided """ Given an array of integers `nums`, define a function that returns the "pivot" index of the array. The "pivot" index is where the sum of all the numbers on the left of that index is equal to the sum of all the numbers on the right of that index. If the input array does not have a "pivot" index, then the function should return `-1`. If there are more than one "pivot" indexes, then you should return the left-most "pivot" index. Example 1: Input: nums = [1,7,3,6,5,6] Output: 3 Explanation: The sum of the numbers to the left of index 3 (1 + 7 + 3 = 11) is equal to the sum of numbers to the right of index 3 (5 + 6 = 11). Also, 3 is the first index where this occurs. Example 2: Input: nums = [1,2,3] Output: -1 Explanation: There is no index that satisfies the conditions in the problem statement. """ nums = [1, 7, 3, 6, 5, 6] # nums = [1,2,3] # O(N^2) solution # def pivot_index(nums): # # iterate array starting at index 1 # # get sum of items on left of i and compare to sum of items on right of i # # if they are equal return i else keep going to the next i # for i in range(len(nums)): # left = sum(nums[:i]) # right = sum(nums[i + 1:]) # if left == right: # return i # return -1 # O(N) solution def pivot_index(nums): if len(nums) <= 1: return -1 left = 0 right = sum(nums) for i in range(len(nums)): right -= nums[i] if right == left: return i left += nums[i] # print('def pivot_index:', pivot_index(nums)) """ You are given a non-empty array that represents the digits of a non-negative integer. Write a function that increments the number by 1. The digits are stored so that the digit representing the most significant place value is at the beginning of the array. Each element in the array only contains a single digit. You will not receive a leading 0 in your input array (except for the number 0 itself). Example 1: Input: [1,3,2] Output: [1,3,3] Explanation: The input array represents the integer 132. 132 + 1 = 133. Example 2: Input: [3,2,1,9] Output: [3,2,2,0] Explanation: The input array represents the integer 3219. 3219 + 1 = 3220. Example 3: Input: [9,9,9] Output: [1,0,0,0] Explanation: The input array represents the integer 999. 999 + 1 = 1000. """ # def plus_one(digits): # turn the numbers in the array into an integer # # The repr() function returns a printable representation of the given object. # number = (''.join(repr(int(n)) for n in digits)) # result = [] # for num in number: # result.append(num) # print(int(number) + 1) def plus_one(digits): # check the last digit if its not 9 we just add 1 # if it is a 9 make it 0 # go left check 2nd to last if its not a 9 add 1 # if it is a 9 index = len(digits) - 1 while index >= 0 and digits[index] == 9: digits[index] = 0 index -= 1 if index == -1: digits.insert(0, 1) else: digits[index] += 1 return digits # print(plus_one([1, 1, 1])) """ You are given the prices of a stock, in the form of an array of integers, prices. Let's say that prices[i] is the price of the stock on the ith day (0-based index). Assuming that you are allowed to buy and sell the stock only once, your task is to find the maximum possible profit (the difference between the buy and sell prices). Note: You can assume there are no fees associated with buying or selling the stock. Example For prices = [6, 3, 1, 2, 5, 4], the output should be buyAndSellStock(prices) = 4. It would be most profitable to buy the stock on day 2 and sell it on day 4. Thus, the maximum profit is prices[4] - prices[2] = 5 - 1 = 4. For prices = [8, 5, 3, 1], the output should be buyAndSellStock(prices) = 0. Since the value of the stock drops each day, there's no way to make a profit from selling it. Hence, the maximum profit is 0. For prices = [3, 100, 1, 97], the output should be buyAndSellStock(prices) = 97. It would be most profitable to buy the stock on day 0 and sell it on day 1. Thus, the maximum profit is prices[1] - prices[0] = 100 - 3 = 97. """ # prices = [6, 3, 1, 2, 5, 4] # prices = [8, 5, 3, 1] prices = [3, 100, 1, 97] # # prices = [] # prices = [61, 91, 6, 15, 28, 30, 39, 69, 78, 81, 62, 38, 56, 69, 22, 95, 47, 82, # 52, 64, 74, 97, 60, 68, 5, 23, 45, 55, 66, 57, 26, 4, 21, 65, 55, 50, # 41, 88, 39, 84, 77, 5, 76, 11, 3, 51, 96, 100, 13, 26, 79, 98, 84, 66, # 93, 65, 98, 60, 57, 35, 12, 40, 83, 62, 46, 60, 26, 94, 59, 29, 70, # 34, 83, 98, 89, 57, 71, 44, 23, 43, 55, 1, 70, 29, 44, 10, 70, 83, 95, # 96, 97, 84, 23, 16, 34, 55, 59, 73, 17, 73] # def buyAndSellStock(prices): # # iterate array, for each item after subtract and store the amount as # # highest profit.. replace if needed with a higher profit # if prices == sorted(prices, reverse=True) or len(prices) < 2: # return 0 # highest_profit = 0 # for indx1 in range(len(prices)): # rest = prices[indx1 + 1:] # for price in range(len(rest)): # if highest_profit >= max(rest): # return highest_profit # if rest[price] - prices[indx1] > highest_profit: # highest_profit = rest[price] - prices[indx1] # if highest_profit < 0: # return 0 # else: # return highest_profit prices = [6, 3, 1, 2, 5, 4] prices = [8, 5, 3, 1] prices = [3, 100, 1, 97] def buyAndSellStock(prices): length = len(prices) # iterate array, for each item after subtract and store the amount as # highest profit.. replace if needed with a higher profit if prices == sorted(prices, reverse=True) or len(prices) < 2: return 0 highest_profit = prices[1] - prices[0] smallest_number = prices[0] for i in range(1, length): # only check if the selected number minus the smallest number before # it is larger than the highest profit to avoid unnecessary checks if prices[i] - smallest_number > highest_profit: highest_profit = prices[i] - smallest_number if prices[i] < smallest_number: smallest_number = prices[i] return highest_profit # print(buyAndSellStock(prices)) """ Given a string, your task is to replace each of its characters by the next one in the English alphabet; i.e. replace a with b, replace b with c, etc (z would be replaced by a). Example For inputString = "crazy", the output should be alphabeticShift(inputString) = "dsbaz". """ inputString = "crazy" def alphabeticShift(inputString): new_string = "" for letter in inputString: new_letter = ord(letter) + 1 if new_letter == 123: new_letter = 97 new_string += chr(new_letter) return new_string # print(alphabeticShift(inputString)) """ You are given a parentheses sequence, check if it's regular. Example For s = "()()(())", the output should be validParenthesesSequence(s) = true; For s = "()()())", the output should be validParenthesesSequence(s) = false """ s = "()()(())" s = "()()())" def validParenthesesSequence(s): check = [] if s == "": return True if s[0] == ")": return False for paren in s: if paren == "(": check.append(paren) else: if len(check) == 0: return False else: check.pop() if check != []: return False return True # print(validParenthesesSequence(s)) # Guided """ Given only a reference to a specific node in a linked list, delete that node from a singly-linked list. Example: The code below should first construct a linked list (x -> y -> z) and then delete `y` from the linked list by calling the function `delete_node`. It is your job to write the `delete_node` function. ```python class LinkedListNode(): def __init__(self, value): self.value = value self.next = None x = LinkedListNode('X') y = LinkedListNode('Y') z = LinkedListNode('Z') x.next = y y.next = z delete_node(y) ``` *Note: We can do this in O(1) time and space! But be aware that our solution will have some side effects...* """ class LinkedListNode: def __init__(self, value): self.value = value self.next = None def delete_node(node_to_delete): next = node_to_delete.next next.next = None node_to_delete.value = next.value node_to_delete.next = next.next x = LinkedListNode("X") y = LinkedListNode("Y") z = LinkedListNode("Z") x.next = y y.next = z # print(delete_node(y)) # print(x.next.value) """ Given a reference to the head node of a singly-linked list, write a function that reverses the linked list in place. The function should return the new head of the reversed list. In order to do this in O(1) space (in-place), you cannot make a new list, you need to use the existing nodes. In order to do this in O(n) time, you should only have to traverse the list once. *Note: If you get stuck, try drawing a picture of a small linked list and running your function by hand. Does it actually work? Also, don't forget to consider edge cases (like a list with only 1 or 0 elements).* """ class LinkedListNode: def __init__(self, value): self.value = value self.next = None def reverse(head_of_list): current_node = head_of_list previous_node = None next_node = None # Until we have 'fallen off' the end of the list while current_node: # Copy a pointer to the next element # before we overwrite current_node.next next_node = current_node.next # Reverse the 'next' pointer current_node.next = previous_node # Step forward in the list previous_node = current_node current_node = next_node return previous_node # Singly-linked lists are already defined with this interface: class ListNode(object): def __init__(self, x): self.value = x self.next = None [1, 3, 4, 6] """ Note: Your solution should have O(n) time complexity, where n is the number of elements in l, since this is what you will be asked to accomplish in an interview. You have a singly linked list l, which is sorted in strictly increasing order, and an integer value. Add value to the list l, preserving its original sorting. Note: in examples below and tests preview linked lists are presented as arrays just for simplicity of visualization: in real data you will be given a head node l of the linked list Example For l = [1, 3, 4, 6] and value = 5, the output should be insertValueIntoSortedLinkedList(l, value) = [1, 3, 4, 5, 6]; For l = [1, 3, 4, 6] and value = 10, the output should be insertValueIntoSortedLinkedList(l, value) = [1, 3, 4, 6, 10]; For l = [1, 3, 4, 6] and value = 0, the output should be insertValueIntoSortedLinkedList(l, value) = [0, 1, 3, 4, 6]. """ def insertValueIntoSortedLinkedList(l, value): # create a new node with the value node = ListNode(value) # if there is no list return the new node if l == None: return node else: # else if the list.value (first item in the list) > the new value if l.value > value: # set new values as the first item in the list node.next = l return node else: # else create a temp value for the current list item and the previous set to None temp, prev = l, None # while the there is a next item and current item value is less # than the value iterate while temp.next and temp.value <= value: # set previous to temp and temp to next prev = temp temp = temp.next # check if temp.next is None (last item) and still not larger than the value if temp.next == None and temp.value <= value: # if so add the value as the last item in the list since it is the largest temp.next = node else: # else if the next item is larger than the value set the next item as the next item of the new value node.next = prev.next # and set the previous item to point to the new value next prev.next = node # return the list return l """ Note: Your solution should have O(l1.length + l2.length) time complexity, since this is what you will be asked to accomplish in an interview. Given two singly linked lists sorted in non-decreasing order, your task is to merge them. In other words, return a singly linked list, also sorted in non-decreasing order, that contains the elements from both original lists. Example For l1 = [1, 2, 3] and l2 = [4, 5, 6], the output should be mergeTwoLinkedLists(l1, l2) = [1, 2, 3, 4, 5, 6]; For l1 = [1, 1, 2, 4] and l2 = [0, 3, 5], the output should be mergeTwoLinkedLists(l1, l2) = [0, 1, 1, 2, 3, 4, 5]. """ # Singly-linked lists are already defined with this interface: class ListNode(object): def __init__(self, x): self.value = x self.next = None def mergeTwoLinkedLists(l1, l2): # create empty node to hold the new merged list merged_node = ListNode(0) # end will hold the end node end = merged_node while True: # if either list becomes empty join lists if l1 is None: end.next = l2 break if l2 is None: end.next = l1 break # merge the smaller list to the end of the larger and create a head from the merged list if l1.value <= l2.value: end.next = l1 l1 = l1.next else: end.next = l2 l2 = l2.next # iterate the end node end = end.next return merged_node.next """ Note: Your solution should have O(n) time complexity, where n is the number of elements in l, and O(1) additional space complexity, since this is what you would be asked to accomplish in an interview. Given a linked list l, reverse its nodes k at a time and return the modified list. k is a positive integer that is less than or equal to the length of l. If the number of nodes in the linked list is not a multiple of k, then the nodes that are left out at the end should remain as-is. You may not alter the values in the nodes - only the nodes themselves can be changed. Example For l = [1, 2, 3, 4, 5] and k = 2, the output should be reverseNodesInKGroups(l, k) = [2, 1, 4, 3, 5]; For l = [1, 2, 3, 4, 5] and k = 1, the output should be reverseNodesInKGroups(l, k) = [1, 2, 3, 4, 5]; For l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] and k = 3, the output should be reverseNodesInKGroups(l, k) = [3, 2, 1, 6, 5, 4, 9, 8, 7, 10, 11]. """ # Singly-linked lists are already defined with this interface: class ListNode(object): def __init__(self, x): self.value = x self.next = None def reverseNodesInKGroups(l, k): # create an empty node to hold the new list new_node = ListNode(0) # set the next value to the list new_node.next = l # set the previous node to the new list prev = new_node while True: # set the start to the new node next start = prev.next # set the end to the prev end = prev # iterate k times for i in range(0, k): # set end to the value its pointing to end = end.next # if the last node if end == None: # return return new_node.next # set the new reverse list at the end of the last reversed list new_reversed = end.next # call the reverse_list function passing in the start and end reverse_list(start, end) # set pointer of prev to end prev.next = end # set pointer of start to the new list start.next = new_reversed # set prev value to the start value prev = start # # function to reverse the list def reverse_list(start, end): # set the last reversed group to the new start old_reversed = start # set the new current to the start current = start # set next node to the node start is pointing to next_node = start.next # while the current node is not the last node while current != end: # iterate current = next_node next_node = next_node.next # set the current pointer to the last reversed current.next = old_reversed # set the last reversed to the current old_reversed = current """ Refactor the Queue class below by adding an `is_empty` method. After writing this method, refactor your other methods to use this method in your other methods. """ class LinkedListNode: def __init__(self, data): self.data = data self.next = None class Queue: def __init__(self): self.front = None self.rear = None def enqueue(self, item): new_node = LinkedListNode(item) # check if queue is empty if self.is_empty(): self.front = new_node self.rear = new_node else: # add new node to rear self.rear.next = new_node # reassign rear to new node self.rear = new_node def dequeue(self): # check if queue is empty if not self.is_empty(): # keep copy of old front old_front = self.front # set new front self.front = old_front.next # check if the queue is now empty if self.is_empty(): # make sure rear is also None self.rear = None return old_front # my code to check if the queue is empty def is_empty(self): return self.front is None and self.rear is None """ Add a peek method to the Stack class. The peek method should return the value of the top item in the stack without actually removing it from the stack. """ class Stack: def __init__(self): self.data = [] def push(self, item): self.data.append(item) # my code for peek method def peek(self, item): return self.data[-1] def pop(self): if len(self.data) > 0: return self.data.pop() return "The stack is empty" """ Add a peek method to the Stack class below. The peek method should return the value of the node that is at the top of the stack without actually removing it from the stack. """ class LinkedListNode: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.top = None def push(self, data): # create new node with data new_node = LinkedListNode(data) # set current top to new node's next new_node.next = self.top # reset the top pointer to the new node self.top = new_node def pop(self): # make sure stack is not empty if self.top is not None: # store popped node popped_node = self.top # reset top pointer to next node self.top = popped_node.next # return the value from the popped node return popped_node.data # my code for peek method def peek(self): if self.top is not None: return self.top """ Queues and stacks guided """ """ You've encountered a situation where you want to easily be able to pull the largest integer from a stack. You already have a `Stack` class that you've implemented using a dynamic array. Use this `Stack` class to implement a new class `MaxStack` with a method `get_max()` that returns the largest element in the stack. `get_max()` should not remove the item. *Note: Your stacks will contain only integers. You should be able to get a runtime of O(1) for push(), pop(), and get_max().* """ class Stack(object): def __init__(self): """Initialize an empty stack""" self.items = [] def push(self, item): """Push a new item onto the stack""" self.items.append(item) def pop(self): """Remove and return the last item""" # If the stack is empty, return None # (it would also be reasonable to throw an exception) if not self.items: return None return self.items.pop() def peek(self): """Return the last item without removing it""" if not self.items: return None return self.items[-1] class MaxStack(object): def __init__(self): # Your code here self.stack = Stack() # self.head = [] self.max_stack = Stack() def push(self, item): """Add a new item onto the top of our stack.""" # Your code here # self.head.append(item) # self.max_value = max(max(self.head), item) current_max = self.get_max() if current_max is None or current_max < item: self.max_stack.push(item) self.stack.push(item) def pop(self): """Remove and return the top item from our stack.""" # Your code here # if not self.head: # return None # self.head.pop() # self.max_value = max(self.head) item = self.stack.pop() self.max_stack.pop() return item def get_max(self): """The last item in maxes_stack is the max item in our stack.""" # Your code here return self.max_stack.peek() max_stack = MaxStack() max_stack.push(1) max_stack.push(2) max_stack.push(5) max_stack.pop() # print(max_stack.get_max()) """ Your goal is to define a `Queue` class that uses two stacks. Your `Queue` class should have an `enqueue()` method and a `dequeue()` method that ensures a "first in first out" (FIFO) order. As you write your methods, you should optimize for time on the `enqueue()` and `dequeue()` method calls. The Stack class that you will use has been provided to you. """ class Stack: def __init__(self): self.data = [] def push(self, item): self.data.append(item) def pop(self): if len(self.data) > 0: return self.data.pop() return "The stack is empty" class QueueTwoStacks: def __init__(self): # Your code here self.stack1 = Stack() self.stack2 = Stack() def enqueue(self, item): # Your code here self.stack1.push(item) def dequeue(self): # Your code here if len(self.stack1.data) != 0: shifted = self.stack1.pop() self.stack2.push(shifted) return self.dequeue() else: if len(self.stack2.data) != 0: last_item = self.stack2.pop() return last_item # queue = QueueTwoStacks() # queue.enqueue(1) # queue.enqueue(3) # queue.enqueue(5) # print('deque:', queue.dequeue()) # print('stack1:', queue.stack1.data) # print('stack2:', queue.stack2.data) """ A colleague of yours keeps including incorrect JavaScript code in pull requests. You are getting tired of parsing through their code to make sure they've included correct brackets, braces, and parentheses. In order to save yourself time, you decide to write a function that can parse the code to make sure it includes the correct amount of opening and closing characters. We will call `(`, `{`, and `[` "openers". We will call `)`, `}`, and `]` "closers". Your input will be a string and your function needs to make sure that there is a correct number of openers and closers and that they are properly nested. Examples: `"{ [ ] ( ) }"` should return `True` `"{ [ ( ] ) }"` should return `False` `"{ [ }"` should return `False` You should be able to do this in one pass with O(n) time and O(n) space complexity. *Note: Remember that just making sure that each opener has a corresponding closer is not enough. You also have to confirm that they are ordered and nested correctly. For example, "{ [ ( ] ) }" should return False, even though each opener can be matched to a closer.* """ code = "{ [ ] ( ) }" code = "{ [ ( ] ) }" code = "{ [ }" def is_valid(code): check = [] if code == "": return True if code[0] == ")" or code[0] == "}" or code[0] == "]": return False for paren in code: if paren == " ": continue if paren == "(" or paren == "{" or paren == "[": print("paren:", paren) check.append(paren) print("append:", check) elif ( paren == ")" and check[-1] == "(" or paren == "}" and check[-1] == "{" or paren == "]" and check[-1] == "[" ): if len(check) == 0: print("len:", len(check)) return False else: print("pop:", paren) check.pop() else: print("else check:", paren, check) return False if check: print("check:", check) return False return True # print(is_valid(code)) """ Implement the missing code, denoted by ellipses. You may not modify the pre-existing code. Implement a queue using two stacks. You are given an array of requests, where requests[i] can be "push <x>" or "pop". Return an array composed of the results of each "pop" operation that is performed. Example For requests = ["push 1", "push 2", "pop", "push 3", "pop"], the output should be queueOnStacks(requests) = [1, 2]. After the first request, the queue is {1}; after the second it is {1, 2}. Then we do the third request, "pop", and add the first element of the queue 1 to the answer array. The queue becomes {2}. After the fourth request, the queue is {2, 3}. Then we perform "pop" again and add 2 to the answer array, and the queue becomes {3}. """ requests = ["push 1", "push 2", "pop", "push 3", "pop"] class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def queueOnStacks(requests): left = Stack() right = Stack() def insert(x): left.push(x) print("queue:", left.items) def remove(): if len(right.items) == 0: while len(left.items) > 0: shifted = left.pop() right.push(shifted) return right.items.pop() ans = [] for request in requests: req = request.split(" ") if req[0] == "push": insert(int(req[1])) else: ans.append(remove()) print("add to ans:", ans) return ans # print(queueOnStacks(requests)) """ Given a string sequence consisting of the characters '(', ')', '[', ']', '{', and '}'. Your task is to determine whether or not the sequence is a valid bracket sequence. The Valid bracket sequence is defined in the following way: An empty bracket sequence is a valid bracket sequence. If S is a valid bracket sequence then (S), [S] and {S} are also valid. If A and B are valid bracket sequences then AB is also valid. Example For sequence = "()", the output should be validBracketSequence(sequence) = true; For sequence = "()[]{}", the output should be validBracketSequence(sequence) = true; For sequence = "(]", the output should be validBracketSequence(sequence) = false; For sequence = "([)]", the output should be validBracketSequence(sequence) = false; For sequence = "{[]}", the output should be validBracketSequence(sequence) = true. """ sequence = "()" def validBracketSequence(sequence): pairs = dict(zip("(,[,{", "),],}")) stack = [] for item in sequence: if item in pairs: stack.append(pairs[item]) elif not (stack and item == stack.pop()): return False return not stack # print(validBracketSequence(sequence)) """ For a given positive integer n determine if it can be represented as a sum of two Fibonacci numbers (possibly equal). Example For n = 1, the output should be fibonacciSimpleSum2(n) = true. Explanation: 1 = 0 + 1 = F0 + F1. For n = 11, the output should be fibonacciSimpleSum2(n) = true. Explanation: 11 = 3 + 8 = F4 + F6. For n = 60, the output should be fibonacciSimpleSum2(n) = true. Explanation: 11 = 5 + 55 = F5 + F10. For n = 66, the output should be fibonacciSimpleSum2(n) = false """ def fibonacciSimpleSum2(n): # if 0 is less than n and n is less than 5 then we know we can return # true because n will be 1-4 which can be created with 2 fib numbers if 0 < n < 5: return True # first get fibonacci sequence up to n seq = [0, 1] # starting from 2 and ending at n for i in range(2, n): # add seq at i - 2 (0 to start) and seq at i - 1 (1 to start) fib = seq[i - 2] + seq[i - 1] # if n is greater than fib if n >= fib: # we can append fib to the sequence seq.append(fib) # if fib is greater than or equal to n we can stop else: break print(seq) # The check I googled # for i, number in enumerate(seq[:-1]): # paired = n - number # if paired in seq[i + 1:]: # return True # check if any 2 of the numbers in seq add up to n # My check for i in range(len(seq) - 1): # O(n^2) j = 0 while (seq[i] + seq[j]) != n: if j == len(seq) - 1: break else: j += 1 if seq[i] + seq[j] == n: return True return False print(fibonacciSimpleSum2(5)) """ Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search for target in nums. If target exists, then return its index, otherwise, return -1. Example 1: Input: nums = [-1,0,3,5,9,12], target = 9 Output: 4 Explanation: 9 exists in nums and its index is 4 Example 2: Input: nums = [-1,0,3,5,9,12], target = 2 Output: -1 Explanation: 2 does not exist in nums so return -1 Note: All elements in nums are unique. The length of nums will be <= 100 The value of each element in nums will be in the range [1, 10000] """ def csBinarySearch(nums, target): min = 0 max = len(nums) - 1 while not max < min: guess = (max + min) // 2 if nums[guess] == target: return guess elif nums[guess] < target: min = guess + 1 else: max = guess - 1 return -1 # print(csBinarySearch([-1, 0, 3, 5, 9, 12], 9)) """ Given an integer array nums sorted in ascending order, and an integer target. Suppose that nums is rotated at some pivot unknown to you beforehand (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You should search for target in nums and if found return its index, otherwise return -1. Example 1: Input: nums = [6,7,0,1,2,3,4,5], target = 0 Output: 2 Example 2: Input: nums = [6,7,0,1,2,3,4,5], target = 3 Output: 5 Example 3: Input: nums = [1], target = 0 Output: -1 Note: 1 <= nums.length < 100 1 <= nums[i] <= 100 All values of nums are unique. """ def csSearchRotatedSortedArray(nums, target): min = 0 max = len(nums) - 1 while not max < min: guess = (max + min) // 2 # print(f'min: {nums[min]} max: {nums[max]} guess:{nums[guess]} target:' # f' {target}') # if the guess is the target we got it and return the guess if nums[guess] == target: # print('guessed the target') return guess # if min is less than or equal to the guess elif nums[min] <= nums[guess]: # print('min less than guess') # if min is less than or equal to the target and less than the guess if nums[min] <= target < nums[guess]: # print('min less than or equal to target and less than guess') # we can set max to the guess because nothing past the guess # can be the target max = guess # else we can set min to guess + 1 because nothing before it # can be the target else: # print('min is greater than target and greater than or equal ' # 'to guess') min = guess + 1 # else if min is greater than the guess else: print("min is greater than or equal to guess") # if max - 1 is greater than the target and greater than the guess if nums[max - 1] >= target > nums[guess]: # print('max - 1 greater than or equal to target and greater ' # 'than guess') # we can set min to guess plus one because nothing before it # can be the target min = guess + 1 else: # print('max -1 less than target and less than or equal to guess') # else we set max equal to guess because nothing after it can # be the target max = guess return -1 # print(f'search rotate' # f'd array: ' # f'' # f'{csSearchRotatedSortedArray([45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44], 48)}') """ Challenge Write a logarithmic expression that is identical to this exponential expression: 2^n = 64 log_2 64 = 6 Write an exponential expression that is identical to this logarithmic expression: log_2 128 = n 2^7 = 128 What keywords should you look out for that might alert you that logarithms are involved? doubles, halves """ """ Rewrite the implementation of linear search below so that the algorithm searches from the end of the list to the beginning. """ def linear_search(arr, target): # loop through each item in the input array i = len(arr) - 1 for idx in range(len(arr)): # check if the item at the current index is equal to the target if arr[i] == target: # return the current index as the match return i i -= 1 # if we were able to loop through the entire array, the target is not present return -1 arr = [1, 2, 3, 4, 5, 6] target = 3 # print(linear_search(arr, target)) """ Write a recursive search function that receives as input an array of integers and a target integer value. This function should return True if the target element exists in the array, and False otherwise. What would be the base case(s) we'd have to consider for implementing this function? How should our recursive solution converge on our base case(s)? In your own words, write out the three rules for recursion and how you can identify when a problem is amenable to using a recursive method. - problem has an obvious base case - the data changes predictably on the way to the base case - the function must call itself """ def recursive_search(arr, target): if arr[0] == target: return True elif len(arr[1:]) > 1: return recursive_search(arr[1:], target) return False # print(recursive_search(arr, target)) """ Binary Search """ def binary_search(arr, target): # 1. Declare min = 0 and max = length of array - 1 min = 0 max = len(arr) - 1 while not max < min: # 2. Figure out the guess value by getting the middle integer between min and max guess = (max + min) // 2 # 3. if array[guess] equals the target, we found the element, return the index if arr[guess] == target: return guess # 4. if the guess was too low, reset min to be one more than the guess elif arr[guess] < target: min = guess + 1 # 5. if the guess was too high, reset max to be one less than the guess else: max = guess - 1 # no match was found return -1 # target = 5 # print(binary_search(arr, target)) """ What is the time complexity of our binary_search function above? - logN Can you turn the function above into a recursive function? Any variables tracked/updated in the while loop will have to become parameters for the recursive function. """ arr = [1, 2, 3, 4, 5, 6] target = 55 def binary_recursive_search(arr, target, min_index, max_index): if min_index >= max_index: return -1 guess = (max_index + min_index) // 2 if arr[guess] == target: return guess elif target < arr[guess]: return binary_recursive_search(arr, target, min_index, guess - 1) else: return binary_recursive_search(arr, target, guess + 1, max_index) # print(binary_recursive_search(arr, target, 0, len(arr))) """ Searching-recursion guided """ """ I was bored one day and decided to look at last names in the phonebook for my area. I flipped open the phonebook to a random page near the middle and started perusing. I wrote each last name that I was unfamiliar with down on paper in increasing order. When I got to the end of the phonebook, I was having so much fun I decided to start from the beginning and keep going until I reached the page where I had started. When I was finished, I had a list of interesting last names that were mostly alphabetical. The problem was that my list starts somewhere near the middle of the alphabet, reaches the end, and then starts from the beginning of the alphabet. In other words, my list of names is sorted, but it is "rotated." Example: surnames = [ 'liu', 'mcdowell', 'nixon', 'sparks', 'zhang', 'ahmed', # <-- rotates here! 'brandt', 'davenport', 'farley', 'glover', 'kennedy', ] Write a function that finds the index of the "rotation point". The "rotation point" is where I started working from the beginning of the phone book. The list I came up was absolutely huge, so make sure your solution is efficient. *Note: you should be able to come up with a solution that has O(log n) time complexity.* """ surnames = [ "sparks", "zhang", "liu", "ahmed", # <-- rotates here! "brandt", "davenport", "farley", "glover", "kennedy", "mcdowell", "nixon", ] # works w numbers not names def find_rotation_point(surnames): # Your code here min = 0 max = len(surnames) - 1 while not max < min: guess = (min + max) // 2 if ( surnames[guess] < surnames[guess + 1] and surnames[guess] < surnames[guess - 1] ): return guess else: if surnames[guess] > surnames[0]: min = guess + 1 elif surnames[guess] < surnames[0]: max = guess - 1 # print('rotation', find_rotation_point([6, 7, 8, 9, 10, 0, 1, 2, 3, 4, 5])) def find_rotation_point(surnames): # Your code here # UNDERSTAND # [ 6, 7, 8, 0, 1, 2, 3, 4, 5] # min max # mid # [ 7, 0, 1, 2, 3, 4, 5, 6] # min # max # mid # Plan: # we should use some kind of a binary search # max and min indices min = 0 max = len(surnames) - 1 # find the middle index mid = (min + max) // 2 # if the middle surname is the rotation point: (base case) # middle surname is rotation if prev element is > than current # return the index # otherwise: # have we rotated yet? # we can tell that by comparing to the first element in the array first_element = surnames[0] while not max <= min: current_element = surnames[mid] # if current element >= first element: we haven't rotated yet, rotation point is "still ahead of us" if current_element >= first_element: # search right # move the min index to middle + 1 min = mid + 1 # else if current element < first element: we have rotated else: # current_element < first_element # search left: # move the max index to middle index max = mid # keep going until max and min cross return min """ You are a new author that is working on your first book. You are working on a series of drafts. Each draft is based on the previous draft. The latest draft of your book has a serious typo. Since each newer draft is based on the previous draft, all the drafts after the draft containing the typo also include the typo. Suppose you have `n` drafts `[1, 2, 3, ..., n]` and you need to find out the first one containing the typo (which causes all the following drafts to have the typo as well). You are given access to an API tool `containsTypo(draft)` that will return `True` if the draft contains a typo and `False` if it does not. You need to implement a function that will find the *first draft that contains a typo*. Also, you have to pay a fee for every call to `containsTypo()`, so make sure that your solution minimizes the number of API calls. Example: Given `n = 5`, and `draft = 4` is the first draft containing a typo. containsTypo(3) -> False containsTypo(5) -> True containsTypo(4) -> True """ n = [1, 2, 3, 4, 5, 6, 7, 8, 9] def firstDraftWithTypo(n): # Your code here pass contains_typo = 4 min = 0 max = len(n) - 1 while not max < min: guess = (min + max) // 2 # if containsTypo were real this line would be: # if containsTypo(n[guess]) and not containsTypo(n[guess -1]): if n[guess] == contains_typo and n[guess - 1] != contains_typo: # resulting in the first occurrence where the typo exists return n[guess] # if containsTypo were real this line would be: # if not containsTypo(n[guess]): elif n[guess] < contains_typo: min = guess + 1 else: max = guess - 1 return -1 # print(firstDraftWithTypo(n)) """ Cookie Monster can eat either 1, 2, or 3 cookies at a time. If he were given a jar of cookies with `n` cookies inside of it, how many ways could he eat all `n` cookies in the cookie jar? Implement a function `eating_cookies` that counts the number of possible ways Cookie Monster can eat all of the cookies in the jar. For example, for a jar of cookies with n = 3 (the jar has 3 cookies inside it), there are 4 possible ways for Cookie Monster to eat all the cookies inside it: He can eat 1 cookie at a time 3 times He can eat 1 cookie, then 2 cookies He can eat 2 cookies, then 1 cookie He can eat 3 cookies all at once. Thus, eating_cookies(3) should return an answer of 4. Can you implement a solution that has a O(n) time complexity and a O(n) space complexity? *Note: Since this question is asking you to generate a bunch of possible permutations, you'll probably want to use recursion for this. Think about base cases that we would want our recursive function to stop recursing on (when do you know you've found a "way" to eat the cookies versus when you have not?).* """ """ 1 1 once = 1 ******** 2 1 twice 2 once = 2 ********* 3 1 1 1 1 and 2 2 and 1 3 once ******** """ n = 3 def eating_cookies(n, cache=None): # if n < 0: # return 0 # if n == 0: # return 1 # return eating_cookies(n-1) + eating_cookies(n - 2) + eating_cookies(n -3) # let the cache be 2 longer than n cache = [0] * (n + 2) print(cache) cache[0] = 1 cache[1] = 1 cache[2] = 2 for i in range(3, n + 1): print("*******i:", i) print( f"cache[i]: {cache[i]} = cache[i - 1]: {cache[i - 1]} + cache[i - 2]: {cache[i - 2]} + cache[i - 3]: {cache[i - 3]}" ) cache[i] = cache[i - 1] + cache[i - 2] + cache[i - 3] return cache[n] """ when he has n cookies, he has three options: eat 1 cookie, eat 2 cookie, or eat 3 cookies. So if you go down each of those options, he then has n - x more cookies to eat, and y ways to eat that amount of cookies. So you can basically sum up the number of ways to eat (n-1) cookies + ways to eat (n-2) cookies + ways to eat (n-3) cookies """ # print(eating_cookies(n)) """ Sprint 1 """ """ Given a string, remove adjacent duplicate characters. Example For s = "aaaaa", the output should be removeAdjacent(s) = "a"; For s = "abccaaab", the output should be removeAdjacent(s) = "abcab". """ # s = "aaaaa" # s = "abccaaab" def removeAdjacent(s): # add first letter to new string if s == "": return s new_str = s[0] # iterate the string for letter in s: # if the next letter is the same as previous continue if letter == new_str[len(new_str) - 1]: continue else: new_str += letter return new_str # print(removeAdjacent(s)) """ Write a function to reverse the given string (the input string is given as an array of characters) and return the result. Note: your solution should be "in-place" with O(1) space complexity. Although many in-place functions do not return the modified input, in this case you should. Hint: you should try using a "two-pointers approach". [execution time limit] 4 seconds (py3) [input] array.char input [output] array.char """ str = "reverse" def reverse_String(str): i, j = 0, len(str) - 1 print(i, j) while i < j: str[i], str[j] = str[j], str[i] i += 1 j -= 1 return str # print(reverse_String(str)) """ Given the string, check if it is a palindrome. Example For inputString = "aabaa", the output should be checkPalindrome(inputString) = true; For inputString = "abac", the output should be checkPalindrome(inputString) = false; For inputString = "a", the output should be checkPalindrome(inputString) = true. """ inputString = "aabaa" # inputString = "abac" # inputString = "a" inputString = "hlbeeykoqqqqokyeeblh" def checkPalindrome(inputString): return inputString == inputString[::-1] # print(checkPalindrome(inputString)) """ *** Data Structures and Algorithms Sprint *** --------------------------------------------- """ """ *** Reverse Linked List *** --------------------------- Note: Your solution should have O(l.length) time complexity and O(1) space complexity, since this is what you will be asked to accomplish in an interview. Given a singly linked list, reverse and return it. Example For l = [1, 2, 3, 4, 5], the output should be reverseLinkedList(l) = [5, 4, 3, 2, 1]. """ # Singly-linked lists are already defined with this interface: # class ListNode(object): # def __init__(self, x): # self.value = x # self.next = None # def reverseLinkedList(l): cur = l prev = None next = None while cur: next = cur.next cur.next = prev prev = cur cur = next return prev """ *** check Blanagrams *** ------------------------ Two words are blanagrams if they are anagrams but exactly one letter has been substituted for another. Given two words, check if they are blanagrams of each other. Example For word1 = "tangram" and word2 = "anagram", the output should be checkBlanagrams(word1, word2) = true; For word1 = "tangram" and word2 = "pangram", the output should be checkBlanagrams(word1, word2) = true. Since a word is an anagram of itself (a so-called trivial anagram), we are not obliged to rearrange letters. Only the substitution of a single letter is required for a word to be a blanagram, and here 't' is changed to 'p'. For word1 = "silent" and word2 = "listen", the output should be checkBlanagrams(word1, word2) = false. These two words are anagrams of each other, but no letter substitution was made (the trivial substitution of a letter with itself shouldn't be considered), so they are not blanagrams. """ word1 = "tangpam" word2 = "anagram" def checkBlanagrams(word1, word2): if word1 == "" or word2 == "": return False work_string = "" diff = 0 sort1 = sorted(word1) # O(n) space O(nlogn) time sort2 = sorted(word2) # O(n) space O(nlogn) time for i in range(len(word1)): # O(n) # check for substitutions if sort1[i] != sort2[i]: diff += 1 work_string += word1[i] # O(n) space print(work_string) print(word1) count = 0 # check if there was more than 1 substitution made for i in range(len(work_string)): # O(n) if work_string[i] not in word2: count += 1 print("count:", count) # if more than 1 substitution return False if count > 1: return False # if no substitutions return false if diff == 0: return False if sorted(work_string) == sorted(word1): return True return False # print(checkBlanagrams(word1, word2)) """ *** Find value sorted shifted array *** --------------------------------------- You are given a sorted array in ascending order that is rotated at some unknown pivot (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]) and a target value. Write a function that returns the target value's index. If the target value is not present in the array, return -1. You may assume no duplicate exists in the array. Your algorithm's runtime complexity must be in the order of O(log n). Example 1: Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Example 2: Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1 """ nums = [4, 5, 6, 7, 0, 1, 2] target = 0 def findValueSortedShiftedArray(nums, target): min = 0 max = len(nums) - 1 while not max < min: guess = (max + min) // 2 if nums[guess] == target: return guess elif nums[min] <= nums[guess]: if nums[min] <= target < nums[guess]: max = guess else: min = guess + 1 else: if nums[max - 1] >= target > nums[guess]: min = guess + 1 else: max = guess return -1
""" Given an array of integers `nums`, define a function that returns the "pivot" index of the array. The "pivot" index is where the sum of all the numbers on the left of that index is equal to the sum of all the numbers on the right of that index. If the input array does not have a "pivot" index, then the function should return `-1`. If there are more than one "pivot" indexes, then you should return the left-most "pivot" index. Example 1: Input: nums = [1,7,3,6,5,6] Output: 3 Explanation: The sum of the numbers to the left of index 3 (1 + 7 + 3 = 11) is equal to the sum of numbers to the right of index 3 (5 + 6 = 11). Also, 3 is the first index where this occurs. Example 2: Input: nums = [1,2,3] Output: -1 Explanation: There is no index that satisfies the conditions in the problem statement. """ nums = [1, 7, 3, 6, 5, 6] def pivot_index(nums): if len(nums) <= 1: return -1 left = 0 right = sum(nums) for i in range(len(nums)): right -= nums[i] if right == left: return i left += nums[i] '\nYou are given a non-empty array that represents the digits of a non-negative integer.\nWrite a function that increments the number by 1.\nThe digits are stored so that the digit representing the most significant place value is at the beginning of the array. Each element in the array only contains a single digit.\nYou will not receive a leading 0 in your input array (except for the number 0 itself).\nExample 1:\nInput: [1,3,2]\nOutput: [1,3,3]\nExplanation: The input array represents the integer 132. 132 + 1 = 133.\nExample 2:\nInput: [3,2,1,9]\nOutput: [3,2,2,0]\nExplanation: The input array represents the integer 3219. 3219 + 1 = 3220.\nExample 3:\nInput: [9,9,9]\nOutput: [1,0,0,0]\nExplanation: The input array represents the integer 999. 999 + 1 = 1000.\n' def plus_one(digits): index = len(digits) - 1 while index >= 0 and digits[index] == 9: digits[index] = 0 index -= 1 if index == -1: digits.insert(0, 1) else: digits[index] += 1 return digits "\nYou are given the prices of a stock, in the form of an array of integers, prices. Let's say that prices[i] is the price of the stock on the ith day (0-based index). Assuming that you are allowed to buy and sell the stock only once, your task is to find the maximum possible profit (the difference between the buy and sell prices).\n\nNote: You can assume there are no fees associated with buying or selling the stock.\n\nExample\n\nFor prices = [6, 3, 1, 2, 5, 4], the output should be buyAndSellStock(prices) = 4.\n\nIt would be most profitable to buy the stock on day 2 and sell it on day 4. Thus, the maximum profit is prices[4] - prices[2] = 5 - 1 = 4.\n\nFor prices = [8, 5, 3, 1], the output should be buyAndSellStock(prices) = 0.\n\nSince the value of the stock drops each day, there's no way to make a profit from selling it. Hence, the maximum profit is 0.\n\nFor prices = [3, 100, 1, 97], the output should be buyAndSellStock(prices) = 97.\n\nIt would be most profitable to buy the stock on day 0 and sell it on day 1. Thus, the maximum profit is prices[1] - prices[0] = 100 - 3 = 97.\n" prices = [3, 100, 1, 97] prices = [6, 3, 1, 2, 5, 4] prices = [8, 5, 3, 1] prices = [3, 100, 1, 97] def buy_and_sell_stock(prices): length = len(prices) if prices == sorted(prices, reverse=True) or len(prices) < 2: return 0 highest_profit = prices[1] - prices[0] smallest_number = prices[0] for i in range(1, length): if prices[i] - smallest_number > highest_profit: highest_profit = prices[i] - smallest_number if prices[i] < smallest_number: smallest_number = prices[i] return highest_profit '\nGiven a string, your task is to replace each of its characters by the next one in the English alphabet; i.e. replace a with b, replace b with c, etc (z would be replaced by a).\n\nExample\n\nFor inputString = "crazy", the output should be alphabeticShift(inputString) = "dsbaz".\n' input_string = 'crazy' def alphabetic_shift(inputString): new_string = '' for letter in inputString: new_letter = ord(letter) + 1 if new_letter == 123: new_letter = 97 new_string += chr(new_letter) return new_string '\nYou are given a parentheses sequence, check if it\'s regular.\n\nExample\n\nFor s = "()()(())", the output should be\nvalidParenthesesSequence(s) = true;\nFor s = "()()())", the output should be\nvalidParenthesesSequence(s) = false\n' s = '()()(())' s = '()()())' def valid_parentheses_sequence(s): check = [] if s == '': return True if s[0] == ')': return False for paren in s: if paren == '(': check.append(paren) elif len(check) == 0: return False else: check.pop() if check != []: return False return True "\nGiven only a reference to a specific node in a linked list, delete that node from a singly-linked list.\nExample:\nThe code below should first construct a linked list (x -> y -> z) and then delete `y` from the linked list by calling the function `delete_node`. It is your job to write the `delete_node` function.\n```python\nclass LinkedListNode():\n def __init__(self, value):\n self.value = value\n self.next = None\nx = LinkedListNode('X')\ny = LinkedListNode('Y')\nz = LinkedListNode('Z')\nx.next = y\ny.next = z\ndelete_node(y)\n```\n*Note: We can do this in O(1) time and space! But be aware that our solution will have some side effects...*\n" class Linkedlistnode: def __init__(self, value): self.value = value self.next = None def delete_node(node_to_delete): next = node_to_delete.next next.next = None node_to_delete.value = next.value node_to_delete.next = next.next x = linked_list_node('X') y = linked_list_node('Y') z = linked_list_node('Z') x.next = y y.next = z "\nGiven a reference to the head node of a singly-linked list, write a function\nthat reverses the linked list in place. The function should return the new head\nof the reversed list.\nIn order to do this in O(1) space (in-place), you cannot make a new list, you\nneed to use the existing nodes.\nIn order to do this in O(n) time, you should only have to traverse the list\nonce.\n*Note: If you get stuck, try drawing a picture of a small linked list and\nrunning your function by hand. Does it actually work? Also, don't forget to\nconsider edge cases (like a list with only 1 or 0 elements).*\n" class Linkedlistnode: def __init__(self, value): self.value = value self.next = None def reverse(head_of_list): current_node = head_of_list previous_node = None next_node = None while current_node: next_node = current_node.next current_node.next = previous_node previous_node = current_node current_node = next_node return previous_node class Listnode(object): def __init__(self, x): self.value = x self.next = None [1, 3, 4, 6] '\nNote: Your solution should have O(n) time complexity, where n is the number of elements in l, since this is what you will be asked to accomplish in an interview.\n\nYou have a singly linked list l, which is sorted in strictly increasing order, and an integer value. Add value to the list l, preserving its original sorting.\n\nNote: in examples below and tests preview linked lists are presented as arrays just for simplicity of visualization: in real data you will be given a head node l of the linked list\n\nExample\n\nFor l = [1, 3, 4, 6] and value = 5, the output should be\ninsertValueIntoSortedLinkedList(l, value) = [1, 3, 4, 5, 6];\nFor l = [1, 3, 4, 6] and value = 10, the output should be\ninsertValueIntoSortedLinkedList(l, value) = [1, 3, 4, 6, 10];\nFor l = [1, 3, 4, 6] and value = 0, the output should be\ninsertValueIntoSortedLinkedList(l, value) = [0, 1, 3, 4, 6].\n' def insert_value_into_sorted_linked_list(l, value): node = list_node(value) if l == None: return node elif l.value > value: node.next = l return node else: (temp, prev) = (l, None) while temp.next and temp.value <= value: prev = temp temp = temp.next if temp.next == None and temp.value <= value: temp.next = node else: node.next = prev.next prev.next = node return l '\nNote: Your solution should have O(l1.length + l2.length) time complexity, since this is what you will be asked to accomplish in an interview.\n\nGiven two singly linked lists sorted in non-decreasing order, your task is to merge them. In other words, return a singly linked list, also sorted in non-decreasing order, that contains the elements from both original lists.\n\nExample\n\nFor l1 = [1, 2, 3] and l2 = [4, 5, 6], the output should be\nmergeTwoLinkedLists(l1, l2) = [1, 2, 3, 4, 5, 6];\nFor l1 = [1, 1, 2, 4] and l2 = [0, 3, 5], the output should be\nmergeTwoLinkedLists(l1, l2) = [0, 1, 1, 2, 3, 4, 5].\n' class Listnode(object): def __init__(self, x): self.value = x self.next = None def merge_two_linked_lists(l1, l2): merged_node = list_node(0) end = merged_node while True: if l1 is None: end.next = l2 break if l2 is None: end.next = l1 break if l1.value <= l2.value: end.next = l1 l1 = l1.next else: end.next = l2 l2 = l2.next end = end.next return merged_node.next '\nNote: Your solution should have O(n) time complexity, where n is the number of elements in l, and O(1) additional space complexity, since this is what you would be asked to accomplish in an interview.\n\nGiven a linked list l, reverse its nodes k at a time and return the modified list. k is a positive integer that is less than or equal to the length of l. If the number of nodes in the linked list is not a multiple of k, then the nodes that are left out at the end should remain as-is.\n\nYou may not alter the values in the nodes - only the nodes themselves can be changed.\n\nExample\n\nFor l = [1, 2, 3, 4, 5] and k = 2, the output should be\nreverseNodesInKGroups(l, k) = [2, 1, 4, 3, 5];\nFor l = [1, 2, 3, 4, 5] and k = 1, the output should be\nreverseNodesInKGroups(l, k) = [1, 2, 3, 4, 5];\nFor l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] and k = 3, the output should be\nreverseNodesInKGroups(l, k) = [3, 2, 1, 6, 5, 4, 9, 8, 7, 10, 11].\n' class Listnode(object): def __init__(self, x): self.value = x self.next = None def reverse_nodes_in_k_groups(l, k): new_node = list_node(0) new_node.next = l prev = new_node while True: start = prev.next end = prev for i in range(0, k): end = end.next if end == None: return new_node.next new_reversed = end.next reverse_list(start, end) prev.next = end start.next = new_reversed prev = start def reverse_list(start, end): old_reversed = start current = start next_node = start.next while current != end: current = next_node next_node = next_node.next current.next = old_reversed old_reversed = current '\nRefactor the Queue class below by adding an `is_empty` method. After writing this method, refactor your other methods to use this method in your other methods.\n' class Linkedlistnode: def __init__(self, data): self.data = data self.next = None class Queue: def __init__(self): self.front = None self.rear = None def enqueue(self, item): new_node = linked_list_node(item) if self.is_empty(): self.front = new_node self.rear = new_node else: self.rear.next = new_node self.rear = new_node def dequeue(self): if not self.is_empty(): old_front = self.front self.front = old_front.next if self.is_empty(): self.rear = None return old_front def is_empty(self): return self.front is None and self.rear is None '\nAdd a peek method to the Stack class. The peek method should return the value of the top item in the stack without actually removing it from the stack.\n' class Stack: def __init__(self): self.data = [] def push(self, item): self.data.append(item) def peek(self, item): return self.data[-1] def pop(self): if len(self.data) > 0: return self.data.pop() return 'The stack is empty' '\nAdd a peek method to the Stack class below. The peek method should return the value of the node that is at the top of the stack without actually removing it from the stack.\n' class Linkedlistnode: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.top = None def push(self, data): new_node = linked_list_node(data) new_node.next = self.top self.top = new_node def pop(self): if self.top is not None: popped_node = self.top self.top = popped_node.next return popped_node.data def peek(self): if self.top is not None: return self.top '\nQueues and stacks guided\n' "\nYou've encountered a situation where you want to easily be able to pull the\nlargest integer from a stack.\nYou already have a `Stack` class that you've implemented using a dynamic array.\nUse this `Stack` class to implement a new class `MaxStack` with a method\n`get_max()` that returns the largest element in the stack. `get_max()` should\nnot remove the item.\n*Note: Your stacks will contain only integers. You should be able to get a\nruntime of O(1) for push(), pop(), and get_max().*\n" class Stack(object): def __init__(self): """Initialize an empty stack""" self.items = [] def push(self, item): """Push a new item onto the stack""" self.items.append(item) def pop(self): """Remove and return the last item""" if not self.items: return None return self.items.pop() def peek(self): """Return the last item without removing it""" if not self.items: return None return self.items[-1] class Maxstack(object): def __init__(self): self.stack = stack() self.max_stack = stack() def push(self, item): """Add a new item onto the top of our stack.""" current_max = self.get_max() if current_max is None or current_max < item: self.max_stack.push(item) self.stack.push(item) def pop(self): """Remove and return the top item from our stack.""" item = self.stack.pop() self.max_stack.pop() return item def get_max(self): """The last item in maxes_stack is the max item in our stack.""" return self.max_stack.peek() max_stack = max_stack() max_stack.push(1) max_stack.push(2) max_stack.push(5) max_stack.pop() '\nYour goal is to define a `Queue` class that uses two stacks. Your `Queue` class\nshould have an `enqueue()` method and a `dequeue()` method that ensures a\n"first in first out" (FIFO) order.\nAs you write your methods, you should optimize for time on the `enqueue()` and\n`dequeue()` method calls.\nThe Stack class that you will use has been provided to you.\n' class Stack: def __init__(self): self.data = [] def push(self, item): self.data.append(item) def pop(self): if len(self.data) > 0: return self.data.pop() return 'The stack is empty' class Queuetwostacks: def __init__(self): self.stack1 = stack() self.stack2 = stack() def enqueue(self, item): self.stack1.push(item) def dequeue(self): if len(self.stack1.data) != 0: shifted = self.stack1.pop() self.stack2.push(shifted) return self.dequeue() elif len(self.stack2.data) != 0: last_item = self.stack2.pop() return last_item '\nA colleague of yours keeps including incorrect JavaScript code in pull\nrequests. You are getting tired of parsing through their code to make sure\nthey\'ve included correct brackets, braces, and parentheses.\nIn order to save yourself time, you decide to write a function that can parse\nthe code to make sure it includes the correct amount of opening and closing\ncharacters.\nWe will call `(`, `{`, and `[` "openers".\nWe will call `)`, `}`, and `]` "closers".\nYour input will be a string and your function needs to make sure that there is\na correct number of openers and closers and that they are properly nested.\nExamples:\n`"{ [ ] ( ) }"` should return `True`\n`"{ [ ( ] ) }"` should return `False`\n`"{ [ }"` should return `False`\nYou should be able to do this in one pass with O(n) time and O(n) space\ncomplexity.\n*Note: Remember that just making sure that each opener has a corresponding\ncloser is not enough. You also have to confirm that they are ordered and nested\ncorrectly. For example, "{ [ ( ] ) }" should return False, even though each\nopener can be matched to a closer.*\n' code = '{ [ ] ( ) }' code = '{ [ ( ] ) }' code = '{ [ }' def is_valid(code): check = [] if code == '': return True if code[0] == ')' or code[0] == '}' or code[0] == ']': return False for paren in code: if paren == ' ': continue if paren == '(' or paren == '{' or paren == '[': print('paren:', paren) check.append(paren) print('append:', check) elif paren == ')' and check[-1] == '(' or (paren == '}' and check[-1] == '{') or (paren == ']' and check[-1] == '['): if len(check) == 0: print('len:', len(check)) return False else: print('pop:', paren) check.pop() else: print('else check:', paren, check) return False if check: print('check:', check) return False return True '\nImplement the missing code, denoted by ellipses. You may not modify the pre-existing code.\nImplement a queue using two stacks.\n\nYou are given an array of requests, where requests[i] can be "push <x>" or "pop". Return an array composed of the results of each "pop" operation that is performed.\n\nExample\n\nFor requests = ["push 1", "push 2", "pop", "push 3", "pop"], the output should be\nqueueOnStacks(requests) = [1, 2].\n\nAfter the first request, the queue is {1}; after the second it is {1, 2}. Then we do the third request, "pop", and add the first element of the queue 1 to the answer array. The queue becomes {2}. After the fourth request, the queue is {2, 3}. Then we perform "pop" again and add 2 to the answer array, and the queue becomes {3}.\n' requests = ['push 1', 'push 2', 'pop', 'push 3', 'pop'] class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def queue_on_stacks(requests): left = stack() right = stack() def insert(x): left.push(x) print('queue:', left.items) def remove(): if len(right.items) == 0: while len(left.items) > 0: shifted = left.pop() right.push(shifted) return right.items.pop() ans = [] for request in requests: req = request.split(' ') if req[0] == 'push': insert(int(req[1])) else: ans.append(remove()) print('add to ans:', ans) return ans '\nGiven a string sequence consisting of the characters \'(\', \')\', \'[\', \']\', \'{\', and \'}\'. Your task is to determine whether or not the sequence is a valid bracket sequence.\n\nThe Valid bracket sequence is defined in the following way:\n\nAn empty bracket sequence is a valid bracket sequence.\nIf S is a valid bracket sequence then (S), [S] and {S} are also valid.\nIf A and B are valid bracket sequences then AB is also valid.\nExample\n\nFor sequence = "()", the output should be validBracketSequence(sequence) = true;\nFor sequence = "()[]{}", the output should be validBracketSequence(sequence) = true;\nFor sequence = "(]", the output should be validBracketSequence(sequence) = false;\nFor sequence = "([)]", the output should be validBracketSequence(sequence) = false;\nFor sequence = "{[]}", the output should be validBracketSequence(sequence) = true.\n' sequence = '()' def valid_bracket_sequence(sequence): pairs = dict(zip('(,[,{', '),],}')) stack = [] for item in sequence: if item in pairs: stack.append(pairs[item]) elif not (stack and item == stack.pop()): return False return not stack '\nFor a given positive integer n determine if it can be represented as a sum of two Fibonacci numbers (possibly equal).\n\nExample\n\nFor n = 1, the output should be\nfibonacciSimpleSum2(n) = true.\n\nExplanation: 1 = 0 + 1 = F0 + F1.\n\nFor n = 11, the output should be\nfibonacciSimpleSum2(n) = true.\n\nExplanation: 11 = 3 + 8 = F4 + F6.\n\nFor n = 60, the output should be\nfibonacciSimpleSum2(n) = true.\n\nExplanation: 11 = 5 + 55 = F5 + F10.\n\nFor n = 66, the output should be\nfibonacciSimpleSum2(n) = false\n' def fibonacci_simple_sum2(n): if 0 < n < 5: return True seq = [0, 1] for i in range(2, n): fib = seq[i - 2] + seq[i - 1] if n >= fib: seq.append(fib) else: break print(seq) for i in range(len(seq) - 1): j = 0 while seq[i] + seq[j] != n: if j == len(seq) - 1: break else: j += 1 if seq[i] + seq[j] == n: return True return False print(fibonacci_simple_sum2(5)) '\nGiven a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search for target in nums. If target exists, then return its index, otherwise, return -1.\n\nExample 1:\nInput: nums = [-1,0,3,5,9,12], target = 9\nOutput: 4\nExplanation: 9 exists in nums and its index is 4\n\nExample 2:\nInput: nums = [-1,0,3,5,9,12], target = 2\nOutput: -1\nExplanation: 2 does not exist in nums so return -1\n\nNote:\n\nAll elements in nums are unique.\nThe length of nums will be <= 100\nThe value of each element in nums will be in the range [1, 10000]\n' def cs_binary_search(nums, target): min = 0 max = len(nums) - 1 while not max < min: guess = (max + min) // 2 if nums[guess] == target: return guess elif nums[guess] < target: min = guess + 1 else: max = guess - 1 return -1 '\nGiven an integer array nums sorted in ascending order, and an integer target.\n\nSuppose that nums is rotated at some pivot unknown to you beforehand (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).\n\nYou should search for target in nums and if found return its index, otherwise return -1.\n\nExample 1:\nInput: nums = [6,7,0,1,2,3,4,5], target = 0\nOutput: 2\n\nExample 2:\nInput: nums = [6,7,0,1,2,3,4,5], target = 3\nOutput: 5\n\nExample 3:\nInput: nums = [1], target = 0\nOutput: -1\n\nNote:\n\n1 <= nums.length < 100\n1 <= nums[i] <= 100\nAll values of nums are unique.\n' def cs_search_rotated_sorted_array(nums, target): min = 0 max = len(nums) - 1 while not max < min: guess = (max + min) // 2 if nums[guess] == target: return guess elif nums[min] <= nums[guess]: if nums[min] <= target < nums[guess]: max = guess else: min = guess + 1 else: print('min is greater than or equal to guess') if nums[max - 1] >= target > nums[guess]: min = guess + 1 else: max = guess return -1 '\nChallenge\nWrite a logarithmic expression that is identical to this exponential expression:\n\n2^n = 64\nlog_2 64 = 6\n\nWrite an exponential expression that is identical to this logarithmic expression:\n\nlog_2 128 = n\n2^7 = 128\n\nWhat keywords should you look out for that might alert you that logarithms are involved?\ndoubles, halves\n' '\nRewrite the implementation of linear search below so that the algorithm searches from the end of the list to the beginning.\n' def linear_search(arr, target): i = len(arr) - 1 for idx in range(len(arr)): if arr[i] == target: return i i -= 1 return -1 arr = [1, 2, 3, 4, 5, 6] target = 3 "\nWrite a recursive search function that receives as input an array of integers and a target integer value. This function should return True if the target element exists in the array, and False otherwise.\nWhat would be the base case(s) we'd have to consider for implementing this function?\nHow should our recursive solution converge on our base case(s)?\n\nIn your own words, write out the three rules for recursion and how you can identify when a problem is amenable to using a recursive method.\n- problem has an obvious base case\n- the data changes predictably on the way to the base case \n- the function must call itself\n" def recursive_search(arr, target): if arr[0] == target: return True elif len(arr[1:]) > 1: return recursive_search(arr[1:], target) return False '\nBinary Search\n' def binary_search(arr, target): min = 0 max = len(arr) - 1 while not max < min: guess = (max + min) // 2 if arr[guess] == target: return guess elif arr[guess] < target: min = guess + 1 else: max = guess - 1 return -1 '\nWhat is the time complexity of our binary_search function above?\n- logN\nCan you turn the function above into a recursive function? Any variables tracked/updated in the while loop will have to become parameters for the recursive function.\n' arr = [1, 2, 3, 4, 5, 6] target = 55 def binary_recursive_search(arr, target, min_index, max_index): if min_index >= max_index: return -1 guess = (max_index + min_index) // 2 if arr[guess] == target: return guess elif target < arr[guess]: return binary_recursive_search(arr, target, min_index, guess - 1) else: return binary_recursive_search(arr, target, guess + 1, max_index) '\nSearching-recursion guided\n' '\nI was bored one day and decided to look at last names in the phonebook for my\narea.\nI flipped open the phonebook to a random page near the middle and started\nperusing. I wrote each last name that I was unfamiliar with down on paper in\nincreasing order. When I got to the end of the phonebook, I was having so much\nfun I decided to start from the beginning and keep going until I reached the\npage where I had started.\nWhen I was finished, I had a list of interesting last names that were mostly\nalphabetical. The problem was that my list starts somewhere near the middle of\nthe alphabet, reaches the end, and then starts from the beginning of the\nalphabet. In other words, my list of names is sorted, but it is "rotated."\nExample:\nsurnames = [\n \'liu\',\n \'mcdowell\',\n \'nixon\',\n \'sparks\',\n \'zhang\',\n \'ahmed\', # <-- rotates here!\n \'brandt\',\n \'davenport\',\n \'farley\',\n \'glover\',\n \'kennedy\',\n]\nWrite a function that finds the index of the "rotation point". The "rotation\npoint" is where I started working from the beginning of the phone book. The\nlist I came up was absolutely huge, so make sure your solution is efficient.\n*Note: you should be able to come up with a solution that has O(log n) time\ncomplexity.*\n' surnames = ['sparks', 'zhang', 'liu', 'ahmed', 'brandt', 'davenport', 'farley', 'glover', 'kennedy', 'mcdowell', 'nixon'] def find_rotation_point(surnames): min = 0 max = len(surnames) - 1 while not max < min: guess = (min + max) // 2 if surnames[guess] < surnames[guess + 1] and surnames[guess] < surnames[guess - 1]: return guess elif surnames[guess] > surnames[0]: min = guess + 1 elif surnames[guess] < surnames[0]: max = guess - 1 def find_rotation_point(surnames): min = 0 max = len(surnames) - 1 mid = (min + max) // 2 first_element = surnames[0] while not max <= min: current_element = surnames[mid] if current_element >= first_element: min = mid + 1 else: max = mid return min '\nYou are a new author that is working on your first book. You are working on a\nseries of drafts. Each draft is based on the previous draft. The latest draft\nof your book has a serious typo. Since each newer draft is based on the\nprevious draft, all the drafts after the draft containing the typo also include\nthe typo.\nSuppose you have `n` drafts `[1, 2, 3, ..., n]` and you need to find out the\nfirst one containing the typo (which causes all the following drafts to have\nthe typo as well).\nYou are given access to an API tool `containsTypo(draft)` that will return\n`True` if the draft contains a typo and `False` if it does not.\nYou need to implement a function that will find the *first draft that contains\na typo*. Also, you have to pay a fee for every call to `containsTypo()`, so\nmake sure that your solution minimizes the number of API calls.\nExample:\nGiven `n = 5`, and `draft = 4` is the first draft containing a typo.\ncontainsTypo(3) -> False\ncontainsTypo(5) -> True\ncontainsTypo(4) -> True\n' n = [1, 2, 3, 4, 5, 6, 7, 8, 9] def first_draft_with_typo(n): pass contains_typo = 4 min = 0 max = len(n) - 1 while not max < min: guess = (min + max) // 2 if n[guess] == contains_typo and n[guess - 1] != contains_typo: return n[guess] elif n[guess] < contains_typo: min = guess + 1 else: max = guess - 1 return -1 '\nCookie Monster can eat either 1, 2, or 3 cookies at a time. If he were given a\njar of cookies with `n` cookies inside of it, how many ways could he eat all\n`n` cookies in the cookie jar? Implement a function `eating_cookies` that\ncounts the number of possible ways Cookie Monster can eat all of the cookies in\nthe jar.\nFor example, for a jar of cookies with n = 3 (the jar has 3 cookies inside it),\nthere are 4 possible ways for Cookie Monster to eat all the cookies inside it:\nHe can eat 1 cookie at a time 3 times\nHe can eat 1 cookie, then 2 cookies\nHe can eat 2 cookies, then 1 cookie\nHe can eat 3 cookies all at once.\nThus, eating_cookies(3) should return an answer of 4.\nCan you implement a solution that has a O(n) time complexity and a O(n) space\ncomplexity?\n*Note: Since this question is asking you to generate a bunch of possible\npermutations, you\'ll probably want to use recursion for this. Think about base\ncases that we would want our recursive function to stop recursing on (when do\nyou know you\'ve found a "way" to eat the cookies versus when you have not?).*\n' '\n1\n1 once\n= 1\n********\n2\n1 twice\n2 once\n= 2\n*********\n3\n1 1 1 \n1 and 2\n2 and 1\n3 once\n********\n' n = 3 def eating_cookies(n, cache=None): cache = [0] * (n + 2) print(cache) cache[0] = 1 cache[1] = 1 cache[2] = 2 for i in range(3, n + 1): print('*******i:', i) print(f'cache[i]: {cache[i]} = cache[i - 1]: {cache[i - 1]} + cache[i - 2]: {cache[i - 2]} + cache[i - 3]: {cache[i - 3]}') cache[i] = cache[i - 1] + cache[i - 2] + cache[i - 3] return cache[n] '\nwhen he has n cookies, he has three options: eat 1 cookie, eat 2 cookie, or eat 3 cookies. So if you go down each of those options, he then has n - x more cookies to eat, and y ways to eat that amount of cookies. So you can basically sum up the number of ways to eat (n-1) cookies + ways to eat (n-2) cookies + ways to eat (n-3) cookies\n' '\nSprint 1\n' '\nGiven a string, remove adjacent duplicate characters.\n\nExample\n\nFor s = "aaaaa", the output should be\nremoveAdjacent(s) = "a";\nFor s = "abccaaab", the output should be\nremoveAdjacent(s) = "abcab".\n' def remove_adjacent(s): if s == '': return s new_str = s[0] for letter in s: if letter == new_str[len(new_str) - 1]: continue else: new_str += letter return new_str '\nWrite a function to reverse the given string (the input string is given as an array of characters) and return the result.\n\nNote: your solution should be "in-place" with O(1) space complexity. Although many in-place functions do not return the modified input, in this case you should.\n\nHint: you should try using a "two-pointers approach".\n\n[execution time limit] 4 seconds (py3)\n\n[input] array.char input\n\n[output] array.char\n' str = 'reverse' def reverse__string(str): (i, j) = (0, len(str) - 1) print(i, j) while i < j: (str[i], str[j]) = (str[j], str[i]) i += 1 j -= 1 return str '\nGiven the string, check if it is a palindrome.\n\nExample\n\nFor inputString = "aabaa", the output should be\ncheckPalindrome(inputString) = true;\nFor inputString = "abac", the output should be\ncheckPalindrome(inputString) = false;\nFor inputString = "a", the output should be\ncheckPalindrome(inputString) = true.\n' input_string = 'aabaa' input_string = 'hlbeeykoqqqqokyeeblh' def check_palindrome(inputString): return inputString == inputString[::-1] '\n*** Data Structures and Algorithms Sprint ***\n---------------------------------------------\n' '\n*** Reverse Linked List ***\n---------------------------\n\nNote: Your solution should have O(l.length) time complexity and O(1) space complexity, since this is what you will be asked to accomplish in an interview.\n\nGiven a singly linked list, reverse and return it.\n\nExample\n\nFor l = [1, 2, 3, 4, 5], the output should be\nreverseLinkedList(l) = [5, 4, 3, 2, 1].\n' def reverse_linked_list(l): cur = l prev = None next = None while cur: next = cur.next cur.next = prev prev = cur cur = next return prev '\n*** check Blanagrams ***\n------------------------\nTwo words are blanagrams if they are anagrams but exactly one letter has been substituted for another.\n\nGiven two words, check if they are blanagrams of each other.\n\nExample\n\nFor word1 = "tangram" and word2 = "anagram", the output should be\ncheckBlanagrams(word1, word2) = true;\n\nFor word1 = "tangram" and word2 = "pangram", the output should be\ncheckBlanagrams(word1, word2) = true.\n\nSince a word is an anagram of itself (a so-called trivial anagram), we are not obliged to rearrange letters. Only the substitution of a single letter is required for a word to be a blanagram, and here \'t\' is changed to \'p\'.\n\nFor word1 = "silent" and word2 = "listen", the output should be\ncheckBlanagrams(word1, word2) = false.\n\nThese two words are anagrams of each other, but no letter substitution was made (the trivial substitution of a letter with itself shouldn\'t be considered), so they are not blanagrams.\n' word1 = 'tangpam' word2 = 'anagram' def check_blanagrams(word1, word2): if word1 == '' or word2 == '': return False work_string = '' diff = 0 sort1 = sorted(word1) sort2 = sorted(word2) for i in range(len(word1)): if sort1[i] != sort2[i]: diff += 1 work_string += word1[i] print(work_string) print(word1) count = 0 for i in range(len(work_string)): if work_string[i] not in word2: count += 1 print('count:', count) if count > 1: return False if diff == 0: return False if sorted(work_string) == sorted(word1): return True return False "\n*** Find value sorted shifted array ***\n---------------------------------------\nYou are given a sorted array in ascending order that is rotated at some unknown pivot (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]) and a target value.\n\nWrite a function that returns the target value's index. If the target value is not present in the array, return -1.\n\nYou may assume no duplicate exists in the array.\n\nYour algorithm's runtime complexity must be in the order of O(log n).\n\nExample 1:\n\nInput: nums = [4,5,6,7,0,1,2], target = 0\nOutput: 4\n\nExample 2:\n\nInput: nums = [4,5,6,7,0,1,2], target = 3\nOutput: -1\n" nums = [4, 5, 6, 7, 0, 1, 2] target = 0 def find_value_sorted_shifted_array(nums, target): min = 0 max = len(nums) - 1 while not max < min: guess = (max + min) // 2 if nums[guess] == target: return guess elif nums[min] <= nums[guess]: if nums[min] <= target < nums[guess]: max = guess else: min = guess + 1 elif nums[max - 1] >= target > nums[guess]: min = guess + 1 else: max = guess return -1
def escreva(texto): print('~' * (len(texto) + 4)) print(f' {texto}') print('~' * (len(texto) + 4)) # Programa Principal text = str(input('Digite: ')) escreva(text) escreva('Gustavo Guanabara') escreva('Curso de Python no Youtube') escreva('CeV')
def escreva(texto): print('~' * (len(texto) + 4)) print(f' {texto}') print('~' * (len(texto) + 4)) text = str(input('Digite: ')) escreva(text) escreva('Gustavo Guanabara') escreva('Curso de Python no Youtube') escreva('CeV')
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/shams3049/catkin_ws/install/include;/usr/local/cuda-9.0/include".split(';') if "/home/shams3049/catkin_ws/install/include;/usr/local/cuda-9.0/include" != "" else [] PROJECT_CATKIN_DEPENDS = "".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "-lkinect2_registration;-l:/usr/lib/x86_64-linux-gnu/libOpenCL.so".split(';') if "-lkinect2_registration;-l:/usr/lib/x86_64-linux-gnu/libOpenCL.so" != "" else [] PROJECT_NAME = "kinect2_registration" PROJECT_SPACE_DIR = "/home/shams3049/catkin_ws/install" PROJECT_VERSION = "0.0.1"
catkin_package_prefix = '' project_pkg_config_include_dirs = '/home/shams3049/catkin_ws/install/include;/usr/local/cuda-9.0/include'.split(';') if '/home/shams3049/catkin_ws/install/include;/usr/local/cuda-9.0/include' != '' else [] project_catkin_depends = ''.replace(';', ' ') pkg_config_libraries_with_prefix = '-lkinect2_registration;-l:/usr/lib/x86_64-linux-gnu/libOpenCL.so'.split(';') if '-lkinect2_registration;-l:/usr/lib/x86_64-linux-gnu/libOpenCL.so' != '' else [] project_name = 'kinect2_registration' project_space_dir = '/home/shams3049/catkin_ws/install' project_version = '0.0.1'
def normalize( self, values, ): """Normalizes axis values Parameters ---------- self: Norm_ref a Norm_ref object values: ndarray axis values Returns ------- Vector of axis values """ return values / self.ref
def normalize(self, values): """Normalizes axis values Parameters ---------- self: Norm_ref a Norm_ref object values: ndarray axis values Returns ------- Vector of axis values """ return values / self.ref
PY_WRAPPER = """ import dash import dash_bootstrap_components as dbc app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP]) {snippet} app.layout = html.Div([{components}]) """ R_WRAPPER = """ library(dash) library(dashBootstrapComponents) library(dashHtmlComponents) app <- Dash$new(external_stylesheets = dbcThemes$BOOTSTRAP) {snippet} app$layout(htmlDiv(list({components}))) app$run_server(port = {port}) """ JL_WRAPPER = """ using Dash, DashBootstrapComponents app = dash(external_stylesheets=[dbc_themes.BOOTSTRAP]); {snippet} app.layout = html_div([{components}]); run_server(app, "127.0.0.1", {port}); """
py_wrapper = '\nimport dash\nimport dash_bootstrap_components as dbc\n\napp = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])\n\n{snippet}\n\napp.layout = html.Div([{components}])\n' r_wrapper = '\nlibrary(dash)\nlibrary(dashBootstrapComponents)\nlibrary(dashHtmlComponents)\n\napp <- Dash$new(external_stylesheets = dbcThemes$BOOTSTRAP)\n\n{snippet}\n\napp$layout(htmlDiv(list({components})))\napp$run_server(port = {port})\n' jl_wrapper = '\nusing Dash, DashBootstrapComponents\n\napp = dash(external_stylesheets=[dbc_themes.BOOTSTRAP]);\n\n{snippet}\n\napp.layout = html_div([{components}]);\nrun_server(app, "127.0.0.1", {port});\n'
""" 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 """ n= int(input()) for i in range(n): for j in range(0,n-i): print(" ",end=' ') for j in range(i+1): if j<i: print(i+1,end=" ") else: print(i+1,end="") if i<n: print()
""" 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 """ n = int(input()) for i in range(n): for j in range(0, n - i): print(' ', end=' ') for j in range(i + 1): if j < i: print(i + 1, end=' ') else: print(i + 1, end='') if i < n: print()
''' .remove(x) This operation removes element from the set. If element does not exist, it raises a KeyError. The .remove(x) operation returns None. Example >>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> s.remove(5) >>> print s set([1, 2, 3, 4, 6, 7, 8, 9]) >>> print s.remove(4) None >>> print s set([1, 2, 3, 6, 7, 8, 9]) >>> s.remove(0) KeyError: 0 .discard(x) This operation also removes element from the set. If element does not exist, it does not raise a KeyError. The .discard(x) operation returns None. Example >>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> s.discard(5) >>> print s set([1, 2, 3, 4, 6, 7, 8, 9]) >>> print s.discard(4) None >>> print s set([1, 2, 3, 6, 7, 8, 9]) >>> s.discard(0) >>> print s set([1, 2, 3, 6, 7, 8, 9]) .pop() This operation removes and return an arbitrary element from the set. If there are no elements to remove, it raises a KeyError. Example >>> s = set([1]) >>> print s.pop() 1 >>> print s set([]) >>> print s.pop() KeyError: pop from an empty set Task You have a non-empty set , and you have to execute commands given in lines. The commands will be pop, remove and discard. Input Format The first line contains integer , the number of elements in the set . The second line contains space separated elements of set . All of the elements are non-negative integers, less than or equal to 9. The third line contains integer , the number of commands. The next lines contains either pop, remove and/or discard commands followed by their associated value. Constraints Output Format Print the sum of the elements of set on a single line. Sample Input 9 1 2 3 4 5 6 7 8 9 10 pop remove 9 discard 9 discard 8 remove 7 pop discard 6 remove 5 pop discard 5 Sample Output 4 Explanation After completing these operations on the set, we get set. Hence, the sum is . Note: Convert the elements of set s to integers while you are assigning them. To ensure the proper input of the set, we have added the first two lines of code to the editor. ''' n = int(input()) s = set(map(int, input().split())) N=int(input()) k=[] for i in range(N): k=input().split() if k[0]=='pop': s.pop() if k[0]=='remove': s.remove(int(k[1])) if k[0]=='discard': s.discard(int(k[1])) print(sum(s))
""" .remove(x) This operation removes element from the set. If element does not exist, it raises a KeyError. The .remove(x) operation returns None. Example >>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> s.remove(5) >>> print s set([1, 2, 3, 4, 6, 7, 8, 9]) >>> print s.remove(4) None >>> print s set([1, 2, 3, 6, 7, 8, 9]) >>> s.remove(0) KeyError: 0 .discard(x) This operation also removes element from the set. If element does not exist, it does not raise a KeyError. The .discard(x) operation returns None. Example >>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> s.discard(5) >>> print s set([1, 2, 3, 4, 6, 7, 8, 9]) >>> print s.discard(4) None >>> print s set([1, 2, 3, 6, 7, 8, 9]) >>> s.discard(0) >>> print s set([1, 2, 3, 6, 7, 8, 9]) .pop() This operation removes and return an arbitrary element from the set. If there are no elements to remove, it raises a KeyError. Example >>> s = set([1]) >>> print s.pop() 1 >>> print s set([]) >>> print s.pop() KeyError: pop from an empty set Task You have a non-empty set , and you have to execute commands given in lines. The commands will be pop, remove and discard. Input Format The first line contains integer , the number of elements in the set . The second line contains space separated elements of set . All of the elements are non-negative integers, less than or equal to 9. The third line contains integer , the number of commands. The next lines contains either pop, remove and/or discard commands followed by their associated value. Constraints Output Format Print the sum of the elements of set on a single line. Sample Input 9 1 2 3 4 5 6 7 8 9 10 pop remove 9 discard 9 discard 8 remove 7 pop discard 6 remove 5 pop discard 5 Sample Output 4 Explanation After completing these operations on the set, we get set. Hence, the sum is . Note: Convert the elements of set s to integers while you are assigning them. To ensure the proper input of the set, we have added the first two lines of code to the editor. """ n = int(input()) s = set(map(int, input().split())) n = int(input()) k = [] for i in range(N): k = input().split() if k[0] == 'pop': s.pop() if k[0] == 'remove': s.remove(int(k[1])) if k[0] == 'discard': s.discard(int(k[1])) print(sum(s))
ERR_SUCCESSFUL = 0 ERR_AUTHENTICATION_FAILED = 1 ERR_DUPLICATE_MODEL = 2 ERR_DOT_NOT_EXIST = 3 ERR_PERMISSION_DENIED = 4 ERR_INVALID_CREDENTIALS = 5 ERR_AUTHENTICATION_FAILED = 6 ERR_USER_IS_INACTIVE = 7 ERR_NOT_AUTHENTICATED = 8 ERR_INPUT_VALIDATION = 9 ERR_PARSE = 10 ERR_UNSUPPORTED_MEDIA = 11 ERR_METHOD_NOT_ALLOWED = 12 ERR_NOT_ACCEPTABLE = 13 ERR_CONFLICT = 14 ERR_INTERNAL = 15
err_successful = 0 err_authentication_failed = 1 err_duplicate_model = 2 err_dot_not_exist = 3 err_permission_denied = 4 err_invalid_credentials = 5 err_authentication_failed = 6 err_user_is_inactive = 7 err_not_authenticated = 8 err_input_validation = 9 err_parse = 10 err_unsupported_media = 11 err_method_not_allowed = 12 err_not_acceptable = 13 err_conflict = 14 err_internal = 15
class CompteBancaire(): """ Gestion des Banques """ def __init__(self, nom = 'Dupont', solde = 1000 ): """ constructeur """ self.nom = nom self.solde = solde def depot(self, somme): """ ajouter somme au solde """ self.solde = self.solde + somme def retrait(self, somme): """ retirer somme du solde """ self.solde = self.solde - somme def affiche(self): print("Le compte bancaire de {0} est de {1} euros".format( self.nom , self.solde)) if __name__ == '__main__': compte1 = CompteBancaire('Duchmo1', 800) compte1.depot(350) compte1.retrait(200) compte1.affiche()
class Comptebancaire: """ Gestion des Banques """ def __init__(self, nom='Dupont', solde=1000): """ constructeur """ self.nom = nom self.solde = solde def depot(self, somme): """ ajouter somme au solde """ self.solde = self.solde + somme def retrait(self, somme): """ retirer somme du solde """ self.solde = self.solde - somme def affiche(self): print('Le compte bancaire de {0} est de {1} euros'.format(self.nom, self.solde)) if __name__ == '__main__': compte1 = compte_bancaire('Duchmo1', 800) compte1.depot(350) compte1.retrait(200) compte1.affiche()
# Bottom-Up Dynamic Programming (Tabulation) class Solution: def minCostClimbingStairs(self, cost: list[int]) -> int: # The array's length should be 1 longer than the length of cost # This is because we can treat the "top floor" as a step to reach minimum_cost = [0] * (len(cost) + 1) # Start iteration from step 2, since the minimum cost of reaching # step 0 and step 1 is 0 for i in range(2, len(cost) + 1): take_one_step = minimum_cost[i - 1] + cost[i - 1] take_two_steps = minimum_cost[i - 2] + cost[i - 2] minimum_cost[i] = min(take_one_step, take_two_steps) # The final element in minimum_cost refers to the top floor return minimum_cost[-1] # Top-Down Dynamic Programming (Recursion + Memoization) class Solution: def minCostClimbingStairs(self, cost: list[int]) -> int: def minimum_cost(i): # Base case, we are allowed to start at either step 0 or step 1 if i <= 1: return 0 # Check if we have already calculated minimum_cost(i) if i in memo: return memo[i] # If not, cache the result in our hash map and return it down_one = cost[i - 1] + minimum_cost(i - 1) down_two = cost[i - 2] + minimum_cost(i - 2) memo[i] = min(down_one, down_two) return memo[i] memo = {} return minimum_cost(len(cost)) # Bottom-Up, Constant Space class Solution: def minCostClimbingStairs(self, cost: list[int]) -> int: down_one = down_two = 0 for i in range(2, len(cost) + 1): temp = down_one down_one = min(down_one + cost[i - 1], down_two + cost[i - 2]) down_two = temp return down_one
class Solution: def min_cost_climbing_stairs(self, cost: list[int]) -> int: minimum_cost = [0] * (len(cost) + 1) for i in range(2, len(cost) + 1): take_one_step = minimum_cost[i - 1] + cost[i - 1] take_two_steps = minimum_cost[i - 2] + cost[i - 2] minimum_cost[i] = min(take_one_step, take_two_steps) return minimum_cost[-1] class Solution: def min_cost_climbing_stairs(self, cost: list[int]) -> int: def minimum_cost(i): if i <= 1: return 0 if i in memo: return memo[i] down_one = cost[i - 1] + minimum_cost(i - 1) down_two = cost[i - 2] + minimum_cost(i - 2) memo[i] = min(down_one, down_two) return memo[i] memo = {} return minimum_cost(len(cost)) class Solution: def min_cost_climbing_stairs(self, cost: list[int]) -> int: down_one = down_two = 0 for i in range(2, len(cost) + 1): temp = down_one down_one = min(down_one + cost[i - 1], down_two + cost[i - 2]) down_two = temp return down_one
nterms = int(input()) n1=0 n2=1 count=0 if nterms <= 0: print("please enter a positive integer") elif nterms==1: print("Fibonacci sequence upto",nterms,":") print(n1) else: print("Fibonacci sequence:") while count < nterms: print(n1) nth=n1+n2 n1=n2 n2=nth count+=1
nterms = int(input()) n1 = 0 n2 = 1 count = 0 if nterms <= 0: print('please enter a positive integer') elif nterms == 1: print('Fibonacci sequence upto', nterms, ':') print(n1) else: print('Fibonacci sequence:') while count < nterms: print(n1) nth = n1 + n2 n1 = n2 n2 = nth count += 1
class Solution: def maxProfit(self, k, prices): """ :type k: int :type prices: List[int] :rtype: int """ n = len(prices) if n == 0: return 0 if k >= n // 2: return sum(max(0, prices[i + 1] - prices[i]) for i in range(n - 1)) dp = [[0] * n for _ in range(k + 1)] for i in range(1, k + 1): mx = -prices[0] for j in range(1, n): dp[i][j] = max(dp[i][j - 1], prices[j] + mx) mx = max(mx, dp[i - 1][j - 1] - prices[j]) return dp[-1][-1]
class Solution: def max_profit(self, k, prices): """ :type k: int :type prices: List[int] :rtype: int """ n = len(prices) if n == 0: return 0 if k >= n // 2: return sum((max(0, prices[i + 1] - prices[i]) for i in range(n - 1))) dp = [[0] * n for _ in range(k + 1)] for i in range(1, k + 1): mx = -prices[0] for j in range(1, n): dp[i][j] = max(dp[i][j - 1], prices[j] + mx) mx = max(mx, dp[i - 1][j - 1] - prices[j]) return dp[-1][-1]
def load(h): return ({'abbr': 0, 'code': 0, 'title': 'Parcel lifted index (to 500 hPa)', 'units': 'K'}, {'abbr': 1, 'code': 1, 'title': 'Best lifted index (to 500 hPa)', 'units': 'K'}, {'abbr': 2, 'code': 2, 'title': 'K index', 'units': 'K'}, {'abbr': 3, 'code': 3, 'title': 'KO index', 'units': 'K'}, {'abbr': 4, 'code': 4, 'title': 'Total totals index', 'units': 'K'}, {'abbr': 5, 'code': 5, 'title': 'Sweat index', 'units': 'Numeric'}, {'abbr': 6, 'code': 6, 'title': 'Convective available potential energy', 'units': 'J kg-1'}, {'abbr': 7, 'code': 7, 'title': 'Convective inhibition', 'units': 'J kg-1'}, {'abbr': 8, 'code': 8, 'title': 'Storm relative helicity', 'units': 'J kg-1'}, {'abbr': 9, 'code': 9, 'title': 'Energy helicity index', 'units': 'Numeric'}, {'abbr': 10, 'code': 10, 'title': 'Surface lifted index', 'units': 'K'}, {'abbr': 11, 'code': 11, 'title': 'Best (4-layer) lifted index', 'units': 'K'}, {'abbr': 12, 'code': 12, 'title': 'Richardson number', 'units': 'Numeric'}, {'abbr': None, 'code': 255, 'title': 'Missing'})
def load(h): return ({'abbr': 0, 'code': 0, 'title': 'Parcel lifted index (to 500 hPa)', 'units': 'K'}, {'abbr': 1, 'code': 1, 'title': 'Best lifted index (to 500 hPa)', 'units': 'K'}, {'abbr': 2, 'code': 2, 'title': 'K index', 'units': 'K'}, {'abbr': 3, 'code': 3, 'title': 'KO index', 'units': 'K'}, {'abbr': 4, 'code': 4, 'title': 'Total totals index', 'units': 'K'}, {'abbr': 5, 'code': 5, 'title': 'Sweat index', 'units': 'Numeric'}, {'abbr': 6, 'code': 6, 'title': 'Convective available potential energy', 'units': 'J kg-1'}, {'abbr': 7, 'code': 7, 'title': 'Convective inhibition', 'units': 'J kg-1'}, {'abbr': 8, 'code': 8, 'title': 'Storm relative helicity', 'units': 'J kg-1'}, {'abbr': 9, 'code': 9, 'title': 'Energy helicity index', 'units': 'Numeric'}, {'abbr': 10, 'code': 10, 'title': 'Surface lifted index', 'units': 'K'}, {'abbr': 11, 'code': 11, 'title': 'Best (4-layer) lifted index', 'units': 'K'}, {'abbr': 12, 'code': 12, 'title': 'Richardson number', 'units': 'Numeric'}, {'abbr': None, 'code': 255, 'title': 'Missing'})
# channel.py # ~~~~~~~~~ # This module implements the Channel class. # :authors: Justin Karneges, Konstantin Bokarius. # :copyright: (c) 2015 by Fanout, Inc. # :license: MIT, see LICENSE for more details. # The Channel class is used to represent a channel in a GRIP proxy and # tracks the previous ID of the last message. class Channel(object): # Initialize with the channel name and an optional previous ID. def __init__(self, name, prev_id=None): self.name = name self.prev_id = prev_id self.filters = []
class Channel(object): def __init__(self, name, prev_id=None): self.name = name self.prev_id = prev_id self.filters = []
def main(): st = input("") print(min(st)) main()
def main(): st = input('') print(min(st)) main()
def sum_of_digits(digits) -> str: if not str(digits).isdecimal(): return '' else: return f'{" + ".join([i for i in str(digits)])} = {sum([int(i) for i in str(digits)])}'
def sum_of_digits(digits) -> str: if not str(digits).isdecimal(): return '' else: return f"{' + '.join([i for i in str(digits)])} = {sum([int(i) for i in str(digits)])}"
"""Constants for the FiveM integration.""" ATTR_PLAYERS_LIST = "players_list" ATTR_RESOURCES_LIST = "resources_list" DOMAIN = "fivem" ICON_PLAYERS_MAX = "mdi:account-multiple" ICON_PLAYERS_ONLINE = "mdi:account-multiple" ICON_RESOURCES = "mdi:playlist-check" MANUFACTURER = "Cfx.re" NAME_PLAYERS_MAX = "Players Max" NAME_PLAYERS_ONLINE = "Players Online" NAME_RESOURCES = "Resources" NAME_STATUS = "Status" SCAN_INTERVAL = 60 UNIT_PLAYERS_MAX = "players" UNIT_PLAYERS_ONLINE = "players" UNIT_RESOURCES = "resources"
"""Constants for the FiveM integration.""" attr_players_list = 'players_list' attr_resources_list = 'resources_list' domain = 'fivem' icon_players_max = 'mdi:account-multiple' icon_players_online = 'mdi:account-multiple' icon_resources = 'mdi:playlist-check' manufacturer = 'Cfx.re' name_players_max = 'Players Max' name_players_online = 'Players Online' name_resources = 'Resources' name_status = 'Status' scan_interval = 60 unit_players_max = 'players' unit_players_online = 'players' unit_resources = 'resources'
str = 'Hello World!' print(str) # Prints complete string print(str[0]) # Prints first character of the string print(str[2:5]) # Prints characters starting from 3rd to 5th print(str[2:]) # Prints string starting from 3rd character print(str * 2) # Prints string two times print(str + "TEST") # Prints concatenated string
str = 'Hello World!' print(str) print(str[0]) print(str[2:5]) print(str[2:]) print(str * 2) print(str + 'TEST')
#D&D D12 die with 12 pentagonal faces af = 7 textH = 2 textD = 0.3 faces = {"1":(0,0), "2":(60,72), "3":(60,72*2), "4":(60,72*3), "5":(60,72*4), "6":(60,0), "C":(180,0),"B":(120,72*3+36),"A":(120,72*4+36),"9":(120,36),"8":(120,72+36),"7":(120,72*2+36)} a = cq.Workplane("XY").sphere(5) for k in faces.keys(): abtY , abtZ = faces[k] a = a.cut(cq.Workplane("XY").transformed(rotate=cq.Vector(abtY,0,0)) .workplane(offset=af/2).rect(10,10).extrude(10).rotate((0,0,0),(0,0,1),abtZ)) a = a.fillet(.5) for k in faces.keys(): abtY , abtZ = faces[k] a = a.cut(cq.Workplane("XY").transformed(rotate=cq.Vector(abtY,0,0)) .workplane(offset=af/2-textD).text(k,textH,textD).rotate((0,0,0),(0,0,1),abtZ))
af = 7 text_h = 2 text_d = 0.3 faces = {'1': (0, 0), '2': (60, 72), '3': (60, 72 * 2), '4': (60, 72 * 3), '5': (60, 72 * 4), '6': (60, 0), 'C': (180, 0), 'B': (120, 72 * 3 + 36), 'A': (120, 72 * 4 + 36), '9': (120, 36), '8': (120, 72 + 36), '7': (120, 72 * 2 + 36)} a = cq.Workplane('XY').sphere(5) for k in faces.keys(): (abt_y, abt_z) = faces[k] a = a.cut(cq.Workplane('XY').transformed(rotate=cq.Vector(abtY, 0, 0)).workplane(offset=af / 2).rect(10, 10).extrude(10).rotate((0, 0, 0), (0, 0, 1), abtZ)) a = a.fillet(0.5) for k in faces.keys(): (abt_y, abt_z) = faces[k] a = a.cut(cq.Workplane('XY').transformed(rotate=cq.Vector(abtY, 0, 0)).workplane(offset=af / 2 - textD).text(k, textH, textD).rotate((0, 0, 0), (0, 0, 1), abtZ))
load("//:compile.bzl", "ProtoCompileInfo") RustProtoLibInfo = provider(fields = { "name": "rule name", "lib": "lib.rs file", }) def _basename(f): return f.basename[:-len(f.extension) - 1] def _rust_proto_lib_impl(ctx): """Generate a lib.rs file for the crates.""" compilation = ctx.attr.compilation[ProtoCompileInfo] deps = ctx.attr.deps srcs = compilation.files lib_rs = ctx.actions.declare_file("%s/lib.rs" % compilation.label.name) # Search in the plugin list for 'protoc_gen_rust_grpc' or similar. grpc = False for plugin in compilation.plugins: if plugin.executable.path.endswith("grpc"): grpc = True break content = ["extern crate protobuf;"] if grpc: content.append("extern crate grpc;") content.append("extern crate tls_api;") # for dep in deps: # content.append("extern crate %s;" % dep.label.name) # content.append("pub use %s::*;" % dep.label.name) for f in srcs: content.append("pub mod %s;" % _basename(f)) content.append("pub use %s::*;" % _basename(f)) ctx.actions.write( lib_rs, "\n".join(content), False, ) return [RustProtoLibInfo( name = ctx.label.name, lib = lib_rs, ), DefaultInfo( files = depset([lib_rs]), )] rust_proto_lib = rule( implementation = _rust_proto_lib_impl, attrs = { "compilation": attr.label( providers = [ProtoCompileInfo], mandatory = True, ), "deps": attr.label_list( # providers = [""], ), }, output_to_genfiles = True, )
load('//:compile.bzl', 'ProtoCompileInfo') rust_proto_lib_info = provider(fields={'name': 'rule name', 'lib': 'lib.rs file'}) def _basename(f): return f.basename[:-len(f.extension) - 1] def _rust_proto_lib_impl(ctx): """Generate a lib.rs file for the crates.""" compilation = ctx.attr.compilation[ProtoCompileInfo] deps = ctx.attr.deps srcs = compilation.files lib_rs = ctx.actions.declare_file('%s/lib.rs' % compilation.label.name) grpc = False for plugin in compilation.plugins: if plugin.executable.path.endswith('grpc'): grpc = True break content = ['extern crate protobuf;'] if grpc: content.append('extern crate grpc;') content.append('extern crate tls_api;') for f in srcs: content.append('pub mod %s;' % _basename(f)) content.append('pub use %s::*;' % _basename(f)) ctx.actions.write(lib_rs, '\n'.join(content), False) return [rust_proto_lib_info(name=ctx.label.name, lib=lib_rs), default_info(files=depset([lib_rs]))] rust_proto_lib = rule(implementation=_rust_proto_lib_impl, attrs={'compilation': attr.label(providers=[ProtoCompileInfo], mandatory=True), 'deps': attr.label_list()}, output_to_genfiles=True)
# noinspection PyUnusedLocal # friend_name = unicode string def hello(friend_name): """ Says hello world param[0] = a String. Ignore for now. @return = a String containing a message """ return "Hello, {}!".format(friend_name)
def hello(friend_name): """ Says hello world param[0] = a String. Ignore for now. @return = a String containing a message """ return 'Hello, {}!'.format(friend_name)
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ! Please change the following two path strings to you own one ! # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ELINA_PYTHON_INTERFACE_PATH = '/home/xxxxx/pkgs/ELINA/python_interface' DEEPG_CODE_PATH = '/home/xxxxx/pkgs/deepg/code' NORM_TYPES = ['0', '1', '2', 'inf'] DATASETS = ["imagenet", "cifar10", "mnist"] METHOD_LIST = ['Clean', 'PGD', 'CW', 'MILP', 'FastMILP', 'PercySDP', 'FazlybSDP', 'AI2', 'RefineZono', 'LPAll', 'kReLU', 'DeepPoly', 'ZicoDualLP', 'CROWN', 'CROWN_IBP', 'CNNCert', 'FastLin_IBP', 'FastLin', 'FastLinSparse', 'FastLip', 'RecurJac', 'Spectral', 'IBP', 'IBPVer2']
elina_python_interface_path = '/home/xxxxx/pkgs/ELINA/python_interface' deepg_code_path = '/home/xxxxx/pkgs/deepg/code' norm_types = ['0', '1', '2', 'inf'] datasets = ['imagenet', 'cifar10', 'mnist'] method_list = ['Clean', 'PGD', 'CW', 'MILP', 'FastMILP', 'PercySDP', 'FazlybSDP', 'AI2', 'RefineZono', 'LPAll', 'kReLU', 'DeepPoly', 'ZicoDualLP', 'CROWN', 'CROWN_IBP', 'CNNCert', 'FastLin_IBP', 'FastLin', 'FastLinSparse', 'FastLip', 'RecurJac', 'Spectral', 'IBP', 'IBPVer2']
def FlagsForFile( filename ): return { 'flags': [ '-Wall', '-Wextra', '-Werror', '-std=c++11', '-x', 'c++', '-isystem', '/usr/include/c++/10', '-isystem', '/usr/include/c++/10/backward', '-isystem', '/usr/local/include', '-isystem', '/usr/include', ] }
def flags_for_file(filename): return {'flags': ['-Wall', '-Wextra', '-Werror', '-std=c++11', '-x', 'c++', '-isystem', '/usr/include/c++/10', '-isystem', '/usr/include/c++/10/backward', '-isystem', '/usr/local/include', '-isystem', '/usr/include']}
# Resources # https://www.geeksforgeeks.org/observer-method-python-design-patterns/ # https://docs.google.com/document/d/1jyrxxQyrVxBG9S_hXYI69ytUMdxQdApyM6MO2CwvYj4/edit class Subject: """Represents what is being observed""" def __init__(self): """create an empty observer list""" self._observers = [] def notify(self, measurements=None): """Alert the observers""" # We notify the observers when we get updated measurements from the Weather Station. for observer in self._observers: if measurements != observer: observer.update(measurements) # Both of the following two methods take an observer as an argument; # That is, the observer to be registered or removed. # In our case CurrentConditionsDisplay, StatisticsDisplay & ForecastDisplay. def attach(self, observer): """If the observer is not in the list, append it into the list""" # When an observer registers, we just add it to the end of the list. if observer not in self._observers: self._observers.append(observer) def detach(self, observer): """Remove the observer from the observer list""" # When an observer wants to un-register, we just take it off the list. try: self._observers.remove(observer) except ValueError: pass class WeatherData(Subject): """Class/Object to be monitored and observed""" def __init__(self, name='WeatherData', temperature=0, humidity=0, pressure=0): Subject.__init__(self) self.name = name self._temperature = temperature self._humidity = humidity self._pressure = pressure @property def temperature(self): return self._temperature @property def humidity(self): return self._humidity @property def pressure(self): return self._pressure @property def measurements(self): return (self._temperature, self._humidity, self._pressure) @temperature.setter def temperature(self, value): self._temperature = value self.notify() @humidity.setter def humidity(self, value): self._humidity = value self.notify() @pressure.setter def pressure(self, value): self._pressure = value self.notify() def setMeasurements(self, temperature, humidity, pressure): self._temperature = temperature self._humidity = humidity self._pressure = pressure self.notify() class Observer: def __init__(self, name='Default-Observer-Interface'): self.name = name def update(self, measurements): print("Updated: \n", self.display(), "with: ", measurements) def display(self): print("Observer: ", self.name) class CurrentConditionsDisplay(Observer): """Updates the CurrentConditionsDisplay viewer""" # The CurrentConditionsDisplay class should keep track of the temperature/humidity/pressure measurements and display them. def __init__(self, name='CurrentConditionsDisplay', subject=None): Observer.__init__(self, name) self._subject = subject def update(self, measurements): self.display() # self._temperature = measurements[0] # self._humidity = measurements[1] # self._pressure = measurements[2] # self.notify() def display(self, subject): print("Current Conditions For %s", subject.name) print("Temperature: %d F degrees", subject.temerature) print("Humidity: %d [%]", subject.humidity) print("Pressure: %d PSI", subject.pressure) # TODO: Implement StatisticsDisplay Class class StatisticsDisplay(Observer): """Updates the StatisticsDisplay viewer""" # The StatisticsDisplay class should keep track of the min/average/max measurements and display them. def __init__(self, name='StatisticsDisplay'): Observer.__init__(self) self._temerature_history = [] self._humidity_history = [] self._pressure_history = [] # self.update() def update(self): self.temerature_min = min(self._temerature_history) self.temerature_max = max(self._temerature_history) self.temerature_average = sum( self._temerature_history)/len(self._temerature_history) self.humidity_min = min(self._humidity_history) self.humidity_max = max(self._humidity_history) self.humidity_average = sum( self._humidity_history)/len(self._humidity_history) self.pressure_min = min(self._pressure_history) self.pressure_max = max(self._pressure_history) self.pressure_average = sum( self._pressure_history)/len(self._pressure_history) self.display() def display(self): print("Current Statistics From %s", subject.name) print(" \t\t\t | min | avge | max |") print("Temperature: \t| %d | %d | %d |", self.temerature_min, self.temerature_average, self.temerature_max) print("Humidity %: \t| %d | %d | %d |", self.humidity_min, self.humidity_average, self.humidity_max) print("Pressure psi: \t| %d | %d | %d |", self.pressure_min, self.pressure_average, self.pressure_max) # TODO: Implement ForecastDisplay Class. class ForecastDisplay(Observer): """Updates the ForecastDisplay viewer""" # The ForecastDisplay class shows the weather forcast based on the current # temperature, humidity and pressure. Use the following formuals : # forcast_temp = temperature + 0.11 * humidity + 0.2 * pressure # forcast_humadity = humidity - 0.9 * humidity # forcast_pressure = pressure + 0.1 * temperature - 0.21 * pressure def update(self): print('OctalViewer: Subject' + str(subject.name) + 'has data '+str(oct(subject.data))) """main function""" if __name__ == "__main__": """provide the data""" WeatherStation = WeatherData('Data 1') print(WeatherStation.measurements) view1 = CurrentConditionsDisplay() WeatherStation.attach(view1) print(WeatherStation.measurements) WeatherStation.setMeasurements(30, 85, 60.8) print(WeatherStation.measurements) # TODO: Create Two Objects A StatisticsDisplay Class & A ForecastDisplay Class. # view2 = StatisticsDisplay() # view3 = ForecastDisplay() # TODO: Register them to the concerete instance of the Subject class so the they get the 'measurements' updates. # WeatherStation.attach(view2) # WeatherStation.attach(view3) # TODO: Test our Statistics & Forecast Display by Adding/Setting the Messurement Vaules # WeatherStation.setMeasurements(80, 65, 30.4) # print(WeatherStation.measurements) # TODO: Un-Register the CurrentConditionsDisplay observer & Test our subscription tracking # WeatherStation.removeObserver(view1) # WeatherStation.setMeasurements(120, 100, 1000) # WeatherStation.measurements = 80, 65, 30.4
class Subject: """Represents what is being observed""" def __init__(self): """create an empty observer list""" self._observers = [] def notify(self, measurements=None): """Alert the observers""" for observer in self._observers: if measurements != observer: observer.update(measurements) def attach(self, observer): """If the observer is not in the list, append it into the list""" if observer not in self._observers: self._observers.append(observer) def detach(self, observer): """Remove the observer from the observer list""" try: self._observers.remove(observer) except ValueError: pass class Weatherdata(Subject): """Class/Object to be monitored and observed""" def __init__(self, name='WeatherData', temperature=0, humidity=0, pressure=0): Subject.__init__(self) self.name = name self._temperature = temperature self._humidity = humidity self._pressure = pressure @property def temperature(self): return self._temperature @property def humidity(self): return self._humidity @property def pressure(self): return self._pressure @property def measurements(self): return (self._temperature, self._humidity, self._pressure) @temperature.setter def temperature(self, value): self._temperature = value self.notify() @humidity.setter def humidity(self, value): self._humidity = value self.notify() @pressure.setter def pressure(self, value): self._pressure = value self.notify() def set_measurements(self, temperature, humidity, pressure): self._temperature = temperature self._humidity = humidity self._pressure = pressure self.notify() class Observer: def __init__(self, name='Default-Observer-Interface'): self.name = name def update(self, measurements): print('Updated: \n', self.display(), 'with: ', measurements) def display(self): print('Observer: ', self.name) class Currentconditionsdisplay(Observer): """Updates the CurrentConditionsDisplay viewer""" def __init__(self, name='CurrentConditionsDisplay', subject=None): Observer.__init__(self, name) self._subject = subject def update(self, measurements): self.display() def display(self, subject): print('Current Conditions For %s', subject.name) print('Temperature: %d F degrees', subject.temerature) print('Humidity: %d [%]', subject.humidity) print('Pressure: %d PSI', subject.pressure) class Statisticsdisplay(Observer): """Updates the StatisticsDisplay viewer""" def __init__(self, name='StatisticsDisplay'): Observer.__init__(self) self._temerature_history = [] self._humidity_history = [] self._pressure_history = [] def update(self): self.temerature_min = min(self._temerature_history) self.temerature_max = max(self._temerature_history) self.temerature_average = sum(self._temerature_history) / len(self._temerature_history) self.humidity_min = min(self._humidity_history) self.humidity_max = max(self._humidity_history) self.humidity_average = sum(self._humidity_history) / len(self._humidity_history) self.pressure_min = min(self._pressure_history) self.pressure_max = max(self._pressure_history) self.pressure_average = sum(self._pressure_history) / len(self._pressure_history) self.display() def display(self): print('Current Statistics From %s', subject.name) print(' \t\t\t | min | avge | max |') print('Temperature: \t| %d | %d | %d |', self.temerature_min, self.temerature_average, self.temerature_max) print('Humidity %: \t| %d | %d | %d |', self.humidity_min, self.humidity_average, self.humidity_max) print('Pressure psi: \t| %d | %d | %d |', self.pressure_min, self.pressure_average, self.pressure_max) class Forecastdisplay(Observer): """Updates the ForecastDisplay viewer""" def update(self): print('OctalViewer: Subject' + str(subject.name) + 'has data ' + str(oct(subject.data))) 'main function' if __name__ == '__main__': 'provide the data' weather_station = weather_data('Data 1') print(WeatherStation.measurements) view1 = current_conditions_display() WeatherStation.attach(view1) print(WeatherStation.measurements) WeatherStation.setMeasurements(30, 85, 60.8) print(WeatherStation.measurements)
class Solution: def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. 1,2,3,4,5 3 3,4,5,1,2 """ move = k % len(nums) nums[:] = nums[-move:] + nums[:-move]
class Solution: def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. 1,2,3,4,5 3 3,4,5,1,2 """ move = k % len(nums) nums[:] = nums[-move:] + nums[:-move]
def increaseNumberRoundness(n): gotToSignificant = False while n > 0: if n % 10 == 0 and gotToSignificant: return True elif n % 10 != 0: gotToSignificant = True n /= 10 return False
def increase_number_roundness(n): got_to_significant = False while n > 0: if n % 10 == 0 and gotToSignificant: return True elif n % 10 != 0: got_to_significant = True n /= 10 return False
fname = input('please enter a file name: ') fhand = open('romeo.txt') new_list = list() for line in fhand: word = line.split() for element in word: if element not in new_list: new_list.append(element) new_list.sort() print(new_list)
fname = input('please enter a file name: ') fhand = open('romeo.txt') new_list = list() for line in fhand: word = line.split() for element in word: if element not in new_list: new_list.append(element) new_list.sort() print(new_list)
# Copyright 2015-2018 Camptocamp SA, Damien Crier # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Colorize field in tree views", "summary": "Allows you to dynamically color fields on tree views", "category": "Hidden/Dependency", "version": "14.0.1.0.0", "depends": ["web"], "author": "Camptocamp, Therp BV, Odoo Community Association (OCA)", "license": "AGPL-3", "website": "https://github.com/OCA/web", "demo": ["demo/res_users.xml"], "data": ["views/web_tree_dynamic_colored_field.xml"], "installable": True, }
{'name': 'Colorize field in tree views', 'summary': 'Allows you to dynamically color fields on tree views', 'category': 'Hidden/Dependency', 'version': '14.0.1.0.0', 'depends': ['web'], 'author': 'Camptocamp, Therp BV, Odoo Community Association (OCA)', 'license': 'AGPL-3', 'website': 'https://github.com/OCA/web', 'demo': ['demo/res_users.xml'], 'data': ['views/web_tree_dynamic_colored_field.xml'], 'installable': True}
# EDA: Target - Q1 print("Number of unique cities in the data set:\n", df_tar['Target City'].nunique()) print("---------------------------------------") most_frequent_cities = df_tar['Target City'].value_counts().sort_values(ascending=False)[:15] print("Most frequent cities:\n", most_frequent_cities) print("---------------------------------------")
print('Number of unique cities in the data set:\n', df_tar['Target City'].nunique()) print('---------------------------------------') most_frequent_cities = df_tar['Target City'].value_counts().sort_values(ascending=False)[:15] print('Most frequent cities:\n', most_frequent_cities) print('---------------------------------------')
class ScreenIdError(ValueError): pass class UssdNamespaceError(RuntimeError): pass
class Screeniderror(ValueError): pass class Ussdnamespaceerror(RuntimeError): pass
def matchParenthesis(string): parenthesis = 0 brackets = 0 curlyBrackets = 0 for i in range(len(string)): l = string[i] if l == '(': if i > 0: if not string[i-1] == ':' and not string[i-1] == ';': parenthesis += 1 else: parenthesis += 1 elif l == '[': brackets += 1 elif l == '{': curlyBrackets += 1 elif l == ')': if i > 0: if not (string[i-1] == ':' or string[i-1] == ';'): if i > 1: if not string[i-2] == '-': parenthesis -= 1 elif l == ']': brackets -= 1 elif l == '}': curlyBrackets -= 1 fix = "" if parenthesis > 0: for i in range(parenthesis): fix += ")" else: for i in range(parenthesis * -1): fix += "(" if brackets > 0: for i in range(brackets): fix += "]" else: for i in range(brackets * -1): fix += "[" if curlyBrackets > 0: for i in range(curlyBrackets): fix += "}" else: for i in range(curlyBrackets * -1): fix += "{" return fix
def match_parenthesis(string): parenthesis = 0 brackets = 0 curly_brackets = 0 for i in range(len(string)): l = string[i] if l == '(': if i > 0: if not string[i - 1] == ':' and (not string[i - 1] == ';'): parenthesis += 1 else: parenthesis += 1 elif l == '[': brackets += 1 elif l == '{': curly_brackets += 1 elif l == ')': if i > 0: if not (string[i - 1] == ':' or string[i - 1] == ';'): if i > 1: if not string[i - 2] == '-': parenthesis -= 1 elif l == ']': brackets -= 1 elif l == '}': curly_brackets -= 1 fix = '' if parenthesis > 0: for i in range(parenthesis): fix += ')' else: for i in range(parenthesis * -1): fix += '(' if brackets > 0: for i in range(brackets): fix += ']' else: for i in range(brackets * -1): fix += '[' if curlyBrackets > 0: for i in range(curlyBrackets): fix += '}' else: for i in range(curlyBrackets * -1): fix += '{' return fix
_base_ = [ '../_base_/datasets/imagenet_bs128.py', '../_base_/schedules/imagenet_bs1024.py', '../_base_/default_runtime.py' ] model = dict( type='ImageClassifier', backbone=dict( type='ResArch', arch='IRNet-18', num_stages=4, out_indices=(1,2,3), style='pytorch'), neck=dict( type='MultiLevelFuse', in_channels=[128, 256, 512], out_channels=256, conv_type='XNOR'), head=dict( type='IRClsHead', num_classes=1000, in_channels=256, loss=dict(type='CrossEntropyLoss', loss_weight=1.0), topk=(1, 5), )) find_unused_parameters=True seed = 166
_base_ = ['../_base_/datasets/imagenet_bs128.py', '../_base_/schedules/imagenet_bs1024.py', '../_base_/default_runtime.py'] model = dict(type='ImageClassifier', backbone=dict(type='ResArch', arch='IRNet-18', num_stages=4, out_indices=(1, 2, 3), style='pytorch'), neck=dict(type='MultiLevelFuse', in_channels=[128, 256, 512], out_channels=256, conv_type='XNOR'), head=dict(type='IRClsHead', num_classes=1000, in_channels=256, loss=dict(type='CrossEntropyLoss', loss_weight=1.0), topk=(1, 5))) find_unused_parameters = True seed = 166
""" docstring """ def exp_lr(optimizer, epoch, init_lr=1e-3, lr_decay_epoch=30): """ Decay learning rate as epochs progress. Parameters: ---------- optimizer: torch.optim optimizer class epoch: int init_lr: float initial learning rate lr_decay_epoch: int number of epochs between decay steps Returns: -------- optimizer """ lr = init_lr * (0.1**(epoch // lr_decay_epoch)) for param_group in optimizer.param_groups: param_group["lr"] = lr return optimizer
""" docstring """ def exp_lr(optimizer, epoch, init_lr=0.001, lr_decay_epoch=30): """ Decay learning rate as epochs progress. Parameters: ---------- optimizer: torch.optim optimizer class epoch: int init_lr: float initial learning rate lr_decay_epoch: int number of epochs between decay steps Returns: -------- optimizer """ lr = init_lr * 0.1 ** (epoch // lr_decay_epoch) for param_group in optimizer.param_groups: param_group['lr'] = lr return optimizer
a = 2 b = 0 try: print(a/b) except ZeroDivisionError: print('Division by zero is not allowed')
a = 2 b = 0 try: print(a / b) except ZeroDivisionError: print('Division by zero is not allowed')
# Problem Set 2, Question 3 # These hold the values of the balance. balance = 320000 origBalance = balance # These hold the values of the annual and monthly interest rates. annualInterestRate = 0.2 monthlyInterestRate = annualInterestRate / 12 lowerBound = balance / 12 upperBound = (balance * (1 + monthlyInterestRate) ** 12) / 12.0 # This goes through all the possibilites. while (abs(balance) > 0.01): # Reset the value of balance to its original value balance = origBalance # Calculate a new monthly payment value from the bounds payment = (upperBound - lowerBound) / 2 + lowerBound # Test if this payment value is sufficient to pay off the entire balance in 12 months for month in range(12): balance -= payment balance *= 1 + monthlyInterestRate # Reset bounds based on the final value of balance if balance > 0: # If the balance is too big, need higher payment so we increase the lower bound lowerBound = payment else: # If the balance is too small, we need a lower payment, so we decrease the upper bound upperBound = payment print ("Lowest Payment: " + str(round(payment, 2)))
balance = 320000 orig_balance = balance annual_interest_rate = 0.2 monthly_interest_rate = annualInterestRate / 12 lower_bound = balance / 12 upper_bound = balance * (1 + monthlyInterestRate) ** 12 / 12.0 while abs(balance) > 0.01: balance = origBalance payment = (upperBound - lowerBound) / 2 + lowerBound for month in range(12): balance -= payment balance *= 1 + monthlyInterestRate if balance > 0: lower_bound = payment else: upper_bound = payment print('Lowest Payment: ' + str(round(payment, 2)))
# Advent of code 2018 # Antti "Waitee" Auranen # Day 4 # Example of the datetime part of the logs: # [1518-10-12 00:15] # # Examples of the message part of the logs: # Guard #1747 begins shift # falls asleep # wakes up def main(): inputs = [] guards = [] while(True): s = input("> ") #split the lines into tuples for easier sorting if len(s) > 0: line = (s[1:17], s[19:]) inputs.append(line) else: break inputs = quickSort(inputs) for a in inputs: # print(a) if a[1][:5] == "Guard": guard = a[1][s.find("#")+1 : s.find("begins") -1] guards.append([guard, 0]) for a in guards: print(a) return 0 def quickSort(xs): before = [] after = [] now = [] if len(xs) > 1: pivot = xs[0][0] for a in xs: if a[0] < pivot: before.append(a) if a[0] == pivot: now.append(a) if a[0] > pivot: after.append(a) return quickSort(before) + now + quickSort(after) else: return xs main()
def main(): inputs = [] guards = [] while True: s = input('> ') if len(s) > 0: line = (s[1:17], s[19:]) inputs.append(line) else: break inputs = quick_sort(inputs) for a in inputs: if a[1][:5] == 'Guard': guard = a[1][s.find('#') + 1:s.find('begins') - 1] guards.append([guard, 0]) for a in guards: print(a) return 0 def quick_sort(xs): before = [] after = [] now = [] if len(xs) > 1: pivot = xs[0][0] for a in xs: if a[0] < pivot: before.append(a) if a[0] == pivot: now.append(a) if a[0] > pivot: after.append(a) return quick_sort(before) + now + quick_sort(after) else: return xs main()
class Solution: def validMountainArray(self, arr: List[int]) -> bool: if len(arr) < 3: return False steps = 0 # Walk upwards, counting steps until first slope down while steps + 1 < len(arr) and arr[steps] < arr[steps + 1]: steps += 1 # Check if there was no incline or it ends in a cliff if steps == 0 or steps == len(arr) -1: return False #Walk downwards the slope counting to make sure there are no inclines again while steps + 1 < len(arr) and arr[steps] > arr[steps + 1]: steps += 1 #compare if length equals to step down return steps == len(arr) - 1
class Solution: def valid_mountain_array(self, arr: List[int]) -> bool: if len(arr) < 3: return False steps = 0 while steps + 1 < len(arr) and arr[steps] < arr[steps + 1]: steps += 1 if steps == 0 or steps == len(arr) - 1: return False while steps + 1 < len(arr) and arr[steps] > arr[steps + 1]: steps += 1 return steps == len(arr) - 1
def run(proj_path, target_name, params): return { "project_name": "Sample", "build_types": ["Debug", "Release"], "archs": [ { "arch": "x86_64", "conan_arch": "x86_64", "conan_profile": "ezored_windows_app_profile", } ], }
def run(proj_path, target_name, params): return {'project_name': 'Sample', 'build_types': ['Debug', 'Release'], 'archs': [{'arch': 'x86_64', 'conan_arch': 'x86_64', 'conan_profile': 'ezored_windows_app_profile'}]}
def feature_extraction(cfg,Z,N) : #function Descriptors=feature_extraction(Z,N) # #% The features are the magnitude of the Zernike moments. #% Collect the moments into (2*l+1)-dimensional vectors #% and define the rotationally invariant 3D Zernike descriptors #% Fnl as norms of vectors Znl. # F=cfg.zeros(N+1,N+1)+cfg.NaN #F=zeros(N+1,N+1)+NaN; #% Calcuate the magnitude for n in cfg.rng(0,N) : #for n=0:N for l in cfg.rng(0,n) : # for l=0:n if cfg.mod(n-l,2)==0 : # if mod(n-l,2)==0 aux_1=Z[n,l,0:(l+1)] #! # aux_1=Z(n+1,l+1,1:l+1); #! matlab col-major; no need to transpose # aux_1=aux_1(:)'; if l > 0 : # if l>0 # % Taking the values for m<0 aux_2=cfg.conj(aux_1[1:(l+1)]) #! # aux_2=conj(aux_1(2:(l+1))); for m in cfg.rng(1,l) : # for m=1:l aux_2[m-1]=aux_2[m-1]*cfg.power(-1,m) #! # aux_2(m)=aux_2(m)*power(-1,m); # end # % Sorting the vector aux_2=cfg.rot90(aux_2,2) # aux_2=rot90(aux_2,2); aux_1=cfg.cat(0,aux_2,aux_1) #! axis # aux_1=cat(2,aux_2,aux_1); # end F[n,l] = cfg.norm(aux_1,2) #! # F(n+1,l+1)=norm(aux_1,2); # end # end #end #% Generate vector of Zernike descriptors #% Column vector that store the magnitude #% of the Zernike moments for n,l. F = F.transpose() #! matlab indexin is col-wise. tranpose does not affect the values, just their ordering idx=cfg.find(F>=0) #idx=find(F>=0); Descriptors = F[idx] #Descriptors=F(idx); return Descriptors
def feature_extraction(cfg, Z, N): f = cfg.zeros(N + 1, N + 1) + cfg.NaN for n in cfg.rng(0, N): for l in cfg.rng(0, n): if cfg.mod(n - l, 2) == 0: aux_1 = Z[n, l, 0:l + 1] if l > 0: aux_2 = cfg.conj(aux_1[1:l + 1]) for m in cfg.rng(1, l): aux_2[m - 1] = aux_2[m - 1] * cfg.power(-1, m) aux_2 = cfg.rot90(aux_2, 2) aux_1 = cfg.cat(0, aux_2, aux_1) F[n, l] = cfg.norm(aux_1, 2) f = F.transpose() idx = cfg.find(F >= 0) descriptors = F[idx] return Descriptors
#!/usr/bin/env python3 ''' Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words ''' def palindrome_permutation(string): # O(n) if len(string) < 2: # any single character or empty string return True counts = [string.count(c) for c in set(string) if c != ' '] # 'tacocat' -> [2,2,2,1] if all(n % 2 == 0 for n in counts): # all characters have an even count return True return [n % 2 == 1 for n in counts].count(True) == 1 # only 1 character can have odd count
""" Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words """ def palindrome_permutation(string): if len(string) < 2: return True counts = [string.count(c) for c in set(string) if c != ' '] if all((n % 2 == 0 for n in counts)): return True return [n % 2 == 1 for n in counts].count(True) == 1
# ../../../../goal/translate.py --gcrootfinder=asmgcc --gc=semispace src8 class A: pass def foo(rec, a1, a2, a3, a4, a5, a6): if rec > 0: b = A() foo(rec-1, b, b, b, b, b, b) foo(rec-1, b, b, b, b, b, b) foo(rec-1, a6, a5, a4, a3, a2, a1) # __________ Entry point __________ def entry_point(argv): foo(5, A(), A(), A(), A(), A(), A()) return 0 # _____ Define and setup target ___ def target(*args): return entry_point, None
class A: pass def foo(rec, a1, a2, a3, a4, a5, a6): if rec > 0: b = a() foo(rec - 1, b, b, b, b, b, b) foo(rec - 1, b, b, b, b, b, b) foo(rec - 1, a6, a5, a4, a3, a2, a1) def entry_point(argv): foo(5, a(), a(), a(), a(), a(), a()) return 0 def target(*args): return (entry_point, None)
# by Kami Bigdely # Split temporary variable patty = 70 # [gr] pickle = 20 # [gr] tomatoes = 25 # [gr] lettuce = 15 # [gr] buns = 95 # [gr] kimchi = 30 # [gr] mayo = 5 # [gr] golden_fried_onion = 20 # [gr] ny_burger_weight = (2 * patty + 4 * pickle + 3 * tomatoes + 2 * lettuce + 2 * buns) kimchi_burger_weight = (2 * patty + 4 * pickle + 3 * tomatoes + kimchi + mayo + golden_fried_onion + 2 * buns) if __name__ == "__main__": print(f"NY Burger Weight {ny_burger_weight}lbs") print(f"Seoul Kimchi Burger Weight {kimchi_burger_weight}lbs")
patty = 70 pickle = 20 tomatoes = 25 lettuce = 15 buns = 95 kimchi = 30 mayo = 5 golden_fried_onion = 20 ny_burger_weight = 2 * patty + 4 * pickle + 3 * tomatoes + 2 * lettuce + 2 * buns kimchi_burger_weight = 2 * patty + 4 * pickle + 3 * tomatoes + kimchi + mayo + golden_fried_onion + 2 * buns if __name__ == '__main__': print(f'NY Burger Weight {ny_burger_weight}lbs') print(f'Seoul Kimchi Burger Weight {kimchi_burger_weight}lbs')
def get_nonempty_wallets_number_query(): pipeline = [ {'$match': {'balance': {'$gt': 0}} }, {'$group': { '_id': 'null', 'count': {'$sum': 1} } }, {'$project': { '_id': 0, 'count': 1 } } ] return pipeline def get_highest_block_number_in_db_query(): pipeline = [ {'$sort': {'height': -1} }, {'$limit': 1 }, {'$project': { 'height': 1 } } ] return pipeline def get_blocks_in_range_query(lower_height, upper_height, projection): pipeline = [ {'$match': {'height': {'$gte': lower_height}} }, {'$match': {'height': {'$lte': upper_height}} }, {'$sort': {'height': 1} }, {'$project': projection } ] return pipeline def get_last_n_blocks_query(interval, projection): pipeline = [ {'$sort': {'height': -1} }, {'$limit': interval }, {'$project': projection } ] return pipeline def get_total_coin_supply_query(): pipeline = [ {'$group': { '_id': 'null', 'total_coin_supply': {'$sum': '$balance'} } }, {'$project': { 'total_coin_supply': 1, '_id': 0 } } ] return pipeline def get_blocks_coinbase_addresses_count_query(interval, lower_height, upper_height): projection = {'tx': {'$arrayElemAt': ['$tx', 0]}} if interval > 0: pipeline = get_last_n_blocks_query(interval, projection) else: pipeline = get_blocks_in_range_query(lower_height, upper_height, projection) pipeline += [ {'$unwind': '$tx.vout'}, {'$match': {'tx.vout.scriptPubKey.addresses': {'$ne': []}}}, {'$project': { 'addresses': '$tx.vout.scriptPubKey.addresses' } }, {'$group': { '_id': '$addresses', 'count': {'$sum': 1} } }, {'$project': { 'address': {'$arrayElemAt': ['$_id', 0]}, 'count': 1, '_id': 0 } } ] return pipeline def get_transactions_average_volume_query(interval, lower_height, upper_height): projection = { 'height': 1, 'time': 1, 'tx': { '$cond': { 'if': {'$eq': [{'$size': '$tx'}, 1]}, 'then': '$$REMOVE', 'else': {'$slice': ['$tx', 1, {'$subtract': [{'$size': '$tx'}, 1]}]} } }, 'count': { '$cond': { 'if': {'$eq': [{'$size': '$tx'}, 1]}, 'then': '$$REMOVE', 'else': {'$size': {'$slice': ['$tx', 1, {'$subtract': [{'$size': '$tx'}, 1]}]}} } } } boundaries = [lower_height + i * interval for i in range(int((upper_height - lower_height) / interval) + 1)] boundaries[-1] += 1 pipeline = get_blocks_in_range_query(lower_height, upper_height, projection) pipeline += [ {'$project': { 'height': 1, 'value': { '$sum': { '$reduce': { 'input': '$tx.vout.value', 'initialValue': [], 'in': {'$concatArrays': ['$$value', '$$this']} } } }, 'count': 1 } }, {'$match': { 'value': {'$gt': 0} } }, {'$bucket': { 'groupBy': '$height', 'boundaries': boundaries, 'default': boundaries[-1], 'output': { 'lower_height': {'$min': '$height'}, 'upper_height': {'$max': '$height'}, 'sum': {'$sum': '$value'}, 'min': {'$min': '$value'}, 'max': {'$max': '$value'}, 'count': {'$sum': '$count'} } } }, {'$project': { 'lower_height': 1, 'upper_height': 1, 'sum': 1, 'avg': {'$divide': ['$sum', '$count']}, 'min': 1, 'max': 1, 'count': 1 } } ] return pipeline def get_blocks_average_difficulty_query(interval, lower_height, upper_height): projection = { 'time': 1, 'height': 1, 'difficulty': 1 } boundaries = [lower_height + i * interval for i in range(int((upper_height - lower_height) / interval) + 1)] boundaries[-1] += 1 pipeline = get_blocks_in_range_query(lower_height, upper_height, projection) pipeline += [ {'$bucket': { 'groupBy': '$height', 'boundaries': boundaries, 'default': boundaries[-1], 'output': { 'lower_height': {'$min': '$height'}, 'upper_height': {'$max': '$height'}, 'avg_difficulty': {'$avg': '$difficulty'} } } } ] return pipeline
def get_nonempty_wallets_number_query(): pipeline = [{'$match': {'balance': {'$gt': 0}}}, {'$group': {'_id': 'null', 'count': {'$sum': 1}}}, {'$project': {'_id': 0, 'count': 1}}] return pipeline def get_highest_block_number_in_db_query(): pipeline = [{'$sort': {'height': -1}}, {'$limit': 1}, {'$project': {'height': 1}}] return pipeline def get_blocks_in_range_query(lower_height, upper_height, projection): pipeline = [{'$match': {'height': {'$gte': lower_height}}}, {'$match': {'height': {'$lte': upper_height}}}, {'$sort': {'height': 1}}, {'$project': projection}] return pipeline def get_last_n_blocks_query(interval, projection): pipeline = [{'$sort': {'height': -1}}, {'$limit': interval}, {'$project': projection}] return pipeline def get_total_coin_supply_query(): pipeline = [{'$group': {'_id': 'null', 'total_coin_supply': {'$sum': '$balance'}}}, {'$project': {'total_coin_supply': 1, '_id': 0}}] return pipeline def get_blocks_coinbase_addresses_count_query(interval, lower_height, upper_height): projection = {'tx': {'$arrayElemAt': ['$tx', 0]}} if interval > 0: pipeline = get_last_n_blocks_query(interval, projection) else: pipeline = get_blocks_in_range_query(lower_height, upper_height, projection) pipeline += [{'$unwind': '$tx.vout'}, {'$match': {'tx.vout.scriptPubKey.addresses': {'$ne': []}}}, {'$project': {'addresses': '$tx.vout.scriptPubKey.addresses'}}, {'$group': {'_id': '$addresses', 'count': {'$sum': 1}}}, {'$project': {'address': {'$arrayElemAt': ['$_id', 0]}, 'count': 1, '_id': 0}}] return pipeline def get_transactions_average_volume_query(interval, lower_height, upper_height): projection = {'height': 1, 'time': 1, 'tx': {'$cond': {'if': {'$eq': [{'$size': '$tx'}, 1]}, 'then': '$$REMOVE', 'else': {'$slice': ['$tx', 1, {'$subtract': [{'$size': '$tx'}, 1]}]}}}, 'count': {'$cond': {'if': {'$eq': [{'$size': '$tx'}, 1]}, 'then': '$$REMOVE', 'else': {'$size': {'$slice': ['$tx', 1, {'$subtract': [{'$size': '$tx'}, 1]}]}}}}} boundaries = [lower_height + i * interval for i in range(int((upper_height - lower_height) / interval) + 1)] boundaries[-1] += 1 pipeline = get_blocks_in_range_query(lower_height, upper_height, projection) pipeline += [{'$project': {'height': 1, 'value': {'$sum': {'$reduce': {'input': '$tx.vout.value', 'initialValue': [], 'in': {'$concatArrays': ['$$value', '$$this']}}}}, 'count': 1}}, {'$match': {'value': {'$gt': 0}}}, {'$bucket': {'groupBy': '$height', 'boundaries': boundaries, 'default': boundaries[-1], 'output': {'lower_height': {'$min': '$height'}, 'upper_height': {'$max': '$height'}, 'sum': {'$sum': '$value'}, 'min': {'$min': '$value'}, 'max': {'$max': '$value'}, 'count': {'$sum': '$count'}}}}, {'$project': {'lower_height': 1, 'upper_height': 1, 'sum': 1, 'avg': {'$divide': ['$sum', '$count']}, 'min': 1, 'max': 1, 'count': 1}}] return pipeline def get_blocks_average_difficulty_query(interval, lower_height, upper_height): projection = {'time': 1, 'height': 1, 'difficulty': 1} boundaries = [lower_height + i * interval for i in range(int((upper_height - lower_height) / interval) + 1)] boundaries[-1] += 1 pipeline = get_blocks_in_range_query(lower_height, upper_height, projection) pipeline += [{'$bucket': {'groupBy': '$height', 'boundaries': boundaries, 'default': boundaries[-1], 'output': {'lower_height': {'$min': '$height'}, 'upper_height': {'$max': '$height'}, 'avg_difficulty': {'$avg': '$difficulty'}}}}] return pipeline
class ship: name = "Unknown" maelstrom_location_data = None quadrant = '' sector = '' def __init__(self, name = "Unknown", maelstrom_location_data = None): self.name = name self.maelstrom_location_data = maelstrom_location_data def getMaelstromLocationData(self): return self.maelstrom_location_data def setMaelstromCoordinates(self, quadrant, sector): self.quadrant = quadrant self.sector = sector def setNewMaelstromLocation(self, maelstrom_location_data): self.maelstrom_location_data = maelstrom_location_data def getShipCoordinates(self): return self.maelstrom_location_data.getCoordinates() def getShipQuadrant(self): return self.maelstrom_location_data.getQuadrant() def getShipSector(self): return self.maelstrom_location_data.getSector() def getMontressorPerceptionCheck(self, quadrant, sector): return self.maelstrom_location_data.getMontressorPerceptionCheck(quadrant, sector)
class Ship: name = 'Unknown' maelstrom_location_data = None quadrant = '' sector = '' def __init__(self, name='Unknown', maelstrom_location_data=None): self.name = name self.maelstrom_location_data = maelstrom_location_data def get_maelstrom_location_data(self): return self.maelstrom_location_data def set_maelstrom_coordinates(self, quadrant, sector): self.quadrant = quadrant self.sector = sector def set_new_maelstrom_location(self, maelstrom_location_data): self.maelstrom_location_data = maelstrom_location_data def get_ship_coordinates(self): return self.maelstrom_location_data.getCoordinates() def get_ship_quadrant(self): return self.maelstrom_location_data.getQuadrant() def get_ship_sector(self): return self.maelstrom_location_data.getSector() def get_montressor_perception_check(self, quadrant, sector): return self.maelstrom_location_data.getMontressorPerceptionCheck(quadrant, sector)
def read_data(): with open ('input.txt') as f: data = f.readlines() return [d.strip() for d in data] def write_data(data): with open('output.txt','w') as f: for d in data: f.write(str(d)+'\n') ### class Instruction(object): """docstring for Instruction""" def __init__(self, text): super(Instruction, self).__init__() a,b = text.split(' = ') self.loc = int(a.strip('mem[').strip(']')) self.val = int(b) def __str__(self): return f'[{self.loc}] = {self.val}' def __repr__(self): return str(self) # destructively produces a mask and instructions def init_next_program(code): mask = code.pop(0) instructions = [] while len(code)>0 and not code[0].startswith('mask'): instructions.append(Instruction(code.pop(0))) return mask, instructions def val_result(mask, val): as_bin = '{0:036b}'.format(val) r = '' for m,b in zip(mask, as_bin): if m=='0': r = r+'0' elif m=='1': r = r+'1' else: r = r+b return int(r,2) class Program(object): """docstring for Program""" def __init__(self, code): super(Program, self).__init__() mask, instructions = init_next_program(code) self.mask = mask.strip('mask = ') self.instructions = instructions def __str__(self): return f'Program with mask {self.mask} and {len(self.instructions)} instructions' def execute(self, memory): for I in self.instructions: memory[I.loc] = val_result(self.mask, I.val) def execute2(self,memory): for I in self.instructions: loc = '{0:036b}'.format(I.loc) for ii in range(2**self.mask.count('X'),-1,-1): fmt = '{:0'+str(self.mask.count('X'))+'b}' as_bin = fmt.format(ii) dest = '' for m,ell in zip(self.mask, loc): if m=='X': dest = dest+as_bin[0] if len(as_bin): as_bin = as_bin[1:] elif m=='0': dest = dest+ell elif m=='1': dest = dest+'1' else: raise ValueError() dest = int(dest,2) memory[dest] = I.val class Computer(object): """docstring for Computer""" def __init__(self, data): self.data = data self.programs = [] while len(data): self.programs.append(Program(data)) self.memory = {} def execute(self): for p in self.programs: p.execute(self.memory) def execute2(self): for p in self.programs: p.execute2(self.memory) def __str__(self): s = f'Computer with {len(self.programs)} program(s):\n' for p in self.programs: s = s+str(p)+'\n' return s def report(self): return sum(self.memory.values()) def part1(): data = read_data() c = Computer(data) c.execute() return c.report() ### def part2(): data = read_data() c = Computer(data) c.execute2() return c.report() print("part 1: {}".format(part1())) print("part 2: {}".format(part2()))
def read_data(): with open('input.txt') as f: data = f.readlines() return [d.strip() for d in data] def write_data(data): with open('output.txt', 'w') as f: for d in data: f.write(str(d) + '\n') class Instruction(object): """docstring for Instruction""" def __init__(self, text): super(Instruction, self).__init__() (a, b) = text.split(' = ') self.loc = int(a.strip('mem[').strip(']')) self.val = int(b) def __str__(self): return f'[{self.loc}] = {self.val}' def __repr__(self): return str(self) def init_next_program(code): mask = code.pop(0) instructions = [] while len(code) > 0 and (not code[0].startswith('mask')): instructions.append(instruction(code.pop(0))) return (mask, instructions) def val_result(mask, val): as_bin = '{0:036b}'.format(val) r = '' for (m, b) in zip(mask, as_bin): if m == '0': r = r + '0' elif m == '1': r = r + '1' else: r = r + b return int(r, 2) class Program(object): """docstring for Program""" def __init__(self, code): super(Program, self).__init__() (mask, instructions) = init_next_program(code) self.mask = mask.strip('mask = ') self.instructions = instructions def __str__(self): return f'Program with mask {self.mask} and {len(self.instructions)} instructions' def execute(self, memory): for i in self.instructions: memory[I.loc] = val_result(self.mask, I.val) def execute2(self, memory): for i in self.instructions: loc = '{0:036b}'.format(I.loc) for ii in range(2 ** self.mask.count('X'), -1, -1): fmt = '{:0' + str(self.mask.count('X')) + 'b}' as_bin = fmt.format(ii) dest = '' for (m, ell) in zip(self.mask, loc): if m == 'X': dest = dest + as_bin[0] if len(as_bin): as_bin = as_bin[1:] elif m == '0': dest = dest + ell elif m == '1': dest = dest + '1' else: raise value_error() dest = int(dest, 2) memory[dest] = I.val class Computer(object): """docstring for Computer""" def __init__(self, data): self.data = data self.programs = [] while len(data): self.programs.append(program(data)) self.memory = {} def execute(self): for p in self.programs: p.execute(self.memory) def execute2(self): for p in self.programs: p.execute2(self.memory) def __str__(self): s = f'Computer with {len(self.programs)} program(s):\n' for p in self.programs: s = s + str(p) + '\n' return s def report(self): return sum(self.memory.values()) def part1(): data = read_data() c = computer(data) c.execute() return c.report() def part2(): data = read_data() c = computer(data) c.execute2() return c.report() print('part 1: {}'.format(part1())) print('part 2: {}'.format(part2()))
def pow(x,y): if y==0: return 1 else: temp = pow(x,int(y/2)) mult = x if y>0 else 1/x if y%2==1: return mult * temp * temp else: return temp * temp if __name__ == "__main__": x = 2 y = 5 res = pow(x,y) print(res) x = 3 y = -2 res = pow(x,y) print(res) x = 1 y = 0 res = pow(x,y) print(res)
def pow(x, y): if y == 0: return 1 else: temp = pow(x, int(y / 2)) mult = x if y > 0 else 1 / x if y % 2 == 1: return mult * temp * temp else: return temp * temp if __name__ == '__main__': x = 2 y = 5 res = pow(x, y) print(res) x = 3 y = -2 res = pow(x, y) print(res) x = 1 y = 0 res = pow(x, y) print(res)
def terminate(): """Terminate this script. If defined, the module's 'stop' function will be called. If this module is debugging, the debugger is stopped. The script's module and any modules imported relative to this module are removed from sys.modules and released.""" pass def autoTerminate(value): """Get or set the autoTerminate flag for this module. The current value is returned when called with no arguments. Call with a single Boolean value to set this current value. When set to True (the default), the script will automatically terminate when code execution returns from the module's main block. When set to False, the script's module will remain loaded until 'terminate' is called or the script is externally stopped. Typically, a script that subscribes to events would set this to False after attaching event handlers to events before returning from it's 'run' function.""" return bool() def doEvents(): """Process any pending system events or messages. This allows the Fusion UI to update and perform any event or message driven operations. This may be useful to avoid blocking UI updates while performing a long operation, or while waiting for asynchronous operations to be processed.""" pass
def terminate(): """Terminate this script. If defined, the module's 'stop' function will be called. If this module is debugging, the debugger is stopped. The script's module and any modules imported relative to this module are removed from sys.modules and released.""" pass def auto_terminate(value): """Get or set the autoTerminate flag for this module. The current value is returned when called with no arguments. Call with a single Boolean value to set this current value. When set to True (the default), the script will automatically terminate when code execution returns from the module's main block. When set to False, the script's module will remain loaded until 'terminate' is called or the script is externally stopped. Typically, a script that subscribes to events would set this to False after attaching event handlers to events before returning from it's 'run' function.""" return bool() def do_events(): """Process any pending system events or messages. This allows the Fusion UI to update and perform any event or message driven operations. This may be useful to avoid blocking UI updates while performing a long operation, or while waiting for asynchronous operations to be processed.""" pass
class Person: def say_hi(self): print('Hello, how are you?') vinit = Person() # object created vinit.say_hi() # object calls class method.
class Person: def say_hi(self): print('Hello, how are you?') vinit = person() vinit.say_hi()
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Internal information about the projector plugin.""" PLUGIN_NAME = "projector" PLUGINS_DIR = "plugins" # must match plugin_asset_util.PLUGINS_DIR PLUGIN_ASSETS_NAME = "org_tensorflow_tensorboard_projector" # FYI - the PROJECTOR_FILENAME is hardcoded in the visualize_embeddings # method in tf.contrib.tensorboard.plugins.projector module. # TODO(@decentralion): Fix duplication when we find a permanent home for the # projector module. PROJECTOR_FILENAME = "projector_config.pbtxt"
"""Internal information about the projector plugin.""" plugin_name = 'projector' plugins_dir = 'plugins' plugin_assets_name = 'org_tensorflow_tensorboard_projector' projector_filename = 'projector_config.pbtxt'
"""Module applying the nonlocal scattering matrix method. This method is theoretically described in ... Here it is applied to the calculation of reflectance and transmittance of planar heterostructures. """ __version__ = "0.1.0"
"""Module applying the nonlocal scattering matrix method. This method is theoretically described in ... Here it is applied to the calculation of reflectance and transmittance of planar heterostructures. """ __version__ = '0.1.0'
# Implementation of the queue data structure. # A list is used to store queue elements, where the tail # of the queue is element 0, and the head is # the last element class Queue: ''' Constructor. Initializes the list items ''' def __init__(self): self.items = [] ''' Returns true if queue is empty, false otherwise ''' def is_empty(self): return self.items == [] ''' Enqueue: Add item to end (tail) of the queue ''' def enqueue(self, item): self.items.insert(0,item) ''' Dequeue: Remove item from font of the queue ''' def dequeue(self): return self.items.pop() ''' Returns queue size ''' def size(self): return len(self.items) def main(): # Illustrates FIFO behavior q = Queue() q.enqueue('hello') q.enqueue('dog') q.enqueue(3) print(q.dequeue()) print(q.dequeue()) print(q.dequeue()) print("Queue size: ", q.size()) if __name__ == '__main__': main()
class Queue: """ Constructor. Initializes the list items """ def __init__(self): self.items = [] '\n Returns true if queue is empty, false otherwise\n ' def is_empty(self): return self.items == [] '\n Enqueue: Add item to end (tail) of the queue\n ' def enqueue(self, item): self.items.insert(0, item) '\n Dequeue: Remove item from font of the queue\n ' def dequeue(self): return self.items.pop() '\n Returns queue size\n ' def size(self): return len(self.items) def main(): q = queue() q.enqueue('hello') q.enqueue('dog') q.enqueue(3) print(q.dequeue()) print(q.dequeue()) print(q.dequeue()) print('Queue size: ', q.size()) if __name__ == '__main__': main()
filename = 'programing.txt' with open(filename, 'a') as f: f.write('I also like data science\n') f.write('I\'m James Noria.\n') #add new things
filename = 'programing.txt' with open(filename, 'a') as f: f.write('I also like data science\n') f.write("I'm James Noria.\n")
# generated from genmsg/cmake/pkg-genmsg.context.in messages_str = "" services_str = "/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/RestartController.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/SetComplianceMargin.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/SetCompliancePunch.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/SetComplianceSlope.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/SetSpeed.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/SetTorqueLimit.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/StartController.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/StopController.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/TorqueEnable.srv" pkg_name = "dynamixel_controllers" dependencies_str = "" langs = "gencpp;geneus;genlisp;gennodejs;genpy" dep_include_paths_str = "" PYTHON_EXECUTABLE = "/usr/bin/python2" package_has_static_sources = 'TRUE' == 'TRUE' genmsg_check_deps_script = "/opt/ros/melodic/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py"
messages_str = '' services_str = '/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/RestartController.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/SetComplianceMargin.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/SetCompliancePunch.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/SetComplianceSlope.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/SetSpeed.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/SetTorqueLimit.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/StartController.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/StopController.srv;/home/gabriel/Cyton_ROS/Cyton-Gamma-1500/catkin_ws/src/cyton_gamma_300-1500_operation_and_simulation/dynamixel_motor-master/dynamixel_controllers/srv/TorqueEnable.srv' pkg_name = 'dynamixel_controllers' dependencies_str = '' langs = 'gencpp;geneus;genlisp;gennodejs;genpy' dep_include_paths_str = '' python_executable = '/usr/bin/python2' package_has_static_sources = 'TRUE' == 'TRUE' genmsg_check_deps_script = '/opt/ros/melodic/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py'
#-- THIS LINE SHOULD BE THE FIRST LINE OF YOUR SUBMISSION! --# def is_divisible_by(n, numbers): if not numbers or 0 in numbers: raise ValueError for num in numbers: if n % num != 0: return False return True #-- THIS LINE SHOULD BE THE LAST LINE OF YOUR SUBMISSION! ---# ### DO NOT SUBMIT THE FOLLOWING LINES!!! THESE ARE FOR LOCAL TESTING ONLY! assert(is_divisible_by(30, [3, 6, 15])) assert(not is_divisible_by(30, [3, 6, 29])) try: is_divisible_by(30, [0, 6, 29]) assert(False) # expected an exception! except ValueError: print( "Well Done") # the correct exception was thrown
def is_divisible_by(n, numbers): if not numbers or 0 in numbers: raise ValueError for num in numbers: if n % num != 0: return False return True assert is_divisible_by(30, [3, 6, 15]) assert not is_divisible_by(30, [3, 6, 29]) try: is_divisible_by(30, [0, 6, 29]) assert False except ValueError: print('Well Done')
registry_repositories = [ { "registry_name": "resoto-do-plugin-test", "name": "hw", "tag_count": 1, "manifest_count": 1, "latest_manifest": { "digest": "sha256:2ce85c6b306674dcab6eae5fda252037d58f78b0e1bbd41aabf95de6cd7e4a9e", "registry_name": "resoto-do-plugin-test", "repository": "hw", "compressed_size_bytes": 5164, "size_bytes": 12660, "updated_at": "2022-03-14T13:32:34Z", "tags": ["latest"], "blobs": [ { "digest": "sha256:18e5af7904737ba5ef7fbbd7d59de5ebe6c4437907bd7fc436bf9b3ef3149ea9", "compressed_size_bytes": 1483, }, { "digest": "sha256:2ce85c6b306674dcab6eae5fda252037d58f78b0e1bbd41aabf95de6cd7e4a9e", "compressed_size_bytes": 425, }, { "digest": "sha256:9523dd148d42344dc126560861fcb71ff901964cd4c15575f9d9cefe389cd818", "compressed_size_bytes": 3256, }, ], }, } ]
registry_repositories = [{'registry_name': 'resoto-do-plugin-test', 'name': 'hw', 'tag_count': 1, 'manifest_count': 1, 'latest_manifest': {'digest': 'sha256:2ce85c6b306674dcab6eae5fda252037d58f78b0e1bbd41aabf95de6cd7e4a9e', 'registry_name': 'resoto-do-plugin-test', 'repository': 'hw', 'compressed_size_bytes': 5164, 'size_bytes': 12660, 'updated_at': '2022-03-14T13:32:34Z', 'tags': ['latest'], 'blobs': [{'digest': 'sha256:18e5af7904737ba5ef7fbbd7d59de5ebe6c4437907bd7fc436bf9b3ef3149ea9', 'compressed_size_bytes': 1483}, {'digest': 'sha256:2ce85c6b306674dcab6eae5fda252037d58f78b0e1bbd41aabf95de6cd7e4a9e', 'compressed_size_bytes': 425}, {'digest': 'sha256:9523dd148d42344dc126560861fcb71ff901964cd4c15575f9d9cefe389cd818', 'compressed_size_bytes': 3256}]}}]
# encoding: utf-8 # module System.Diagnostics.CodeAnalysis calls itself CodeAnalysis # from mscorlib,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089,System,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089 # by generator 1.145 """ NamespaceTracker represent a CLS namespace. """ # no imports # no functions # classes class ExcludeFromCodeCoverageAttribute(Attribute,_Attribute): """ Specifies that the attributed code should be excluded from code coverage information. ExcludeFromCodeCoverageAttribute() """ def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass class SuppressMessageAttribute(Attribute,_Attribute): """ Suppresses reporting of a specific static analysis tool rule violation,allowing multiple suppressions on a single code artifact. SuppressMessageAttribute(category: str,checkId: str) """ def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass @staticmethod def __new__(self,category,checkId): """ __new__(cls: type,category: str,checkId: str) """ pass Category=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the category identifying the classification of the attribute. Get: Category(self: SuppressMessageAttribute) -> str """ CheckId=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the identifier of the static analysis tool rule to be suppressed. Get: CheckId(self: SuppressMessageAttribute) -> str """ Justification=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the justification for suppressing the code analysis message. Get: Justification(self: SuppressMessageAttribute) -> str Set: Justification(self: SuppressMessageAttribute)=value """ MessageId=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets an optional argument expanding on exclusion criteria. Get: MessageId(self: SuppressMessageAttribute) -> str Set: MessageId(self: SuppressMessageAttribute)=value """ Scope=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the scope of the code that is relevant for the attribute. Get: Scope(self: SuppressMessageAttribute) -> str Set: Scope(self: SuppressMessageAttribute)=value """ Target=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets a fully qualified path that represents the target of the attribute. Get: Target(self: SuppressMessageAttribute) -> str Set: Target(self: SuppressMessageAttribute)=value """
""" NamespaceTracker represent a CLS namespace. """ class Excludefromcodecoverageattribute(Attribute, _Attribute): """ Specifies that the attributed code should be excluded from code coverage information. ExcludeFromCodeCoverageAttribute() """ def __init__(self, *args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass class Suppressmessageattribute(Attribute, _Attribute): """ Suppresses reporting of a specific static analysis tool rule violation,allowing multiple suppressions on a single code artifact. SuppressMessageAttribute(category: str,checkId: str) """ def __init__(self, *args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass @staticmethod def __new__(self, category, checkId): """ __new__(cls: type,category: str,checkId: str) """ pass category = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets the category identifying the classification of the attribute.\n\n\n\nGet: Category(self: SuppressMessageAttribute) -> str\n\n\n\n' check_id = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets the identifier of the static analysis tool rule to be suppressed.\n\n\n\nGet: CheckId(self: SuppressMessageAttribute) -> str\n\n\n\n' justification = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets or sets the justification for suppressing the code analysis message.\n\n\n\nGet: Justification(self: SuppressMessageAttribute) -> str\n\n\n\nSet: Justification(self: SuppressMessageAttribute)=value\n\n' message_id = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets or sets an optional argument expanding on exclusion criteria.\n\n\n\nGet: MessageId(self: SuppressMessageAttribute) -> str\n\n\n\nSet: MessageId(self: SuppressMessageAttribute)=value\n\n' scope = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets or sets the scope of the code that is relevant for the attribute.\n\n\n\nGet: Scope(self: SuppressMessageAttribute) -> str\n\n\n\nSet: Scope(self: SuppressMessageAttribute)=value\n\n' target = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets or sets a fully qualified path that represents the target of the attribute.\n\n\n\nGet: Target(self: SuppressMessageAttribute) -> str\n\n\n\nSet: Target(self: SuppressMessageAttribute)=value\n\n'
def OnEditApart(s1, s2): if abs(len(s1) - len(s2)) > 1: return False if s1 in s2 or s2 in s1: return True mismatch = 0 for i in range(len(s1)): if s1[i]!=s2[i]: mismatch+=1 if mismatch > 1: return False return True
def on_edit_apart(s1, s2): if abs(len(s1) - len(s2)) > 1: return False if s1 in s2 or s2 in s1: return True mismatch = 0 for i in range(len(s1)): if s1[i] != s2[i]: mismatch += 1 if mismatch > 1: return False return True
S = list(map(str, input())) if '7' in S: print('Yes') else: print('No')
s = list(map(str, input())) if '7' in S: print('Yes') else: print('No')
# python3 class JobQueue: def read_data(self): self.num_workers, m = map(int, input().split()) self.array = [[0]*2 for i in range(self.num_workers)] self.jobs = list(map(int, input().split())) assert m == len(self.jobs) self.workers = [None] * len(self.jobs) self.start = [0] * len(self.jobs) def initialize(self): worker = 0 for i in range(min(self.num_workers,len(self.jobs))): self.array[i] = [self.jobs[i],i] self.workers[i] = worker worker+=1 self.start[i] = 0 for i in range(self.num_workers//2, -1,-1): self.swapdown(i) def write_response(self): for i in range(len(self.jobs)): print(self.workers[i], self.start[i]) def swapdown(self,i): min_index = i l = 2*i+1 if (2*i+1<self.num_workers) else -1 r = 2*i+2 if (2*i+2<self.num_workers) else -1 if (l != -1) and ((self.array[l][0] < self.array[min_index][0]) or ((self.array[l][0] == self.array[min_index][0]) and self.array[l][1] < self.array[min_index][1] )): min_index = l if (r != -1) and ((self.array[r][0] < self.array[min_index][0]) or ((self.array[r][0] == self.array[min_index][0]) and (self.array[r][1] < self.array[min_index][1]))): min_index = r if i != min_index: self.array[i], self.array[min_index] = \ self.array[min_index], self.array[i] self.swapdown(min_index) def sorttheheap(self): for i in range(self.num_workers//2, -1,-1): self.swapdown(i) def assign_jobs(self): self.initialize() lasttime = 0 if len(self.jobs)>self.num_workers: for i in range(self.num_workers,len(self.jobs)): # print(1,self.array) self.swapdown(0) #don't need to sort here only swapping would do # print(2,self.array) lasttime =self.array[0][0] # if self.array[0][0]!=self.array[1][0]: self.workers[i] = self.array[0][1] self.start[i] = lasttime # elif self.array[0][0] ==self.array[1][0]: # temp=0 # print(self.array) self.array[0][0] += self.jobs[i] def solve(self): self.read_data() self.assign_jobs() self.write_response() if __name__ == '__main__': job_queue = JobQueue() job_queue.solve()
class Jobqueue: def read_data(self): (self.num_workers, m) = map(int, input().split()) self.array = [[0] * 2 for i in range(self.num_workers)] self.jobs = list(map(int, input().split())) assert m == len(self.jobs) self.workers = [None] * len(self.jobs) self.start = [0] * len(self.jobs) def initialize(self): worker = 0 for i in range(min(self.num_workers, len(self.jobs))): self.array[i] = [self.jobs[i], i] self.workers[i] = worker worker += 1 self.start[i] = 0 for i in range(self.num_workers // 2, -1, -1): self.swapdown(i) def write_response(self): for i in range(len(self.jobs)): print(self.workers[i], self.start[i]) def swapdown(self, i): min_index = i l = 2 * i + 1 if 2 * i + 1 < self.num_workers else -1 r = 2 * i + 2 if 2 * i + 2 < self.num_workers else -1 if l != -1 and (self.array[l][0] < self.array[min_index][0] or (self.array[l][0] == self.array[min_index][0] and self.array[l][1] < self.array[min_index][1])): min_index = l if r != -1 and (self.array[r][0] < self.array[min_index][0] or (self.array[r][0] == self.array[min_index][0] and self.array[r][1] < self.array[min_index][1])): min_index = r if i != min_index: (self.array[i], self.array[min_index]) = (self.array[min_index], self.array[i]) self.swapdown(min_index) def sorttheheap(self): for i in range(self.num_workers // 2, -1, -1): self.swapdown(i) def assign_jobs(self): self.initialize() lasttime = 0 if len(self.jobs) > self.num_workers: for i in range(self.num_workers, len(self.jobs)): self.swapdown(0) lasttime = self.array[0][0] self.workers[i] = self.array[0][1] self.start[i] = lasttime self.array[0][0] += self.jobs[i] def solve(self): self.read_data() self.assign_jobs() self.write_response() if __name__ == '__main__': job_queue = job_queue() job_queue.solve()
# https://leetcode.com/problems/queue-reconstruction-by-height class Solution: def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]: people.sort(key=lambda x: (-x[0], x[1])) output = [] for p in people: output.insert(p[1], p) return output
class Solution: def reconstruct_queue(self, people: List[List[int]]) -> List[List[int]]: people.sort(key=lambda x: (-x[0], x[1])) output = [] for p in people: output.insert(p[1], p) return output
# Have the function KaprekarsConstant(num) take the num parameter being passed which will be a 4-digit number with at least two distinct digits. Your program should perform the following routine on the number: Arrange the digits in descending order and in ascending order (adding zeroes to fit it to a 4-digit number), and subtract the smaller number from the bigger number. Then repeat the previous step. Performing this routine will always cause you to reach a fixed number: 6174. Then performing the routine on 6174 will always give you 6174 (7641 - 1467 = 6174). Your program should return the number of times this routine must be performed until 6174 is reached. For example: if num is 3524 your program should return 3 because of the following steps: (1) 5432 - 2345 = 3087, (2) 8730 - 0378 = 8352, (3) 8532 - 2358 = 6174. def kaprekars_constant(str): # code goes here return str
def kaprekars_constant(str): return str
try: f = open("textfile", "r") f.write("write a TEST LINE ") except TypeError: print("There was a type error") except OSError: print("Hey you have an OS error") except: print("All other exception") finally: print("I always run")
try: f = open('textfile', 'r') f.write('write a TEST LINE ') except TypeError: print('There was a type error') except OSError: print('Hey you have an OS error') except: print('All other exception') finally: print('I always run')
def selectionSort(alist): for slot in range(len(alist) - 1, 0, -1): iMax = 0 for index in range(1, slot + 1): if alist[index] > alist[iMax]: iMax = index alist[slot], alist[iMax] = alist[iMax], alist[slot]
def selection_sort(alist): for slot in range(len(alist) - 1, 0, -1): i_max = 0 for index in range(1, slot + 1): if alist[index] > alist[iMax]: i_max = index (alist[slot], alist[iMax]) = (alist[iMax], alist[slot])
src = Glob('*.c') component = aos_component('libid2', src) component.add_global_includes('include') component.add_comp_deps('security/plat_gen', 'security/libkm') component.add_global_macros('CONFIG_AOS_SUPPORT=1') component.add_prebuilt_libs('lib/' + component.get_arch() + '/libid2.a')
src = glob('*.c') component = aos_component('libid2', src) component.add_global_includes('include') component.add_comp_deps('security/plat_gen', 'security/libkm') component.add_global_macros('CONFIG_AOS_SUPPORT=1') component.add_prebuilt_libs('lib/' + component.get_arch() + '/libid2.a')
my_list = [1, 2, 3, 4, 5] def sqr(x): return x ** 2; def map(list_, f): return [f(x) for x in list_] def map_iter(list_, f): new_list = [] for i in list_: new_list.append(f(i)) return new_list
my_list = [1, 2, 3, 4, 5] def sqr(x): return x ** 2 def map(list_, f): return [f(x) for x in list_] def map_iter(list_, f): new_list = [] for i in list_: new_list.append(f(i)) return new_list
def twoStrings(s1, s2): """Compares two strings to find matching substring.""" for i in s1: if i in s2: return "YES" return "NO" def twoStrings(s1, s2): """Compares two strings to find matching substring using set.""" a = set(s1) if len(s1 >= s2) else set(s2) for i in s1: if i in s2: return "YES" return "NO" print(twoStrings("abc", "rattle")) print(twoStrings("bcd", "rattle")) print(twoStrings("bcd", "battle"))
def two_strings(s1, s2): """Compares two strings to find matching substring.""" for i in s1: if i in s2: return 'YES' return 'NO' def two_strings(s1, s2): """Compares two strings to find matching substring using set.""" a = set(s1) if len(s1 >= s2) else set(s2) for i in s1: if i in s2: return 'YES' return 'NO' print(two_strings('abc', 'rattle')) print(two_strings('bcd', 'rattle')) print(two_strings('bcd', 'battle'))
# https://www.codewars.com/kata/returning-strings/train/python # My solution def greet(name): return "Hello, %s how are you doing today?" % name # ... def greet(name): return f'Hello, {name} how are you doing today?' # ... def greet(name): return "Hello, {} how are you doing today?".format(name)
def greet(name): return 'Hello, %s how are you doing today?' % name def greet(name): return f'Hello, {name} how are you doing today?' def greet(name): return 'Hello, {} how are you doing today?'.format(name)
def envelopeHiBounds(valueList, wnd): return envelopeBounds(valueList, wnd, 0.025) def envelopeLoBounds(valueList, wnd): return envelopeBounds(valueList, wnd, 0.025) def envelopeBounds(valueList, wnd, ratio): return valueList.ewm(wnd).mean() * (1 + ratio)
def envelope_hi_bounds(valueList, wnd): return envelope_bounds(valueList, wnd, 0.025) def envelope_lo_bounds(valueList, wnd): return envelope_bounds(valueList, wnd, 0.025) def envelope_bounds(valueList, wnd, ratio): return valueList.ewm(wnd).mean() * (1 + ratio)
# test lists assert 3 in [1, 2, 3] assert 3 not in [1, 2] assert not (3 in [1, 2]) assert not (3 not in [1, 2, 3]) # test strings assert "foo" in "foobar" assert "whatever" not in "foobar" # test bytes # TODO: uncomment this when bytes are implemented # assert b"foo" in b"foobar" # assert b"whatever" not in b"foobar" assert b"1" < b"2" assert b"1" <= b"2" assert b"5" <= b"5" assert b"4" > b"2" assert not b"1" >= b"2" assert b"10" >= b"10" try: bytes() > 2 except TypeError: pass else: assert False, "TypeError not raised" # test tuple assert 1 in (1, 2) assert 3 not in (1, 2) # test set assert 1 in set([1, 2]) assert 3 not in set([1, 2]) # test dicts # TODO: test dicts when keys other than strings will be allowed assert "a" in {"a": 0, "b": 0} assert "c" not in {"a": 0, "b": 0} # test iter assert 3 in iter([1, 2, 3]) assert 3 not in iter([1, 2]) # test sequence # TODO: uncomment this when ranges are usable # assert 1 in range(0, 2) # assert 3 not in range(0, 2) # test __contains__ in user objects class MyNotContainingClass(): pass try: 1 in MyNotContainingClass() except TypeError: pass else: assert False, "TypeError not raised" class MyContainingClass(): def __init__(self, value): self.value = value def __contains__(self, something): return something == self.value assert 2 in MyContainingClass(2) assert 1 not in MyContainingClass(2)
assert 3 in [1, 2, 3] assert 3 not in [1, 2] assert not 3 in [1, 2] assert not 3 not in [1, 2, 3] assert 'foo' in 'foobar' assert 'whatever' not in 'foobar' assert b'1' < b'2' assert b'1' <= b'2' assert b'5' <= b'5' assert b'4' > b'2' assert not b'1' >= b'2' assert b'10' >= b'10' try: bytes() > 2 except TypeError: pass else: assert False, 'TypeError not raised' assert 1 in (1, 2) assert 3 not in (1, 2) assert 1 in set([1, 2]) assert 3 not in set([1, 2]) assert 'a' in {'a': 0, 'b': 0} assert 'c' not in {'a': 0, 'b': 0} assert 3 in iter([1, 2, 3]) assert 3 not in iter([1, 2]) class Mynotcontainingclass: pass try: 1 in my_not_containing_class() except TypeError: pass else: assert False, 'TypeError not raised' class Mycontainingclass: def __init__(self, value): self.value = value def __contains__(self, something): return something == self.value assert 2 in my_containing_class(2) assert 1 not in my_containing_class(2)
# coding=utf-8 __author__ = 'mlaptev' if __name__ == "__main__": matrix = [] line = input() while line != 'end': matrix.append([int(i) for i in line.split()]) line = input() for i in range(len(matrix)): for j in range(len(matrix[i])): print(matrix[i-1][j] + matrix[(i+1)%len(matrix)][j] + matrix[i][j-1] + matrix[i][(j+1)%len(matrix[i])], end=' ') print()
__author__ = 'mlaptev' if __name__ == '__main__': matrix = [] line = input() while line != 'end': matrix.append([int(i) for i in line.split()]) line = input() for i in range(len(matrix)): for j in range(len(matrix[i])): print(matrix[i - 1][j] + matrix[(i + 1) % len(matrix)][j] + matrix[i][j - 1] + matrix[i][(j + 1) % len(matrix[i])], end=' ') print()
""" Error module holds all custom errors for the scraper class """ class InvalidWebsite(Exception): """ An Invalid website was proided to the scraper """ pass
""" Error module holds all custom errors for the scraper class """ class Invalidwebsite(Exception): """ An Invalid website was proided to the scraper """ pass
load("@io_bazel_rules_closure//closure:defs.bzl", "closure_js_binary", "closure_js_library") def _internal_closure_fragment_export_impl(ctx): ctx.actions.write( output = ctx.outputs.out, content = """ goog.require('%s'); goog.exportSymbol('_', %s); """ % (ctx.attr.module, ctx.attr.function), ) _internal_closure_fragment_export = rule( implementation = _internal_closure_fragment_export_impl, attrs = { "function": attr.string(mandatory = True), "module": attr.string(mandatory = True), }, outputs = {"out": "%{name}.js"}, ) def _closure_fragment_impl(ctx): defs = ctx.attr.defines + [ "goog.userAgent.ASSUME_MOBILE_WEBKIT=true", "goog.userAgent.product.ASSUME_ANDROID=true", ] def closure_fragment( name, module, function, browsers = None, **kwargs): if browsers == None: browsers = [] if type(browsers) != "list": fail("browsers must be None or a list of strings") exports_file_name = "_%s_exports" % name _internal_closure_fragment_export( name = exports_file_name, module = module, function = function, ) exports_lib_name = "%s_lib" % exports_file_name closure_js_library( name = exports_lib_name, srcs = [exports_file_name], deps = kwargs.get("deps", []), ) # Wrap the output in two functions. The outer function ensures the # compiled fragment never pollutes the global scope by using its # own scope on each invocation. We must import window.navigator into # this unique scope since Closure's goog.userAgent package assumes # navigator and document are defined on goog.global. Normally, this # would be window, but we are explicitly defining the fragment so that # goog.global is _not_ window. # See http://code.google.com/p/selenium/issues/detail?id=1333 wrapper = ( "function(){" + "return (function(){%output%; return this._.apply(null,arguments);}).apply({" + "navigator:typeof window!='undefined'?window.navigator:null," + "document:typeof window!='undefined'?window.document:null" + "}, arguments);}" ) browser_defs = { "*": [], "android": [ "--define=goog.userAgent.ASSUME_MOBILE_WEBKIT=true", "--define=goog.userAgent.product.ASSUME_ANDROID=true", ], "chrome": [ "--define=goog.userAgent.ASSUME_WEBKIT=true", "--define=goog.userAgent.product.ASSUME_CHROME=true", "--define=goog.NATIVE_ARRAY_PROTOTYPES=false", "--use_types_for_optimization=false", ], "ie": [ "--define=goog.userAgent.ASSUME_IE=true", ], "ios": [ "--define=goog.userAgent.ASSUME_MOBILE_WEBKIT=true", ], "firefox": [ "--define=goog.userAgent.ASSUME_GECKO=true", "--define=goog.userAgent.product.ASSUME_FIREFOX=true", ], } for browser, defs in browser_defs.items(): if len(browsers) > 0 and (browser == "*" or browser not in browsers): continue bin_name = name if browser != "*": bin_name = bin_name + "-" + browser closure_js_binary( name = bin_name, deps = [":" + exports_lib_name], defs = kwargs.get("defs", []) + defs, output_wrapper = wrapper, visibility = kwargs.get("visibility"), )
load('@io_bazel_rules_closure//closure:defs.bzl', 'closure_js_binary', 'closure_js_library') def _internal_closure_fragment_export_impl(ctx): ctx.actions.write(output=ctx.outputs.out, content="\ngoog.require('%s');\ngoog.exportSymbol('_', %s);\n" % (ctx.attr.module, ctx.attr.function)) _internal_closure_fragment_export = rule(implementation=_internal_closure_fragment_export_impl, attrs={'function': attr.string(mandatory=True), 'module': attr.string(mandatory=True)}, outputs={'out': '%{name}.js'}) def _closure_fragment_impl(ctx): defs = ctx.attr.defines + ['goog.userAgent.ASSUME_MOBILE_WEBKIT=true', 'goog.userAgent.product.ASSUME_ANDROID=true'] def closure_fragment(name, module, function, browsers=None, **kwargs): if browsers == None: browsers = [] if type(browsers) != 'list': fail('browsers must be None or a list of strings') exports_file_name = '_%s_exports' % name _internal_closure_fragment_export(name=exports_file_name, module=module, function=function) exports_lib_name = '%s_lib' % exports_file_name closure_js_library(name=exports_lib_name, srcs=[exports_file_name], deps=kwargs.get('deps', [])) wrapper = 'function(){' + 'return (function(){%output%; return this._.apply(null,arguments);}).apply({' + "navigator:typeof window!='undefined'?window.navigator:null," + "document:typeof window!='undefined'?window.document:null" + '}, arguments);}' browser_defs = {'*': [], 'android': ['--define=goog.userAgent.ASSUME_MOBILE_WEBKIT=true', '--define=goog.userAgent.product.ASSUME_ANDROID=true'], 'chrome': ['--define=goog.userAgent.ASSUME_WEBKIT=true', '--define=goog.userAgent.product.ASSUME_CHROME=true', '--define=goog.NATIVE_ARRAY_PROTOTYPES=false', '--use_types_for_optimization=false'], 'ie': ['--define=goog.userAgent.ASSUME_IE=true'], 'ios': ['--define=goog.userAgent.ASSUME_MOBILE_WEBKIT=true'], 'firefox': ['--define=goog.userAgent.ASSUME_GECKO=true', '--define=goog.userAgent.product.ASSUME_FIREFOX=true']} for (browser, defs) in browser_defs.items(): if len(browsers) > 0 and (browser == '*' or browser not in browsers): continue bin_name = name if browser != '*': bin_name = bin_name + '-' + browser closure_js_binary(name=bin_name, deps=[':' + exports_lib_name], defs=kwargs.get('defs', []) + defs, output_wrapper=wrapper, visibility=kwargs.get('visibility'))
"""Rio-Cogeo Errors and Warnings.""" class DeprecationWarning(UserWarning): """Rio-cogeo module deprecations warning.""" class LossyCompression(UserWarning): """Rio-cogeo module Lossy compression warning.""" class IncompatibleBlockRasterSize(UserWarning): """Rio-cogeo module incompatible raster block/size warning."""
"""Rio-Cogeo Errors and Warnings.""" class Deprecationwarning(UserWarning): """Rio-cogeo module deprecations warning.""" class Lossycompression(UserWarning): """Rio-cogeo module Lossy compression warning.""" class Incompatibleblockrastersize(UserWarning): """Rio-cogeo module incompatible raster block/size warning."""