content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
"""This program takes a score between 0.0 and 1.0 and returns an appropriate grade for score inputted""" try: grade = float(input('Enter your score: ')) if grade < 0.6: print('Your score', grade, 'is F') elif 0.6 <= grade <= 0.7: print('Your score', grade, 'is D') elif 0.7 <= grade <= 0.8: print('Your score', grade, 'is C') elif 0.8 <= grade <= 0.9: print('Your score', grade, 'is B') elif 0.9 <= grade <= 1.0: print('Your score', grade, 'is A') elif grade > 1.0: print('Your score', grade, 'is out of range') except: print('Bad score')
"""This program takes a score between 0.0 and 1.0 and returns an appropriate grade for score inputted""" try: grade = float(input('Enter your score: ')) if grade < 0.6: print('Your score', grade, 'is F') elif 0.6 <= grade <= 0.7: print('Your score', grade, 'is D') elif 0.7 <= grade <= 0.8: print('Your score', grade, 'is C') elif 0.8 <= grade <= 0.9: print('Your score', grade, 'is B') elif 0.9 <= grade <= 1.0: print('Your score', grade, 'is A') elif grade > 1.0: print('Your score', grade, 'is out of range') except: print('Bad score')
# You can gen a bcrypt hash here: ## http://bcrypthashgenerator.apphb.com/ pwhash = 'bcrypt' # You can generate salts and other secrets with openssl # For example: # $ openssl rand -hex 16 # 1ca632d8567743f94352545abe2e313d salt = "141202e6b20aa53596a339a0d0b92e79" secret_key = 'fe65757e00193b8bc2e18444fa51d873' mongo_db = 'mydatabase' mongo_host = 'localhost' mongo_port = 27017 user_enable_registration = True user_enable_tracking = True user_from_email = "[email protected]" user_register_email_subject = "Thank you for signing up" mail_url = "mail.yoursite.com" mail_port = "25" mail_SSL = False mail_TLS = False mail_user = "username_goes_here" mail_pass = "password_goes_here"
pwhash = 'bcrypt' salt = '141202e6b20aa53596a339a0d0b92e79' secret_key = 'fe65757e00193b8bc2e18444fa51d873' mongo_db = 'mydatabase' mongo_host = 'localhost' mongo_port = 27017 user_enable_registration = True user_enable_tracking = True user_from_email = '[email protected]' user_register_email_subject = 'Thank you for signing up' mail_url = 'mail.yoursite.com' mail_port = '25' mail_ssl = False mail_tls = False mail_user = 'username_goes_here' mail_pass = 'password_goes_here'
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def shell_sort(list_: list) -> list: """Returns a sorted list, by shell sort method :param list_: The list to be sorted :type list_: list :rtype: list :return: Sorted list, by shell sort method """ half = len(list_) // 2 while half > 0: for i in range(half, len(list_)): tmp = list_[i] j = i while j >= half and list_[j - half] > tmp: list_[j] = list_[j - half] j -= half list_[j] = tmp half //= 2 return list_
def shell_sort(list_: list) -> list: """Returns a sorted list, by shell sort method :param list_: The list to be sorted :type list_: list :rtype: list :return: Sorted list, by shell sort method """ half = len(list_) // 2 while half > 0: for i in range(half, len(list_)): tmp = list_[i] j = i while j >= half and list_[j - half] > tmp: list_[j] = list_[j - half] j -= half list_[j] = tmp half //= 2 return list_
sbox = [ 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F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 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d ] vector_table = [2, 3, 1, 1, 1, 2, 3, 1, 1, 1, 2, 3, 3, 1, 1, 2] table_2 = [ 0x00, 0x02, 0x04, 0x06, 0x08, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14, 0x16, 0x18, 0x1a, 0x1c, 0x1e, 0x20, 0x22, 0x24, 0x26, 0x28, 0x2a, 0x2c, 0x2e, 0x30, 0x32, 0x34, 0x36, 0x38, 0x3a, 0x3c, 0x3e, 0x40, 0x42, 0x44, 0x46, 0x48, 0x4a, 0x4c, 0x4e, 0x50, 0x52, 0x54, 0x56, 0x58, 0x5a, 0x5c, 0x5e, 0x60, 0x62, 0x64, 0x66, 0x68, 0x6a, 0x6c, 0x6e, 0x70, 0x72, 0x74, 0x76, 0x78, 0x7a, 0x7c, 0x7e, 0x80, 0x82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0x83, 0x8d]
sbox = [99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22] sbox_inv = [82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125] r_con = [141, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54, 108, 216, 171, 77, 154, 47, 94, 188, 99, 198, 151, 53, 106, 212, 179, 125, 250, 239, 197, 145, 57, 114, 228, 211, 189, 97, 194, 159, 37, 74, 148, 51, 102, 204, 131, 29, 58, 116, 232, 203, 141, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54, 108, 216, 171, 77, 154, 47, 94, 188, 99, 198, 151, 53, 106, 212, 179, 125, 250, 239, 197, 145, 57, 114, 228, 211, 189, 97, 194, 159, 37, 74, 148, 51, 102, 204, 131, 29, 58, 116, 232, 203, 141, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54, 108, 216, 171, 77, 154, 47, 94, 188, 99, 198, 151, 53, 106, 212, 179, 125, 250, 239, 197, 145, 57, 114, 228, 211, 189, 97, 194, 159, 37, 74, 148, 51, 102, 204, 131, 29, 58, 116, 232, 203, 141, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54, 108, 216, 171, 77, 154, 47, 94, 188, 99, 198, 151, 53, 106, 212, 179, 125, 250, 239, 197, 145, 57, 114, 228, 211, 189, 97, 194, 159, 37, 74, 148, 51, 102, 204, 131, 29, 58, 116, 232, 203, 141, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54, 108, 216, 171, 77, 154, 47, 94, 188, 99, 198, 151, 53, 106, 212, 179, 125, 250, 239, 197, 145, 57, 114, 228, 211, 189, 97, 194, 159, 37, 74, 148, 51, 102, 204, 131, 29, 58, 116, 232, 203, 141] vector_table = [2, 3, 1, 1, 1, 2, 3, 1, 1, 1, 2, 3, 3, 1, 1, 2] table_2 = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104, 106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126, 128, 130, 132, 134, 136, 138, 140, 142, 144, 146, 148, 150, 152, 154, 156, 158, 160, 162, 164, 166, 168, 170, 172, 174, 176, 178, 180, 182, 184, 186, 188, 190, 192, 194, 196, 198, 200, 202, 204, 206, 208, 210, 212, 214, 216, 218, 220, 222, 224, 226, 228, 230, 232, 234, 236, 238, 240, 242, 244, 246, 248, 250, 252, 254, 27, 25, 31, 29, 19, 17, 23, 21, 11, 9, 15, 13, 3, 1, 7, 5, 59, 57, 63, 61, 51, 49, 55, 53, 43, 41, 47, 45, 35, 33, 39, 37, 91, 89, 95, 93, 83, 81, 87, 85, 75, 73, 79, 77, 67, 65, 71, 69, 123, 121, 127, 125, 115, 113, 119, 117, 107, 105, 111, 109, 99, 97, 103, 101, 155, 153, 159, 157, 147, 145, 151, 149, 139, 137, 143, 141, 131, 129, 135, 133, 187, 185, 191, 189, 179, 177, 183, 181, 171, 169, 175, 173, 163, 161, 167, 165, 219, 217, 223, 221, 211, 209, 215, 213, 203, 201, 207, 205, 195, 193, 199, 197, 251, 249, 255, 253, 243, 241, 247, 245, 235, 233, 239, 237, 227, 225, 231, 229] table_3 = [0, 3, 6, 5, 12, 15, 10, 9, 24, 27, 30, 29, 20, 23, 18, 17, 48, 51, 54, 53, 60, 63, 58, 57, 40, 43, 46, 45, 36, 39, 34, 33, 96, 99, 102, 101, 108, 111, 106, 105, 120, 123, 126, 125, 116, 119, 114, 113, 80, 83, 86, 85, 92, 95, 90, 89, 72, 75, 78, 77, 68, 71, 66, 65, 192, 195, 198, 197, 204, 207, 202, 201, 216, 219, 222, 221, 212, 215, 210, 209, 240, 243, 246, 245, 252, 255, 250, 249, 232, 235, 238, 237, 228, 231, 226, 225, 160, 163, 166, 165, 172, 175, 170, 169, 184, 187, 190, 189, 180, 183, 178, 177, 144, 147, 150, 149, 156, 159, 154, 153, 136, 139, 142, 141, 132, 135, 130, 129, 155, 152, 157, 158, 151, 148, 145, 146, 131, 128, 133, 134, 143, 140, 137, 138, 171, 168, 173, 174, 167, 164, 161, 162, 179, 176, 181, 182, 191, 188, 185, 186, 251, 248, 253, 254, 247, 244, 241, 242, 227, 224, 229, 230, 239, 236, 233, 234, 203, 200, 205, 206, 199, 196, 193, 194, 211, 208, 213, 214, 223, 220, 217, 218, 91, 88, 93, 94, 87, 84, 81, 82, 67, 64, 69, 70, 79, 76, 73, 74, 107, 104, 109, 110, 103, 100, 97, 98, 115, 112, 117, 118, 127, 124, 121, 122, 59, 56, 61, 62, 55, 52, 49, 50, 35, 32, 37, 38, 47, 44, 41, 42, 11, 8, 13, 14, 7, 4, 1, 2, 19, 16, 21, 22, 31, 28, 25, 26] table_9 = [0, 9, 18, 27, 36, 45, 54, 63, 72, 65, 90, 83, 108, 101, 126, 119, 144, 153, 130, 139, 180, 189, 166, 175, 216, 209, 202, 195, 252, 245, 238, 231, 59, 50, 41, 32, 31, 22, 13, 4, 115, 122, 97, 104, 87, 94, 69, 76, 171, 162, 185, 176, 143, 134, 157, 148, 227, 234, 241, 248, 199, 206, 213, 220, 118, 127, 100, 109, 82, 91, 64, 73, 62, 55, 44, 37, 26, 19, 8, 1, 230, 239, 244, 253, 194, 203, 208, 217, 174, 167, 188, 181, 138, 131, 152, 145, 77, 68, 95, 86, 105, 96, 123, 114, 5, 12, 23, 30, 33, 40, 51, 58, 221, 212, 207, 198, 249, 240, 235, 226, 149, 156, 135, 142, 177, 184, 163, 170, 236, 229, 254, 247, 200, 193, 218, 211, 164, 173, 182, 191, 128, 137, 146, 155, 124, 117, 110, 103, 88, 81, 74, 67, 52, 61, 38, 47, 16, 25, 2, 11, 215, 222, 197, 204, 243, 250, 225, 232, 159, 150, 141, 132, 187, 178, 169, 160, 71, 78, 85, 92, 99, 106, 113, 120, 15, 6, 29, 20, 43, 34, 57, 48, 154, 147, 136, 129, 190, 183, 172, 165, 210, 219, 192, 201, 246, 255, 228, 237, 10, 3, 24, 17, 46, 39, 60, 53, 66, 75, 80, 89, 102, 111, 116, 125, 161, 168, 179, 186, 133, 140, 151, 158, 233, 224, 251, 242, 205, 196, 223, 214, 49, 56, 35, 42, 21, 28, 7, 14, 121, 112, 107, 98, 93, 84, 79, 70] table_11 = [0, 11, 22, 29, 44, 39, 58, 49, 88, 83, 78, 69, 116, 127, 98, 105, 176, 187, 166, 173, 156, 151, 138, 129, 232, 227, 254, 245, 196, 207, 210, 217, 123, 112, 109, 102, 87, 92, 65, 74, 35, 40, 53, 62, 15, 4, 25, 18, 203, 192, 221, 214, 231, 236, 241, 250, 147, 152, 133, 142, 191, 180, 169, 162, 246, 253, 224, 235, 218, 209, 204, 199, 174, 165, 184, 179, 130, 137, 148, 159, 70, 77, 80, 91, 106, 97, 124, 119, 30, 21, 8, 3, 50, 57, 36, 47, 141, 134, 155, 144, 161, 170, 183, 188, 213, 222, 195, 200, 249, 242, 239, 228, 61, 54, 43, 32, 17, 26, 7, 12, 101, 110, 115, 120, 73, 66, 95, 84, 247, 252, 225, 234, 219, 208, 205, 198, 175, 164, 185, 178, 131, 136, 149, 158, 71, 76, 81, 90, 107, 96, 125, 118, 31, 20, 9, 2, 51, 56, 37, 46, 140, 135, 154, 145, 160, 171, 182, 189, 212, 223, 194, 201, 248, 243, 238, 229, 60, 55, 42, 33, 16, 27, 6, 13, 100, 111, 114, 121, 72, 67, 94, 85, 1, 10, 23, 28, 45, 38, 59, 48, 89, 82, 79, 68, 117, 126, 99, 104, 177, 186, 167, 172, 157, 150, 139, 128, 233, 226, 255, 244, 197, 206, 211, 216, 122, 113, 108, 103, 86, 93, 64, 75, 34, 41, 52, 63, 14, 5, 24, 19, 202, 193, 220, 215, 230, 237, 240, 251, 146, 153, 132, 143, 190, 181, 168, 163] table_13 = [0, 13, 26, 23, 52, 57, 46, 35, 104, 101, 114, 127, 92, 81, 70, 75, 208, 221, 202, 199, 228, 233, 254, 243, 184, 181, 162, 175, 140, 129, 150, 155, 187, 182, 161, 172, 143, 130, 149, 152, 211, 222, 201, 196, 231, 234, 253, 240, 107, 102, 113, 124, 95, 82, 69, 72, 3, 14, 25, 20, 55, 58, 45, 32, 109, 96, 119, 122, 89, 84, 67, 78, 5, 8, 31, 18, 49, 60, 43, 38, 189, 176, 167, 170, 137, 132, 147, 158, 213, 216, 207, 194, 225, 236, 251, 246, 214, 219, 204, 193, 226, 239, 248, 245, 190, 179, 164, 169, 138, 135, 144, 157, 6, 11, 28, 17, 50, 63, 40, 37, 110, 99, 116, 121, 90, 87, 64, 77, 218, 215, 192, 205, 238, 227, 244, 249, 178, 191, 168, 165, 134, 139, 156, 145, 10, 7, 16, 29, 62, 51, 36, 41, 98, 111, 120, 117, 86, 91, 76, 65, 97, 108, 123, 118, 85, 88, 79, 66, 9, 4, 19, 30, 61, 48, 39, 42, 177, 188, 171, 166, 133, 136, 159, 146, 217, 212, 195, 206, 237, 224, 247, 250, 183, 186, 173, 160, 131, 142, 153, 148, 223, 210, 197, 200, 235, 230, 241, 252, 103, 106, 125, 112, 83, 94, 73, 68, 15, 2, 21, 24, 59, 54, 33, 44, 12, 1, 22, 27, 56, 53, 34, 47, 100, 105, 126, 115, 80, 93, 74, 71, 220, 209, 198, 203, 232, 229, 242, 255, 180, 185, 174, 163, 128, 141, 154, 151] table_14 = [0, 14, 28, 18, 56, 54, 36, 42, 112, 126, 108, 98, 72, 70, 84, 90, 224, 238, 252, 242, 216, 214, 196, 202, 144, 158, 140, 130, 168, 166, 180, 186, 219, 213, 199, 201, 227, 237, 255, 241, 171, 165, 183, 185, 147, 157, 143, 129, 59, 53, 39, 41, 3, 13, 31, 17, 75, 69, 87, 89, 115, 125, 111, 97, 173, 163, 177, 191, 149, 155, 137, 135, 221, 211, 193, 207, 229, 235, 249, 247, 77, 67, 81, 95, 117, 123, 105, 103, 61, 51, 33, 47, 5, 11, 25, 23, 118, 120, 106, 100, 78, 64, 82, 92, 6, 8, 26, 20, 62, 48, 34, 44, 150, 152, 138, 132, 174, 160, 178, 188, 230, 232, 250, 244, 222, 208, 194, 204, 65, 79, 93, 83, 121, 119, 101, 107, 49, 63, 45, 35, 9, 7, 21, 27, 161, 175, 189, 179, 153, 151, 133, 139, 209, 223, 205, 195, 233, 231, 245, 251, 154, 148, 134, 136, 162, 172, 190, 176, 234, 228, 246, 248, 210, 220, 206, 192, 122, 116, 102, 104, 66, 76, 94, 80, 10, 4, 22, 24, 50, 60, 46, 32, 236, 226, 240, 254, 212, 218, 200, 198, 156, 146, 128, 142, 164, 170, 184, 182, 12, 2, 16, 30, 52, 58, 40, 38, 124, 114, 96, 110, 68, 74, 88, 86, 55, 57, 43, 37, 15, 1, 19, 29, 71, 73, 91, 85, 127, 113, 99, 109, 215, 217, 203, 197, 239, 225, 243, 253, 167, 169, 187, 181, 159, 145, 131, 141]
""" Syntax Scoring https://adventofcode.com/2021/day/10 """ MATCHES = { '<': '>', '(': ')', '{': '}', '[': ']' } ERROR_SCORE = { ')': 3, ']': 57, '}': 1197, '>': 25137, } AUTOCOMPLETE_SCORE = { ')': 1, ']': 2, '}': 3, '>': 4, } def find_error(line): """returns error score and remaining stack""" stack = [] for char in line: if char in '[({<': stack.append(char) else: m = stack.pop() match = MATCHES[m] if char != match: return ERROR_SCORE[char], [] return 0, stack def autocomplete(stack): prod = 0 for char in stack[::-1]: prod *= 5 prod += AUTOCOMPLETE_SCORE[MATCHES[char]] return prod def solve(data): total = 0 for line in data.strip().split('\n'): score, _ = find_error(line) total += score return total def solve2(data): autos = [] for line in data.strip().split('\n'): score, stack = find_error(line) if score == 0: autos.append(autocomplete(stack)) autos.sort() middle = len(autos) // 2 return autos[middle] if __name__ == '__main__': input_data = open('input_data.txt').read() result = solve(input_data) print(f'Example 1: {result}') # 268845 result = solve2(input_data) print(f'Example 2: {result}') # 4038824534
""" Syntax Scoring https://adventofcode.com/2021/day/10 """ matches = {'<': '>', '(': ')', '{': '}', '[': ']'} error_score = {')': 3, ']': 57, '}': 1197, '>': 25137} autocomplete_score = {')': 1, ']': 2, '}': 3, '>': 4} def find_error(line): """returns error score and remaining stack""" stack = [] for char in line: if char in '[({<': stack.append(char) else: m = stack.pop() match = MATCHES[m] if char != match: return (ERROR_SCORE[char], []) return (0, stack) def autocomplete(stack): prod = 0 for char in stack[::-1]: prod *= 5 prod += AUTOCOMPLETE_SCORE[MATCHES[char]] return prod def solve(data): total = 0 for line in data.strip().split('\n'): (score, _) = find_error(line) total += score return total def solve2(data): autos = [] for line in data.strip().split('\n'): (score, stack) = find_error(line) if score == 0: autos.append(autocomplete(stack)) autos.sort() middle = len(autos) // 2 return autos[middle] if __name__ == '__main__': input_data = open('input_data.txt').read() result = solve(input_data) print(f'Example 1: {result}') result = solve2(input_data) print(f'Example 2: {result}')
TAG_TYPE = "#type" TAG_XML = "#xml" TAG_VERSION = "@version" TAG_UIVERSION = "@uiVersion" TAG_NAMESPACE = "@xmlns" TAG_NAME = "@name" TAG_META = "meta" TAG_FORM = 'form' ATTACHMENT_NAME = "form.xml" MAGIC_PROPERTY = 'xml_submission_file' RESERVED_WORDS = [TAG_TYPE, TAG_XML, TAG_VERSION, TAG_UIVERSION, TAG_NAMESPACE, TAG_NAME, TAG_META, ATTACHMENT_NAME, 'case', MAGIC_PROPERTY] DEVICE_LOG_XMLNS = 'http://code.javarosa.org/devicereport'
tag_type = '#type' tag_xml = '#xml' tag_version = '@version' tag_uiversion = '@uiVersion' tag_namespace = '@xmlns' tag_name = '@name' tag_meta = 'meta' tag_form = 'form' attachment_name = 'form.xml' magic_property = 'xml_submission_file' reserved_words = [TAG_TYPE, TAG_XML, TAG_VERSION, TAG_UIVERSION, TAG_NAMESPACE, TAG_NAME, TAG_META, ATTACHMENT_NAME, 'case', MAGIC_PROPERTY] device_log_xmlns = 'http://code.javarosa.org/devicereport'
def Merge_Sort(list): n= len(list) if n > 1 : mid = int(n/2) left =list[0:mid] right = list[mid:n] Merge_Sort(left) Merge_Sort(right) Merge (left, right, list) return list def Merge(left, right, list): i = 0 j = 0 k = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: list[k] = left[i] i = i + 1 else : list[k] = right[j] j = j + 1 k = k + 1 while i < len(left): list[k] = left[i] i += 1 k += 1 while j < len(right): list[k] = right[j] j += 1 k += 1 if __name__=="__main__": list1=[8,4,23,42,16,15] print(Merge_Sort(list1)) list_2=[20,18,12,8,5,-2] #Reverse-sorted print(Merge_Sort(list_2)) #[-2, 5, 8, 12, 18, 20] list_3=[5,12,7,5,5,7] #Few uniques print(Merge_Sort(list_3)) #[5, 5, 5, 7, 7, 12] list_4=[2,3,5,7,13,11] #Nearly-sorted print(Merge_Sort(list_4)) #[2, 3, 5, 7, 11, 13]
def merge__sort(list): n = len(list) if n > 1: mid = int(n / 2) left = list[0:mid] right = list[mid:n] merge__sort(left) merge__sort(right) merge(left, right, list) return list def merge(left, right, list): i = 0 j = 0 k = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: list[k] = left[i] i = i + 1 else: list[k] = right[j] j = j + 1 k = k + 1 while i < len(left): list[k] = left[i] i += 1 k += 1 while j < len(right): list[k] = right[j] j += 1 k += 1 if __name__ == '__main__': list1 = [8, 4, 23, 42, 16, 15] print(merge__sort(list1)) list_2 = [20, 18, 12, 8, 5, -2] print(merge__sort(list_2)) list_3 = [5, 12, 7, 5, 5, 7] print(merge__sort(list_3)) list_4 = [2, 3, 5, 7, 13, 11] print(merge__sort(list_4))
#!python def merge(items1, items2): """Merge given lists of items, each assumed to already be in sorted order, and return a new list containing all items in sorted order. TODO: Running time: ??? Why and under what conditions? TODO: Memory usage: ??? Why and under what conditions?""" merge_list = [] index_items1 = 0 index_items2 = 0 # comparing both lists and adding the element to the merge_list or/and to know the point where both list are in order correctly, this loop stops when you have completely traverse one of the arrays to merge while index_items1 < len(items1) and index_items2 < len(items2): # compare the two sorted arrays, items1 and items2 if items1[index_items1] < items2[index_items2]: # element in items1 is smaller than items 2 so append to merge_list merge_list.append(items1[index_items1]) index_items1 += 1 else: # element in items1 is greater than items 2 so append element of items2 to list merge_list.append(items2[index_items2]) index_items2 += 1 # add whatever is left because in our while loop we stop the moment either the index left or index right is > len(items) merge_list += items1[index_items1:] merge_list += items2[index_items2:] return merge_list def merge_sort(items): """Sort given items by splitting list into two approximately equal halves, sorting each recursively, and merging results into a list in sorted order. Running time: O(nlogn) because breaking the list down every recursive call; divide and conquer Memory usage: O(n) because calling function resursively so just grows linearly with input""" if items == []: return items # base case in recursive call if len(items) == 1: return items else: # not necessary cause then return is run the function stops but helpful to understand mid = len(items) // 2 left = items[0:mid] right = items[mid:] # return merge(merge_sort(left), merge_sort(right)) # items[:] = this so it's manipulating the items array instead of returning a new array items[:] = merge(merge_sort(left), merge_sort(right)) return items[:] def partition(items, low, high): """Return index `p` after in-place partitioning given items in range `[low...high]` by choosing a pivot (TODO: document your method here) from that range, moving pivot into index `p`, items less than pivot into range `[low...p-1]`, and items greater than pivot into range `[p+1...high]`. TODO: Running time: ??? Why and under what conditions? TODO: Memory usage: ??? Why and under what conditions?""" # TODO: Choose a pivot any way and document your method in docstring above # TODO: Loop through all items in range [low...high] # TODO: Move items less than pivot into front of range [low...p-1] # TODO: Move items greater than pivot into back of range [p+1...high] # TODO: Move pivot item into final position [p] and return index p pass def quick_sort(arr, low=None, high=None): """Sort given items in place by partitioning items in range `[low...high]` around a pivot item and recursively sorting each remaining sublist range. Best case running time: O(nlogn) because your unsort list gets smaller and smaller with each recursive call Worst case running time: O(n^2) when you pick all high numbers then you need to traverse entire length of array and made only progress sorting on that highest number. Memory usage: O(n) because calling function recursively""" # base case in recursive call <=1 because last element is the pivot and poping it if len(arr) <= 1: return arr else: # not necessary cause when return is run the function stops but helpful to understand # pops and sets first item as pivot _value until len(arr) is 1 or less pivot_value = arr.pop(0) # 2 lists for items that are greater or less than pivot items_greater_pivot = [] items_lower_pivot = [] # loop through array to see if element is less or greater than pivot_value and add to proper list for num in arr: if num > pivot_value: items_greater_pivot.append(num) else: items_lower_pivot.append(num) # arr[:] = just so to get to pass sorting_test.py by mutating original array # recursively calls items_lower_pivot and items_greater_pivot to add to final sorted array. # each call will have quick_sort(items_lower_pivot) + pivot_value and pivot_value + quick_sort(items_greater_pivot) arr[:] = quick_sort(items_lower_pivot) + [pivot_value] + quick_sort(items_greater_pivot) return arr[:]
def merge(items1, items2): """Merge given lists of items, each assumed to already be in sorted order, and return a new list containing all items in sorted order. TODO: Running time: ??? Why and under what conditions? TODO: Memory usage: ??? Why and under what conditions?""" merge_list = [] index_items1 = 0 index_items2 = 0 while index_items1 < len(items1) and index_items2 < len(items2): if items1[index_items1] < items2[index_items2]: merge_list.append(items1[index_items1]) index_items1 += 1 else: merge_list.append(items2[index_items2]) index_items2 += 1 merge_list += items1[index_items1:] merge_list += items2[index_items2:] return merge_list def merge_sort(items): """Sort given items by splitting list into two approximately equal halves, sorting each recursively, and merging results into a list in sorted order. Running time: O(nlogn) because breaking the list down every recursive call; divide and conquer Memory usage: O(n) because calling function resursively so just grows linearly with input""" if items == []: return items if len(items) == 1: return items else: mid = len(items) // 2 left = items[0:mid] right = items[mid:] items[:] = merge(merge_sort(left), merge_sort(right)) return items[:] def partition(items, low, high): """Return index `p` after in-place partitioning given items in range `[low...high]` by choosing a pivot (TODO: document your method here) from that range, moving pivot into index `p`, items less than pivot into range `[low...p-1]`, and items greater than pivot into range `[p+1...high]`. TODO: Running time: ??? Why and under what conditions? TODO: Memory usage: ??? Why and under what conditions?""" pass def quick_sort(arr, low=None, high=None): """Sort given items in place by partitioning items in range `[low...high]` around a pivot item and recursively sorting each remaining sublist range. Best case running time: O(nlogn) because your unsort list gets smaller and smaller with each recursive call Worst case running time: O(n^2) when you pick all high numbers then you need to traverse entire length of array and made only progress sorting on that highest number. Memory usage: O(n) because calling function recursively""" if len(arr) <= 1: return arr else: pivot_value = arr.pop(0) items_greater_pivot = [] items_lower_pivot = [] for num in arr: if num > pivot_value: items_greater_pivot.append(num) else: items_lower_pivot.append(num) arr[:] = quick_sort(items_lower_pivot) + [pivot_value] + quick_sort(items_greater_pivot) return arr[:]
def default_copts(ignored = []): opts = [ "-std=c++20", "-Wall", "-Werror", "-Wextra", "-Wno-ignored-qualifiers", "-Wvla", ] ignored_map = {opt: opt for opt in ignored} return [opt for opt in opts if ignored_map.get(opt) == None]
def default_copts(ignored=[]): opts = ['-std=c++20', '-Wall', '-Werror', '-Wextra', '-Wno-ignored-qualifiers', '-Wvla'] ignored_map = {opt: opt for opt in ignored} return [opt for opt in opts if ignored_map.get(opt) == None]
{ "targets": [ { "target_name": "usb", "conditions": [ [ "OS==\"win\"", { "sources": [ "third_party/usb/src/win.cc" ], "libraries": [ "-lhid" ] } ], [ "OS==\"linux\"", { "sources": [ "third_party/usb/src/linux.cc" ], "libraries": [ "-ludev" ] } ], [ "OS==\"mac\"", { "sources": [ "third_party/usb/src/mac.cc" ], "LDFLAGS": [ "-framework IOKit", "-framework CoreFoundation", "-framework AppKit" ], "xcode_settings": { "OTHER_LDFLAGS": [ "-framework IOKit", "-framework CoreFoundation", "-framework AppKit" ], } } ] ] }, { "target_name": "sign", "conditions": [ [ "OS==\"win\"", { "sources": [ "third_party/sign/src/win.cc" ], "libraries": [ "-lcrypt32" ] } ], [ "OS==\"linux\"", { "sources": [ "third_party/sign/src/linux.cc" ] } ], [ "OS==\"mac\"", { "sources": [ "third_party/sign/src/mac.cc" ], "LDFLAGS": [ "-framework CoreFoundation", "-framework AppKit" ], "xcode_settings": { "OTHER_LDFLAGS": [ "-framework CoreFoundation", "-framework AppKit" ], } } ] ] }, { "target_name": "pcsc", "sources": [ "third_party/pcsc/src/pcsc.cc", "third_party/pcsc/src/service.cc", "third_party/pcsc/src/card.cc", "third_party/pcsc/src/device.cc" ], "include_dirs": [ "third_party/pcsc/src" ], "conditions": [ [ "OS==\"win\"", { "libraries": [ "-lwinscard" ] } ], [ "OS==\"mac\"", { "LDFLAGS": [ "-framework PCSC" ], "xcode_settings": { "OTHER_LDFLAGS": [ "-framework PCSC" ] } } ], [ "OS==\"linux\"", { "include_dirs": [ "/usr/include/PCSC" ], "cflags": [ "-pthread", "-Wno-cast-function-type" ], "libraries": [ "-lpcsclite" ] } ] ] } ] }
{'targets': [{'target_name': 'usb', 'conditions': [['OS=="win"', {'sources': ['third_party/usb/src/win.cc'], 'libraries': ['-lhid']}], ['OS=="linux"', {'sources': ['third_party/usb/src/linux.cc'], 'libraries': ['-ludev']}], ['OS=="mac"', {'sources': ['third_party/usb/src/mac.cc'], 'LDFLAGS': ['-framework IOKit', '-framework CoreFoundation', '-framework AppKit'], 'xcode_settings': {'OTHER_LDFLAGS': ['-framework IOKit', '-framework CoreFoundation', '-framework AppKit']}}]]}, {'target_name': 'sign', 'conditions': [['OS=="win"', {'sources': ['third_party/sign/src/win.cc'], 'libraries': ['-lcrypt32']}], ['OS=="linux"', {'sources': ['third_party/sign/src/linux.cc']}], ['OS=="mac"', {'sources': ['third_party/sign/src/mac.cc'], 'LDFLAGS': ['-framework CoreFoundation', '-framework AppKit'], 'xcode_settings': {'OTHER_LDFLAGS': ['-framework CoreFoundation', '-framework AppKit']}}]]}, {'target_name': 'pcsc', 'sources': ['third_party/pcsc/src/pcsc.cc', 'third_party/pcsc/src/service.cc', 'third_party/pcsc/src/card.cc', 'third_party/pcsc/src/device.cc'], 'include_dirs': ['third_party/pcsc/src'], 'conditions': [['OS=="win"', {'libraries': ['-lwinscard']}], ['OS=="mac"', {'LDFLAGS': ['-framework PCSC'], 'xcode_settings': {'OTHER_LDFLAGS': ['-framework PCSC']}}], ['OS=="linux"', {'include_dirs': ['/usr/include/PCSC'], 'cflags': ['-pthread', '-Wno-cast-function-type'], 'libraries': ['-lpcsclite']}]]}]}
# Challenge 4 : Create a function named movie_review() that has one parameter named rating. # If rating is less than or equal to 5, return "Avoid at all costs!". # If rating is between 5 and 9, return "This one was fun.". # If rating is 9 or above, return "Outstanding!" # Date : Thu 28 May 2020 07:31:11 AM IST def movie_review(rating): if rating <= 5: return "Avoid at all costs!" elif (rating >= 5) and (rating <= 9): return "This one was fun." elif rating >= 9: return "Outstanding!" print(movie_review(9)) print(movie_review(4)) print(movie_review(6))
def movie_review(rating): if rating <= 5: return 'Avoid at all costs!' elif rating >= 5 and rating <= 9: return 'This one was fun.' elif rating >= 9: return 'Outstanding!' print(movie_review(9)) print(movie_review(4)) print(movie_review(6))
colors = {"clean": "\033[m", "red": "\033[31m", "green": "\033[32m", "yellow": "\033[33m", "blue": "\033[34m", "purple": "\033[35m", "cian": "\033[36m"} msg = "Hello World!!!" print("{}{}".format(colors["cian"], msg))
colors = {'clean': '\x1b[m', 'red': '\x1b[31m', 'green': '\x1b[32m', 'yellow': '\x1b[33m', 'blue': '\x1b[34m', 'purple': '\x1b[35m', 'cian': '\x1b[36m'} msg = 'Hello World!!!' print('{}{}'.format(colors['cian'], msg))
def difference(a, b): c = [] for el in a: if el not in b: c.append(el) return c ll = [1, 2, 3, 4, 5] ll2 = [4, 5, 6, 7, 8] # print(difference(ll, ll2)) # = CTRL + / set1 = {1, 2, 3, 4, 5} set2 = {4, 5, 6, 7, 8} set_difference = set1.difference(set2) # print(set_difference) # print(difference(ll, ll2) == list(set_difference))
def difference(a, b): c = [] for el in a: if el not in b: c.append(el) return c ll = [1, 2, 3, 4, 5] ll2 = [4, 5, 6, 7, 8] set1 = {1, 2, 3, 4, 5} set2 = {4, 5, 6, 7, 8} set_difference = set1.difference(set2)
# -- # File: a1000_consts.py # # Copyright (c) ReversingLabs Inc 2016-2018 # # This unpublished material is proprietary to ReversingLabs Inc. # All rights reserved. # Reproduction or distribution, in whole # or in part, is forbidden except by express written permission # of ReversingLabs Inc. # # -- A1000_JSON_BASE_URL = "base_url" A1000_JSON_TASK_ID = "task_id" A1000_JSON_API_KEY = "api_key" A1000_JSON_MALWARE = "malware" A1000_JSON_TASK_ID = "id" A1000_JSON_VAULT_ID = "vault_id" A1000_JSON_URL = "url" A1000_JSON_HASH = "hash" A1000_JSON_PLATFORM = "platform" A1000_JSON_POLL_TIMEOUT_MINS = "timeout" A1000_ERR_UNABLE_TO_PARSE_REPLY = "Unable to parse reply from device" A1000_ERR_REPLY_FORMAT_KEY_MISSING = "None '{key}' missing in reply from device" A1000_ERR_REPLY_NOT_SUCCESS = "REST call returned '{status}'" A1000_SUCC_REST_CALL_SUCCEEDED = "REST Api call succeeded" A1000_ERR_REST_API = "REST Api Call returned error, status_code: {status_code}, detail: {detail}" A1000_TEST_PDF_FILE = "a1000_test_connectivity.pdf" A1000_SLEEP_SECS = 3 A1000_MSG_REPORT_PENDING = "Report Not Found" A1000_MSG_MAX_POLLS_REACHED = "Reached max polling attempts. Please use the MD5 or Sha256 of the file as a parameter to <b>get report</b> to query the report status." A1000_PARAM_LIST = { "fields": [ "file_type", "file_subtype", "file_size", "extracted_file_count", "local_first_seen", "local_last_seen", "classification_origin", "classification_reason", "threat_status", "trust_factor", "threat_level", "threat_name", "summary"] } # in minutes A1000_MAX_TIMEOUT_DEF = 10
a1000_json_base_url = 'base_url' a1000_json_task_id = 'task_id' a1000_json_api_key = 'api_key' a1000_json_malware = 'malware' a1000_json_task_id = 'id' a1000_json_vault_id = 'vault_id' a1000_json_url = 'url' a1000_json_hash = 'hash' a1000_json_platform = 'platform' a1000_json_poll_timeout_mins = 'timeout' a1000_err_unable_to_parse_reply = 'Unable to parse reply from device' a1000_err_reply_format_key_missing = "None '{key}' missing in reply from device" a1000_err_reply_not_success = "REST call returned '{status}'" a1000_succ_rest_call_succeeded = 'REST Api call succeeded' a1000_err_rest_api = 'REST Api Call returned error, status_code: {status_code}, detail: {detail}' a1000_test_pdf_file = 'a1000_test_connectivity.pdf' a1000_sleep_secs = 3 a1000_msg_report_pending = 'Report Not Found' a1000_msg_max_polls_reached = 'Reached max polling attempts. Please use the MD5 or Sha256 of the file as a parameter to <b>get report</b> to query the report status.' a1000_param_list = {'fields': ['file_type', 'file_subtype', 'file_size', 'extracted_file_count', 'local_first_seen', 'local_last_seen', 'classification_origin', 'classification_reason', 'threat_status', 'trust_factor', 'threat_level', 'threat_name', 'summary']} a1000_max_timeout_def = 10
# Provided by Dr. Marzieh Ahmadzadeh & Nick Cheng. Edited by Yufei Cui class DNode(object): '''represents a node as a building block of a double linked list''' def __init__(self, element, prev_node=None, next_node=None): '''(Node, obj, Node, Node) -> NoneType construct a Dnode as building block of a double linked list''' # Representation invariant: # element is an object, that is hold this node # _prev is a DNode # _next is a DNode # _prev is the node immediately before this node (i.e. self) # _next is the node immediately after this node (i.e. self) self._element = element self._next = next_node self._prev = prev_node def set_next(self, next_node): '''(Node, Node) -> NoneType set node to point to next_node''' self._next = next_node def set_prev(self, prev_node): '''(Node, Node) -> NoneType set node to point to prev_node''' self._prev = prev_node def set_element(self, element): '''(Node, obj) ->NoneType set the _element to a new value''' self._element = element def get_next(self): '''(Node) -> Node returns the reference to next node''' return self._next def get_prev(self): '''(Node) -> Node returns the reference to previous node''' return self._prev def get_element(self): '''(Node) -> obj returns the element of this node''' return self._element def __str__(self): '''(Node) -> str returns the element of this node and the reference to next node''' return "(" + str(hex(id(self._prev))) + ", " + str(self._element) + ", " + str(hex(id(self._next))) + ")" class DoubleLinkedList(object): ''' represents a double linked list''' def __init__(self): '''(DoubleLinkedList) ->NoneType initializes the references of an empty DLL''' # set the size self._size = 0 # head and tails are a dummy node self._head = DNode(None, None, None) self._tail = DNode(None, None, None) # head points to tail and tail to head self._head.set_next(self._tail) self._tail.set_prev(self._head) def is_empty(self): '''(DoubleLinkedList) -> bool returns true if no item is in this DLL''' return self._size == 0 def size(self): '''(DoubleLinkedList) -> int returns the number of items in this DLL''' return self._size def add_first(self, element): '''(DoubleLinkedList, obj) -> NoneType adds a node to the front of the DLL, after the head''' # create a node that head points to. Also the node points to the node after the head node = DNode(element, self._head, self._head.get_next()) # have the node after head to point to this node (_prev) self._head.get_next().set_prev(node) # have the head to point to this new node self._head.set_next(node) # increment the size self._size += 1 def add_last(self, element): '''(DoubleLinkedList, obj) -> NoneType adds a node to the end of this DLL''' # create a DNode with the given element that points to tail from right and to the node before the tail from left node = DNode(element, self._tail.get_prev(), self._tail) # let the node to the left of the tail to point to this new node self._tail.get_prev().set_next(node) # let the _prev part of the tail to point to newly created node self._tail.set_prev(node) # increment the size self._size += 1 def remove_first(self): '''(DoubleLinkedList, obj) -> obj remove the node from the head of this DLL and returns the element stored in this node''' # set element to None in case DLL was empty element = None # if DLL is not empty if not self.is_empty(): # get the first node to the right of the head node = self._head.get_next() # have head point to the second node after the head self._head.set_next(node.get_next()) # have the second node after the head to point to head from left node.get_next().set_prev(self._head) # decrement the size self._size -= 1 # set the _next & _prev of the removed node to point to None (for garbage collection purpose) node.set_next(None) node.set_prev(None) # get the element stored in the node element = node.get_element() # return the element of the removed node return element def remove_last(self): '''(DoubleLinkedList, obj) -> obj remove the node from the tail of this DLL and returns the element stored in this node''' # set element to None in case DLL was empty element = None # if DLL is not empty if not self.is_empty(): # get the first node to the left of the tail node = self._tail.get_prev() # have tail point to the second node before the tail self._tail.set_prev(node.get_prev()) # have the second node before the tail to point to tail from right node.get_prev().set_next(self._tail) # decrement the size self._size -= 1 # set the _next, _prev of removed node to point to None (for garbage collection purpose) node.set_next(None) node.set_prev(None) # get the element stored in the node element = node.get_element() # return the element of the removed node return element def __str__(self): '''(DoubleLinkedList) -> str returns the items in the DLL in a string form ''' # define a node, which points to the first node after the head cur = self._head.get_next() # define an empty string to be used as a container for the items in the SLL result = "" # loop over the DLL until you get to the end of the DLL while cur is not self._tail: # get the element of the current node and attach it to the final result result = result + str(cur.get_element()) + ", " # proceed to next node cur = cur.get_next() # enclose the result in a parentheses result = "(" + result[:-2] + ")" # return the result return result if __name__ == "__main__": node_1 = DNode("A") node_2 = DNode("B", node_1) node_3 = DNode("C", node_1, node_2) print(node_1) print(node_2) print(node_3) print(str(hex(id(node_1)))) print(str(hex(id(node_2)))) dll = DoubleLinkedList() print(dll) dll.add_first("A") dll.add_first("B") dll.add_last("C") dll.add_last("D") print(dll) print(dll.remove_last()) print(dll.remove_last()) print(dll.remove_last()) print(dll.remove_last()) print(dll)
class Dnode(object): """represents a node as a building block of a double linked list""" def __init__(self, element, prev_node=None, next_node=None): """(Node, obj, Node, Node) -> NoneType construct a Dnode as building block of a double linked list""" self._element = element self._next = next_node self._prev = prev_node def set_next(self, next_node): """(Node, Node) -> NoneType set node to point to next_node""" self._next = next_node def set_prev(self, prev_node): """(Node, Node) -> NoneType set node to point to prev_node""" self._prev = prev_node def set_element(self, element): """(Node, obj) ->NoneType set the _element to a new value""" self._element = element def get_next(self): """(Node) -> Node returns the reference to next node""" return self._next def get_prev(self): """(Node) -> Node returns the reference to previous node""" return self._prev def get_element(self): """(Node) -> obj returns the element of this node""" return self._element def __str__(self): """(Node) -> str returns the element of this node and the reference to next node""" return '(' + str(hex(id(self._prev))) + ', ' + str(self._element) + ', ' + str(hex(id(self._next))) + ')' class Doublelinkedlist(object): """ represents a double linked list""" def __init__(self): """(DoubleLinkedList) ->NoneType initializes the references of an empty DLL""" self._size = 0 self._head = d_node(None, None, None) self._tail = d_node(None, None, None) self._head.set_next(self._tail) self._tail.set_prev(self._head) def is_empty(self): """(DoubleLinkedList) -> bool returns true if no item is in this DLL""" return self._size == 0 def size(self): """(DoubleLinkedList) -> int returns the number of items in this DLL""" return self._size def add_first(self, element): """(DoubleLinkedList, obj) -> NoneType adds a node to the front of the DLL, after the head""" node = d_node(element, self._head, self._head.get_next()) self._head.get_next().set_prev(node) self._head.set_next(node) self._size += 1 def add_last(self, element): """(DoubleLinkedList, obj) -> NoneType adds a node to the end of this DLL""" node = d_node(element, self._tail.get_prev(), self._tail) self._tail.get_prev().set_next(node) self._tail.set_prev(node) self._size += 1 def remove_first(self): """(DoubleLinkedList, obj) -> obj remove the node from the head of this DLL and returns the element stored in this node""" element = None if not self.is_empty(): node = self._head.get_next() self._head.set_next(node.get_next()) node.get_next().set_prev(self._head) self._size -= 1 node.set_next(None) node.set_prev(None) element = node.get_element() return element def remove_last(self): """(DoubleLinkedList, obj) -> obj remove the node from the tail of this DLL and returns the element stored in this node""" element = None if not self.is_empty(): node = self._tail.get_prev() self._tail.set_prev(node.get_prev()) node.get_prev().set_next(self._tail) self._size -= 1 node.set_next(None) node.set_prev(None) element = node.get_element() return element def __str__(self): """(DoubleLinkedList) -> str returns the items in the DLL in a string form """ cur = self._head.get_next() result = '' while cur is not self._tail: result = result + str(cur.get_element()) + ', ' cur = cur.get_next() result = '(' + result[:-2] + ')' return result if __name__ == '__main__': node_1 = d_node('A') node_2 = d_node('B', node_1) node_3 = d_node('C', node_1, node_2) print(node_1) print(node_2) print(node_3) print(str(hex(id(node_1)))) print(str(hex(id(node_2)))) dll = double_linked_list() print(dll) dll.add_first('A') dll.add_first('B') dll.add_last('C') dll.add_last('D') print(dll) print(dll.remove_last()) print(dll.remove_last()) print(dll.remove_last()) print(dll.remove_last()) print(dll)
a = 256 b = 256 print(a is b) """ output:True """ c = 257 d = 257 print(id(c),id(d))
a = 256 b = 256 print(a is b) '\noutput:True\n' c = 257 d = 257 print(id(c), id(d))
class ProductLabels(object): def __init__(self, labels, labels_tags, labels_fr): self.Labels = labels self.LabelsTags = labels_tags self.LabelsFr = labels_fr def __str__(self): return self .Labels
class Productlabels(object): def __init__(self, labels, labels_tags, labels_fr): self.Labels = labels self.LabelsTags = labels_tags self.LabelsFr = labels_fr def __str__(self): return self.Labels
def dds_insert(d, s, p, o): if d.get(s) is None: d[s] = {} if d[s].get(p) is None: d[s][p] = set() d[s][p].add(o) def dds_remove(d, s, p, o): if d.get(s) is not None and d[s].get(p) is not None: d[s][p].remove(o) if not d[s][p]: del d[s][p] if not d[s]: del d[s] class JsonLDIndex: def __init__(self, spo=None, pos=None): self.spo = {} if spo is None else spo self.pos = {} if pos is None else pos # def insert_triples(self, triples): for subj, pred, obj in triples: dds_insert(self.spo, subj, pred, obj) # dds_insert(self.spo, obj, '~'+pred, subj) dds_insert(self.pos, pred, obj, subj) dds_insert(self.pos, '~'+pred, subj, obj) # return self # def remove_triples(self, triples): for subj, pred, obj in triples: dds_remove(self.spo, subj, pred, obj) # dds_remove(self.spo, obj, '~'+pred, subj) dds_remove(self.pos, pred, obj, subj) dds_remove(self.pos, '~'+pred, subj, obj) # return self
def dds_insert(d, s, p, o): if d.get(s) is None: d[s] = {} if d[s].get(p) is None: d[s][p] = set() d[s][p].add(o) def dds_remove(d, s, p, o): if d.get(s) is not None and d[s].get(p) is not None: d[s][p].remove(o) if not d[s][p]: del d[s][p] if not d[s]: del d[s] class Jsonldindex: def __init__(self, spo=None, pos=None): self.spo = {} if spo is None else spo self.pos = {} if pos is None else pos def insert_triples(self, triples): for (subj, pred, obj) in triples: dds_insert(self.spo, subj, pred, obj) dds_insert(self.pos, pred, obj, subj) dds_insert(self.pos, '~' + pred, subj, obj) return self def remove_triples(self, triples): for (subj, pred, obj) in triples: dds_remove(self.spo, subj, pred, obj) dds_remove(self.pos, pred, obj, subj) dds_remove(self.pos, '~' + pred, subj, obj) return self
# BGR colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) GRAY25 = (64, 64, 64) GRAY50 = (128, 128, 128) GRAY75 = (192, 192, 192) GRAY33 = (85, 85, 85) GRAY66 = (170, 170, 170) BLUE = (255, 0, 0) GREEN = (0, 255, 0) RED = (0, 0, 255) CYAN = (255, 255, 0) MAGENTA = (255, 0, 255) YELLOW = (0, 255, 255) ORANGE = (0, 128, 255) PURPLE = (255, 0, 128) MINT = (128, 255, 0) LIME = (0, 255, 128) PINK = (128, 0, 255)
white = (255, 255, 255) black = (0, 0, 0) gray25 = (64, 64, 64) gray50 = (128, 128, 128) gray75 = (192, 192, 192) gray33 = (85, 85, 85) gray66 = (170, 170, 170) blue = (255, 0, 0) green = (0, 255, 0) red = (0, 0, 255) cyan = (255, 255, 0) magenta = (255, 0, 255) yellow = (0, 255, 255) orange = (0, 128, 255) purple = (255, 0, 128) mint = (128, 255, 0) lime = (0, 255, 128) pink = (128, 0, 255)
class Node(object): value = None left_child = None right_child = None def __init__(self, value, left=None, right=None): self.value = value if left: self.left_child = left if right: self.right_child = right def __str__(self): return self.value def has_left(self): return True if self.left_child else False def has_right(self): return True if self.right_child else False class BinaryTree(object): root: Node = None def __init__(self, node: Node = None): if not self.root and node: self.root = node def __add__(self, node: Node, parent: Node = None): if not self.root: self.__init__(node=node) else: if parent: if parent.value >= node.value: if parent.has_right(): self.__add__(node=node, parent=parent.right_child) else: parent.right_child = node else: if parent.has_left(): self.__add__(node=node, parent=parent.left_child) else: parent.left_child = node else: self.__add__(node=node, parent=self.root) def search_back(self, number, node: Node, level_count): if number == node.value: return level_count, True else: if number < node.value: if node.has_left(): self.search_back(number=number, node=node.left_child, level_count=level_count + 1) else: return False else: if node.has_right(): self.search_back(number=number, node=node.right_child, level_count=level_count + 1) else: return False def search(self, number): return self.search_back(number=number, node=self.root, level_count=0) def print_level(self, level_count, node: Node, result: list): if not node: return else: if level_count == 0: result.append(node) self.print_level(level_count=level_count - 1, node=node.left_child, result=result) self.print_level(level_count=level_count - 1, node=node.right_child, result=result) def print_tree(self, result: list, node: Node): result.append(node) if node.has_left(): self.print_tree(result=result, node=node.left_child) elif node.has_right(): self.print_tree(result=result, node=node.right_child) def height(self, node: Node): if not node: return 0 else: if node.has_left(): l_height = self.height(node=node.left_child) else: l_height = -1 if node.has_right(): r_height = self.height(node=node.right_child) else: r_height = -1 max_height = l_height if l_height > r_height else r_height return max_height + 1 def to_array_values(self, result: list, node: Node): result.append(node.value) if node.has_left(): self.to_array_values(result=result, node=node.left_child) elif node.has_right(): self.to_array_values(result=result, node=node.right_child) def to_array_nodes(self, result: list, node: Node): result.append(node) if node.has_left(): self.to_array_values(result=result, node=node.left_child) elif node.has_right(): self.to_array_values(result=result, node=node.right_child) def join_trees(bst_1: BinaryTree, bst_2: BinaryTree): tree_array_1 = [] tree_array_2 = [] bst_1.to_array_values(tree_array_1, bst_1.root) bst_2.to_array_values(tree_array_2, bst_2.root) result_array = [*tree_array_1, *tree_array_2] bst_result = BinaryTree() for item in result_array: node = Node(item) bst_result.__add__(node=node) return bst_result
class Node(object): value = None left_child = None right_child = None def __init__(self, value, left=None, right=None): self.value = value if left: self.left_child = left if right: self.right_child = right def __str__(self): return self.value def has_left(self): return True if self.left_child else False def has_right(self): return True if self.right_child else False class Binarytree(object): root: Node = None def __init__(self, node: Node=None): if not self.root and node: self.root = node def __add__(self, node: Node, parent: Node=None): if not self.root: self.__init__(node=node) elif parent: if parent.value >= node.value: if parent.has_right(): self.__add__(node=node, parent=parent.right_child) else: parent.right_child = node elif parent.has_left(): self.__add__(node=node, parent=parent.left_child) else: parent.left_child = node else: self.__add__(node=node, parent=self.root) def search_back(self, number, node: Node, level_count): if number == node.value: return (level_count, True) elif number < node.value: if node.has_left(): self.search_back(number=number, node=node.left_child, level_count=level_count + 1) else: return False elif node.has_right(): self.search_back(number=number, node=node.right_child, level_count=level_count + 1) else: return False def search(self, number): return self.search_back(number=number, node=self.root, level_count=0) def print_level(self, level_count, node: Node, result: list): if not node: return else: if level_count == 0: result.append(node) self.print_level(level_count=level_count - 1, node=node.left_child, result=result) self.print_level(level_count=level_count - 1, node=node.right_child, result=result) def print_tree(self, result: list, node: Node): result.append(node) if node.has_left(): self.print_tree(result=result, node=node.left_child) elif node.has_right(): self.print_tree(result=result, node=node.right_child) def height(self, node: Node): if not node: return 0 else: if node.has_left(): l_height = self.height(node=node.left_child) else: l_height = -1 if node.has_right(): r_height = self.height(node=node.right_child) else: r_height = -1 max_height = l_height if l_height > r_height else r_height return max_height + 1 def to_array_values(self, result: list, node: Node): result.append(node.value) if node.has_left(): self.to_array_values(result=result, node=node.left_child) elif node.has_right(): self.to_array_values(result=result, node=node.right_child) def to_array_nodes(self, result: list, node: Node): result.append(node) if node.has_left(): self.to_array_values(result=result, node=node.left_child) elif node.has_right(): self.to_array_values(result=result, node=node.right_child) def join_trees(bst_1: BinaryTree, bst_2: BinaryTree): tree_array_1 = [] tree_array_2 = [] bst_1.to_array_values(tree_array_1, bst_1.root) bst_2.to_array_values(tree_array_2, bst_2.root) result_array = [*tree_array_1, *tree_array_2] bst_result = binary_tree() for item in result_array: node = node(item) bst_result.__add__(node=node) return bst_result
# START LAB EXERCISE 04 print('Lab Exercise 04 \n') # SETUP city_state = ["Detroit|MI", "Philadelphia|PA", "Hollywood|CA", "Oakland|CA", "Boston|MA", "Atlanta|GA", "Phoenix|AZ", "Birmingham|AL", "Houston|TX", "Tampa|FL"] # END SETUP # PROBLEM 1.0 (5 Points) # PROBLEM 2.0 (5 Points) # PROBLEM 3.0 (10 Points) # END LAB EXERCISE
print('Lab Exercise 04 \n') city_state = ['Detroit|MI', 'Philadelphia|PA', 'Hollywood|CA', 'Oakland|CA', 'Boston|MA', 'Atlanta|GA', 'Phoenix|AZ', 'Birmingham|AL', 'Houston|TX', 'Tampa|FL']
# -*- coding: utf-8 -*- string1 = "Becomes" string2 = "becomes" string3 = "BEAR" string4 = " bEautiful" string1 = string1.lower() # (string2 will pass unmodified) string3 = string3.lower() string4 = string4.strip().lower() print(string1.startswith("be")) print(string2.startswith("be")) print(string3.startswith("be")) print(string4.startswith("be"))
string1 = 'Becomes' string2 = 'becomes' string3 = 'BEAR' string4 = ' bEautiful' string1 = string1.lower() string3 = string3.lower() string4 = string4.strip().lower() print(string1.startswith('be')) print(string2.startswith('be')) print(string3.startswith('be')) print(string4.startswith('be'))
class Node(object): def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right class BinarySearchTree(object): def __init__(self, root=None): self.root = root def get_root(self): return self.root def insert(self, item): if self.root is None: self.root = Node(item) else: cur_node = self.root while cur_node is not None: if item < cur_node.data: if cur_node.left is None: cur_node = Node(item) return else: cur_node = cur_node.left else: if cur_node.right is None: cur_node = Node(item) return else: cur_node = cur_node.right
class Node(object): def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right class Binarysearchtree(object): def __init__(self, root=None): self.root = root def get_root(self): return self.root def insert(self, item): if self.root is None: self.root = node(item) else: cur_node = self.root while cur_node is not None: if item < cur_node.data: if cur_node.left is None: cur_node = node(item) return else: cur_node = cur_node.left elif cur_node.right is None: cur_node = node(item) return else: cur_node = cur_node.right
input = """af AND ah -> ai NOT lk -> ll hz RSHIFT 1 -> is NOT go -> gp du OR dt -> dv x RSHIFT 5 -> aa at OR az -> ba eo LSHIFT 15 -> es ci OR ct -> cu b RSHIFT 5 -> f fm OR fn -> fo NOT ag -> ah v OR w -> x g AND i -> j an LSHIFT 15 -> ar 1 AND cx -> cy jq AND jw -> jy iu RSHIFT 5 -> ix gl AND gm -> go NOT bw -> bx jp RSHIFT 3 -> jr hg AND hh -> hj bv AND bx -> by er OR es -> et kl OR kr -> ks et RSHIFT 1 -> fm e AND f -> h u LSHIFT 1 -> ao he RSHIFT 1 -> hx eg AND ei -> ej bo AND bu -> bw dz OR ef -> eg dy RSHIFT 3 -> ea gl OR gm -> gn da LSHIFT 1 -> du au OR av -> aw gj OR gu -> gv eu OR fa -> fb lg OR lm -> ln e OR f -> g NOT dm -> dn NOT l -> m aq OR ar -> as gj RSHIFT 5 -> gm hm AND ho -> hp ge LSHIFT 15 -> gi jp RSHIFT 1 -> ki hg OR hh -> hi lc LSHIFT 1 -> lw km OR kn -> ko eq LSHIFT 1 -> fk 1 AND am -> an gj RSHIFT 1 -> hc aj AND al -> am gj AND gu -> gw ko AND kq -> kr ha OR gz -> hb bn OR by -> bz iv OR jb -> jc NOT ac -> ad bo OR bu -> bv d AND j -> l bk LSHIFT 1 -> ce de OR dk -> dl dd RSHIFT 1 -> dw hz AND ik -> im NOT jd -> je fo RSHIFT 2 -> fp hb LSHIFT 1 -> hv lf RSHIFT 2 -> lg gj RSHIFT 3 -> gl ki OR kj -> kk NOT ak -> al ld OR le -> lf ci RSHIFT 3 -> ck 1 AND cc -> cd NOT kx -> ky fp OR fv -> fw ev AND ew -> ey dt LSHIFT 15 -> dx NOT ax -> ay bp AND bq -> bs NOT ii -> ij ci AND ct -> cv iq OR ip -> ir x RSHIFT 2 -> y fq OR fr -> fs bn RSHIFT 5 -> bq 0 -> c 14146 -> b d OR j -> k z OR aa -> ab gf OR ge -> gg df OR dg -> dh NOT hj -> hk NOT di -> dj fj LSHIFT 15 -> fn lf RSHIFT 1 -> ly b AND n -> p jq OR jw -> jx gn AND gp -> gq x RSHIFT 1 -> aq ex AND ez -> fa NOT fc -> fd bj OR bi -> bk as RSHIFT 5 -> av hu LSHIFT 15 -> hy NOT gs -> gt fs AND fu -> fv dh AND dj -> dk bz AND cb -> cc dy RSHIFT 1 -> er hc OR hd -> he fo OR fz -> ga t OR s -> u b RSHIFT 2 -> d NOT jy -> jz hz RSHIFT 2 -> ia kk AND kv -> kx ga AND gc -> gd fl LSHIFT 1 -> gf bn AND by -> ca NOT hr -> hs NOT bs -> bt lf RSHIFT 3 -> lh au AND av -> ax 1 AND gd -> ge jr OR js -> jt fw AND fy -> fz NOT iz -> ja c LSHIFT 1 -> t dy RSHIFT 5 -> eb bp OR bq -> br NOT h -> i 1 AND ds -> dt ab AND ad -> ae ap LSHIFT 1 -> bj br AND bt -> bu NOT ca -> cb NOT el -> em s LSHIFT 15 -> w gk OR gq -> gr ff AND fh -> fi kf LSHIFT 15 -> kj fp AND fv -> fx lh OR li -> lj bn RSHIFT 3 -> bp jp OR ka -> kb lw OR lv -> lx iy AND ja -> jb dy OR ej -> ek 1 AND bh -> bi NOT kt -> ku ao OR an -> ap ia AND ig -> ii NOT ey -> ez bn RSHIFT 1 -> cg fk OR fj -> fl ce OR cd -> cf eu AND fa -> fc kg OR kf -> kh jr AND js -> ju iu RSHIFT 3 -> iw df AND dg -> di dl AND dn -> do la LSHIFT 15 -> le fo RSHIFT 1 -> gh NOT gw -> gx NOT gb -> gc ir LSHIFT 1 -> jl x AND ai -> ak he RSHIFT 5 -> hh 1 AND lu -> lv NOT ft -> fu gh OR gi -> gj lf RSHIFT 5 -> li x RSHIFT 3 -> z b RSHIFT 3 -> e he RSHIFT 2 -> hf NOT fx -> fy jt AND jv -> jw hx OR hy -> hz jp AND ka -> kc fb AND fd -> fe hz OR ik -> il ci RSHIFT 1 -> db fo AND fz -> gb fq AND fr -> ft gj RSHIFT 2 -> gk cg OR ch -> ci cd LSHIFT 15 -> ch jm LSHIFT 1 -> kg ih AND ij -> ik fo RSHIFT 3 -> fq fo RSHIFT 5 -> fr 1 AND fi -> fj 1 AND kz -> la iu AND jf -> jh cq AND cs -> ct dv LSHIFT 1 -> ep hf OR hl -> hm km AND kn -> kp de AND dk -> dm dd RSHIFT 5 -> dg NOT lo -> lp NOT ju -> jv NOT fg -> fh cm AND co -> cp ea AND eb -> ed dd RSHIFT 3 -> df gr AND gt -> gu ep OR eo -> eq cj AND cp -> cr lf OR lq -> lr gg LSHIFT 1 -> ha et RSHIFT 2 -> eu NOT jh -> ji ek AND em -> en jk LSHIFT 15 -> jo ia OR ig -> ih gv AND gx -> gy et AND fe -> fg lh AND li -> lk 1 AND io -> ip kb AND kd -> ke kk RSHIFT 5 -> kn id AND if -> ig NOT ls -> lt dw OR dx -> dy dd AND do -> dq lf AND lq -> ls NOT kc -> kd dy AND ej -> el 1 AND ke -> kf et OR fe -> ff hz RSHIFT 5 -> ic dd OR do -> dp cj OR cp -> cq NOT dq -> dr kk RSHIFT 1 -> ld jg AND ji -> jj he OR hp -> hq hi AND hk -> hl dp AND dr -> ds dz AND ef -> eh hz RSHIFT 3 -> ib db OR dc -> dd hw LSHIFT 1 -> iq he AND hp -> hr NOT cr -> cs lg AND lm -> lo hv OR hu -> hw il AND in -> io NOT eh -> ei gz LSHIFT 15 -> hd gk AND gq -> gs 1 AND en -> eo NOT kp -> kq et RSHIFT 5 -> ew lj AND ll -> lm he RSHIFT 3 -> hg et RSHIFT 3 -> ev as AND bd -> bf cu AND cw -> cx jx AND jz -> ka b OR n -> o be AND bg -> bh 1 AND ht -> hu 1 AND gy -> gz NOT hn -> ho ck OR cl -> cm ec AND ee -> ef lv LSHIFT 15 -> lz ks AND ku -> kv NOT ie -> if hf AND hl -> hn 1 AND r -> s ib AND ic -> ie hq AND hs -> ht y AND ae -> ag NOT ed -> ee bi LSHIFT 15 -> bm dy RSHIFT 2 -> dz ci RSHIFT 2 -> cj NOT bf -> bg NOT im -> in ev OR ew -> ex ib OR ic -> id bn RSHIFT 2 -> bo dd RSHIFT 2 -> de bl OR bm -> bn as RSHIFT 1 -> bl ea OR eb -> ec ln AND lp -> lq kk RSHIFT 3 -> km is OR it -> iu iu RSHIFT 2 -> iv as OR bd -> be ip LSHIFT 15 -> it iw OR ix -> iy kk RSHIFT 2 -> kl NOT bb -> bc ci RSHIFT 5 -> cl ly OR lz -> ma z AND aa -> ac iu RSHIFT 1 -> jn cy LSHIFT 15 -> dc cf LSHIFT 1 -> cz as RSHIFT 3 -> au cz OR cy -> da kw AND ky -> kz lx -> a iw AND ix -> iz lr AND lt -> lu jp RSHIFT 5 -> js aw AND ay -> az jc AND je -> jf lb OR la -> lc NOT cn -> co kh LSHIFT 1 -> lb 1 AND jj -> jk y OR ae -> af ck AND cl -> cn kk OR kv -> kw NOT cv -> cw kl AND kr -> kt iu OR jf -> jg at AND az -> bb jp RSHIFT 2 -> jq iv AND jb -> jd jn OR jo -> jp x OR ai -> aj ba AND bc -> bd jl OR jk -> jm b RSHIFT 1 -> v o AND q -> r NOT p -> q k AND m -> n as RSHIFT 2 -> at""" values = {} mapping = {} for line in input.split("\n"): destination = line.split("->")[-1].strip() provider = line.split("->")[0].strip() mapping[destination] = provider # evaluate for a def evaluate(target): if target.isnumeric(): return int(target) if target in values: return values[target] if target not in mapping: print("Unknown target", target) exit(1) target_provider = mapping[target] args = target_provider.split() if len(args) == 1: # Assignment values[target] = evaluate(args[0]) elif len(args) == 2: # NOT values[target] = ~evaluate(args[1]) else: if args[1] == "AND": values[target] = evaluate(args[0]) & evaluate(args[2]) elif args[1] == "OR": values[target] = evaluate(args[0]) | evaluate(args[2]) elif args[1] == "LSHIFT": values[target] = evaluate(args[0]) << evaluate(args[2]) elif args[1] == "RSHIFT": values[target] = evaluate(args[0]) >> evaluate(args[2]) else: print("unknown operator", args[1]) exit(1) if target not in values: print("How did i get here") exit(1) return values[target] print(evaluate("a"))
input = 'af AND ah -> ai\nNOT lk -> ll\nhz RSHIFT 1 -> is\nNOT go -> gp\ndu OR dt -> dv\nx RSHIFT 5 -> aa\nat OR az -> ba\neo LSHIFT 15 -> es\nci OR ct -> cu\nb RSHIFT 5 -> f\nfm OR fn -> fo\nNOT ag -> ah\nv OR w -> x\ng AND i -> j\nan LSHIFT 15 -> ar\n1 AND cx -> cy\njq AND jw -> jy\niu RSHIFT 5 -> ix\ngl AND gm -> go\nNOT bw -> bx\njp RSHIFT 3 -> jr\nhg AND hh -> hj\nbv AND bx -> by\ner OR es -> et\nkl OR kr -> ks\net RSHIFT 1 -> fm\ne AND f -> h\nu LSHIFT 1 -> ao\nhe RSHIFT 1 -> hx\neg AND ei -> ej\nbo AND bu -> bw\ndz OR ef -> eg\ndy RSHIFT 3 -> ea\ngl OR gm -> gn\nda LSHIFT 1 -> du\nau OR av -> aw\ngj OR gu -> gv\neu OR fa -> fb\nlg OR lm -> ln\ne OR f -> g\nNOT dm -> dn\nNOT l -> m\naq OR ar -> as\ngj RSHIFT 5 -> gm\nhm AND ho -> hp\nge LSHIFT 15 -> gi\njp RSHIFT 1 -> ki\nhg OR hh -> hi\nlc LSHIFT 1 -> lw\nkm OR kn -> ko\neq LSHIFT 1 -> fk\n1 AND am -> an\ngj RSHIFT 1 -> hc\naj AND al -> am\ngj AND gu -> gw\nko AND kq -> kr\nha OR gz -> hb\nbn OR by -> bz\niv OR jb -> jc\nNOT ac -> ad\nbo OR bu -> bv\nd AND j -> l\nbk LSHIFT 1 -> ce\nde OR dk -> dl\ndd RSHIFT 1 -> dw\nhz AND ik -> im\nNOT jd -> je\nfo RSHIFT 2 -> fp\nhb LSHIFT 1 -> hv\nlf RSHIFT 2 -> lg\ngj RSHIFT 3 -> gl\nki OR kj -> kk\nNOT ak -> al\nld OR le -> lf\nci RSHIFT 3 -> ck\n1 AND cc -> cd\nNOT kx -> ky\nfp OR fv -> fw\nev AND ew -> ey\ndt LSHIFT 15 -> dx\nNOT ax -> ay\nbp AND bq -> bs\nNOT ii -> ij\nci AND ct -> cv\niq OR ip -> ir\nx RSHIFT 2 -> y\nfq OR fr -> fs\nbn RSHIFT 5 -> bq\n0 -> c\n14146 -> b\nd OR j -> k\nz OR aa -> ab\ngf OR ge -> gg\ndf OR dg -> dh\nNOT hj -> hk\nNOT di -> dj\nfj LSHIFT 15 -> fn\nlf RSHIFT 1 -> ly\nb AND n -> p\njq OR jw -> jx\ngn AND gp -> gq\nx RSHIFT 1 -> aq\nex AND ez -> fa\nNOT fc -> fd\nbj OR bi -> bk\nas RSHIFT 5 -> av\nhu LSHIFT 15 -> hy\nNOT gs -> gt\nfs AND fu -> fv\ndh AND dj -> dk\nbz AND cb -> cc\ndy RSHIFT 1 -> er\nhc OR hd -> he\nfo OR fz -> ga\nt OR s -> u\nb RSHIFT 2 -> d\nNOT jy -> jz\nhz RSHIFT 2 -> ia\nkk AND kv -> kx\nga AND gc -> gd\nfl LSHIFT 1 -> gf\nbn AND by -> ca\nNOT hr -> hs\nNOT bs -> bt\nlf RSHIFT 3 -> lh\nau AND av -> ax\n1 AND gd -> ge\njr OR js -> jt\nfw AND fy -> fz\nNOT iz -> ja\nc LSHIFT 1 -> t\ndy RSHIFT 5 -> eb\nbp OR bq -> br\nNOT h -> i\n1 AND ds -> dt\nab AND ad -> ae\nap LSHIFT 1 -> bj\nbr AND bt -> bu\nNOT ca -> cb\nNOT el -> em\ns LSHIFT 15 -> w\ngk OR gq -> gr\nff AND fh -> fi\nkf LSHIFT 15 -> kj\nfp AND fv -> fx\nlh OR li -> lj\nbn RSHIFT 3 -> bp\njp OR ka -> kb\nlw OR lv -> lx\niy AND ja -> jb\ndy OR ej -> ek\n1 AND bh -> bi\nNOT kt -> ku\nao OR an -> ap\nia AND ig -> ii\nNOT ey -> ez\nbn RSHIFT 1 -> cg\nfk OR fj -> fl\nce OR cd -> cf\neu AND fa -> fc\nkg OR kf -> kh\njr AND js -> ju\niu RSHIFT 3 -> iw\ndf AND dg -> di\ndl AND dn -> do\nla LSHIFT 15 -> le\nfo RSHIFT 1 -> gh\nNOT gw -> gx\nNOT gb -> gc\nir LSHIFT 1 -> jl\nx AND ai -> ak\nhe RSHIFT 5 -> hh\n1 AND lu -> lv\nNOT ft -> fu\ngh OR gi -> gj\nlf RSHIFT 5 -> li\nx RSHIFT 3 -> z\nb RSHIFT 3 -> e\nhe RSHIFT 2 -> hf\nNOT fx -> fy\njt AND jv -> jw\nhx OR hy -> hz\njp AND ka -> kc\nfb AND fd -> fe\nhz OR ik -> il\nci RSHIFT 1 -> db\nfo AND fz -> gb\nfq AND fr -> ft\ngj RSHIFT 2 -> gk\ncg OR ch -> ci\ncd LSHIFT 15 -> ch\njm LSHIFT 1 -> kg\nih AND ij -> ik\nfo RSHIFT 3 -> fq\nfo RSHIFT 5 -> fr\n1 AND fi -> fj\n1 AND kz -> la\niu AND jf -> jh\ncq AND cs -> ct\ndv LSHIFT 1 -> ep\nhf OR hl -> hm\nkm AND kn -> kp\nde AND dk -> dm\ndd RSHIFT 5 -> dg\nNOT lo -> lp\nNOT ju -> jv\nNOT fg -> fh\ncm AND co -> cp\nea AND eb -> ed\ndd RSHIFT 3 -> df\ngr AND gt -> gu\nep OR eo -> eq\ncj AND cp -> cr\nlf OR lq -> lr\ngg LSHIFT 1 -> ha\net RSHIFT 2 -> eu\nNOT jh -> ji\nek AND em -> en\njk LSHIFT 15 -> jo\nia OR ig -> ih\ngv AND gx -> gy\net AND fe -> fg\nlh AND li -> lk\n1 AND io -> ip\nkb AND kd -> ke\nkk RSHIFT 5 -> kn\nid AND if -> ig\nNOT ls -> lt\ndw OR dx -> dy\ndd AND do -> dq\nlf AND lq -> ls\nNOT kc -> kd\ndy AND ej -> el\n1 AND ke -> kf\net OR fe -> ff\nhz RSHIFT 5 -> ic\ndd OR do -> dp\ncj OR cp -> cq\nNOT dq -> dr\nkk RSHIFT 1 -> ld\njg AND ji -> jj\nhe OR hp -> hq\nhi AND hk -> hl\ndp AND dr -> ds\ndz AND ef -> eh\nhz RSHIFT 3 -> ib\ndb OR dc -> dd\nhw LSHIFT 1 -> iq\nhe AND hp -> hr\nNOT cr -> cs\nlg AND lm -> lo\nhv OR hu -> hw\nil AND in -> io\nNOT eh -> ei\ngz LSHIFT 15 -> hd\ngk AND gq -> gs\n1 AND en -> eo\nNOT kp -> kq\net RSHIFT 5 -> ew\nlj AND ll -> lm\nhe RSHIFT 3 -> hg\net RSHIFT 3 -> ev\nas AND bd -> bf\ncu AND cw -> cx\njx AND jz -> ka\nb OR n -> o\nbe AND bg -> bh\n1 AND ht -> hu\n1 AND gy -> gz\nNOT hn -> ho\nck OR cl -> cm\nec AND ee -> ef\nlv LSHIFT 15 -> lz\nks AND ku -> kv\nNOT ie -> if\nhf AND hl -> hn\n1 AND r -> s\nib AND ic -> ie\nhq AND hs -> ht\ny AND ae -> ag\nNOT ed -> ee\nbi LSHIFT 15 -> bm\ndy RSHIFT 2 -> dz\nci RSHIFT 2 -> cj\nNOT bf -> bg\nNOT im -> in\nev OR ew -> ex\nib OR ic -> id\nbn RSHIFT 2 -> bo\ndd RSHIFT 2 -> de\nbl OR bm -> bn\nas RSHIFT 1 -> bl\nea OR eb -> ec\nln AND lp -> lq\nkk RSHIFT 3 -> km\nis OR it -> iu\niu RSHIFT 2 -> iv\nas OR bd -> be\nip LSHIFT 15 -> it\niw OR ix -> iy\nkk RSHIFT 2 -> kl\nNOT bb -> bc\nci RSHIFT 5 -> cl\nly OR lz -> ma\nz AND aa -> ac\niu RSHIFT 1 -> jn\ncy LSHIFT 15 -> dc\ncf LSHIFT 1 -> cz\nas RSHIFT 3 -> au\ncz OR cy -> da\nkw AND ky -> kz\nlx -> a\niw AND ix -> iz\nlr AND lt -> lu\njp RSHIFT 5 -> js\naw AND ay -> az\njc AND je -> jf\nlb OR la -> lc\nNOT cn -> co\nkh LSHIFT 1 -> lb\n1 AND jj -> jk\ny OR ae -> af\nck AND cl -> cn\nkk OR kv -> kw\nNOT cv -> cw\nkl AND kr -> kt\niu OR jf -> jg\nat AND az -> bb\njp RSHIFT 2 -> jq\niv AND jb -> jd\njn OR jo -> jp\nx OR ai -> aj\nba AND bc -> bd\njl OR jk -> jm\nb RSHIFT 1 -> v\no AND q -> r\nNOT p -> q\nk AND m -> n\nas RSHIFT 2 -> at' values = {} mapping = {} for line in input.split('\n'): destination = line.split('->')[-1].strip() provider = line.split('->')[0].strip() mapping[destination] = provider def evaluate(target): if target.isnumeric(): return int(target) if target in values: return values[target] if target not in mapping: print('Unknown target', target) exit(1) target_provider = mapping[target] args = target_provider.split() if len(args) == 1: values[target] = evaluate(args[0]) elif len(args) == 2: values[target] = ~evaluate(args[1]) elif args[1] == 'AND': values[target] = evaluate(args[0]) & evaluate(args[2]) elif args[1] == 'OR': values[target] = evaluate(args[0]) | evaluate(args[2]) elif args[1] == 'LSHIFT': values[target] = evaluate(args[0]) << evaluate(args[2]) elif args[1] == 'RSHIFT': values[target] = evaluate(args[0]) >> evaluate(args[2]) else: print('unknown operator', args[1]) exit(1) if target not in values: print('How did i get here') exit(1) return values[target] print(evaluate('a'))
# -*- coding: utf-8 -*- # Copyright 2021 Cohesity Inc. class CentrifySchemaEnum(object): """Implementation of the 'CentrifySchema' enum. Specifies the schema of this Centrify zone. The below list of schemas and their values are taken from the document Centrify Server Suite 2016 Windows API Programmer's Guide https://docs.centrify.com/en/css/suite2016/centrify-win-progguide.pdf 'kCentrifyDynamicSchema_1_0' specifies dynamic schema, version 1.0. 'kCentrifyDynamicSchema_2_0' specifies dynamic schema, version 2.0. 'kCentrifyDynamicSchema_3_0' specifies dynamic schema, version 3.0. 'kCentrifyDynamicSchema_5_0' specifies dynamic schema, version 5.0. 'kCentrifySfu_3_0' specifies sfu schema, version 3.0. 'kCentrifySfu_3_0_V5' specifies sfu schema, 3.0.5. 'kCentrifySfu_4_0' specifies sfu schema, version 4.0. 'kCentrifyCdcRfc2307' specifies cdcrfc2307 schema. 'kCentrifyCdcRfc2307_2' specifies cdcrfc2307, version 2. 'kCentrifyCdcRfc2307_3' specifies cdcrfc2307, version 3. Attributes: KCENTRIFYDYNAMICSCHEMA_1_0: TODO: type description here. KCENTRIFYDYNAMICSCHEMA_2_0: TODO: type description here. KCENTRIFYSFU_3_0: TODO: type description here. KCENTRIFYSFU_4_0: TODO: type description here. KCENTRIFYCDCRFC2307: TODO: type description here. KCENTRIFYDYNAMICSCHEMA_3_0: TODO: type description here. KCENTRIFYCDCRFC2307_2: TODO: type description here. KCENTRIFYDYNAMICSCHEMA_5_0: TODO: type description here. KCENTRIFYCDCRFC2307_3: TODO: type description here. KCENTRIFYSFU_3_0_V5: TODO: type description here. """ KCENTRIFYDYNAMICSCHEMA_1_0 = 'kCentrifyDynamicSchema_1_0' KCENTRIFYDYNAMICSCHEMA_2_0 = 'kCentrifyDynamicSchema_2_0' KCENTRIFYSFU_3_0 = 'kCentrifySfu_3_0' KCENTRIFYSFU_4_0 = 'kCentrifySfu_4_0' KCENTRIFYCDCRFC2307 = 'kCentrifyCdcRfc2307' KCENTRIFYDYNAMICSCHEMA_3_0 = 'kCentrifyDynamicSchema_3_0' KCENTRIFYCDCRFC2307_2 = 'kCentrifyCdcRfc2307_2' KCENTRIFYDYNAMICSCHEMA_5_0 = 'kCentrifyDynamicSchema_5_0' KCENTRIFYCDCRFC2307_3 = 'kCentrifyCdcRfc2307_3' KCENTRIFYSFU_3_0_V5 = 'kCentrifySfu_3_0_V5'
class Centrifyschemaenum(object): """Implementation of the 'CentrifySchema' enum. Specifies the schema of this Centrify zone. The below list of schemas and their values are taken from the document Centrify Server Suite 2016 Windows API Programmer's Guide https://docs.centrify.com/en/css/suite2016/centrify-win-progguide.pdf 'kCentrifyDynamicSchema_1_0' specifies dynamic schema, version 1.0. 'kCentrifyDynamicSchema_2_0' specifies dynamic schema, version 2.0. 'kCentrifyDynamicSchema_3_0' specifies dynamic schema, version 3.0. 'kCentrifyDynamicSchema_5_0' specifies dynamic schema, version 5.0. 'kCentrifySfu_3_0' specifies sfu schema, version 3.0. 'kCentrifySfu_3_0_V5' specifies sfu schema, 3.0.5. 'kCentrifySfu_4_0' specifies sfu schema, version 4.0. 'kCentrifyCdcRfc2307' specifies cdcrfc2307 schema. 'kCentrifyCdcRfc2307_2' specifies cdcrfc2307, version 2. 'kCentrifyCdcRfc2307_3' specifies cdcrfc2307, version 3. Attributes: KCENTRIFYDYNAMICSCHEMA_1_0: TODO: type description here. KCENTRIFYDYNAMICSCHEMA_2_0: TODO: type description here. KCENTRIFYSFU_3_0: TODO: type description here. KCENTRIFYSFU_4_0: TODO: type description here. KCENTRIFYCDCRFC2307: TODO: type description here. KCENTRIFYDYNAMICSCHEMA_3_0: TODO: type description here. KCENTRIFYCDCRFC2307_2: TODO: type description here. KCENTRIFYDYNAMICSCHEMA_5_0: TODO: type description here. KCENTRIFYCDCRFC2307_3: TODO: type description here. KCENTRIFYSFU_3_0_V5: TODO: type description here. """ kcentrifydynamicschema_1_0 = 'kCentrifyDynamicSchema_1_0' kcentrifydynamicschema_2_0 = 'kCentrifyDynamicSchema_2_0' kcentrifysfu_3_0 = 'kCentrifySfu_3_0' kcentrifysfu_4_0 = 'kCentrifySfu_4_0' kcentrifycdcrfc2307 = 'kCentrifyCdcRfc2307' kcentrifydynamicschema_3_0 = 'kCentrifyDynamicSchema_3_0' kcentrifycdcrfc2307_2 = 'kCentrifyCdcRfc2307_2' kcentrifydynamicschema_5_0 = 'kCentrifyDynamicSchema_5_0' kcentrifycdcrfc2307_3 = 'kCentrifyCdcRfc2307_3' kcentrifysfu_3_0_v5 = 'kCentrifySfu_3_0_V5'
def ask_question(): print("Who is the founder of Facebook?") option=["Mark Zuckerberg","Bill Gates","Steve Jobs","Larry Page"] for i in option: print(i) ask_question() i=0 while i<100: ask_question() i+=1 def say_hello(name): print ("Hello ", name) print ("Aap kaise ho?") say_hello("jai") def add_number(num1,num2): print("hum2 numbers ko add krenge") print(num1+num2) add_number(112,3) varx=10 vary=20 add_number(varx,vary) def say_lang(name,language): if language=="punjabi": print("sat sri akaal",name) elif language=="hindi": print("Namestye",name) elif language=="English": print("good morning",name) say_lang("rishabh","hindi") say_lang("jai","English") def print_lines(name,position): print("mera naam "+str(name)+" hai") print("mein "+str(position)+" ka co-founder hu") print_lines("jai","Navgurkul") def add_numbers(number1,number2): add=number1+number2 print(number1,"aur",number2," ka sum:-",add) add_numbers(56,12) num1=[15,20,30] num2=[20,30,40] def add_num_list(num1,num2): i=0 b = [] while i<len(num1): add = num1[i]+num2[i] i+=1 b.append(add) return (b) print(add_num_list(num1,num2)) num1=[15,20,30,2, 6, 18, 10, 3, 75] num2=[20,30,40,6, 19, 24, 12, 3, 87] def add_num_list(num1,num2): i=0 while i<len(num1): if num1[i]%2==0 and num2[i]%2==0: print("even hai") else: print("odd hai") i+=1 (add_num_list(num1,num2)) def add_numbers_print(number_x, number_y): number_sum = number_x + number_y return number_sum sum4 = add_numbers_print(4, 5) print (sum4) print (type(sum4)) def calculator(numx,numy,operator): if operator=="add": add=numx+numy return add elif operator=="subtract": subtract=numx-numy return subtract elif operator=="multiply": multiply=numx*numy return multiply elif operator=="divide": divide=numx/numy return divide num1=int(input("Enter the 1st number :- ")) num2=int(input("Enter the 2nd number :- ")) num3=input("which action you want to perform (add/subtract/multiply/divide)") print(calculator(num1,num2,num3)) a=[3,4,5,6] b=[2,4,5,6] def list_change(a,b): i=0 multiply=0 c=[] while i<len(a): multiply=a[i]*b[i] c.append(multiply) i+=1 return c print(list_change(a,b))
def ask_question(): print('Who is the founder of Facebook?') option = ['Mark Zuckerberg', 'Bill Gates', 'Steve Jobs', 'Larry Page'] for i in option: print(i) ask_question() i = 0 while i < 100: ask_question() i += 1 def say_hello(name): print('Hello ', name) print('Aap kaise ho?') say_hello('jai') def add_number(num1, num2): print('hum2 numbers ko add krenge') print(num1 + num2) add_number(112, 3) varx = 10 vary = 20 add_number(varx, vary) def say_lang(name, language): if language == 'punjabi': print('sat sri akaal', name) elif language == 'hindi': print('Namestye', name) elif language == 'English': print('good morning', name) say_lang('rishabh', 'hindi') say_lang('jai', 'English') def print_lines(name, position): print('mera naam ' + str(name) + ' hai') print('mein ' + str(position) + ' ka co-founder hu') print_lines('jai', 'Navgurkul') def add_numbers(number1, number2): add = number1 + number2 print(number1, 'aur', number2, ' ka sum:-', add) add_numbers(56, 12) num1 = [15, 20, 30] num2 = [20, 30, 40] def add_num_list(num1, num2): i = 0 b = [] while i < len(num1): add = num1[i] + num2[i] i += 1 b.append(add) return b print(add_num_list(num1, num2)) num1 = [15, 20, 30, 2, 6, 18, 10, 3, 75] num2 = [20, 30, 40, 6, 19, 24, 12, 3, 87] def add_num_list(num1, num2): i = 0 while i < len(num1): if num1[i] % 2 == 0 and num2[i] % 2 == 0: print('even hai') else: print('odd hai') i += 1 add_num_list(num1, num2) def add_numbers_print(number_x, number_y): number_sum = number_x + number_y return number_sum sum4 = add_numbers_print(4, 5) print(sum4) print(type(sum4)) def calculator(numx, numy, operator): if operator == 'add': add = numx + numy return add elif operator == 'subtract': subtract = numx - numy return subtract elif operator == 'multiply': multiply = numx * numy return multiply elif operator == 'divide': divide = numx / numy return divide num1 = int(input('Enter the 1st number :- ')) num2 = int(input('Enter the 2nd number :- ')) num3 = input('which action you want to perform (add/subtract/multiply/divide)') print(calculator(num1, num2, num3)) a = [3, 4, 5, 6] b = [2, 4, 5, 6] def list_change(a, b): i = 0 multiply = 0 c = [] while i < len(a): multiply = a[i] * b[i] c.append(multiply) i += 1 return c print(list_change(a, b))
input_file = open("input.txt","r") lines = input_file.readlines() count = 0 answers = set() for line in lines: if line == "\n": count += len(answers) print(answers) answers.clear() for character in line: #print(character) if character != "\n": answers.add(character) count += len(answers) print(answers) answers.clear() print(count)
input_file = open('input.txt', 'r') lines = input_file.readlines() count = 0 answers = set() for line in lines: if line == '\n': count += len(answers) print(answers) answers.clear() for character in line: if character != '\n': answers.add(character) count += len(answers) print(answers) answers.clear() print(count)
class BankAccount: def __init__(self): self.accountNum = 0 self.accountOwner = "" self.accountBalance = 0.00 def ModifyAccount(self, id, name, balance): self.accountNum = id self.accountOwner = name self.accountBalance = balance account = BankAccount() account.ModifyAccount(12345, "John Doe", 123456.78) print("Account ID: {}, Name: {}, Balance: ${}".format(account.accountNum, account.accountOwner, account.accountBalance))
class Bankaccount: def __init__(self): self.accountNum = 0 self.accountOwner = '' self.accountBalance = 0.0 def modify_account(self, id, name, balance): self.accountNum = id self.accountOwner = name self.accountBalance = balance account = bank_account() account.ModifyAccount(12345, 'John Doe', 123456.78) print('Account ID: {}, Name: {}, Balance: ${}'.format(account.accountNum, account.accountOwner, account.accountBalance))
# Tai Sakuma <[email protected]> ##__________________________________________________________________|| def expand_path_cfg(path_cfg, alias_dict={ }, overriding_kargs={ }): """expand a path config Args: path_cfg (str, tuple, dict): a config for path alias_dict (dict): a dict for aliases overriding_kargs (dict): to be used for recursive call """ if isinstance(path_cfg, str): return _expand_str(path_cfg, alias_dict, overriding_kargs) if isinstance(path_cfg, dict): return _expand_dict(path_cfg, alias_dict) # assume tuple or list return _expand_tuple(path_cfg, alias_dict, overriding_kargs) ##__________________________________________________________________|| def _expand_str(path_cfg, alias_dict, overriding_kargs): """expand a path config given as a string """ if path_cfg in alias_dict: # e.g., path_cfg = 'var_cut' return _expand_str_alias(path_cfg, alias_dict, overriding_kargs) # e.g., path_cfg = 'ev : {low} <= ev.var[0] < {high}' return _expand_for_lambda_str(path_cfg, alias_dict, overriding_kargs) def _expand_for_lambda_str(path_cfg, alias_dict, overriding_kargs): # e.g., # path_cfg = 'ev : {low} <= ev.var[0] < {high}' ret = dict(factory='LambdaStrFactory', lambda_str=path_cfg, components=()) # e.g., # { # 'factory': 'LambdaStrFactory', # 'lambda_str': 'ev : {low} <= ev.var[0] < {high}' # } overriding_kargs_copy = overriding_kargs.copy() # e.g., {'low': 25, 'high': 200, 'alias': 'var_cut', 'name': 'var_cut25'} if 'alias' in overriding_kargs: ret['name'] = overriding_kargs_copy.pop('alias') if 'name' in overriding_kargs: ret['name'] = overriding_kargs_copy.pop('name') ret.update(overriding_kargs_copy) # e.g., # { # 'factory': 'LambdaStrFactory', # 'lambda_str': 'ev : {low} <= ev.var[0] < {high}', # 'name': 'var_cut25', # 'low': 25, 'high': 200 # } return ret def _expand_str_alias(path_cfg, alias_dict, overriding_kargs): """expand a path config given as a string Args: path_cfg (str): an alias alias_dict (dict): overriding_kargs (dict): """ # e.g., # path_cfg = 'var_cut' new_path_cfg = alias_dict[path_cfg] # e.g., ('ev : {low} <= ev.var[0] < {high}', {'low': 10, 'high': 200}) new_overriding_kargs = dict(alias=path_cfg) # e.g., {'alias': 'var_cut'} new_overriding_kargs.update(overriding_kargs) # e.g., {'alias': 'var_cut', 'name': 'var_cut25', 'low': 25} return expand_path_cfg(new_path_cfg, alias_dict,new_overriding_kargs) ##__________________________________________________________________|| def _expand_tuple(path_cfg, alias_dict, overriding_kargs): """expand a path config given as a tuple """ # e.g., # path_cfg = ('ev : {low} <= ev.var[0] < {high}', {'low': 10, 'high': 200}) # overriding_kargs = {'alias': 'var_cut', 'name': 'var_cut25', 'low': 25} new_path_cfg = path_cfg[0] # e.g., 'ev : {low} <= ev.var[0] < {high}' new_overriding_kargs = path_cfg[1].copy() # e.g., {'low': 10, 'high': 200} new_overriding_kargs.update(overriding_kargs) # e.g., {'low': 25, 'high': 200, 'alias': 'var_cut', 'name': 'var_cut25'} return expand_path_cfg( new_path_cfg, overriding_kargs=new_overriding_kargs, alias_dict=alias_dict ) ##__________________________________________________________________|| def _expand_dict(path_cfg, alias_dict): if 'factory' in path_cfg: return path_cfg if not sum([k in path_cfg for k in ('All', 'Any', 'Not')]) <= 1: raise ValueError("Any pair of 'All', 'Any', 'Not' cannot be simultaneously given unless factory is given!") if 'All' in path_cfg: new_path_cfg = path_cfg.copy() new_path_cfg['factory'] = 'AllFactory' new_path_cfg['components'] = tuple([expand_path_cfg(p, alias_dict=alias_dict) for p in new_path_cfg.pop('All')]) return new_path_cfg if 'Any' in path_cfg: new_path_cfg = path_cfg.copy() new_path_cfg['factory'] = 'AnyFactory' new_path_cfg['components'] = tuple([expand_path_cfg(p, alias_dict=alias_dict) for p in new_path_cfg.pop('Any')]) return new_path_cfg if 'Not' in path_cfg: new_path_cfg = path_cfg.copy() new_path_cfg['factory'] = 'NotFactory' new_path_cfg['components'] = (expand_path_cfg(new_path_cfg.pop('Not'), alias_dict=alias_dict), ) return new_path_cfg raise ValueError("cannot recognize the path_cfg") ##__________________________________________________________________||
def expand_path_cfg(path_cfg, alias_dict={}, overriding_kargs={}): """expand a path config Args: path_cfg (str, tuple, dict): a config for path alias_dict (dict): a dict for aliases overriding_kargs (dict): to be used for recursive call """ if isinstance(path_cfg, str): return _expand_str(path_cfg, alias_dict, overriding_kargs) if isinstance(path_cfg, dict): return _expand_dict(path_cfg, alias_dict) return _expand_tuple(path_cfg, alias_dict, overriding_kargs) def _expand_str(path_cfg, alias_dict, overriding_kargs): """expand a path config given as a string """ if path_cfg in alias_dict: return _expand_str_alias(path_cfg, alias_dict, overriding_kargs) return _expand_for_lambda_str(path_cfg, alias_dict, overriding_kargs) def _expand_for_lambda_str(path_cfg, alias_dict, overriding_kargs): ret = dict(factory='LambdaStrFactory', lambda_str=path_cfg, components=()) overriding_kargs_copy = overriding_kargs.copy() if 'alias' in overriding_kargs: ret['name'] = overriding_kargs_copy.pop('alias') if 'name' in overriding_kargs: ret['name'] = overriding_kargs_copy.pop('name') ret.update(overriding_kargs_copy) return ret def _expand_str_alias(path_cfg, alias_dict, overriding_kargs): """expand a path config given as a string Args: path_cfg (str): an alias alias_dict (dict): overriding_kargs (dict): """ new_path_cfg = alias_dict[path_cfg] new_overriding_kargs = dict(alias=path_cfg) new_overriding_kargs.update(overriding_kargs) return expand_path_cfg(new_path_cfg, alias_dict, new_overriding_kargs) def _expand_tuple(path_cfg, alias_dict, overriding_kargs): """expand a path config given as a tuple """ new_path_cfg = path_cfg[0] new_overriding_kargs = path_cfg[1].copy() new_overriding_kargs.update(overriding_kargs) return expand_path_cfg(new_path_cfg, overriding_kargs=new_overriding_kargs, alias_dict=alias_dict) def _expand_dict(path_cfg, alias_dict): if 'factory' in path_cfg: return path_cfg if not sum([k in path_cfg for k in ('All', 'Any', 'Not')]) <= 1: raise value_error("Any pair of 'All', 'Any', 'Not' cannot be simultaneously given unless factory is given!") if 'All' in path_cfg: new_path_cfg = path_cfg.copy() new_path_cfg['factory'] = 'AllFactory' new_path_cfg['components'] = tuple([expand_path_cfg(p, alias_dict=alias_dict) for p in new_path_cfg.pop('All')]) return new_path_cfg if 'Any' in path_cfg: new_path_cfg = path_cfg.copy() new_path_cfg['factory'] = 'AnyFactory' new_path_cfg['components'] = tuple([expand_path_cfg(p, alias_dict=alias_dict) for p in new_path_cfg.pop('Any')]) return new_path_cfg if 'Not' in path_cfg: new_path_cfg = path_cfg.copy() new_path_cfg['factory'] = 'NotFactory' new_path_cfg['components'] = (expand_path_cfg(new_path_cfg.pop('Not'), alias_dict=alias_dict),) return new_path_cfg raise value_error('cannot recognize the path_cfg')
class Solution: def maxDepth(self, root): if root is None: return 0 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
class Solution: def max_depth(self, root): if root is None: return 0 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
""" Extension 3 (ext3) Used primarily for concurrent Linux systems (ext2 + journalling) """
""" Extension 3 (ext3) Used primarily for concurrent Linux systems (ext2 + journalling) """
lis = [] for i in range (10): num = int(input()) lis.append(num) print(lis) for i in range (len(lis)): print(lis[i])
lis = [] for i in range(10): num = int(input()) lis.append(num) print(lis) for i in range(len(lis)): print(lis[i])
n = int(input('enter number to find the factorial: ')) fact=1; for i in range(1,n+1,1): fact=fact*i print(fact)
n = int(input('enter number to find the factorial: ')) fact = 1 for i in range(1, n + 1, 1): fact = fact * i print(fact)
"""Configuration package. This package handle all information that could be given to pycodeanalyzer in the configuration. """
"""Configuration package. This package handle all information that could be given to pycodeanalyzer in the configuration. """
Automoviles=['Dodge Challeger', 'VW Gti', 'Jeep Rubicon', 'Alfa Romeo Quadro', 'Ford ST', 'Dodge RAM', 'Ford FX4'] M1="Me gustaria compar un " + Automoviles[0].title()+"." M2="Mi vecino choco su nuevo " + Automoviles[1].title() + "." M3="El nuevo " + Automoviles[2].title()+ " es mucho mas economico." M4="Hay una gran diferencia entre el " + Automoviles[3].title() + " y el " + Automoviles[4].title()+"." M5="La camioneta " + Automoviles[5].title() + " es de gasolina, mientras que la " + Automoviles[6].title() +" es de Diesel." print(M1) print(M2) print(M3) print(M4) print(M5)
automoviles = ['Dodge Challeger', 'VW Gti', 'Jeep Rubicon', 'Alfa Romeo Quadro', 'Ford ST', 'Dodge RAM', 'Ford FX4'] m1 = 'Me gustaria compar un ' + Automoviles[0].title() + '.' m2 = 'Mi vecino choco su nuevo ' + Automoviles[1].title() + '.' m3 = 'El nuevo ' + Automoviles[2].title() + ' es mucho mas economico.' m4 = 'Hay una gran diferencia entre el ' + Automoviles[3].title() + ' y el ' + Automoviles[4].title() + '.' m5 = 'La camioneta ' + Automoviles[5].title() + ' es de gasolina, mientras que la ' + Automoviles[6].title() + ' es de Diesel.' print(M1) print(M2) print(M3) print(M4) print(M5)
class Stock: def __init__(self, symbol, name): self.__name = name self.__symbol = symbol self.__stockPlate = [] self.__carePlate = [] @property def name(self): return self.__name @property def symbol(self): return self.__symbol @property def stockPlate(self): return self.stockPlate @property def carePlate(self): return self.__carePlate def addCarePlate(self, cp): if cp in self.__carePlate: print("Already exist!") else: self.__carePlate.append(cp) def addStockPlate(self, sp): if sp in self.__stockPlate: print("Already exist!") else: self.__stockPlate.append(sp) # print("Success") def formatPlateInfo(self): # print(self.__carePlate) return {"name": self.__name, "carePlate":self.__carePlate, "stockPlate": self.__stockPlate}
class Stock: def __init__(self, symbol, name): self.__name = name self.__symbol = symbol self.__stockPlate = [] self.__carePlate = [] @property def name(self): return self.__name @property def symbol(self): return self.__symbol @property def stock_plate(self): return self.stockPlate @property def care_plate(self): return self.__carePlate def add_care_plate(self, cp): if cp in self.__carePlate: print('Already exist!') else: self.__carePlate.append(cp) def add_stock_plate(self, sp): if sp in self.__stockPlate: print('Already exist!') else: self.__stockPlate.append(sp) def format_plate_info(self): return {'name': self.__name, 'carePlate': self.__carePlate, 'stockPlate': self.__stockPlate}
#Programa para evaluar si un numero es feliz numero_a_evaluar = input("Introduce el numero a evaluar: ") n = numero_a_evaluar suma = 2 primer_digito = 0 segundo_digito = 0 tercer_digito = 0 cuarto_digito = 0 while suma > 1: primer_digito = numero_a_evaluar[0] primer_digito = int(primer_digito) print(primer_digito) try: segundo_digito = numero_a_evaluar[1] segundo_digito = int(segundo_digito) print(segundo_digito) except IndexError as Numeromenorandigits: pass try: tercer_digito = numero_a_evaluar[2] tercer_digito = int(tercer_digito) print(tercer_digito) except IndexError as Numeromenorandigits: pass try: cuarto_digito = numero_a_evaluar[3] cuarto_digito = int(cuarto_digito) print(cuarto_digito) except IndexError as Numeromenorandigits: pass suma = primer_digito ** 2 + segundo_digito ** 2 + tercer_digito ** 2 print (suma) numero_a_evaluar = suma numero_a_evaluar = str(numero_a_evaluar) if suma == 1: print(n,"es un numero feliz")
numero_a_evaluar = input('Introduce el numero a evaluar: ') n = numero_a_evaluar suma = 2 primer_digito = 0 segundo_digito = 0 tercer_digito = 0 cuarto_digito = 0 while suma > 1: primer_digito = numero_a_evaluar[0] primer_digito = int(primer_digito) print(primer_digito) try: segundo_digito = numero_a_evaluar[1] segundo_digito = int(segundo_digito) print(segundo_digito) except IndexError as Numeromenorandigits: pass try: tercer_digito = numero_a_evaluar[2] tercer_digito = int(tercer_digito) print(tercer_digito) except IndexError as Numeromenorandigits: pass try: cuarto_digito = numero_a_evaluar[3] cuarto_digito = int(cuarto_digito) print(cuarto_digito) except IndexError as Numeromenorandigits: pass suma = primer_digito ** 2 + segundo_digito ** 2 + tercer_digito ** 2 print(suma) numero_a_evaluar = suma numero_a_evaluar = str(numero_a_evaluar) if suma == 1: print(n, 'es un numero feliz')
# -*- coding: utf-8 -*- # Copyright 2018, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. """ A property set is maintained by the PassManager to keep information about the current state of the circuit """ class PropertySet(dict): """ A default dictionary-like object """ def __missing__(self, key): return None
""" A property set is maintained by the PassManager to keep information about the current state of the circuit """ class Propertyset(dict): """ A default dictionary-like object """ def __missing__(self, key): return None
def read_label_pbtxt(label_path: str) -> dict: with open(label_path, "r") as label_file: lines = label_file.readlines() labels = {} for row, content in enumerate(lines): labels[row] = {"id": row, "name": content.strip()} return labels
def read_label_pbtxt(label_path: str) -> dict: with open(label_path, 'r') as label_file: lines = label_file.readlines() labels = {} for (row, content) in enumerate(lines): labels[row] = {'id': row, 'name': content.strip()} return labels
co2 = input("Please input air quality value: ") co2 = int(co2) if co2 > 399 and co2 < 698: print("Excelent") elif co2 > 699 and co2 < 898: print("Good") elif co2 > 899 and co2 < 1098: print("Fair") elif co2 > 1099 and co2 < 1598: print("Mediocre, contaminated indoor air") elif co2 > 1599 and co2 < 2101: print("Bad, heavily contaminated indoor air")
co2 = input('Please input air quality value: ') co2 = int(co2) if co2 > 399 and co2 < 698: print('Excelent') elif co2 > 699 and co2 < 898: print('Good') elif co2 > 899 and co2 < 1098: print('Fair') elif co2 > 1099 and co2 < 1598: print('Mediocre, contaminated indoor air') elif co2 > 1599 and co2 < 2101: print('Bad, heavily contaminated indoor air')
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"GH_HOST": "00_core.ipynb", "GhApi": "00_core.ipynb", "date2gh": "00_core.ipynb", "gh2date": "00_core.ipynb", "print_summary": "00_core.ipynb", "GhApi.delete_release": "00_core.ipynb", "GhApi.upload_file": "00_core.ipynb", "GhApi.create_release": "00_core.ipynb", "GhApi.list_tags": "00_core.ipynb", "GhApi.list_branches": "00_core.ipynb", "EMPTY_TREE_SHA": "00_core.ipynb", "GhApi.create_branch_empty": "00_core.ipynb", "GhApi.delete_tag": "00_core.ipynb", "GhApi.delete_branch": "00_core.ipynb", "GhApi.get_branch": "00_core.ipynb", "GhApi.list_files": "00_core.ipynb", "GhApi.get_content": "00_core.ipynb", "GhApi.update_contents": "00_core.ipynb", "GhApi.enable_pages": "00_core.ipynb", "contexts": "01_actions.ipynb", "env_github": "01_actions.ipynb", "user_repo": "01_actions.ipynb", "Event": "01_actions.ipynb", "create_workflow_files": "01_actions.ipynb", "fill_workflow_templates": "01_actions.ipynb", "env_contexts": "01_actions.ipynb", "def_pipinst": "01_actions.ipynb", "create_workflow": "01_actions.ipynb", "gh_create_workflow": "01_actions.ipynb", "example_payload": "01_actions.ipynb", "github_token": "01_actions.ipynb", "actions_output": "01_actions.ipynb", "actions_debug": "01_actions.ipynb", "actions_warn": "01_actions.ipynb", "actions_error": "01_actions.ipynb", "actions_group": "01_actions.ipynb", "actions_endgroup": "01_actions.ipynb", "actions_mask": "01_actions.ipynb", "set_git_user": "01_actions.ipynb", "Scope": "02_auth.ipynb", "scope_str": "02_auth.ipynb", "GhDeviceAuth": "02_auth.ipynb", "GhDeviceAuth.url_docs": "02_auth.ipynb", "GhDeviceAuth.open_browser": "02_auth.ipynb", "GhDeviceAuth.auth": "02_auth.ipynb", "GhDeviceAuth.wait": "02_auth.ipynb", "paged": "03_page.ipynb", "parse_link_hdr": "03_page.ipynb", "GhApi.last_page": "03_page.ipynb", "pages": "03_page.ipynb", "GhApi.list_events": "04_event.ipynb", "GhApi.list_events_parallel": "04_event.ipynb", "GhEvent": "04_event.ipynb", "GhApi.fetch_events": "04_event.ipynb", "load_sample_events": "04_event.ipynb", "save_sample_events": "04_event.ipynb", "full_type": "04_event.ipynb", "evt_emojis": "04_event.ipynb", "description": "04_event.ipynb", "emoji": "04_event.ipynb", "text": "04_event.ipynb", "described_evts": "04_event.ipynb", "ghapi": "10_cli.ipynb", "ghpath": "10_cli.ipynb", "ghraw": "10_cli.ipynb", "completion_ghapi": "10_cli.ipynb", "GH_OPENAPI_URL": "90_build_lib.ipynb", "build_funcs": "90_build_lib.ipynb", "GhMeta": "90_build_lib.ipynb"} modules = ["core.py", "actions.py", "auth.py", "page.py", "event.py", "cli.py", "build_lib.py"] doc_url = "https://ghapi.fast.ai/" git_url = "https://github.com/fastai/ghapi/tree/master/" def custom_doc_links(name): return None
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'GH_HOST': '00_core.ipynb', 'GhApi': '00_core.ipynb', 'date2gh': '00_core.ipynb', 'gh2date': '00_core.ipynb', 'print_summary': '00_core.ipynb', 'GhApi.delete_release': '00_core.ipynb', 'GhApi.upload_file': '00_core.ipynb', 'GhApi.create_release': '00_core.ipynb', 'GhApi.list_tags': '00_core.ipynb', 'GhApi.list_branches': '00_core.ipynb', 'EMPTY_TREE_SHA': '00_core.ipynb', 'GhApi.create_branch_empty': '00_core.ipynb', 'GhApi.delete_tag': '00_core.ipynb', 'GhApi.delete_branch': '00_core.ipynb', 'GhApi.get_branch': '00_core.ipynb', 'GhApi.list_files': '00_core.ipynb', 'GhApi.get_content': '00_core.ipynb', 'GhApi.update_contents': '00_core.ipynb', 'GhApi.enable_pages': '00_core.ipynb', 'contexts': '01_actions.ipynb', 'env_github': '01_actions.ipynb', 'user_repo': '01_actions.ipynb', 'Event': '01_actions.ipynb', 'create_workflow_files': '01_actions.ipynb', 'fill_workflow_templates': '01_actions.ipynb', 'env_contexts': '01_actions.ipynb', 'def_pipinst': '01_actions.ipynb', 'create_workflow': '01_actions.ipynb', 'gh_create_workflow': '01_actions.ipynb', 'example_payload': '01_actions.ipynb', 'github_token': '01_actions.ipynb', 'actions_output': '01_actions.ipynb', 'actions_debug': '01_actions.ipynb', 'actions_warn': '01_actions.ipynb', 'actions_error': '01_actions.ipynb', 'actions_group': '01_actions.ipynb', 'actions_endgroup': '01_actions.ipynb', 'actions_mask': '01_actions.ipynb', 'set_git_user': '01_actions.ipynb', 'Scope': '02_auth.ipynb', 'scope_str': '02_auth.ipynb', 'GhDeviceAuth': '02_auth.ipynb', 'GhDeviceAuth.url_docs': '02_auth.ipynb', 'GhDeviceAuth.open_browser': '02_auth.ipynb', 'GhDeviceAuth.auth': '02_auth.ipynb', 'GhDeviceAuth.wait': '02_auth.ipynb', 'paged': '03_page.ipynb', 'parse_link_hdr': '03_page.ipynb', 'GhApi.last_page': '03_page.ipynb', 'pages': '03_page.ipynb', 'GhApi.list_events': '04_event.ipynb', 'GhApi.list_events_parallel': '04_event.ipynb', 'GhEvent': '04_event.ipynb', 'GhApi.fetch_events': '04_event.ipynb', 'load_sample_events': '04_event.ipynb', 'save_sample_events': '04_event.ipynb', 'full_type': '04_event.ipynb', 'evt_emojis': '04_event.ipynb', 'description': '04_event.ipynb', 'emoji': '04_event.ipynb', 'text': '04_event.ipynb', 'described_evts': '04_event.ipynb', 'ghapi': '10_cli.ipynb', 'ghpath': '10_cli.ipynb', 'ghraw': '10_cli.ipynb', 'completion_ghapi': '10_cli.ipynb', 'GH_OPENAPI_URL': '90_build_lib.ipynb', 'build_funcs': '90_build_lib.ipynb', 'GhMeta': '90_build_lib.ipynb'} modules = ['core.py', 'actions.py', 'auth.py', 'page.py', 'event.py', 'cli.py', 'build_lib.py'] doc_url = 'https://ghapi.fast.ai/' git_url = 'https://github.com/fastai/ghapi/tree/master/' def custom_doc_links(name): return None
def wypisz(par1, par2): print('{0} {1}'.format(par1, par2)) def sprawdz(arg1, arg2): if arg1 > arg2: return True else: return False
def wypisz(par1, par2): print('{0} {1}'.format(par1, par2)) def sprawdz(arg1, arg2): if arg1 > arg2: return True else: return False
ce,nll=input("<<") lx=ce*(nll/1200) print("The interest is",lx)
(ce, nll) = input('<<') lx = ce * (nll / 1200) print('The interest is', lx)
class Edge: def __init__(self, src, dst, line): self.src = src self.dst = dst self.line = line assert src != dst, f"Source and destination are the same!" def reverse(self): return Edge(self.dst, self.src, self.line.reverse()) def to_dict(self): return { "src": self.src.id if self.src else None, "dst": self.dst.id if self.dst else None, } def __str__(self): src_id = self.src.id if self.src else "None" dst_id = self.dst.id if self.dst else "None" return f"{src_id} -> {dst_id}"
class Edge: def __init__(self, src, dst, line): self.src = src self.dst = dst self.line = line assert src != dst, f'Source and destination are the same!' def reverse(self): return edge(self.dst, self.src, self.line.reverse()) def to_dict(self): return {'src': self.src.id if self.src else None, 'dst': self.dst.id if self.dst else None} def __str__(self): src_id = self.src.id if self.src else 'None' dst_id = self.dst.id if self.dst else 'None' return f'{src_id} -> {dst_id}'
def to_url_representation(path: str) -> str: """Convert path to a representation that can be used in urls/queries""" return path.replace("_", "-_-").replace("/", "__") def from_url_representation(url_rep: str) -> str: """Reconvert url representation of path to actual path""" return url_rep.replace("__", "/").replace("-_-", "_")
def to_url_representation(path: str) -> str: """Convert path to a representation that can be used in urls/queries""" return path.replace('_', '-_-').replace('/', '__') def from_url_representation(url_rep: str) -> str: """Reconvert url representation of path to actual path""" return url_rep.replace('__', '/').replace('-_-', '_')
with open('log', 'r') as logfile: for line in logfile: if line.__contains__('LOG'): print(line) #pvahdatn@cs-arch-20:~/git/dandelion-lib$ sbt "testOnly dataflow.test03Tester" > log
with open('log', 'r') as logfile: for line in logfile: if line.__contains__('LOG'): print(line)
''' Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. Given linked list -- head = [4,5,1,9], which looks like following: Example 1: Input: head = [4,5,1,9], node = 5 Output: [4,1,9] Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. Example 2: Input: head = [4,5,1,9], node = 1 Output: [4,5,9] Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. Note: * The linked list will have at least two elements. * All of the nodes' values will be unique. * The given node will not be the tail and it will always be a valid node of the linked list. * Do not return anything from your function. ''' # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None def __str__(self): output = "" curr = self while curr != None: output = output + str(curr.val) + "-> " curr = curr.next output += "NULL" return output class Solution(object): def deleteNode(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ node.val = node.next.val node.next = node.next.next sol = Solution() x_1, x_2, x_3, x_4 = ListNode(1), ListNode(2), ListNode(3), ListNode(4) x_1.next = x_2 x_2.next = x_3 x_3.next = x_4 # print(x_1) sol.deleteNode(x_2) print(x_1)
""" Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. Given linked list -- head = [4,5,1,9], which looks like following: Example 1: Input: head = [4,5,1,9], node = 5 Output: [4,1,9] Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. Example 2: Input: head = [4,5,1,9], node = 1 Output: [4,5,9] Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. Note: * The linked list will have at least two elements. * All of the nodes' values will be unique. * The given node will not be the tail and it will always be a valid node of the linked list. * Do not return anything from your function. """ class Listnode(object): def __init__(self, x): self.val = x self.next = None def __str__(self): output = '' curr = self while curr != None: output = output + str(curr.val) + '-> ' curr = curr.next output += 'NULL' return output class Solution(object): def delete_node(self, node): """ :type node: ListNode :rtype: void Do not return anything, modify node in-place instead. """ node.val = node.next.val node.next = node.next.next sol = solution() (x_1, x_2, x_3, x_4) = (list_node(1), list_node(2), list_node(3), list_node(4)) x_1.next = x_2 x_2.next = x_3 x_3.next = x_4 sol.deleteNode(x_2) print(x_1)
class SortStrategy: def sort(self, dataset): pass class BubbleSortStrategy(SortStrategy): def sort(self, dataset): print('Sorting using bubble sort') return dataset class QuickSortStrategy(SortStrategy): def sort(self, dataset): print('Sorting using quick sort') return dataset class Sorter: _sorter = None def __init__(self, sorter): self._sorter = sorter def sort(self, dataset): return self._sorter.sort(dataset) dataset = [1, 5, 4, 3, 2, 8] sorter = Sorter(BubbleSortStrategy()) sorter.sort(dataset) sorter = Sorter(QuickSortStrategy()) sorter.sort(dataset)
class Sortstrategy: def sort(self, dataset): pass class Bubblesortstrategy(SortStrategy): def sort(self, dataset): print('Sorting using bubble sort') return dataset class Quicksortstrategy(SortStrategy): def sort(self, dataset): print('Sorting using quick sort') return dataset class Sorter: _sorter = None def __init__(self, sorter): self._sorter = sorter def sort(self, dataset): return self._sorter.sort(dataset) dataset = [1, 5, 4, 3, 2, 8] sorter = sorter(bubble_sort_strategy()) sorter.sort(dataset) sorter = sorter(quick_sort_strategy()) sorter.sort(dataset)
''' BF C(n,k)*n O(n!) LeetCode 516 DP find the longest palindrome sequence O(n^2) ''' class Solution: def isValidPalindrome(self, s: str, k: int) -> bool: n = len(str) dp = [[0]*n for _ in range(n)] for i in range(n-2, -1, -1): dp[i][i] = 1 for j in range(i+1, n): if s[i]==s[j]: dp[i][j] = dp[i+1][j-1] + 2 else: dp[i][j] = max(dp[i+1][j], dp[i][j-1]) return dp[0][n-1]+k >=len(s)
""" BF C(n,k)*n O(n!) LeetCode 516 DP find the longest palindrome sequence O(n^2) """ class Solution: def is_valid_palindrome(self, s: str, k: int) -> bool: n = len(str) dp = [[0] * n for _ in range(n)] for i in range(n - 2, -1, -1): dp[i][i] = 1 for j in range(i + 1, n): if s[i] == s[j]: dp[i][j] = dp[i + 1][j - 1] + 2 else: dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]) return dp[0][n - 1] + k >= len(s)
def calcula_se_um_numero_eh_par(numero): if type(numero) == int: if numero % 2 == 0: return True return False
def calcula_se_um_numero_eh_par(numero): if type(numero) == int: if numero % 2 == 0: return True return False
class StompError(Exception): def __init__(self, message, detail): super(StompError, self).__init__(message) self.detail = detail class StompDisconnectedError(Exception): pass class ExceededRetryCount(Exception): pass
class Stomperror(Exception): def __init__(self, message, detail): super(StompError, self).__init__(message) self.detail = detail class Stompdisconnectederror(Exception): pass class Exceededretrycount(Exception): pass
""" BiNode: Consider a simple data structure called BiNode, which has pointers to two other nodes. The data structure BiNode could be used to represent both a binary tree (where nodel is the left node and node2 is the right node) or a doubly linked list (where nodel is the previous node and node2 is the next node). Implement a method to convert a binary search tree (implemented with BiNode) into a doubly linked list. The values should be kept in order and the operation should be performed in place (that is, on the original data structure). (17.12, p571) SOLUTION: recursion Left and right halves of the tree form their own "sub-parts" of the linked list (i.e., they appear consecutively in the linked list). So, if we recursively converted the left and right subtrees to a doubly linked list, we can build the final linked list from those parts. How to return the head and tail of a linked list? Return the head of a doubly linked list. Tree as doubly linked list: form the triangle where root is middle of the list. mid // \\ head tail If left subtree is not empty, left.next = root, root.prev = left If right subtree is not empty, root.next = right, right.prev = root If both left and right subtrees are not empty, right.next = left, left.prev = right O(n) time: each node is touched an average of O(1) times. O(n) space: depth of call stack """ class BiNode: def __init__(self, key, left=None, right=None): self.key = key self.left = left self.right = right def append(self, other): self.right = other other.left = self @staticmethod def as_circular_linked_list(root): if root is None: return None lsub = BiNode.as_circular_linked_list(root.left) rsub = BiNode.as_circular_linked_list(root.right) if lsub is None and rsub is None: root.left = root root.right = root return root rsub_tail = None if rsub is None else rsub.left # join left to root if lsub is None: rsub.left.append(root) else: lsub.left.append(root) # join right to root if rsub is None: root.append(lsub) else: root.append(rsub) # join right to left if lsub is not None and rsub is not None: rsub_tail.append(lsub) return root if lsub is None else lsub @staticmethod def as_linked_list(root): """Takes the circular linked list and break the circular connection.""" head = BiNode.as_circular_linked_list(root) if head is None: return None head.left.right = None head.left = None return head
""" BiNode: Consider a simple data structure called BiNode, which has pointers to two other nodes. The data structure BiNode could be used to represent both a binary tree (where nodel is the left node and node2 is the right node) or a doubly linked list (where nodel is the previous node and node2 is the next node). Implement a method to convert a binary search tree (implemented with BiNode) into a doubly linked list. The values should be kept in order and the operation should be performed in place (that is, on the original data structure). (17.12, p571) SOLUTION: recursion Left and right halves of the tree form their own "sub-parts" of the linked list (i.e., they appear consecutively in the linked list). So, if we recursively converted the left and right subtrees to a doubly linked list, we can build the final linked list from those parts. How to return the head and tail of a linked list? Return the head of a doubly linked list. Tree as doubly linked list: form the triangle where root is middle of the list. mid // \\ head tail If left subtree is not empty, left.next = root, root.prev = left If right subtree is not empty, root.next = right, right.prev = root If both left and right subtrees are not empty, right.next = left, left.prev = right O(n) time: each node is touched an average of O(1) times. O(n) space: depth of call stack """ class Binode: def __init__(self, key, left=None, right=None): self.key = key self.left = left self.right = right def append(self, other): self.right = other other.left = self @staticmethod def as_circular_linked_list(root): if root is None: return None lsub = BiNode.as_circular_linked_list(root.left) rsub = BiNode.as_circular_linked_list(root.right) if lsub is None and rsub is None: root.left = root root.right = root return root rsub_tail = None if rsub is None else rsub.left if lsub is None: rsub.left.append(root) else: lsub.left.append(root) if rsub is None: root.append(lsub) else: root.append(rsub) if lsub is not None and rsub is not None: rsub_tail.append(lsub) return root if lsub is None else lsub @staticmethod def as_linked_list(root): """Takes the circular linked list and break the circular connection.""" head = BiNode.as_circular_linked_list(root) if head is None: return None head.left.right = None head.left = None return head
class ParticleDataAccessor(object): """ This class provides access to the underlying data model. """ LINE_STYLE_SOLID = 0 LINE_STYLE_DASH = 1 LINE_STYLE_WAVE = 2 LINE_STYLE_SPIRAL = 3 LINE_VERTEX = 4 def id(self, object): """ Returns an id to identify given object. Usually it is sufficient to identify python objects directly with themselves. Overwrite this function if this is not true for your objects. """ return id(object) def particleId(self, object): raise NotImplementedError def isQuark(self, object): raise NotImplementedError def isLepton(self, object): raise NotImplementedError def isGluon(self, object): raise NotImplementedError def isBoson(self, object): raise NotImplementedError def color(self, object): raise NotImplementedError def lineStyle(self, object): raise NotImplementedError def createParticle(self): raise NotImplementedError def charge(self, object): raise NotImplementedError def linkMother(self, object, mother): raise NotImplementedError def linkDaughter(self, object, daughter): raise NotImplementedError
class Particledataaccessor(object): """ This class provides access to the underlying data model. """ line_style_solid = 0 line_style_dash = 1 line_style_wave = 2 line_style_spiral = 3 line_vertex = 4 def id(self, object): """ Returns an id to identify given object. Usually it is sufficient to identify python objects directly with themselves. Overwrite this function if this is not true for your objects. """ return id(object) def particle_id(self, object): raise NotImplementedError def is_quark(self, object): raise NotImplementedError def is_lepton(self, object): raise NotImplementedError def is_gluon(self, object): raise NotImplementedError def is_boson(self, object): raise NotImplementedError def color(self, object): raise NotImplementedError def line_style(self, object): raise NotImplementedError def create_particle(self): raise NotImplementedError def charge(self, object): raise NotImplementedError def link_mother(self, object, mother): raise NotImplementedError def link_daughter(self, object, daughter): raise NotImplementedError
description = 'setup for the NICOS collector' group = 'special' devices = dict( CacheKafka=device( 'nicos_ess.devices.cache_kafka_forwarder.CacheKafkaForwarder', dev_ignore=['space', 'sample'], brokers=configdata('config.KAFKA_BROKERS'), output_topic="nicos_cache", update_interval=10. ), Collector=device('nicos.services.collector.Collector', cache='localhost:14869', forwarders=['CacheKafka'], ), )
description = 'setup for the NICOS collector' group = 'special' devices = dict(CacheKafka=device('nicos_ess.devices.cache_kafka_forwarder.CacheKafkaForwarder', dev_ignore=['space', 'sample'], brokers=configdata('config.KAFKA_BROKERS'), output_topic='nicos_cache', update_interval=10.0), Collector=device('nicos.services.collector.Collector', cache='localhost:14869', forwarders=['CacheKafka']))
class Solution: def kLengthApart(self, nums: List[int], k: int) -> bool: if 1 not in nums: return True start, end = nums.index(1), nums.index(1)+1 while end < len(nums): if nums[start] == 1 and nums[end] == 1 and end - start <= k: return False elif nums[start] == 1 and nums[end] == 1: start = end end += 1 else: end += 1 return True
class Solution: def k_length_apart(self, nums: List[int], k: int) -> bool: if 1 not in nums: return True (start, end) = (nums.index(1), nums.index(1) + 1) while end < len(nums): if nums[start] == 1 and nums[end] == 1 and (end - start <= k): return False elif nums[start] == 1 and nums[end] == 1: start = end end += 1 else: end += 1 return True
""" This module contains all notification payload objects.""" class BaseMsg(dict): """The BaseClass of all objects in notification payload.""" apns_keys = [] def __init__(self, custom_fields={}, **apn_args): super(BaseMsg, self).__init__(custom_fields, **apn_args) if custom_fields: self.update(custom_fields) def update_keys(self, apn_args, msg_obj_keys): """Transform the input keys with '_' to apns format with '-'.""" for k, v in apn_args.iteritems(): formated_k = k.replace('_', '-') if formated_k in msg_obj_keys: del apn_args[k] apn_args[formated_k] = v class Alert(BaseMsg): """The alert piece in aps section.""" apns_keys = [ 'title', 'body', 'title-loc-key', 'title-loc-key', 'action-loc-key', 'loc-key', 'loc-args', 'launch-image'] def __init__(self, body=None, **apn_args): self.update_keys(apn_args, Alert.apns_keys) self.__setitem__('body', body) super(Alert, self).__init__(**apn_args) class APS(BaseMsg): """The aps section in the payload.""" apns_keys = [ 'mutable-content', 'alert', 'badge', 'sound', 'content-available', 'category', 'thread-id'] def __init__(self, **apn_args): self.update_keys(apn_args, APS.apns_keys) super(APS, self).__init__(**apn_args) class Payload(BaseMsg): """The whole payload to send to APNs as the request body.""" def __init__(self, aps, **apn_args): self.__setitem__('aps', aps) super(Payload, self).__init__(**apn_args) class Headers(BaseMsg): """The request headers to send to APNs.""" apns_keys = [ 'authorization', 'apns-id', 'apns-expiration', 'apns-priority', 'apns-topic', 'apns-collapse-id'] def __init__(self, **apn_args): self.update_keys(apn_args, Headers.apns_keys) super(Headers, self).__init__(**apn_args)
""" This module contains all notification payload objects.""" class Basemsg(dict): """The BaseClass of all objects in notification payload.""" apns_keys = [] def __init__(self, custom_fields={}, **apn_args): super(BaseMsg, self).__init__(custom_fields, **apn_args) if custom_fields: self.update(custom_fields) def update_keys(self, apn_args, msg_obj_keys): """Transform the input keys with '_' to apns format with '-'.""" for (k, v) in apn_args.iteritems(): formated_k = k.replace('_', '-') if formated_k in msg_obj_keys: del apn_args[k] apn_args[formated_k] = v class Alert(BaseMsg): """The alert piece in aps section.""" apns_keys = ['title', 'body', 'title-loc-key', 'title-loc-key', 'action-loc-key', 'loc-key', 'loc-args', 'launch-image'] def __init__(self, body=None, **apn_args): self.update_keys(apn_args, Alert.apns_keys) self.__setitem__('body', body) super(Alert, self).__init__(**apn_args) class Aps(BaseMsg): """The aps section in the payload.""" apns_keys = ['mutable-content', 'alert', 'badge', 'sound', 'content-available', 'category', 'thread-id'] def __init__(self, **apn_args): self.update_keys(apn_args, APS.apns_keys) super(APS, self).__init__(**apn_args) class Payload(BaseMsg): """The whole payload to send to APNs as the request body.""" def __init__(self, aps, **apn_args): self.__setitem__('aps', aps) super(Payload, self).__init__(**apn_args) class Headers(BaseMsg): """The request headers to send to APNs.""" apns_keys = ['authorization', 'apns-id', 'apns-expiration', 'apns-priority', 'apns-topic', 'apns-collapse-id'] def __init__(self, **apn_args): self.update_keys(apn_args, Headers.apns_keys) super(Headers, self).__init__(**apn_args)
# Copyright https://www.globaletraining.com/ # List comprehensions provide a concise way to create lists. my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def main(): final_list = [] for n in my_list: final_list.append(n + 10) print(final_list) # TODO: Using Comprehension final_list_comp1 = [n + 10 for n in my_list] print(final_list_comp1) # TODO: Using Comprehension & condition final_list_comp2 = [n + 10 for n in my_list if n % 2 == 0] print(final_list_comp2) if __name__ == '__main__': main()
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def main(): final_list = [] for n in my_list: final_list.append(n + 10) print(final_list) final_list_comp1 = [n + 10 for n in my_list] print(final_list_comp1) final_list_comp2 = [n + 10 for n in my_list if n % 2 == 0] print(final_list_comp2) if __name__ == '__main__': main()
"""Win animation frames for Mystery Mansion. Animation from: http://www.angelfire.com/ca/mathcool/fireworks.html """ win_animation = [ """ .| | | |'| ._____ ___ | | |. |' .---"| _ .-' '-. | | .--'| || | _| | .-'| _.| | || '-__ | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """, """ .| | | |'| ' ._____ ___ | | . |. |' .---"| _ .-' '-. | | . .--'| || | _| | .-'| _.| | || '-__ | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """, """ .| _\\/_ | | /\\ |'| ' ._____ ___ | | . |. |' .---"| _ .-' '-. | | . .--'| || | _| | .-'| _.| | || '-__ | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """, """ * * .| *_\\/_* | | * /\\ * |'| * * ._____ ___ | | |. |' .---"| _ .-' '-. | | .--'| || | _| | .-'| _.| | || '-__ | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """, """ * * .| * * | | * * _\\/_ _\\/_ |'| * * /\\ ._____ /\\ ___ | | |. |' .---"| _ .-' '-. | | .--'| || | _| | .-'| _.| | || '-__ | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """, """ * * _\\/_ .| * * .::. .''. /\\ | | * :_\\/_: :_\\/_: |'| * * : /\\ :_____ : /\\ :___ | | o '::'|. |' .---"| _ '..-' '-. | | .--'| || | _| | .-'| _.| | || '-__ | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """, """ .''. * :_\\/_: .| .::. .''.: /\\ : | | : : : :'..' |'| \\'/ : :_____ : :___ | | = o = '::'|. |' .---"| _ '..-' '-. | | /.\\.--'| || | _| | .-'| _.| | || '-__ | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """, """ _\\)/_ .''. /(\\ : : .| _\\/_ .''.: : | | : /\\ : :'..' |'|'.\\'/.' ._____ : :___ | |-= o =- |. |' .---"| _ '..-' '-. | |.'/.\\:--'| || | _| | .-'| _.| | || '-__: | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """, """ . _\\)/_ .''. /(\\ .''. : : .| ' :_\\/_: : : | | : : /\\ : '..' |'|'. ' .' '..'._____ ___ | |-= =- |. |' .---"| _ .-' '-. | |.' . :--'| || | _| | .-'| _.| | || '-__: | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """, """ _\\/_ .''. /\\ .| : : | | : : |'| '..'._____ ___ | | |. |' .---"| _ .-' '-. | | :--'| || | _| | .-'| _.| | || '-__: | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """, """ \\'/ * * = o = *_\\/_* /.\\ .''. * /\\ * .| : : * * | | : : |'| '..'._____ ___ | | |. |' .---"| _ .-' '-. | | :--'| || | _| | .-'| _.| | || '-__: | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """, """ '.\\'/.' * * -= o =- * * .'/.\\'. * * .| : * * | | |'| ._____ ___ | | |. |' .---"| _ .-' '-. | | :--'| || | _| | .-'| _.| | || '-__: | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """, """ '.\\'/.' -= =- o .'/.\\'. o .| : | | .:. |'| ':' ._____ ___ | | |. |' .---"| _ .-' '-. | | :--'| || | _| | .-'| _.| | || '-__: | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """, """ '. ' .' \\'/ - - \\'/ = o = .' . '. = o = /.\\ .| : .:::. /.\\ | | ::::::: |'| ':::'_____ ___ | | |. |' .---"| _ .-' '-. | | :--'| || | _| | .-'| _.| | || '-__: | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """, """ : : '.\\'/.' '.\\'/.'-= o =- .:::. -= o =-.'/.\\'..| ::::::: .'/.\\'. : | | ::::::: : |'| ':::'_____ ___ | | |. |' .---"| _ .-' '-. | | :--'| || | _| | .-'| _.| | || '-__: | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """, """ : : '.\\'/.' '.\\'/.'-= =- * .:::. -= =-.'/.\\'..| ::' ':: .'/.\\'. : | | ::. .:: : |'| ':::'_____ ___ | | |. |' .---"| _ .-' '-. | | :--'| || | _| | .-'| _.| | || '-__: | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """, """ : . : '. ' .' _\\)/_ '. ' .'- - /(\\ .'''. - -.' . '..| ' : : .' . '. : | | : : : |'| '...'_____ ___ | | |. |' .---"| _ .-' '-. | | :--'| || | _| | .-'| _.| | || '-__: | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """, """ . _\\)/_ _\\/_ /(\\ _\\/_ /\\ .| ' /\\ | | |'| ._____ ___ | | |. |' .---"| _ .-' '-. | | :--'| || | _| | .-'| _.| | || '-__: | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """, """ . .''. _\\)/_ .''. :_\\/_: /(\\ :_\\/_:: /\\ : .| ' : /\\ : '..' o | | '..' |'| ._____ ___ | | |. |' .---"| _ .-' '-. | | :--'| || | _| | .-'| _.| | || '-__: | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """, """ .''. .''. : : _\\/_ : :: : \\'/ .| /\\ : : '..' = o = | | _\\/_ '..' /.\\ |'| /\\ ._____ ___ | | |. |' .---"| _ .-' '-. | | :--'| || | _| | .-'| _.| | || '-__: | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """, """ .''. : :_\\/_: '.\\'/.' .| : /\\.:'. -= o =- | | '.:_\\/_: .'/.\\'. |'| : /\\ : ._____ :__ | | '..' |. |' .---"| _ .-' '-. | | :--'| || | _| | .-'| _.| | || '-__: | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """, """ .''. : : : '.\\'/.' .| : .:'. -= =- | | '.: : .'/.\\'. |'| : : ._____ :__ | | '..' |. |' .---"| _ .-' '-. | | :--'| || | _| | .-'| _.| | || '-__: | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """, """ .''. : : : '. ' .' .| : .:'. - - | | '.: : .' . '. |'| : : ._____ :__ | | '..' |. |' .---"| _ .-' '-. | | :--'| || | _| | .-'| _.| | || '-__: | | | || | |' | |. | || | | | | || | ___| '-' ' "" '-' '-.' '` |____ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """]
"""Win animation frames for Mystery Mansion. Animation from: http://www.angelfire.com/ca/mathcool/fireworks.html """ win_animation = ['\n\n\n\n\n .|\n | |\n |\'| ._____\n ___ | | |. |\' .---"|\n _ .-\' \'-. | | .--\'| || | _| |\n .-\'| _.| | || \'-__ | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n', '\n\n\n\n\n .|\n | |\n |\'| \' ._____\n ___ | | . |. |\' .---"|\n _ .-\' \'-. | | . .--\'| || | _| |\n .-\'| _.| | || \'-__ | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n', '\n\n\n\n\n .| _\\/_\n | | /\\\n |\'| \' ._____\n ___ | | . |. |\' .---"|\n _ .-\' \'-. | | . .--\'| || | _| |\n .-\'| _.| | || \'-__ | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n', '\n\n\n\n * *\n .| *_\\/_*\n | | * /\\ *\n |\'| * * ._____\n ___ | | |. |\' .---"|\n _ .-\' \'-. | | .--\'| || | _| |\n .-\'| _.| | || \'-__ | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n', '\n\n\n\n * *\n .| * *\n | | * * _\\/_\n _\\/_ |\'| * * /\\ ._____\n /\\ ___ | | |. |\' .---"|\n _ .-\' \'-. | | .--\'| || | _| |\n .-\'| _.| | || \'-__ | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n', '\n\n\n\n * *\n _\\/_ .| * * .::.\n .\'\'. /\\ | | * :_\\/_:\n :_\\/_: |\'| * * : /\\ :_____\n : /\\ :___ | | o \'::\'|. |\' .---"|\n _ \'..-\' \'-. | | .--\'| || | _| |\n .-\'| _.| | || \'-__ | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n', '\n\n\n\n .\'\'. *\n :_\\/_: .| .::.\n .\'\'.: /\\ : | | : :\n : :\'..\' |\'| \\\'/ : :_____\n : :___ | | = o = \'::\'|. |\' .---"|\n _ \'..-\' \'-. | | /.\\.--\'| || | _| |\n .-\'| _.| | || \'-__ | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n', '\n\n\n _\\)/_\n .\'\'. /(\\\n : : .| _\\/_\n .\'\'.: : | | : /\\\n : :\'..\' |\'|\'.\\\'/.\' ._____\n : :___ | |-= o =- |. |\' .---"|\n _ \'..-\' \'-. | |.\'/.\\:--\'| || | _| |\n .-\'| _.| | || \'-__: | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n', '\n\n .\n _\\)/_\n .\'\'. /(\\ .\'\'.\n : : .| \' :_\\/_:\n : : | | : : /\\ :\n \'..\' |\'|\'. \' .\' \'..\'._____\n ___ | |-= =- |. |\' .---"|\n _ .-\' \'-. | |.\' . :--\'| || | _| |\n .-\'| _.| | || \'-__: | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n', '\n\n\n\n _\\/_ .\'\'.\n /\\ .| : :\n | | : :\n |\'| \'..\'._____\n ___ | | |. |\' .---"|\n _ .-\' \'-. | | :--\'| || | _| |\n .-\'| _.| | || \'-__: | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n', '\n\n \\\'/\n * * = o =\n *_\\/_* /.\\ .\'\'.\n * /\\ * .| : :\n * * | | : :\n |\'| \'..\'._____\n ___ | | |. |\' .---"|\n _ .-\' \'-. | | :--\'| || | _| |\n .-\'| _.| | || \'-__: | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n', '\n\n \'.\\\'/.\'\n * * -= o =-\n * * .\'/.\\\'.\n * * .| :\n * * | |\n |\'| ._____\n ___ | | |. |\' .---"|\n _ .-\' \'-. | | :--\'| || | _| |\n .-\'| _.| | || \'-__: | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n', '\n\n \'.\\\'/.\'\n -= =-\n o .\'/.\\\'.\n o .| :\n | | .:.\n |\'| \':\' ._____\n ___ | | |. |\' .---"|\n _ .-\' \'-. | | :--\'| || | _| |\n .-\'| _.| | || \'-__: | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n', '\n\n \'. \' .\'\n \\\'/ - -\n \\\'/ = o = .\' . \'.\n = o = /.\\ .| : .:::.\n /.\\ | | :::::::\n |\'| \':::\'_____\n ___ | | |. |\' .---"|\n _ .-\' \'-. | | :--\'| || | _| |\n .-\'| _.| | || \'-__: | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n', '\n\n :\n : \'.\\\'/.\'\n \'.\\\'/.\'-= o =- .:::.\n -= o =-.\'/.\\\'..| :::::::\n .\'/.\\\'. : | | :::::::\n : |\'| \':::\'_____\n ___ | | |. |\' .---"|\n _ .-\' \'-. | | :--\'| || | _| |\n .-\'| _.| | || \'-__: | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n', '\n\n :\n : \'.\\\'/.\'\n \'.\\\'/.\'-= =- * .:::.\n -= =-.\'/.\\\'..| ::\' \'::\n .\'/.\\\'. : | | ::. .::\n : |\'| \':::\'_____\n ___ | | |. |\' .---"|\n _ .-\' \'-. | | :--\'| || | _| |\n .-\'| _.| | || \'-__: | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n', '\n\n : .\n : \'. \' .\' _\\)/_\n \'. \' .\'- - /(\\ .\'\'\'.\n - -.\' . \'..| \' : :\n .\' . \'. : | | : :\n : |\'| \'...\'_____\n ___ | | |. |\' .---"|\n _ .-\' \'-. | | :--\'| || | _| |\n .-\'| _.| | || \'-__: | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n', '\n\n .\n _\\)/_ _\\/_\n /(\\ _\\/_ /\\\n .| \' /\\\n | |\n |\'| ._____\n ___ | | |. |\' .---"|\n _ .-\' \'-. | | :--\'| || | _| |\n .-\'| _.| | || \'-__: | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n', '\n\n . .\'\'.\n _\\)/_ .\'\'. :_\\/_:\n /(\\ :_\\/_:: /\\ :\n .| \' : /\\ : \'..\'\n o | | \'..\'\n |\'| ._____\n ___ | | |. |\' .---"|\n _ .-\' \'-. | | :--\'| || | _| |\n .-\'| _.| | || \'-__: | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n', '\n\n .\'\'.\n .\'\'. : :\n _\\/_ : :: :\n \\\'/ .| /\\ : : \'..\'\n = o = | | _\\/_ \'..\'\n /.\\ |\'| /\\ ._____\n ___ | | |. |\' .---"|\n _ .-\' \'-. | | :--\'| || | _| |\n .-\'| _.| | || \'-__: | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n', '\n\n\n .\'\'.\n : :_\\/_:\n \'.\\\'/.\' .| : /\\.:\'.\n -= o =- | | \'.:_\\/_:\n .\'/.\\\'. |\'| : /\\ : ._____\n :__ | | \'..\' |. |\' .---"|\n _ .-\' \'-. | | :--\'| || | _| |\n .-\'| _.| | || \'-__: | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n', '\n\n\n .\'\'.\n : : :\n \'.\\\'/.\' .| : .:\'.\n -= =- | | \'.: :\n .\'/.\\\'. |\'| : : ._____\n :__ | | \'..\' |. |\' .---"|\n _ .-\' \'-. | | :--\'| || | _| |\n .-\'| _.| | || \'-__: | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n', '\n\n\n .\'\'.\n : : :\n \'. \' .\' .| : .:\'.\n - - | | \'.: :\n .\' . \'. |\'| : : ._____\n :__ | | \'..\' |. |\' .---"|\n _ .-\' \'-. | | :--\'| || | _| |\n .-\'| _.| | || \'-__: | | | || |\n |\' | |. | || | | | | || |\n ___| \'-\' \' "" \'-\' \'-.\' \'` |____\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n']
#!/usr/local/bin/python3 def main(): for i in range(1, 8): print("============================") print("Towers of Hanoi: {} Disks".format(i)) towers_of_hanoi(i) print("Number of moves: {}".format(2**i - 1)) print("============================") return 0 def towers_of_hanoi(n, s="source", t="target", b="buffer"): # n is number of disks, smaller disk must always be on top of larger one assert n > 0 if n == 1: print("Move {} to {}".format(s, t)) return else: # Recursively move n-1 disks from source to buffer towers_of_hanoi(n-1, s, b, t) # Move largest disk from source to target towers_of_hanoi(1, s, t, b) # Recursively move n-1 disks from buffer to target towers_of_hanoi(n-1, b, t, s) if __name__ == '__main__': main()
def main(): for i in range(1, 8): print('============================') print('Towers of Hanoi: {} Disks'.format(i)) towers_of_hanoi(i) print('Number of moves: {}'.format(2 ** i - 1)) print('============================') return 0 def towers_of_hanoi(n, s='source', t='target', b='buffer'): assert n > 0 if n == 1: print('Move {} to {}'.format(s, t)) return else: towers_of_hanoi(n - 1, s, b, t) towers_of_hanoi(1, s, t, b) towers_of_hanoi(n - 1, b, t, s) if __name__ == '__main__': main()
def domino(): """Imprime todas las fichas de domino""" a = 0 b = 0 for k in range (0,7): a = k for i in range (a, 7): b = i print (a, b)
def domino(): """Imprime todas las fichas de domino""" a = 0 b = 0 for k in range(0, 7): a = k for i in range(a, 7): b = i print(a, b)
# -*- coding: utf-8 -*- """PACKAGE INFO This module provides some basic information about the package. """ # Set the package release version version_info = (0, 0, 0) __version__ = '.'.join(str(c) for c in version_info) # Set the package details __author__ = 'Jonah Crawford' __email__ = '[email protected]' __year__ = '2019' __url__ = 'https://github.com/minskmaz/dckrclstrpanic' __description__ = 'Roll panic tests for https://gun.eco' __requires__ = ['sh', 'zope.component'] # Your package dependencies # Default package properties __license__ = 'MIT' __about__ = ('{} \n\n Author: {} \n Email: {} \n Year: {} \n {} \n\n' ''.format(__name__, __author__, __email__, __year__, __description__)) __setup_requires__ = ['pytest-runner', ] __tests_require__ = ['pytest', 'pytest-cov', 'pytest-pep8']
"""PACKAGE INFO This module provides some basic information about the package. """ version_info = (0, 0, 0) __version__ = '.'.join((str(c) for c in version_info)) __author__ = 'Jonah Crawford' __email__ = '[email protected]' __year__ = '2019' __url__ = 'https://github.com/minskmaz/dckrclstrpanic' __description__ = 'Roll panic tests for https://gun.eco' __requires__ = ['sh', 'zope.component'] __license__ = 'MIT' __about__ = '{} \n\n Author: {} \n Email: {} \n Year: {} \n {} \n\n'.format(__name__, __author__, __email__, __year__, __description__) __setup_requires__ = ['pytest-runner'] __tests_require__ = ['pytest', 'pytest-cov', 'pytest-pep8']
# generated from genmsg/cmake/pkg-genmsg.context.in messages_str = "/home/tekmen0/meturone_egitim/src/meturone_egitim/msg/Dummy.msg;/home/tekmen0/meturone_egitim/src/meturone_egitim/msg/answer.msg" services_str = "" pkg_name = "meturone_egitim" dependencies_str = "std_msgs" langs = "gencpp;geneus;genlisp;gennodejs;genpy" dep_include_paths_str = "meturone_egitim;/home/tekmen0/meturone_egitim/src/meturone_egitim/msg;std_msgs;/opt/ros/noetic/share/std_msgs/cmake/../msg" PYTHON_EXECUTABLE = "/usr/bin/python3" package_has_static_sources = '' == 'TRUE' genmsg_check_deps_script = "/opt/ros/noetic/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py"
messages_str = '/home/tekmen0/meturone_egitim/src/meturone_egitim/msg/Dummy.msg;/home/tekmen0/meturone_egitim/src/meturone_egitim/msg/answer.msg' services_str = '' pkg_name = 'meturone_egitim' dependencies_str = 'std_msgs' langs = 'gencpp;geneus;genlisp;gennodejs;genpy' dep_include_paths_str = 'meturone_egitim;/home/tekmen0/meturone_egitim/src/meturone_egitim/msg;std_msgs;/opt/ros/noetic/share/std_msgs/cmake/../msg' python_executable = '/usr/bin/python3' package_has_static_sources = '' == 'TRUE' genmsg_check_deps_script = '/opt/ros/noetic/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py'
XK_Greek_ALPHAaccent = 0x7a1 XK_Greek_EPSILONaccent = 0x7a2 XK_Greek_ETAaccent = 0x7a3 XK_Greek_IOTAaccent = 0x7a4 XK_Greek_IOTAdiaeresis = 0x7a5 XK_Greek_OMICRONaccent = 0x7a7 XK_Greek_UPSILONaccent = 0x7a8 XK_Greek_UPSILONdieresis = 0x7a9 XK_Greek_OMEGAaccent = 0x7ab XK_Greek_accentdieresis = 0x7ae XK_Greek_horizbar = 0x7af XK_Greek_alphaaccent = 0x7b1 XK_Greek_epsilonaccent = 0x7b2 XK_Greek_etaaccent = 0x7b3 XK_Greek_iotaaccent = 0x7b4 XK_Greek_iotadieresis = 0x7b5 XK_Greek_iotaaccentdieresis = 0x7b6 XK_Greek_omicronaccent = 0x7b7 XK_Greek_upsilonaccent = 0x7b8 XK_Greek_upsilondieresis = 0x7b9 XK_Greek_upsilonaccentdieresis = 0x7ba XK_Greek_omegaaccent = 0x7bb XK_Greek_ALPHA = 0x7c1 XK_Greek_BETA = 0x7c2 XK_Greek_GAMMA = 0x7c3 XK_Greek_DELTA = 0x7c4 XK_Greek_EPSILON = 0x7c5 XK_Greek_ZETA = 0x7c6 XK_Greek_ETA = 0x7c7 XK_Greek_THETA = 0x7c8 XK_Greek_IOTA = 0x7c9 XK_Greek_KAPPA = 0x7ca XK_Greek_LAMDA = 0x7cb XK_Greek_LAMBDA = 0x7cb XK_Greek_MU = 0x7cc XK_Greek_NU = 0x7cd XK_Greek_XI = 0x7ce XK_Greek_OMICRON = 0x7cf XK_Greek_PI = 0x7d0 XK_Greek_RHO = 0x7d1 XK_Greek_SIGMA = 0x7d2 XK_Greek_TAU = 0x7d4 XK_Greek_UPSILON = 0x7d5 XK_Greek_PHI = 0x7d6 XK_Greek_CHI = 0x7d7 XK_Greek_PSI = 0x7d8 XK_Greek_OMEGA = 0x7d9 XK_Greek_alpha = 0x7e1 XK_Greek_beta = 0x7e2 XK_Greek_gamma = 0x7e3 XK_Greek_delta = 0x7e4 XK_Greek_epsilon = 0x7e5 XK_Greek_zeta = 0x7e6 XK_Greek_eta = 0x7e7 XK_Greek_theta = 0x7e8 XK_Greek_iota = 0x7e9 XK_Greek_kappa = 0x7ea XK_Greek_lamda = 0x7eb XK_Greek_lambda = 0x7eb XK_Greek_mu = 0x7ec XK_Greek_nu = 0x7ed XK_Greek_xi = 0x7ee XK_Greek_omicron = 0x7ef XK_Greek_pi = 0x7f0 XK_Greek_rho = 0x7f1 XK_Greek_sigma = 0x7f2 XK_Greek_finalsmallsigma = 0x7f3 XK_Greek_tau = 0x7f4 XK_Greek_upsilon = 0x7f5 XK_Greek_phi = 0x7f6 XK_Greek_chi = 0x7f7 XK_Greek_psi = 0x7f8 XK_Greek_omega = 0x7f9 XK_Greek_switch = 0xFF7E
xk__greek_alph_aaccent = 1953 xk__greek_epsilo_naccent = 1954 xk__greek_et_aaccent = 1955 xk__greek_iot_aaccent = 1956 xk__greek_iot_adiaeresis = 1957 xk__greek_omicro_naccent = 1959 xk__greek_upsilo_naccent = 1960 xk__greek_upsilo_ndieresis = 1961 xk__greek_omeg_aaccent = 1963 xk__greek_accentdieresis = 1966 xk__greek_horizbar = 1967 xk__greek_alphaaccent = 1969 xk__greek_epsilonaccent = 1970 xk__greek_etaaccent = 1971 xk__greek_iotaaccent = 1972 xk__greek_iotadieresis = 1973 xk__greek_iotaaccentdieresis = 1974 xk__greek_omicronaccent = 1975 xk__greek_upsilonaccent = 1976 xk__greek_upsilondieresis = 1977 xk__greek_upsilonaccentdieresis = 1978 xk__greek_omegaaccent = 1979 xk__greek_alpha = 1985 xk__greek_beta = 1986 xk__greek_gamma = 1987 xk__greek_delta = 1988 xk__greek_epsilon = 1989 xk__greek_zeta = 1990 xk__greek_eta = 1991 xk__greek_theta = 1992 xk__greek_iota = 1993 xk__greek_kappa = 1994 xk__greek_lamda = 1995 xk__greek_lambda = 1995 xk__greek_mu = 1996 xk__greek_nu = 1997 xk__greek_xi = 1998 xk__greek_omicron = 1999 xk__greek_pi = 2000 xk__greek_rho = 2001 xk__greek_sigma = 2002 xk__greek_tau = 2004 xk__greek_upsilon = 2005 xk__greek_phi = 2006 xk__greek_chi = 2007 xk__greek_psi = 2008 xk__greek_omega = 2009 xk__greek_alpha = 2017 xk__greek_beta = 2018 xk__greek_gamma = 2019 xk__greek_delta = 2020 xk__greek_epsilon = 2021 xk__greek_zeta = 2022 xk__greek_eta = 2023 xk__greek_theta = 2024 xk__greek_iota = 2025 xk__greek_kappa = 2026 xk__greek_lamda = 2027 xk__greek_lambda = 2027 xk__greek_mu = 2028 xk__greek_nu = 2029 xk__greek_xi = 2030 xk__greek_omicron = 2031 xk__greek_pi = 2032 xk__greek_rho = 2033 xk__greek_sigma = 2034 xk__greek_finalsmallsigma = 2035 xk__greek_tau = 2036 xk__greek_upsilon = 2037 xk__greek_phi = 2038 xk__greek_chi = 2039 xk__greek_psi = 2040 xk__greek_omega = 2041 xk__greek_switch = 65406
#moveable_player class MoveablePlayer: def __init__(self, x=2, y=2, dir="FORWARD", color="170"): self.x = x self.y = y self.direction = dir self.color = color
class Moveableplayer: def __init__(self, x=2, y=2, dir='FORWARD', color='170'): self.x = x self.y = y self.direction = dir self.color = color
# ============================================================================================= # # ============================================================================================= # # 2 16 20 3 4 21 # GPIO Pin number # | | | | | | # -----|-----|-----|-----|-----|-----|----- # 12 11 10 9 8 7 # Display Pin number # 1 a f 2 3 b # Segment/Digit Identifier # # # e d h c g 4 # Segment/Digit Identifier # 1 2 3 4 5 6 # Display Pin number # -----|-----|-----|-----|-----|-----|----- # 5 6 13 19 20 17 # GPIO Pin number # digits = [2,3,4,17] One = [2] Two = [3] Three = [4] Four = [17]
digits = [2, 3, 4, 17] one = [2] two = [3] three = [4] four = [17]
# -*- coding: utf-8 -*- class Trial(object): ''' Created Fri 2 Aug 2013 - ajl Last edited: Sun 4 Aug 2013 - ajl This class contains all variables and methods associated with a single trial ''' def __init__(self, trialid = 0, staircaseid = 0, condition = 0, stimval = 0, interval = 1): ''' Constructor ''' self._TrialID = trialid; self._StaircaseID = staircaseid; self._Condition = condition; self._Stimval = stimval; self._Interval = interval; self._Response = None; self._ReactionTime = None; # show the values of this specific trial def __str__(self): return '#%2.f \t %2.f \t %2.f' % (self._TrialID, self._StaircaseID, self._Stimval); # s = '[ #%2.f ] \t (%.f) \t\t Stim(%4.f) \t Interval(%.f) \t Resp(%.f)' % \ # (self._TrialID+1, self._Condition, self._Stimval, self._Interval, self._Response) ''' Fields or properties ''' @property def Response(self): return self._Response; @Response.setter def Response(self, value): self._Response = value; ''' Methods ''' # returns the name of the current condition def GetConditionName(self): # this is really quite awkward return
class Trial(object): """ Created Fri 2 Aug 2013 - ajl Last edited: Sun 4 Aug 2013 - ajl This class contains all variables and methods associated with a single trial """ def __init__(self, trialid=0, staircaseid=0, condition=0, stimval=0, interval=1): """ Constructor """ self._TrialID = trialid self._StaircaseID = staircaseid self._Condition = condition self._Stimval = stimval self._Interval = interval self._Response = None self._ReactionTime = None def __str__(self): return '#%2.f \t %2.f \t %2.f' % (self._TrialID, self._StaircaseID, self._Stimval) ' Fields or properties ' @property def response(self): return self._Response @Response.setter def response(self, value): self._Response = value ' Methods ' def get_condition_name(self): return
## Q2: What is the time complexity of ## O(n), porque es un for de i=n hasta i=1 # Algoritmo # for (i = n; i > 0; i--) { # n # statement; # 1 # } n = 5 for i in range(n, 0, -1): # n print(i); # 1
n = 5 for i in range(n, 0, -1): print(i)
# pylint: disable=redefined-outer-name,protected-access # pylint: disable=missing-function-docstring,missing-module-docstring,missing-class-docstring def test_can_construct_author(author): assert isinstance(author.name, str) assert isinstance(author.url, str) assert isinstance(author.github_url, str) assert isinstance(author.github_avatar_url, str) assert str(author) == author.name assert repr(author) == author.name assert author._repr_html_(width="21x", height="22px") == ( '<a href="https://github.com/holoviz/" title="Author: panel" target="_blank">' '<img application="https://avatars2.githubusercontent.com/u/51678735" alt="panel" ' 'style="border-radius: 50%;width: 21x;height: 22px;vertical-align: text-bottom;">' "</img></a>" )
def test_can_construct_author(author): assert isinstance(author.name, str) assert isinstance(author.url, str) assert isinstance(author.github_url, str) assert isinstance(author.github_avatar_url, str) assert str(author) == author.name assert repr(author) == author.name assert author._repr_html_(width='21x', height='22px') == '<a href="https://github.com/holoviz/" title="Author: panel" target="_blank"><img application="https://avatars2.githubusercontent.com/u/51678735" alt="panel" style="border-radius: 50%;width: 21x;height: 22px;vertical-align: text-bottom;"></img></a>'
# ------------------------------------------------------------------------------ # Program: The LDAR Simulator (LDAR-Sim) # File: LDAR-Sim input mapper sample # Purpose: Example input mapper # # Copyright (C) 2018-2021 Intelligent Methane Monitoring and Management System (IM3S) Group # # This program is free software: you can redistribute it and/or modify # it under the terms of the MIT License as published # by the Free Software Foundation, version 3. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MIT License for more details. # You should have received a copy of the MIT License # along with this program. If not, see <https://opensource.org/licenses/MIT>. # # ------------------------------------------------------------------------------ def input_mapper_v1(parameters): """Function to perform all input mapping from version 1.0 parameter files to presently compliant parameter files. This is necessary to ensure reverse compatibility - to allow older parameter files to run properly. **** THIS IS AN EXAMPLE FILE THAT IS PROVIDED AS A TEMPLATE **** This function is a series of hooks that fall into several categories: 1) Construction hooks: these hooks construct newer parameters from older parameters. This is necessary if parameters were depreciated in the newest version of the model, but relied upon in older versions. For example, newer versions of the program may simply allow specification of a start and end date, but not include specification of the number of timesteps. To allow this, a construction hook could create start and end date from the number of timesteps using any necessary rules to maintain compatibility. 2) Destruction hooks: these hooks destruct parameters that are no longer in the default set of parameters in the model. To continue the above example, if the present version of the model does not use number of timesteps, and the number of timesteps is no longer specified in the default parameter file - that key should be removed. The issue here is without destruction of depreciated parameters - this parameter file will fail validation. Of course, destruction must be called AFTER construction so the information in the depreciated parameters is used to map to the new parameters before being deleted! 3) Recalculation hooks: these hooks recalculate variables or map the values. For example, if the units have changed, but the key has not - these hooks are necessary to recalculate the new units to be compliant with the present version of the model. If the older version of the model had a spelling mistake in a string specification, this type of hook would map the parameters. Several examples: # map a old spelling mistake properly - the present version of LDAR Sim has corrected the # spelling mistake but old parameter files continue to use the misspelled value if parameters['calculation_method'] == 'categoricle': parameters['calculation_method'] = 'categorical' # map the leak rate parameter from one unit to another, the newest version uses a different # unit, where 0.003332 is the conversion factor parameters['leak_rate] = parameters['leak_rate'] * 0.003332 4) Key-change hooks: these hooks change the key name to a new key name to map the old name to the new name. :param parameters = a dictionary of parameters that must be mapped to a compliant version :return returns a model compliant parameter file dictionary and global parameter file (see notes in code). In cases where the global parameters are not returned, the global parameters are returned as an empty dictionary """ # ---------------------------------------------------------------------------------------------- # 1. Construction hooks # NOTES: Version 1.0 parameter files used to create global parameters by pulling some parameters # from the P_ref program. Thus, this function returns global parameters as well as the # parameters dictionary under analysis. There were no global parameters in v1.0. They # were defined inline in the code. # Version 1.0 files are all program files # if 'parameter_level' not in parameters: # parameters['parameter_level'] = 'program' # Set version # if 'version' not in parameters: # parameters['version'] = '1.0' # Check if this is P_ref, if so, mine the global parameters mined_global_parameters = {} # parameters_to_make_global = ['n_simulations', 'timesteps', 'start_year', 'weather_file', # 'print_from_simulations', 'write_data'] # if parameters['program_name'] == 'P_ref': # for i in parameters_to_make_global: # mined_global_parameters[i] = parameters[i] # Construct a programs key # mined_global_parameters['programs'] = [] # ---------------------------------------------------------------------------------------------- # 2. Destruction hooks # Delete the parameters that are now globals from this program definition - these do nothing # for i in parameters_to_make_global: # _ = parameters.pop(i) # ---------------------------------------------------------------------------------------------- # 3. Recalculation hooks pass # ---------------------------------------------------------------------------------------------- # 4. Key-change hooks pass return(parameters, mined_global_parameters)
def input_mapper_v1(parameters): """Function to perform all input mapping from version 1.0 parameter files to presently compliant parameter files. This is necessary to ensure reverse compatibility - to allow older parameter files to run properly. **** THIS IS AN EXAMPLE FILE THAT IS PROVIDED AS A TEMPLATE **** This function is a series of hooks that fall into several categories: 1) Construction hooks: these hooks construct newer parameters from older parameters. This is necessary if parameters were depreciated in the newest version of the model, but relied upon in older versions. For example, newer versions of the program may simply allow specification of a start and end date, but not include specification of the number of timesteps. To allow this, a construction hook could create start and end date from the number of timesteps using any necessary rules to maintain compatibility. 2) Destruction hooks: these hooks destruct parameters that are no longer in the default set of parameters in the model. To continue the above example, if the present version of the model does not use number of timesteps, and the number of timesteps is no longer specified in the default parameter file - that key should be removed. The issue here is without destruction of depreciated parameters - this parameter file will fail validation. Of course, destruction must be called AFTER construction so the information in the depreciated parameters is used to map to the new parameters before being deleted! 3) Recalculation hooks: these hooks recalculate variables or map the values. For example, if the units have changed, but the key has not - these hooks are necessary to recalculate the new units to be compliant with the present version of the model. If the older version of the model had a spelling mistake in a string specification, this type of hook would map the parameters. Several examples: # map a old spelling mistake properly - the present version of LDAR Sim has corrected the # spelling mistake but old parameter files continue to use the misspelled value if parameters['calculation_method'] == 'categoricle': parameters['calculation_method'] = 'categorical' # map the leak rate parameter from one unit to another, the newest version uses a different # unit, where 0.003332 is the conversion factor parameters['leak_rate] = parameters['leak_rate'] * 0.003332 4) Key-change hooks: these hooks change the key name to a new key name to map the old name to the new name. :param parameters = a dictionary of parameters that must be mapped to a compliant version :return returns a model compliant parameter file dictionary and global parameter file (see notes in code). In cases where the global parameters are not returned, the global parameters are returned as an empty dictionary """ mined_global_parameters = {} pass pass return (parameters, mined_global_parameters)
#%% VARIABLES 'Variables' # var1 = 10 # var2 = "Hello World" # var3 = None # var4 = 3.5 # if 0: # print ("hello world 0") #el 0 fnciona como Falsey # if 1: # print ("hello world 1") #el 1 funciona como Truthy # x1 = 100 # x2 = 20 # x3 = -5 # y = x1 + x2 + x3 # z = x1 - x2 * x3 # w = (x1+x2+x3) - (x1-x2*x3) # num = 23 # data = True # var = 40.0 # res1 = num + data # res2 = data/var # res3 = num*var # num = 23 # data = False # var = 40.0 # res1 = num + data # res2 = data/var # res3 = num*var # result = 70 # data = False # value = '158' # var1 = result*data # var2 = data+value # var3 = result/value # result = 5 # value = '158' # location = 'payunia' # name = 'Mike ' # phrase = 'needs a coffee' # full_phrase = name + phrase # extended_phrase = full_phrase + ' urgente!' # subnet = '192.168.0' # host = '34' # ip = subnet + '.' + host # message = 'IP address: ' + ip #%% ACTIVIDADES 'Actividad 1' a = 50 b = 6 c = 8 d = 2*a + 1/(b-5*c) d1 = ((a*b+c)/(2-a) + ((a*b+c)/(2-a) + 2)/(c+b)) * (1 + (a*b+c)/(2-a)) 'Actividad 2' # word0 = 'Life' # word1 = 'ocean' # word2 = 'up' # word3 = 'down' # word4 = word0 + ' is like the ' + word1 + ", it goes " + word2 +\ # " and " + word3 word0 ='Mars' word1 = 'Earth' word2 = 'round' word3 = 'round' word4 = word0 + ' is like the ' + word1 + ", it goes " + word2 +\ " and " + word3
"""Variables""" 'Actividad 1' a = 50 b = 6 c = 8 d = 2 * a + 1 / (b - 5 * c) d1 = ((a * b + c) / (2 - a) + ((a * b + c) / (2 - a) + 2) / (c + b)) * (1 + (a * b + c) / (2 - a)) 'Actividad 2' word0 = 'Mars' word1 = 'Earth' word2 = 'round' word3 = 'round' word4 = word0 + ' is like the ' + word1 + ', it goes ' + word2 + ' and ' + word3
# Given inorder and postorder traversal of a tree, construct the binary tree. # Note: # You may assume that duplicates do not exist in the tree. # For example, given # inorder = [9,3,15,20,7] # postorder = [9,15,7,20,3] # Return the following binary tree: # 3 # / \ # 9 20 # / \ # 15 7 # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def buildTree(self, inorder, postorder): """ :type inorder: List[int] :type postorder: List[int] :rtype: TreeNode """ if not inorder or not postorder or len(inorder) == 0 or len(postorder) == 0: return None else: index = inorder.index(postorder[-1]) root = TreeNode(inorder[index]) root.left = self.buildTree(inorder[:index], postorder[:index]) root.right = self.buildTree(inorder[index+1:], postorder[index:-1]) return root # Time:O(n) # Space: O(n) # Difficulty: medium
class Solution(object): def build_tree(self, inorder, postorder): """ :type inorder: List[int] :type postorder: List[int] :rtype: TreeNode """ if not inorder or not postorder or len(inorder) == 0 or (len(postorder) == 0): return None else: index = inorder.index(postorder[-1]) root = tree_node(inorder[index]) root.left = self.buildTree(inorder[:index], postorder[:index]) root.right = self.buildTree(inorder[index + 1:], postorder[index:-1]) return root
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Help text and other strings used in the Drive module. """ __author__ = [ '[email protected] (Nick Retallack)', ] SERVICE_ACCOUNT_JSON_DESCRIPTION = """ Create a service account in Google App Engine and paste the JSON here. """ SERVICE_ACCOUNT_JSON_PARSE_FAILURE = """ The JSON is invalid. Make sure you copy the whole thing including any curly braces. Do not use the P12 format.""" SERVICE_ACCOUNT_JSON_MISSING_FIELDS = """ The JSON is valid but it doesn't look like a service account key. Try creating a new "Service account key" in the Credentials section of the developer console. You can only download this JSON when you first create the key. You can't use the "Download JSON" button later as this will not include the key.""" SYNC_FREQUENCY_DESCRIPTION = """ The document will be checked for changes in Google Drive this often. """ AVAILABILITY_DESCRIPTION = """ Synced items default to the availability of the course, but may also be restricted to admins (Private) or open to the public (Public). """ SHARE_PERMISSION_ERROR = """ You do not have permission to share this file. """ SHARE_UNKNOWN_ERROR = """ An unknown error occurred when sharing this file. Check your Drive or Google API configuration or try again. """ SHARE_META_ERROR = """ File shared, but Drive API failed to fetch metadata. Please try again or check your Drive configuration. """ TIMEOUT_ERROR = """ Google Drive timed out. Please try again. """
""" Help text and other strings used in the Drive module. """ __author__ = ['[email protected] (Nick Retallack)'] service_account_json_description = '\nCreate a service account in Google App Engine and paste the JSON here.\n' service_account_json_parse_failure = '\nThe JSON is invalid. Make sure you copy the whole thing including any curly\nbraces. Do not use the P12 format.' service_account_json_missing_fields = '\nThe JSON is valid but it doesn\'t look like a service account key. Try creating a\nnew "Service account key" in the Credentials section of the developer console.\nYou can only download this JSON when you first create the key. You can\'t use\nthe "Download JSON" button later as this will not include the key.' sync_frequency_description = '\nThe document will be checked for changes in Google Drive this often.\n' availability_description = '\nSynced items default to the availability of the course, but may also be\nrestricted to admins (Private) or open to the public (Public).\n' share_permission_error = '\nYou do not have permission to share this file.\n' share_unknown_error = '\nAn unknown error occurred when sharing this file. Check your Drive or Google\nAPI configuration or try again.\n' share_meta_error = '\nFile shared, but Drive API failed to fetch metadata. Please try again or check\nyour Drive configuration.\n' timeout_error = '\nGoogle Drive timed out. Please try again.\n'
# Time: O(m * n) # Space: O(1) class Solution(object): def findDiagonalOrder(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ if not matrix or not matrix[0]: return [] result = [] row, col, d = 0, 0, 0 dirs = [(-1, 1), (1, -1)] for i in range(len(matrix) * len(matrix[0])): result.append(matrix[row][col]) row += dirs[d][0] col += dirs[d][1] if row >= len(matrix): row = len(matrix) - 1 col += 2 d = 1 - d elif col >= len(matrix[0]): col = len(matrix[0]) - 1 row += 2 d = 1 - d elif row < 0: row = 0 d = 1 - d elif col < 0: col = 0 d = 1 - d return result
class Solution(object): def find_diagonal_order(self, matrix): """ :type matrix: List[List[int]] :rtype: List[int] """ if not matrix or not matrix[0]: return [] result = [] (row, col, d) = (0, 0, 0) dirs = [(-1, 1), (1, -1)] for i in range(len(matrix) * len(matrix[0])): result.append(matrix[row][col]) row += dirs[d][0] col += dirs[d][1] if row >= len(matrix): row = len(matrix) - 1 col += 2 d = 1 - d elif col >= len(matrix[0]): col = len(matrix[0]) - 1 row += 2 d = 1 - d elif row < 0: row = 0 d = 1 - d elif col < 0: col = 0 d = 1 - d return result
class PingPacket: def __init__(self): self.type = "PING" self.serial = 0 def read(self, reader): self.serial = reader.readInt32()
class Pingpacket: def __init__(self): self.type = 'PING' self.serial = 0 def read(self, reader): self.serial = reader.readInt32()
n = int(input()) for teste in range(n): m = int(input()) lista = [int(x) for x in input().split()] impares = [] for x in lista: if x%2 == 1: impares.append(x) impares.sort() laercio = [] while len(impares) > 0: laercio.append(impares.pop()) impares.reverse() print(*laercio)
n = int(input()) for teste in range(n): m = int(input()) lista = [int(x) for x in input().split()] impares = [] for x in lista: if x % 2 == 1: impares.append(x) impares.sort() laercio = [] while len(impares) > 0: laercio.append(impares.pop()) impares.reverse() print(*laercio)
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- class ProjectFailed(object): def __init__(self, message): self.valid = False self.message = message
class Projectfailed(object): def __init__(self, message): self.valid = False self.message = message
"""Define nodejs and yarn dependencies""" load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") http_archive( name = "build_bazel_rules_nodejs", sha256 = "a09edc4ba3931a856a5ac6836f248c302d55055d35d36e390a0549799c33145b", urls = ["https://github.com/bazelbuild/rules_nodejs/releases/download/5.0.0/rules_nodejs-5.0.0.tar.gz"], )
"""Define nodejs and yarn dependencies""" load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive') http_archive(name='build_bazel_rules_nodejs', sha256='a09edc4ba3931a856a5ac6836f248c302d55055d35d36e390a0549799c33145b', urls=['https://github.com/bazelbuild/rules_nodejs/releases/download/5.0.0/rules_nodejs-5.0.0.tar.gz'])
class Matrix: def __init__(self, *args, **kwargs): if len(args) > 0: if isinstance(args[0], Matrix): m = args[0].copy() else: m = {'vals': [], 'w': 0, 'h': 0} self.vals = m.vals self.w = m.w self.h = m.h def copy(self): new_m = Matrix() for i in self.vals: new_m.vals.append(i) new_m.w = self.w new_m.h = self.h return new_m @property def width(self): return self.w @property def height(self): return self.h def value_at(self, row, col): return self.vals[row*self.w + col] def at(self, row, col): return self.value_at(row, col) def row(self, pos): return [self.vals[pos*self.w + i] for i in range(self.w)] @property def rows(self): return [self.row(i) for i in range(self.h)] def col(self, pos): return [self.vals[i*self.w + pos] for i in range(self.h)] @property def cols(self): return [self.col(i) for i in range(self.w)] @staticmethod def _isnumeric(i): return isinstance(i, float) or isinstance(i, int) def _add(self, r, p, q, *args): r = len(args) if r <= 0 else r for i in range(r): try: if self._isnumeric(args[i]): self.vals.insert(i*(p + 1) + self.w*q, args[i]) except IndexError: self.vals.insert(i*(p + 1) + self.w*q, 0) return r def addrow(self, *args): self.w = self._add(self.w, 0, self.h, *args) self.h += 1 def addcol(self, *args): self.h = self._add(self.h, self.w, 1, *args) self.w += 1 def _fill(self, val, pos, r, lt, p, q, addfunc): if self._isnumeric(val): if pos < lt: for i in range(self.w): self.vals[pos*p + i*q] = val else: addfunc(*[val for _ in range(r)]) def rowfill(self, val, pos): self._fill(val, pos, self.w, self.h, self.w, 1, self.addrow) def colfill(self, val, pos): self._fill(val, pos, self.h, self.w, 1, self.w, self.addcol) def removerow(self, pos): if self.h > 0 and pos < self.h: for _ in range(self.w): self.vals.pop(self.w*pos) self.h -= 1 if self.h == 0: self.w = 0 def removecol(self, pos): if self.w > 0 and pos < self.w: pos %= self.w for i in range(self.h): self.vals.pop(i*(self.w-1) + pos) self.w -= 1 if self.w == 0: self.h = 0 def __add__(self, other): new_m = Matrix() def __mul__(self, other): new_m = Matrix() for col in other.cols: s = [sum([self.at(l, i)*c for i, c in enumerate(col)]) for l in range(self.h)] print(s) #new_m.addcol() return new_m @property def det(self): if self.w * self.h == 1: return self.vals[0] if (self.w, self.h) == (2,2): return self.at(0, 0)*self.at(1, 1) - self.at(0, 1)*self.at(1, 0) d = 0 for i in range(self.h): for j in range(self.w): b = [[y for y in (x[:j] + x[j+1:])] for x in self.cols[:i] + self.cols[i+1:]] d += det(val) if (i+j)%2 == 0 else -det(val) return d def __len__(self): return self.w * self.h def __repr__(self): if (self.w, self.h) == (0, 0): return "()" res = "" for i, val in enumerate(self.vals): end = "\n" if (i+1)%self.w == 0 else "\t" res += f"{val}{end}" return res def __str__(self): return self.__repr__()
class Matrix: def __init__(self, *args, **kwargs): if len(args) > 0: if isinstance(args[0], Matrix): m = args[0].copy() else: m = {'vals': [], 'w': 0, 'h': 0} self.vals = m.vals self.w = m.w self.h = m.h def copy(self): new_m = matrix() for i in self.vals: new_m.vals.append(i) new_m.w = self.w new_m.h = self.h return new_m @property def width(self): return self.w @property def height(self): return self.h def value_at(self, row, col): return self.vals[row * self.w + col] def at(self, row, col): return self.value_at(row, col) def row(self, pos): return [self.vals[pos * self.w + i] for i in range(self.w)] @property def rows(self): return [self.row(i) for i in range(self.h)] def col(self, pos): return [self.vals[i * self.w + pos] for i in range(self.h)] @property def cols(self): return [self.col(i) for i in range(self.w)] @staticmethod def _isnumeric(i): return isinstance(i, float) or isinstance(i, int) def _add(self, r, p, q, *args): r = len(args) if r <= 0 else r for i in range(r): try: if self._isnumeric(args[i]): self.vals.insert(i * (p + 1) + self.w * q, args[i]) except IndexError: self.vals.insert(i * (p + 1) + self.w * q, 0) return r def addrow(self, *args): self.w = self._add(self.w, 0, self.h, *args) self.h += 1 def addcol(self, *args): self.h = self._add(self.h, self.w, 1, *args) self.w += 1 def _fill(self, val, pos, r, lt, p, q, addfunc): if self._isnumeric(val): if pos < lt: for i in range(self.w): self.vals[pos * p + i * q] = val else: addfunc(*[val for _ in range(r)]) def rowfill(self, val, pos): self._fill(val, pos, self.w, self.h, self.w, 1, self.addrow) def colfill(self, val, pos): self._fill(val, pos, self.h, self.w, 1, self.w, self.addcol) def removerow(self, pos): if self.h > 0 and pos < self.h: for _ in range(self.w): self.vals.pop(self.w * pos) self.h -= 1 if self.h == 0: self.w = 0 def removecol(self, pos): if self.w > 0 and pos < self.w: pos %= self.w for i in range(self.h): self.vals.pop(i * (self.w - 1) + pos) self.w -= 1 if self.w == 0: self.h = 0 def __add__(self, other): new_m = matrix() def __mul__(self, other): new_m = matrix() for col in other.cols: s = [sum([self.at(l, i) * c for (i, c) in enumerate(col)]) for l in range(self.h)] print(s) return new_m @property def det(self): if self.w * self.h == 1: return self.vals[0] if (self.w, self.h) == (2, 2): return self.at(0, 0) * self.at(1, 1) - self.at(0, 1) * self.at(1, 0) d = 0 for i in range(self.h): for j in range(self.w): b = [[y for y in x[:j] + x[j + 1:]] for x in self.cols[:i] + self.cols[i + 1:]] d += det(val) if (i + j) % 2 == 0 else -det(val) return d def __len__(self): return self.w * self.h def __repr__(self): if (self.w, self.h) == (0, 0): return '()' res = '' for (i, val) in enumerate(self.vals): end = '\n' if (i + 1) % self.w == 0 else '\t' res += f'{val}{end}' return res def __str__(self): return self.__repr__()
# # @lc app=leetcode id=67 lang=python3 # # [67] Add Binary # # @lc code=start class Solution: def addBinary(self, a: str, b: str) -> str: m = len(a) n = len(b) i = m - 1 j = n - 1 extra = 0 res = '' while i >=0 or j >= 0: if i < 0: x = int(b[j]) + extra elif j < 0: x = int(a[i]) + extra else: x = int(a[i]) + int(b[j]) + extra extra = x // 2 res = str(x%2) + res i -= 1 j -= 1 if extra: return str(extra) + res else: return res tests = [ ('11', '1', '100'), ('1010', '1011', '10101') ] # @lc code=end
class Solution: def add_binary(self, a: str, b: str) -> str: m = len(a) n = len(b) i = m - 1 j = n - 1 extra = 0 res = '' while i >= 0 or j >= 0: if i < 0: x = int(b[j]) + extra elif j < 0: x = int(a[i]) + extra else: x = int(a[i]) + int(b[j]) + extra extra = x // 2 res = str(x % 2) + res i -= 1 j -= 1 if extra: return str(extra) + res else: return res tests = [('11', '1', '100'), ('1010', '1011', '10101')]
def test(): # if an assertion fails, the message will be displayed # --> must have the output in a comment assert "Mean: 5.0" in __solution__, "Did you record the correct program output as a comment?" # --> must have the output in a comment assert "Mean: 4.0" in __solution__, "Did you record the correct program output as a comment?" # --> must have the first function call assert "mean(numbers_one)" in __solution__, "Did you call the mean function with numbers_one as input?" # --> must have the second function call assert "mean(numbers_two)" in __solution__, "Did you call the mean function with numbers_two as input?" # --> must not have a TODO marker in the solution assert "TODO" not in __solution__, "Did you remove the TODO marker when finished?" # display a congratulations for a correct solution __msg__.good("Well done!")
def test(): assert 'Mean: 5.0' in __solution__, 'Did you record the correct program output as a comment?' assert 'Mean: 4.0' in __solution__, 'Did you record the correct program output as a comment?' assert 'mean(numbers_one)' in __solution__, 'Did you call the mean function with numbers_one as input?' assert 'mean(numbers_two)' in __solution__, 'Did you call the mean function with numbers_two as input?' assert 'TODO' not in __solution__, 'Did you remove the TODO marker when finished?' __msg__.good('Well done!')
# 17. Distinct strings in the first column # Find distinct strings (a set of strings) of the first column of the file. Confirm the result by using cut, sort, and uniq commands. def removeDuplicates(list): newList = [] for i in list: if not(i in newList): newList.append(i) return newList with open('popular-names.txt') as f: firstColumn = [] lines = f.readlines() for i in lines: lineArray = i.split('\t') firstColumn.append(lineArray[0]) size = len(removeDuplicates(firstColumn)) print(f'There are {size} set of strings') f.close
def remove_duplicates(list): new_list = [] for i in list: if not i in newList: newList.append(i) return newList with open('popular-names.txt') as f: first_column = [] lines = f.readlines() for i in lines: line_array = i.split('\t') firstColumn.append(lineArray[0]) size = len(remove_duplicates(firstColumn)) print(f'There are {size} set of strings') f.close
name = input("Enter your name: ") date = input("Enter a date: ") adjective = input("Enter an adjective: ") noun = input("Enter a noun: ") verb = input("Enter a verb in past tense: ") adverb = input("Enter an adverb: ") adjective = input("Enter another adjective: ") noun = input("Enter another noun: ") noun = input("Enter another noun: ") adjective = input("Enter another adjective: ") verb = input("Enter a verb: ") adverb = input("Enter another adverb: ") verb = input("Enter another verb in past tense: ") adjective = input("Enter another adjective: ") print("Name: " + name + " Date: " + date ) print("Today I went to the zoo. I saw a " + adjective + " " + noun + " jumping up and down in its tree.") print("He " + verb + " " + adverb + " through the large tunnel that led to its " + adjective + " " + noun + ".") print("I got some peanuts and passed them through the cage to a gigantic gray " + noun + " towering above my head.") print("Feeding the animals made me hungry. I went to get a " + adjective + " scoop of ice cream. It filled my stomach.") print("Afterwards I had to " + verb + " " + adverb + " to catch our bus.") print("When I got home I " + verb + " my mom for a " + adjective + " day at the zoo.")
name = input('Enter your name: ') date = input('Enter a date: ') adjective = input('Enter an adjective: ') noun = input('Enter a noun: ') verb = input('Enter a verb in past tense: ') adverb = input('Enter an adverb: ') adjective = input('Enter another adjective: ') noun = input('Enter another noun: ') noun = input('Enter another noun: ') adjective = input('Enter another adjective: ') verb = input('Enter a verb: ') adverb = input('Enter another adverb: ') verb = input('Enter another verb in past tense: ') adjective = input('Enter another adjective: ') print('Name: ' + name + ' Date: ' + date) print('Today I went to the zoo. I saw a ' + adjective + ' ' + noun + ' jumping up and down in its tree.') print('He ' + verb + ' ' + adverb + ' through the large tunnel that led to its ' + adjective + ' ' + noun + '.') print('I got some peanuts and passed them through the cage to a gigantic gray ' + noun + ' towering above my head.') print('Feeding the animals made me hungry. I went to get a ' + adjective + ' scoop of ice cream. It filled my stomach.') print('Afterwards I had to ' + verb + ' ' + adverb + ' to catch our bus.') print('When I got home I ' + verb + ' my mom for a ' + adjective + ' day at the zoo.')
input=__import__('sys').stdin.readline n,m=map(int,input().split());g=[list(input()) for _ in range(n)];c=[[0]*m for _ in range(n)] q=__import__('collections').deque();q.append((0,0));c[0][0]=1 while q: x,y=q.popleft() for nx,ny in (x+1,y),(x-1,y),(x,y+1),(x,y-1): if 0<=nx<n and 0<=ny<m and g[nx][ny]=='1' and c[nx][ny]==0: c[nx][ny]=c[x][y]+1 q.append((nx,ny)) print(c[n-1][m-1])
input = __import__('sys').stdin.readline (n, m) = map(int, input().split()) g = [list(input()) for _ in range(n)] c = [[0] * m for _ in range(n)] q = __import__('collections').deque() q.append((0, 0)) c[0][0] = 1 while q: (x, y) = q.popleft() for (nx, ny) in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)): if 0 <= nx < n and 0 <= ny < m and (g[nx][ny] == '1') and (c[nx][ny] == 0): c[nx][ny] = c[x][y] + 1 q.append((nx, ny)) print(c[n - 1][m - 1])
# normalize data 0-1 def normalize(data): normalized = [] for i in range(len(data[0])): col_min = min([item[i] for item in data]) col_max = max([item[i] for item in data]) for q, item in enumerate([item[i] for item in data]): if len(normalized) > q: normalized[q].append((item - col_min) / (col_max - col_min)) else: normalized.append([]) normalized[q].append((item - col_min) / (col_max - col_min)) return normalized
def normalize(data): normalized = [] for i in range(len(data[0])): col_min = min([item[i] for item in data]) col_max = max([item[i] for item in data]) for (q, item) in enumerate([item[i] for item in data]): if len(normalized) > q: normalized[q].append((item - col_min) / (col_max - col_min)) else: normalized.append([]) normalized[q].append((item - col_min) / (col_max - col_min)) return normalized
''' You are given a linked list with one pointer of each node pointing to the next node just like the usual. Every node, however, also has a second pointer that can point to any node in the list. Now write a program to deep copy this list. Solution 1: First backup all the nodes' next pointers node to another array. next_backup = [node1, node2, node3 ... None] Meaning next_backup[0] = node[0].next = node1. Note that these are just references. Now just deep-copy the original linked list, only considering the next pointers. While copying (or after it), point `original_0.next = copy_0` and `copy_0.random = original_0` Now, while traversing the copy list, set the random pointers of copies correctly: copy.random = copy.random.random.next Now, traverse the original list and fix back the next pointers using the next_backup array. Total complexity -> O(n+n+n) = O(n) Space complexity = O(n) SOLUTION 2: We can also do it in space complexity O(1). This is actually easier to understand. ;) For every node original_i, make a copy of it just in front of it. For example, if original_0.next = original_1, then now it will become `original_0.next = copy_0` `copy_0.next = original_1` Now, set the random pointers of copies: `copy_i.random = original_i.random.next` We can do this because we know that the copy of a node is just after the original. Now, fix the next pointers of all the nodes: original_i.next = original_i.next.next copy_i.next = copy_i.next.next Time complexity = O(n) Space complexity = O(1) '''
""" You are given a linked list with one pointer of each node pointing to the next node just like the usual. Every node, however, also has a second pointer that can point to any node in the list. Now write a program to deep copy this list. Solution 1: First backup all the nodes' next pointers node to another array. next_backup = [node1, node2, node3 ... None] Meaning next_backup[0] = node[0].next = node1. Note that these are just references. Now just deep-copy the original linked list, only considering the next pointers. While copying (or after it), point `original_0.next = copy_0` and `copy_0.random = original_0` Now, while traversing the copy list, set the random pointers of copies correctly: copy.random = copy.random.random.next Now, traverse the original list and fix back the next pointers using the next_backup array. Total complexity -> O(n+n+n) = O(n) Space complexity = O(n) SOLUTION 2: We can also do it in space complexity O(1). This is actually easier to understand. ;) For every node original_i, make a copy of it just in front of it. For example, if original_0.next = original_1, then now it will become `original_0.next = copy_0` `copy_0.next = original_1` Now, set the random pointers of copies: `copy_i.random = original_i.random.next` We can do this because we know that the copy of a node is just after the original. Now, fix the next pointers of all the nodes: original_i.next = original_i.next.next copy_i.next = copy_i.next.next Time complexity = O(n) Space complexity = O(1) """
class PointCloudObject(RhinoObject): # no doc def DuplicatePointCloudGeometry(self): """ DuplicatePointCloudGeometry(self: PointCloudObject) -> PointCloud """ pass PointCloudGeometry=property(lambda self: object(),lambda self,v: None,lambda self: None) """Get: PointCloudGeometry(self: PointCloudObject) -> PointCloud """
class Pointcloudobject(RhinoObject): def duplicate_point_cloud_geometry(self): """ DuplicatePointCloudGeometry(self: PointCloudObject) -> PointCloud """ pass point_cloud_geometry = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Get: PointCloudGeometry(self: PointCloudObject) -> PointCloud\n\n\n\n'
''' Kattis - lineup Compare list with the sorted version of the list. Time: O(n log n), Space: O(n) ''' n = int(input()) arr = [input() for _ in range(n)] if arr == sorted(arr): print("INCREASING") elif arr == sorted(arr, reverse=True): print("DECREASING") else: print("NEITHER")
""" Kattis - lineup Compare list with the sorted version of the list. Time: O(n log n), Space: O(n) """ n = int(input()) arr = [input() for _ in range(n)] if arr == sorted(arr): print('INCREASING') elif arr == sorted(arr, reverse=True): print('DECREASING') else: print('NEITHER')
""" quick_sort.py Implementation of quick sort on a list and returns a sorted list. Quick Sort Overview: ------------------------ Uses partitioning to recursively divide and sort the list Time Complexity: O(n**2) worst case Space Complexity: O(n**2) this version Stable: No Psuedo Code: CLRS. Introduction to Algorithms. 3rd ed. """ def sort(seq): if len(seq) < 1: return seq else: pivot = seq[0] left = sort([x for x in seq[1:] if x < pivot]) right = sort([x for x in seq[1:] if x >= pivot]) return left + [pivot] + right
""" quick_sort.py Implementation of quick sort on a list and returns a sorted list. Quick Sort Overview: ------------------------ Uses partitioning to recursively divide and sort the list Time Complexity: O(n**2) worst case Space Complexity: O(n**2) this version Stable: No Psuedo Code: CLRS. Introduction to Algorithms. 3rd ed. """ def sort(seq): if len(seq) < 1: return seq else: pivot = seq[0] left = sort([x for x in seq[1:] if x < pivot]) right = sort([x for x in seq[1:] if x >= pivot]) return left + [pivot] + right
# coding=utf-8 def test_method(param): """ Should not show up :param param: any param :return: None """ return None
def test_method(param): """ Should not show up :param param: any param :return: None """ return None
#program to find the single element appears once in a list where every element # appears four times except for one. class Solution_once: def singleNumber(self, arr): ones, twos = 0, 0 for x in arr: ones, twos = (ones ^ x) & ~twos, (ones & x) | (twos & ~x) assert twos == 0 return ones class Solution_twice: def single_number(arr): ones, twos, threes = 0, 0, 0 for x in arr: ones, twos, threes = (~x & ones) | (x & ~ones & ~twos & ~threes), (~x & twos) | (x & ones), (~x & threes) | (x & twos) return twos if __name__ == "__main__": print(Solution_once().singleNumber([1, 1, 1, 2, 2, 2, 3])) print(Solution_once().singleNumber([5, 3, 0, 3, 5, 5, 3]))
class Solution_Once: def single_number(self, arr): (ones, twos) = (0, 0) for x in arr: (ones, twos) = ((ones ^ x) & ~twos, ones & x | twos & ~x) assert twos == 0 return ones class Solution_Twice: def single_number(arr): (ones, twos, threes) = (0, 0, 0) for x in arr: (ones, twos, threes) = (~x & ones | x & ~ones & ~twos & ~threes, ~x & twos | x & ones, ~x & threes | x & twos) return twos if __name__ == '__main__': print(solution_once().singleNumber([1, 1, 1, 2, 2, 2, 3])) print(solution_once().singleNumber([5, 3, 0, 3, 5, 5, 3]))
''' Given a collection of numbers that might contain duplicates, return all possible unique permutations. For example, [1,1,2] have the following unique permutations: [1,1,2], [1,2,1], and [2,1,1]. ''' class Solution(object): def permuteUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ result = [] nums.sort() self.get_permute([], nums, result) return result def get_permute(self, current, num, result): if not num: result.append(current + []) return for i, v in enumerate(num): if i - 1 >= 0 and num[i] == num[i - 1]: continue current.append(num[i]) self.get_permute(current, num[:i] + num[i + 1:], result) current.pop() if __name__ == "__main__": assert Solution().permuteUnique([1, 2, 1]) == [[1, 1, 2], [1, 2, 1], [2, 1, 1]]
""" Given a collection of numbers that might contain duplicates, return all possible unique permutations. For example, [1,1,2] have the following unique permutations: [1,1,2], [1,2,1], and [2,1,1]. """ class Solution(object): def permute_unique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ result = [] nums.sort() self.get_permute([], nums, result) return result def get_permute(self, current, num, result): if not num: result.append(current + []) return for (i, v) in enumerate(num): if i - 1 >= 0 and num[i] == num[i - 1]: continue current.append(num[i]) self.get_permute(current, num[:i] + num[i + 1:], result) current.pop() if __name__ == '__main__': assert solution().permuteUnique([1, 2, 1]) == [[1, 1, 2], [1, 2, 1], [2, 1, 1]]
class Bank: def __init__(self,owner,balance): self.owner=owner self.balance=balance def deposit(self,d): self.balance=d+self.balance print("amount : {}".format(d)) print("deposit accepted!!") return self.balance def withdraw(self,w): if w>self.balance: print("amount has exceeded the limit!!") print('balance : {}'.format(self.balance)) else: self.balance= self.balance-w print("amount withdrawn : {}".format(w)) print("withdrawal completed!!") return self.balance def __str__(self): return (f"Account owner : {self.owner} \nAccount balance : {self.balance}")
class Bank: def __init__(self, owner, balance): self.owner = owner self.balance = balance def deposit(self, d): self.balance = d + self.balance print('amount : {}'.format(d)) print('deposit accepted!!') return self.balance def withdraw(self, w): if w > self.balance: print('amount has exceeded the limit!!') print('balance : {}'.format(self.balance)) else: self.balance = self.balance - w print('amount withdrawn : {}'.format(w)) print('withdrawal completed!!') return self.balance def __str__(self): return f'Account owner : {self.owner} \nAccount balance : {self.balance}'
""" Various constants used to build bazel-diff """ DEFAULT_JVM_EXTERNAL_TAG = "3.3" RULES_JVM_EXTERNAL_SHA = "d85951a92c0908c80bd8551002d66cb23c3434409c814179c0ff026b53544dab" BUILD_PROTO_MESSAGE_SHA = "50b79faec3c4154bed274371de5678b221165e38ab59c6167cc94b922d9d9152" BAZEL_DIFF_MAVEN_ARTIFACTS = [ "junit:junit:4.12", "org.mockito:mockito-core:3.3.3", "info.picocli:picocli:jar:4.3.2", "com.google.code.gson:gson:jar:2.8.6", "com.google.guava:guava:29.0-jre" ]
""" Various constants used to build bazel-diff """ default_jvm_external_tag = '3.3' rules_jvm_external_sha = 'd85951a92c0908c80bd8551002d66cb23c3434409c814179c0ff026b53544dab' build_proto_message_sha = '50b79faec3c4154bed274371de5678b221165e38ab59c6167cc94b922d9d9152' bazel_diff_maven_artifacts = ['junit:junit:4.12', 'org.mockito:mockito-core:3.3.3', 'info.picocli:picocli:jar:4.3.2', 'com.google.code.gson:gson:jar:2.8.6', 'com.google.guava:guava:29.0-jre']
# # @lc app=leetcode id=206 lang=python3 # # [206] Reverse Linked List # # https://leetcode.com/problems/reverse-linked-list/description/ # # algorithms # Easy (65.21%) # Likes: 6441 # Dislikes: 123 # Total Accepted: 1.3M # Total Submissions: 2M # Testcase Example: '[1,2,3,4,5]' # # Given the head of a singly linked list, reverse the list, and return the # reversed list. # # # Example 1: # # # Input: head = [1,2,3,4,5] # Output: [5,4,3,2,1] # # # Example 2: # # # Input: head = [1,2] # Output: [2,1] # # # Example 3: # # # Input: head = [] # Output: [] # # # # Constraints: # # # The number of nodes in the list is the range [0, 5000]. # -5000 <= Node.val <= 5000 # # # # Follow up: A linked list can be reversed either iteratively or recursively. # Could you implement both? # # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next # class Solution: # def reverseList(self, head: ListNode) -> ListNode: # rever_tail = ListNode() # curr = rever_tail # while head != None: # curr.val = head.val # new_node = ListNode() # new_node.next = curr # curr = new_node # head = head.next # return curr.next class Solution: def reverseList(self, head: ListNode) -> ListNode: prev = None curr = head while curr: next = curr.next curr.next = prev prev = curr curr = next return prev # @lc code=end
class Solution: def reverse_list(self, head: ListNode) -> ListNode: prev = None curr = head while curr: next = curr.next curr.next = prev prev = curr curr = next return prev
# Bubble Sort # # Time Complexity: O(n*log(n)) # Space Complexity: O(1) class Solution: def bubbleSort(self, array: [int]) -> [int]: dirty = False for i in range(len(array)): for j in range(0, len(array) - 1 - i): if array[j] > array[j + 1]: dirty = True array[j], array[j + 1] = array[j + 1], array[j] if not dirty: break dirty = False return array
class Solution: def bubble_sort(self, array: [int]) -> [int]: dirty = False for i in range(len(array)): for j in range(0, len(array) - 1 - i): if array[j] > array[j + 1]: dirty = True (array[j], array[j + 1]) = (array[j + 1], array[j]) if not dirty: break dirty = False return array
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: [email protected] Version: 0.0.1 Created Time: 2016-03-07 Last_modify: 2016-03-07 ****************************************** ''' ''' Given a **singly linked list** where elements are sorted in ascending order, convert it to a height balanced BST. ''' # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def sortedListToBST(self, head): """ :type head: ListNode :rtype: TreeNode """ p = head n = 0 while p: p = p.next n += 1 self.cur = head return self.helper(n) def helper(self, n): if n <= 0: return None root = TreeNode(0) root.left = self.helper(n // 2) root.val = self.cur.val self.cur = self.cur.next root.right = self.helper(n - (n // 2) - 1) return root
""" ***************************************** Author: zhlinh Email: [email protected] Version: 0.0.1 Created Time: 2016-03-07 Last_modify: 2016-03-07 ****************************************** """ '\nGiven a **singly linked list** where elements are\nsorted in ascending order, convert it to a height balanced BST.\n' class Listnode(object): def __init__(self, x): self.val = x self.next = None class Treenode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def sorted_list_to_bst(self, head): """ :type head: ListNode :rtype: TreeNode """ p = head n = 0 while p: p = p.next n += 1 self.cur = head return self.helper(n) def helper(self, n): if n <= 0: return None root = tree_node(0) root.left = self.helper(n // 2) root.val = self.cur.val self.cur = self.cur.next root.right = self.helper(n - n // 2 - 1) return root
# -*- coding: utf-8 -*- """ repoclone.exceptions ----------------------- All exceptions used in the repoclone code base are defined here. """ class RepocloneException(Exception): """ Base exception class. All Cookiecutter-specific exceptions should subclass this class. """
""" repoclone.exceptions ----------------------- All exceptions used in the repoclone code base are defined here. """ class Repocloneexception(Exception): """ Base exception class. All Cookiecutter-specific exceptions should subclass this class. """
inputFile = str(input("Input file")) f = open(inputFile,"r") data = f.readlines() f.close() runningFuelSum = 0 for line in data: line = line.replace("\n","") mass = int(line) fuelNeeded = (mass//3)-2 runningFuelSum += fuelNeeded while(fuelNeeded > 0): fuelNeeded = (fuelNeeded//3)-2 if(fuelNeeded>=0): runningFuelSum += fuelNeeded print(runningFuelSum)
input_file = str(input('Input file')) f = open(inputFile, 'r') data = f.readlines() f.close() running_fuel_sum = 0 for line in data: line = line.replace('\n', '') mass = int(line) fuel_needed = mass // 3 - 2 running_fuel_sum += fuelNeeded while fuelNeeded > 0: fuel_needed = fuelNeeded // 3 - 2 if fuelNeeded >= 0: running_fuel_sum += fuelNeeded print(runningFuelSum)
class Settings: def __init__(self): self.screen_width, self.screen_height = 800, 300 self.bg_color = (225, 225, 225)
class Settings: def __init__(self): (self.screen_width, self.screen_height) = (800, 300) self.bg_color = (225, 225, 225)
class Solution: def sortColors(self, nums: List[int]) -> None: zero = -1 one = -1 two = -1 for num in nums: if num == 0: two += 1 one += 1 zero += 1 nums[two] = 2 nums[one] = 1 nums[zero] = 0 elif num == 1: two += 1 one += 1 nums[two] = 2 nums[one] = 1 else: two += 1 nums[two] = 2
class Solution: def sort_colors(self, nums: List[int]) -> None: zero = -1 one = -1 two = -1 for num in nums: if num == 0: two += 1 one += 1 zero += 1 nums[two] = 2 nums[one] = 1 nums[zero] = 0 elif num == 1: two += 1 one += 1 nums[two] = 2 nums[one] = 1 else: two += 1 nums[two] = 2