content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def test_accounts(client): client.session.get.return_value.json.return_value.update({'accounts': [1, ]}) client.accounts() client.session.get.called_once_with('https://api.getdrip.com/v2/accounts/') def test_account(client): client.session.get.return_value.json.return_value.update({'accounts': [1, ]}) client.account(1234) client.session.get.called_once_with('https://api.getdrip.com/v2/accounts/1234')
def test_accounts(client): client.session.get.return_value.json.return_value.update({'accounts': [1]}) client.accounts() client.session.get.called_once_with('https://api.getdrip.com/v2/accounts/') def test_account(client): client.session.get.return_value.json.return_value.update({'accounts': [1]}) client.account(1234) client.session.get.called_once_with('https://api.getdrip.com/v2/accounts/1234')
""" for image in os.listdir(images_path): img = Image.open(os.path.join(images_path,image)) frame_draw = img.copy() draw = ImageDraw.Draw(frame_draw) for box in boxes: draw.rectangle(box.tolist(), outline=(255, 0, 0), width=6) for landmark in landmarks_points: print(landmark) draw.point(landmark,fill="black") frame_draw.show() d = display.display(draw, display_id=True) """ sys.exit() # For a model pretrained on VGGFace2 model = InceptionResnetV1(pretrained='vggface2').eval() # For a model pretrained on CASIA-Webface model = InceptionResnetV1(pretrained='casia-webface').eval() # For an untrained model with 100 classes model = InceptionResnetV1(num_classes=100).eval() # For an untrained 1001-class classifier model = InceptionResnetV1(classify=True, num_classes=1001).eval() # If required, create a face detection pipeline using MTCNN: #mtcnn = MTCNN(image_size=<image_size>, margin=<margin>) # Draw faces frame_draw = img.copy() draw = ImageDraw.Draw(frame_draw) for box in boxes: draw.rectangle(box.tolist(), outline=(255, 0, 0), width=6) draw.point() frame_draw.show() d = display.display(draw, display_id=True) # Create an inception resnet (in eval mode): resnet = InceptionResnetV1(pretrained='vggface2').eval()
""" for image in os.listdir(images_path): img = Image.open(os.path.join(images_path,image)) frame_draw = img.copy() draw = ImageDraw.Draw(frame_draw) for box in boxes: draw.rectangle(box.tolist(), outline=(255, 0, 0), width=6) for landmark in landmarks_points: print(landmark) draw.point(landmark,fill="black") frame_draw.show() d = display.display(draw, display_id=True) """ sys.exit() model = inception_resnet_v1(pretrained='vggface2').eval() model = inception_resnet_v1(pretrained='casia-webface').eval() model = inception_resnet_v1(num_classes=100).eval() model = inception_resnet_v1(classify=True, num_classes=1001).eval() frame_draw = img.copy() draw = ImageDraw.Draw(frame_draw) for box in boxes: draw.rectangle(box.tolist(), outline=(255, 0, 0), width=6) draw.point() frame_draw.show() d = display.display(draw, display_id=True) resnet = inception_resnet_v1(pretrained='vggface2').eval()
# model model = Model() i1 = Input("op1", "TENSOR_INT32", "{1, 2, 2, 1}") i2 = Output("op2", "TENSOR_INT32", "{1, 2, 2, 1}") model = model.Operation("ZEROS_LIKE_EX", i1).To(i2) # Example 1. Input in operand 0, input0 = {i1: # input 0 [-2, -1, 0, 3]} output0 = {i2: # output 0 [0, 0, 0, 0]} # Instantiate an example Example((input0, output0))
model = model() i1 = input('op1', 'TENSOR_INT32', '{1, 2, 2, 1}') i2 = output('op2', 'TENSOR_INT32', '{1, 2, 2, 1}') model = model.Operation('ZEROS_LIKE_EX', i1).To(i2) input0 = {i1: [-2, -1, 0, 3]} output0 = {i2: [0, 0, 0, 0]} example((input0, output0))
# -*- coding: utf-8 -*- """ Global Configuration """ mssql = { 'server' : 'localhost\SQL2016', 'database' : 'bkrob', 'username' : 'bkrob_adm', 'password' : 'bkrob_adm' } google_geocode_api = 'api key'
""" Global Configuration """ mssql = {'server': 'localhost\\SQL2016', 'database': 'bkrob', 'username': 'bkrob_adm', 'password': 'bkrob_adm'} google_geocode_api = 'api key'
def hello(): # Hey i'm a comment # I am a helpful note for humans, and will not be ran pass if __name__ == '__main__': hello()
def hello(): pass if __name__ == '__main__': hello()
# Prob 2 # Create a small program that will: # Ask for user input # Count the number of vowels in the user text ('a', 'e', 'i', 'o', 'u', 'y') # Display the number of vowels in user text print("Please enter a string") my_string = input() vowels = ['a', 'e', 'i', 'o', 'u', 'y'] count = 0 for letter in my_string.lower(): if letter in vowels: count += 1 print("Number of vowels in string: " + str(count)) # Prob 3 # Create a small program where # The user inputs an email # The program checks if the email ends with @gmail.com # The program prints True if email ends with @gmail.com and False if it doesn't print("Please enter a Gmail email") email = input() print(email[-10:] == "@gmail.com")
print('Please enter a string') my_string = input() vowels = ['a', 'e', 'i', 'o', 'u', 'y'] count = 0 for letter in my_string.lower(): if letter in vowels: count += 1 print('Number of vowels in string: ' + str(count)) print('Please enter a Gmail email') email = input() print(email[-10:] == '@gmail.com')
def my_func(arr1, arr2, arr3): ln1 = len(arr1) ln2 = len(arr2) ln3 = len(arr3) ptr1 = 0 ptr2 = 0 ptr3 = 0 while ptr1 < ln1 and ptr2 < ln2 and ptr3 < ln3: if arr1[ptr1] < arr2[ptr2]: if arr3[ptr3] < arr2[ptr2]: arr1[ptr1] = -1 arr3[ptr3] = -1 ptr3 += 1 ptr1 += 1 else: arr1[ptr1] = -1 ptr1 += 1 elif arr2[ptr2] < arr3[ptr3]: if arr1[ptr1] < arr3[ptr3]: arr1[ptr1] = -1 arr2[ptr2] = -1 ptr1 += 1 ptr2 += 1 else: arr2[ptr2] = -1 ptr2 += 1 elif arr3[ptr3] < arr1[ptr1]: if arr2[ptr2] < arr1[ptr1]: arr2[ptr2] = -1 arr3[ptr3] = -1 ptr2 += 1 ptr3 += 1 else: arr3[ptr3] = -1 ptr3 += 1 else: ptr1 += 1 ptr2 += 1 ptr3 += 1 for i in arr1: if i != -1: print(i, end=' ') ls1 = [1, 5, 5] ls2 = [3, 4, 5, 5, 10] ls3 = [5, 5, 10, 20] my_func(ls1, ls2, ls3)
def my_func(arr1, arr2, arr3): ln1 = len(arr1) ln2 = len(arr2) ln3 = len(arr3) ptr1 = 0 ptr2 = 0 ptr3 = 0 while ptr1 < ln1 and ptr2 < ln2 and (ptr3 < ln3): if arr1[ptr1] < arr2[ptr2]: if arr3[ptr3] < arr2[ptr2]: arr1[ptr1] = -1 arr3[ptr3] = -1 ptr3 += 1 ptr1 += 1 else: arr1[ptr1] = -1 ptr1 += 1 elif arr2[ptr2] < arr3[ptr3]: if arr1[ptr1] < arr3[ptr3]: arr1[ptr1] = -1 arr2[ptr2] = -1 ptr1 += 1 ptr2 += 1 else: arr2[ptr2] = -1 ptr2 += 1 elif arr3[ptr3] < arr1[ptr1]: if arr2[ptr2] < arr1[ptr1]: arr2[ptr2] = -1 arr3[ptr3] = -1 ptr2 += 1 ptr3 += 1 else: arr3[ptr3] = -1 ptr3 += 1 else: ptr1 += 1 ptr2 += 1 ptr3 += 1 for i in arr1: if i != -1: print(i, end=' ') ls1 = [1, 5, 5] ls2 = [3, 4, 5, 5, 10] ls3 = [5, 5, 10, 20] my_func(ls1, ls2, ls3)
# # PySNMP MIB module RAPTOR-SNMPv1-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RAPTOR-SNMPv1-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:43:39 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") MibIdentifier, Gauge32, enterprises, Counter64, Bits, Unsigned32, Counter32, ModuleIdentity, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, IpAddress, NotificationType, NotificationType, iso, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "Gauge32", "enterprises", "Counter64", "Bits", "Unsigned32", "Counter32", "ModuleIdentity", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "IpAddress", "NotificationType", "NotificationType", "iso", "TimeTicks") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") raptorSystems = MibIdentifier((1, 3, 6, 1, 4, 1, 1294)) raptorModules = MibIdentifier((1, 3, 6, 1, 4, 1, 1294, 1)) raptorObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 1294, 2)) raptorTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 1294, 3)) raptorNotifyMessage = MibScalar((1, 3, 6, 1, 4, 1, 1294, 2, 1), OctetString()) if mibBuilder.loadTexts: raptorNotifyMessage.setStatus('mandatory') raptorNotifyTrap = NotificationType((1, 3, 6, 1, 4, 1, 1294) + (0,1)).setObjects(("RAPTOR-SNMPv1-MIB", "raptorNotifyMessage")) mibBuilder.exportSymbols("RAPTOR-SNMPv1-MIB", raptorTraps=raptorTraps, raptorNotifyMessage=raptorNotifyMessage, raptorSystems=raptorSystems, raptorModules=raptorModules, raptorNotifyTrap=raptorNotifyTrap, raptorObjects=raptorObjects)
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, constraints_intersection, value_size_constraint, constraints_union, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ConstraintsIntersection', 'ValueSizeConstraint', 'ConstraintsUnion', 'ValueRangeConstraint') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (mib_identifier, gauge32, enterprises, counter64, bits, unsigned32, counter32, module_identity, integer32, mib_scalar, mib_table, mib_table_row, mib_table_column, object_identity, ip_address, notification_type, notification_type, iso, time_ticks) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibIdentifier', 'Gauge32', 'enterprises', 'Counter64', 'Bits', 'Unsigned32', 'Counter32', 'ModuleIdentity', 'Integer32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ObjectIdentity', 'IpAddress', 'NotificationType', 'NotificationType', 'iso', 'TimeTicks') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') raptor_systems = mib_identifier((1, 3, 6, 1, 4, 1, 1294)) raptor_modules = mib_identifier((1, 3, 6, 1, 4, 1, 1294, 1)) raptor_objects = mib_identifier((1, 3, 6, 1, 4, 1, 1294, 2)) raptor_traps = mib_identifier((1, 3, 6, 1, 4, 1, 1294, 3)) raptor_notify_message = mib_scalar((1, 3, 6, 1, 4, 1, 1294, 2, 1), octet_string()) if mibBuilder.loadTexts: raptorNotifyMessage.setStatus('mandatory') raptor_notify_trap = notification_type((1, 3, 6, 1, 4, 1, 1294) + (0, 1)).setObjects(('RAPTOR-SNMPv1-MIB', 'raptorNotifyMessage')) mibBuilder.exportSymbols('RAPTOR-SNMPv1-MIB', raptorTraps=raptorTraps, raptorNotifyMessage=raptorNotifyMessage, raptorSystems=raptorSystems, raptorModules=raptorModules, raptorNotifyTrap=raptorNotifyTrap, raptorObjects=raptorObjects)
class AppNotFoundError(Exception): pass class ClassNotFoundError(Exception): pass
class Appnotfounderror(Exception): pass class Classnotfounderror(Exception): pass
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 29 10:26:43 2020 @author: fa19 """
""" Created on Sun Nov 29 10:26:43 2020 @author: fa19 """
class FilterDoesNotExistError(Exception): """ Raised when a filter does not exist. """ pass class APIError(Exception): """ Error returned by the API. """ pass class ValidationError(Exception): """ Raised when filters receive invalid data """ pass
class Filterdoesnotexisterror(Exception): """ Raised when a filter does not exist. """ pass class Apierror(Exception): """ Error returned by the API. """ pass class Validationerror(Exception): """ Raised when filters receive invalid data """ pass
#!/usr/bin/env python3 """ Boolean data 1 bit 0,1 """ def encode(value): return [int(value) & 0x01] def decode(data): return (data & 0x01)
""" Boolean data 1 bit 0,1 """ def encode(value): return [int(value) & 1] def decode(data): return data & 1
#!/usr/bin/env python3 # fileencoding=utf-8 def char_width(char): # For japanese. if len(char) == 1: return 1 else: return 2 def string_width(_string): char_width_list = [] for c in _string.decode('utf-8'): char_width_list.append(char_width(c)) return char_width_list def add_space(_string, num): return _string+' '*num def constant_width(_string, width): out = '' char_width_list = string_width(_string) width_sum = 0 _end = 0 if sum(char_width_list) < width: return add_space(_string, width - sum(char_width_list)) for i, val in enumerate(char_width_list): width_sum += val if width_sum > width: _end = i break ustring = _str return out
def char_width(char): if len(char) == 1: return 1 else: return 2 def string_width(_string): char_width_list = [] for c in _string.decode('utf-8'): char_width_list.append(char_width(c)) return char_width_list def add_space(_string, num): return _string + ' ' * num def constant_width(_string, width): out = '' char_width_list = string_width(_string) width_sum = 0 _end = 0 if sum(char_width_list) < width: return add_space(_string, width - sum(char_width_list)) for (i, val) in enumerate(char_width_list): width_sum += val if width_sum > width: _end = i break ustring = _str return out
x = "Hello" y = 15 print(bool(x)) print(bool(y))
x = 'Hello' y = 15 print(bool(x)) print(bool(y))
class Solution: def findMedianSortedArrarys(self, A, B): lengthA = len(A) lengthB = len(B) new_arr = [] i = j = 0 while i < lengthA and j < lengthB: if A[i] < B[j]: new_arr.append(A[i]) i += 1 else: new_arr.append(B[j]) j += 1 while i < lengthA: new_arr.append(A[i]) i += 1 while j < lengthB: new_arr.append(B[j]) j += 1 if((lengthA + lengthB)%2 == 1): return(new_arr[int((lengthA+lengthB)/2)]) else: return((new_arr[int((lengthA+lengthB)/2)]+new_arr[int((lengthA+lengthB)/2)-1])/2)
class Solution: def find_median_sorted_arrarys(self, A, B): length_a = len(A) length_b = len(B) new_arr = [] i = j = 0 while i < lengthA and j < lengthB: if A[i] < B[j]: new_arr.append(A[i]) i += 1 else: new_arr.append(B[j]) j += 1 while i < lengthA: new_arr.append(A[i]) i += 1 while j < lengthB: new_arr.append(B[j]) j += 1 if (lengthA + lengthB) % 2 == 1: return new_arr[int((lengthA + lengthB) / 2)] else: return (new_arr[int((lengthA + lengthB) / 2)] + new_arr[int((lengthA + lengthB) / 2) - 1]) / 2
#!/usr/bin/env python3 count = 0 with open("romeo.txt") as romeo: text = romeo.readlines() for line in text: if "ROMEO" in line: count += 1 print(count)
count = 0 with open('romeo.txt') as romeo: text = romeo.readlines() for line in text: if 'ROMEO' in line: count += 1 print(count)
# 22004 | Fixing the Fence (Evan intro) sm.setSpeakerID(1013103) sm.sendNext("Ah, did you bring all the Thick Branches? That's my kid! What shall i give you as reward?... Let's see... Oh, right! \r\n #fUI/UIWindow2.img/QuestIcon/4/0# \r\n #v3010097# Strong Wooden Chair \r\n #fUI/UIWindow2.img/QuestIcon/8/0# 210 exp") if sm.canHold(3010097): sm.giveItem(3010097) sm.giveExp(210) sm.completeQuest(parentID) sm.dispose() else: sm.sendNext("Please make room in your Set-up Inventory") sm.dispose()
sm.setSpeakerID(1013103) sm.sendNext("Ah, did you bring all the Thick Branches? That's my kid! What shall i give you as reward?... Let's see... Oh, right! \r\n #fUI/UIWindow2.img/QuestIcon/4/0# \r\n #v3010097# Strong Wooden Chair \r\n #fUI/UIWindow2.img/QuestIcon/8/0# 210 exp") if sm.canHold(3010097): sm.giveItem(3010097) sm.giveExp(210) sm.completeQuest(parentID) sm.dispose() else: sm.sendNext('Please make room in your Set-up Inventory') sm.dispose()
# Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrder(self, A): queue = [] ansr_queue = [] queue.append(A) marker = "$" queue.append(marker) row = [] while len(queue) > 0: ele = queue.pop(0) if ele != marker: row.append(ele.val) if ele.left is not None: left = ele.left queue.append(left) if ele.right is not None: right = ele.right queue.append(right) else: ansr_queue.append(row) row = [] if len(queue) == 0: break queue.append(marker) return ansr_queue
class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def level_order(self, A): queue = [] ansr_queue = [] queue.append(A) marker = '$' queue.append(marker) row = [] while len(queue) > 0: ele = queue.pop(0) if ele != marker: row.append(ele.val) if ele.left is not None: left = ele.left queue.append(left) if ele.right is not None: right = ele.right queue.append(right) else: ansr_queue.append(row) row = [] if len(queue) == 0: break queue.append(marker) return ansr_queue
""" SPI typing class This class includes full support for using ESP32 SPI peripheral in master mode Only SPI master mode is supported for now. Python exception wil be raised if the requested spihost is used by SD Card driver (sdcard in spi mode). If the requested spihost is VSPI and the psRAM is used at 80 MHz, the exception will be raised. The exception will be raised if SPI cannot be configured for given configurations. """ class SPI: def deinit(self): """ Deinitialize the SPI object, free all used resources. """ pass def read(self, len, val): """ Read len bytes from SPI device. Returns the string of read bytes. If the optional val argument is given, outputs val byte on mosi during read (if duplex mode is used). """ pass def readinto(self, buf, val): """ Read bytes from SPI device into buffer object buf. Length of buf bytes are read. If the optional val argument is given, outputs val byte on mosi during read (if duplex mode is used). """ pass def readfrom_mem(self, address, length, addrlen): """ Writes address to the spi device and reads length bytes. The number of the address bytes to write is determined from the address value (1 byte for 0-255, 2 bytes for 256-65535, ...). The number of address bytes to be written can also be set by the optional argument addrlen (1-4). Returns the string of read bytes. """ pass def write(self, buf): """ Write bytes from buffer object buf to the SPI device. Returns True on success, False ion error """ pass def write_readinto(self, wr_buf, rd_buf): """ Write bytes from buffer object wr_buf to the SPI device and reads from SPI device into buffer object rd_buf. The lenghts of wr_buf and rd_buf can be different. In fullduplex mode write and read are simultaneous. In halfduplex mode the data are first written to the device, then read from it. Returns True on success, False ion error """ pass def select(self): """ Activates the CS pin if it was configured when the spi object was created. """ pass
""" SPI typing class This class includes full support for using ESP32 SPI peripheral in master mode Only SPI master mode is supported for now. Python exception wil be raised if the requested spihost is used by SD Card driver (sdcard in spi mode). If the requested spihost is VSPI and the psRAM is used at 80 MHz, the exception will be raised. The exception will be raised if SPI cannot be configured for given configurations. """ class Spi: def deinit(self): """ Deinitialize the SPI object, free all used resources. """ pass def read(self, len, val): """ Read len bytes from SPI device. Returns the string of read bytes. If the optional val argument is given, outputs val byte on mosi during read (if duplex mode is used). """ pass def readinto(self, buf, val): """ Read bytes from SPI device into buffer object buf. Length of buf bytes are read. If the optional val argument is given, outputs val byte on mosi during read (if duplex mode is used). """ pass def readfrom_mem(self, address, length, addrlen): """ Writes address to the spi device and reads length bytes. The number of the address bytes to write is determined from the address value (1 byte for 0-255, 2 bytes for 256-65535, ...). The number of address bytes to be written can also be set by the optional argument addrlen (1-4). Returns the string of read bytes. """ pass def write(self, buf): """ Write bytes from buffer object buf to the SPI device. Returns True on success, False ion error """ pass def write_readinto(self, wr_buf, rd_buf): """ Write bytes from buffer object wr_buf to the SPI device and reads from SPI device into buffer object rd_buf. The lenghts of wr_buf and rd_buf can be different. In fullduplex mode write and read are simultaneous. In halfduplex mode the data are first written to the device, then read from it. Returns True on success, False ion error """ pass def select(self): """ Activates the CS pin if it was configured when the spi object was created. """ pass
class Solution: def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ # using library # itertools.permutations(nums) - tuples on iterating # return list(map(list, itertools.permutations(nums))) # recursive # if len(nums) == 1: # return [nums] # result = [] # for i in range(len(nums)): # result = result + [[nums[i]] + l for l in self.permute(nums[:i]+nums[i+1:])] # return result # iterative result = [[]] for n in nums: new_permutations = [] # each current configuration has to have this n inserted in it for permutation in result: # insert current n at all possible positions (including front and back) for i in range(len(permutation) + 1): new_permutations.append(permutation[:i] + [n] + permutation[i:]) result = new_permutations return result
class Solution: def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ result = [[]] for n in nums: new_permutations = [] for permutation in result: for i in range(len(permutation) + 1): new_permutations.append(permutation[:i] + [n] + permutation[i:]) result = new_permutations return result
class Solution: def numberOfWays(self, numPeople: int) -> int: kMod = int(1e9) + 7 # dp[i] := # of ways i handshakes pair w//o crossing dp = [1] + [0] * (numPeople // 2) for i in range(1, numPeople // 2 + 1): for j in range(i): dp[i] += dp[j] * dp[i - 1 - j] dp[i] %= kMod return dp[numPeople // 2]
class Solution: def number_of_ways(self, numPeople: int) -> int: k_mod = int(1000000000.0) + 7 dp = [1] + [0] * (numPeople // 2) for i in range(1, numPeople // 2 + 1): for j in range(i): dp[i] += dp[j] * dp[i - 1 - j] dp[i] %= kMod return dp[numPeople // 2]
# Language: Python 3 n = int(input()) if (n % 2 != 0): print("Weird") elif (2 <= n <= 5): print("Not Weird") elif (6 <= n <= 20): print("Weird") else: print("Not Weird")
n = int(input()) if n % 2 != 0: print('Weird') elif 2 <= n <= 5: print('Not Weird') elif 6 <= n <= 20: print('Weird') else: print('Not Weird')
bot_token = "" bot_token_dev = "" db_url = "" mod_db_url = "" cloudflare_email = "" cloudflare_token = "" error_webhook_token = "" error_webhook_id = 0 consumer_key = "" consumer_secret_key = "" access_token = "" access_token_secret = ""
bot_token = '' bot_token_dev = '' db_url = '' mod_db_url = '' cloudflare_email = '' cloudflare_token = '' error_webhook_token = '' error_webhook_id = 0 consumer_key = '' consumer_secret_key = '' access_token = '' access_token_secret = ''
# map function #iterable as list or array #function as def or lambda #map(function,iterable) or numbers=[1,2,3,4,5,6] #example def Sqrt(number): return number**2 a=list(map(Sqrt,numbers)) print(a) #example b=list(map(lambda number:number**3,numbers)) print(b) #map(str,int,double variable as convert,iterable) #example str_numbers=["1","2","3","4","5","6"] c=list(map(int,str_numbers)) print(c)
numbers = [1, 2, 3, 4, 5, 6] def sqrt(number): return number ** 2 a = list(map(Sqrt, numbers)) print(a) b = list(map(lambda number: number ** 3, numbers)) print(b) str_numbers = ['1', '2', '3', '4', '5', '6'] c = list(map(int, str_numbers)) print(c)
# # PySNMP MIB module ChrTrap-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ChrTrap-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:36:20 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection") chrComTrap, = mibBuilder.importSymbols("Chromatis-MIB", "chrComTrap") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") IpAddress, NotificationType, iso, TimeTicks, NotificationType, Counter64, Counter32, Integer32, ObjectIdentity, Gauge32, ModuleIdentity, MibIdentifier, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "NotificationType", "iso", "TimeTicks", "NotificationType", "Counter64", "Counter32", "Integer32", "ObjectIdentity", "Gauge32", "ModuleIdentity", "MibIdentifier", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") chrComTrapLoggedTrap = NotificationType((1, 3, 6, 1, 4, 1, 3695, 1, 6) + (0,1)) if mibBuilder.loadTexts: chrComTrapLoggedTrap.setDescription('This trap informs about a new event that was reported to the TrapLog table.') mibBuilder.exportSymbols("ChrTrap-MIB", chrComTrapLoggedTrap=chrComTrapLoggedTrap)
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_size_constraint, value_range_constraint, constraints_union, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsUnion', 'ConstraintsIntersection') (chr_com_trap,) = mibBuilder.importSymbols('Chromatis-MIB', 'chrComTrap') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (ip_address, notification_type, iso, time_ticks, notification_type, counter64, counter32, integer32, object_identity, gauge32, module_identity, mib_identifier, unsigned32, mib_scalar, mib_table, mib_table_row, mib_table_column, bits) = mibBuilder.importSymbols('SNMPv2-SMI', 'IpAddress', 'NotificationType', 'iso', 'TimeTicks', 'NotificationType', 'Counter64', 'Counter32', 'Integer32', 'ObjectIdentity', 'Gauge32', 'ModuleIdentity', 'MibIdentifier', 'Unsigned32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Bits') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') chr_com_trap_logged_trap = notification_type((1, 3, 6, 1, 4, 1, 3695, 1, 6) + (0, 1)) if mibBuilder.loadTexts: chrComTrapLoggedTrap.setDescription('This trap informs about a new event that was reported to the TrapLog table.') mibBuilder.exportSymbols('ChrTrap-MIB', chrComTrapLoggedTrap=chrComTrapLoggedTrap)
# Time: 218 ms # Memory: 4 KB for i in range(5): m = list(map(int, input().split())) if 1 in m: r, c = (m.index(1)), (i) sol = abs(r - 2) + abs(2 - c) print(sol)
for i in range(5): m = list(map(int, input().split())) if 1 in m: (r, c) = (m.index(1), i) sol = abs(r - 2) + abs(2 - c) print(sol)
nama = "azmi" umur_5_tahun_lalu = 23 print ("nama saya") print(nama) print("sedangkan umur saat ini adalah") print(umur_5_tahun_lalu + 5) if (nama == "nathan") : print("selamat datang Nathan!") elif (nama == "azmi") : print("selamat datang Azmi!") else : print("Selamat datang pak") print(nama)
nama = 'azmi' umur_5_tahun_lalu = 23 print('nama saya') print(nama) print('sedangkan umur saat ini adalah') print(umur_5_tahun_lalu + 5) if nama == 'nathan': print('selamat datang Nathan!') elif nama == 'azmi': print('selamat datang Azmi!') else: print('Selamat datang pak') print(nama)
def exact_cover(X, Y): X = {j: set() for j in X} for i, row in Y.items(): for j in row: X[j].add(i) return X, Y def select(X, Y, r): cols = [] for j in Y[r]: for i in X[j]: for k in Y[i]: if k != j: X[k].remove(i) cols.append(X.pop(j)) return cols def deselect(X, Y, r, cols): for j in reversed(Y[r]): X[j] = cols.pop() for i in X[j]: for k in Y[i]: if k != j: X[k].add(i) def solve(X, Y, solution): if not X: yield list(solution) else: c = min(X, key=lambda c: len(X[c])) for r in list(X[c]): solution.append(r) cols = select(X, Y, r) for s in solve(X, Y, solution): yield s deselect(X, Y, r, cols) solution.pop()
def exact_cover(X, Y): x = {j: set() for j in X} for (i, row) in Y.items(): for j in row: X[j].add(i) return (X, Y) def select(X, Y, r): cols = [] for j in Y[r]: for i in X[j]: for k in Y[i]: if k != j: X[k].remove(i) cols.append(X.pop(j)) return cols def deselect(X, Y, r, cols): for j in reversed(Y[r]): X[j] = cols.pop() for i in X[j]: for k in Y[i]: if k != j: X[k].add(i) def solve(X, Y, solution): if not X: yield list(solution) else: c = min(X, key=lambda c: len(X[c])) for r in list(X[c]): solution.append(r) cols = select(X, Y, r) for s in solve(X, Y, solution): yield s deselect(X, Y, r, cols) solution.pop()
class Node(object): '''Binary Tree Node''' def __init__(self, data): self.data = data self.left = None self.right = None class BinaryTree(object): '''Building binary Tree''' def __init__(self, data): self.root = Node(data) def addLeft(self, data): if self.root.left is None: self.root.left = Node(data) else: binary_tree_obj = Node(data) binary_tree_obj.left = self.root.left self.root.left = binary_tree_obj def addRight(self, data): if self.root.right is None: self.root.right = Node(data) else: binary_tree_obj = Node(data) binary_tree_obj.right = self.root.right self.root.right = binary_tree_obj def getRightChild(self): return self.root.right def getLeftChild(self): return self.root.left def setRightChild(self, value): self.root.right = value def setLeftChild(self, value): self.root.left = value def setRootValue(self, value): self.root.data = value def getRootValue(self): return self.root.data def __repr__(self): return str(self.root.data) binary_tree = BinaryTree(10) binary_tree.addLeft(20) binary_tree.addLeft(34) binary_tree.addRight(4) binary_tree.addRight(50) print(binary_tree) # This prints only the node # Create Binary tree
class Node(object): """Binary Tree Node""" def __init__(self, data): self.data = data self.left = None self.right = None class Binarytree(object): """Building binary Tree""" def __init__(self, data): self.root = node(data) def add_left(self, data): if self.root.left is None: self.root.left = node(data) else: binary_tree_obj = node(data) binary_tree_obj.left = self.root.left self.root.left = binary_tree_obj def add_right(self, data): if self.root.right is None: self.root.right = node(data) else: binary_tree_obj = node(data) binary_tree_obj.right = self.root.right self.root.right = binary_tree_obj def get_right_child(self): return self.root.right def get_left_child(self): return self.root.left def set_right_child(self, value): self.root.right = value def set_left_child(self, value): self.root.left = value def set_root_value(self, value): self.root.data = value def get_root_value(self): return self.root.data def __repr__(self): return str(self.root.data) binary_tree = binary_tree(10) binary_tree.addLeft(20) binary_tree.addLeft(34) binary_tree.addRight(4) binary_tree.addRight(50) print(binary_tree)
def is_k_anonymous(df, partition, sensitive_column, k=3): """ :param df: The dataframe on which to check the partition. :param partition: The partition of the dataframe to check. :param sensitive_column: The name of the sensitive column :param k: The desired k :returns : True if the partition is valid according to our k-anonymity criteria, False otherwise. """ if len(partition) < k: # we cannot split this partition further... return False return True def partition_dataset(df, feature_columns, sensitive_column, scale, is_valid): """ :param df: The dataframe to be partitioned. :param feature_columns: A list of column names along which to partition the dataset. :param sensitive_column: The name of the sensitive column (to be passed on to the `is_valid` function) :param scale: The column spans as generated before. :param is_valid: A function that takes a dataframe and a partition and returns True if the partition is valid. :returns : A list of valid partitions that cover the entire dataframe. """ finished_partitions = [] partitions = [df.index] while partitions: partition = partitions.pop(0) spans = get_spans(df[feature_columns], partition, scale) for column, span in sorted(spans.items(), key=lambda x:-x[1]): #we try to split this partition along a given column lp, rp = split(df, partition, column) if not is_valid(df, lp, sensitive_column) or not is_valid(df, rp, sensitive_column): continue # the split is valid, we put the new partitions on the list and continue partitions.extend((lp, rp)) break else: # no split was possible, we add the partition to the finished partitions finished_partitions.append(partition) return finished_partitions
def is_k_anonymous(df, partition, sensitive_column, k=3): """ :param df: The dataframe on which to check the partition. :param partition: The partition of the dataframe to check. :param sensitive_column: The name of the sensitive column :param k: The desired k :returns : True if the partition is valid according to our k-anonymity criteria, False otherwise. """ if len(partition) < k: return False return True def partition_dataset(df, feature_columns, sensitive_column, scale, is_valid): """ :param df: The dataframe to be partitioned. :param feature_columns: A list of column names along which to partition the dataset. :param sensitive_column: The name of the sensitive column (to be passed on to the `is_valid` function) :param scale: The column spans as generated before. :param is_valid: A function that takes a dataframe and a partition and returns True if the partition is valid. :returns : A list of valid partitions that cover the entire dataframe. """ finished_partitions = [] partitions = [df.index] while partitions: partition = partitions.pop(0) spans = get_spans(df[feature_columns], partition, scale) for (column, span) in sorted(spans.items(), key=lambda x: -x[1]): (lp, rp) = split(df, partition, column) if not is_valid(df, lp, sensitive_column) or not is_valid(df, rp, sensitive_column): continue partitions.extend((lp, rp)) break else: finished_partitions.append(partition) return finished_partitions
YELLOW = (255, 255, 0) CYAN = (0, 255, 255) RED = (255, 0, 0)
yellow = (255, 255, 0) cyan = (0, 255, 255) red = (255, 0, 0)
# this is a python file created in jupyter notbook def list_fruits(fruits=[]): for fruit in fruits: print(fruit) fruits = ['apple','kiwi','banana'] list_fruit(fruits)
def list_fruits(fruits=[]): for fruit in fruits: print(fruit) fruits = ['apple', 'kiwi', 'banana'] list_fruit(fruits)
lst = [['Harry', 37.21],['Berry', 37.21],['Tina', 37.2],['Akriti', 41],['Harsh', 39]] second_highest = sorted(list(set([marks for name, marks in lst])))[1] print('\n'.join([a for a,b in sorted(lst) if b == second_highest]))
lst = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]] second_highest = sorted(list(set([marks for (name, marks) in lst])))[1] print('\n'.join([a for (a, b) in sorted(lst) if b == second_highest]))
_menu_name = "Networking" _ordering = [ "wpa_cli", "network", "nmap", "upnp"]
_menu_name = 'Networking' _ordering = ['wpa_cli', 'network', 'nmap', 'upnp']
i = 0 while True: n, q = map(int, input().split()) if n == 0 and q == 0: break marble_numbers = [] while n>0: n -= 1 num = int(input()) marble_numbers.append(num) marble_numbers.sort() i += 1 print(f"CASE# {i}:") while q > 0: q -= 1 qy = int(input()) if qy in marble_numbers: print(f"{qy} found at {marble_numbers.index(qy) + 1}") else: print(f"{qy} not found")
i = 0 while True: (n, q) = map(int, input().split()) if n == 0 and q == 0: break marble_numbers = [] while n > 0: n -= 1 num = int(input()) marble_numbers.append(num) marble_numbers.sort() i += 1 print(f'CASE# {i}:') while q > 0: q -= 1 qy = int(input()) if qy in marble_numbers: print(f'{qy} found at {marble_numbers.index(qy) + 1}') else: print(f'{qy} not found')
class Board: ''' A 3x3 board for TicTacToe ''' __board = '' __print_board = '' def __init__(self): self.__board = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']] self.make_printable() def __str__(self): self.make_printable() return self.__print_board def get_board(self): return self.__board def make_printable(self): c_gap = ' ----------- ' r_gap = ' | ' self.__print_board = c_gap + '\n' for l_board in self.__board: self.__print_board += r_gap for d in l_board: self.__print_board += d self.__print_board += r_gap self.__print_board += '\n' + c_gap + '\n' def is_space_available(self, pos: str): row1 = self.__board[0] row2 = self.__board[1] row3 = self.__board[2] if not pos.isdigit(): return False r1 = range(1, 4).count(int(pos)) and row1[int(pos) - 1] == str(pos) r2 = range(4, 7).count(int(pos)) and row2[int(pos) - 4] == str(pos) r3 = range(7, 10).count(int(pos)) and row3[int(pos) - 7] == str(pos) return r1 or r2 or r3 def is_full(self): board = self.__board for row in board: for elem in row: if elem.isdigit(): return False return True def place(self, marker: str, pos: str): if not (int(pos) >= 1 and int(pos) <= 9): return False for row in self.__board: if pos in row: row[row.index(pos)] = marker return True return False
class Board: """ A 3x3 board for TicTacToe """ __board = '' __print_board = '' def __init__(self): self.__board = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']] self.make_printable() def __str__(self): self.make_printable() return self.__print_board def get_board(self): return self.__board def make_printable(self): c_gap = ' ----------- ' r_gap = ' | ' self.__print_board = c_gap + '\n' for l_board in self.__board: self.__print_board += r_gap for d in l_board: self.__print_board += d self.__print_board += r_gap self.__print_board += '\n' + c_gap + '\n' def is_space_available(self, pos: str): row1 = self.__board[0] row2 = self.__board[1] row3 = self.__board[2] if not pos.isdigit(): return False r1 = range(1, 4).count(int(pos)) and row1[int(pos) - 1] == str(pos) r2 = range(4, 7).count(int(pos)) and row2[int(pos) - 4] == str(pos) r3 = range(7, 10).count(int(pos)) and row3[int(pos) - 7] == str(pos) return r1 or r2 or r3 def is_full(self): board = self.__board for row in board: for elem in row: if elem.isdigit(): return False return True def place(self, marker: str, pos: str): if not (int(pos) >= 1 and int(pos) <= 9): return False for row in self.__board: if pos in row: row[row.index(pos)] = marker return True return False
#TempConvert_loop.py for i in range(3): val = input("Input the temp:(32C)") if val[-1] in ['C','c']: f = 1.8 * float(val[0:-1]) + 32 print("Converted temp is: %.2fF"%f) elif val[-1] in ['F','f']: c = (float(val[0:-1]) - 32) / 1.8 print("Converted temp is: %.2fC"%c) else: print("Wrong input")
for i in range(3): val = input('Input the temp:(32C)') if val[-1] in ['C', 'c']: f = 1.8 * float(val[0:-1]) + 32 print('Converted temp is: %.2fF' % f) elif val[-1] in ['F', 'f']: c = (float(val[0:-1]) - 32) / 1.8 print('Converted temp is: %.2fC' % c) else: print('Wrong input')
CLASSIFIER_SCALE = 1.1 CLASSIFIER_NEIGHBORS = 5 CLASSIFIER_MIN_SZ = (50, 50) MIN_SAMPLES_PER_USER = 50 FACE_BOX_COLOR = (255, 0, 255) FACE_TXT_COLOR = (115, 249, 255) LBP_RADIUS = 2 LBP_NEIGHBORS = 16 LBP_GRID_X = 8 LBP_GRID_Y = 8 KNOWN_USER_FILE = 'users.lst' LBPH_MACHINE_LEARNING_FILE = 'lbph_face_recognizer.yaml' HEURISTIC_FILE_PREFIX = 'heuristic_face_recognizer' LIB_FACE_RECOGNITION_FILE_PREFIX = 'lib_face_recognition' ALLOWED_METHODS = ['lbph_machinelearning', 'heuristic', 'lib_face_recognition'] HEURISTIC_CERTAIN = .15
classifier_scale = 1.1 classifier_neighbors = 5 classifier_min_sz = (50, 50) min_samples_per_user = 50 face_box_color = (255, 0, 255) face_txt_color = (115, 249, 255) lbp_radius = 2 lbp_neighbors = 16 lbp_grid_x = 8 lbp_grid_y = 8 known_user_file = 'users.lst' lbph_machine_learning_file = 'lbph_face_recognizer.yaml' heuristic_file_prefix = 'heuristic_face_recognizer' lib_face_recognition_file_prefix = 'lib_face_recognition' allowed_methods = ['lbph_machinelearning', 'heuristic', 'lib_face_recognition'] heuristic_certain = 0.15
potencia = int(input()) tempo = int(input()) qw = potencia / 1000 hr = tempo / 60 kwh = hr * qw print('{:.1f} kWh'.format(kwh))
potencia = int(input()) tempo = int(input()) qw = potencia / 1000 hr = tempo / 60 kwh = hr * qw print('{:.1f} kWh'.format(kwh))
n = 60 for i in range(10000): 2 ** n
n = 60 for i in range(10000): 2 ** n
"""Script to fix indentation of given ``.po`` files.""" __author__ = """Julien Palard""" __email__ = "julien@palard.fr" __version__ = "1.0.0"
"""Script to fix indentation of given ``.po`` files.""" __author__ = 'Julien Palard' __email__ = 'julien@palard.fr' __version__ = '1.0.0'
class Solution(object): def XXX(self, m, n): """ :type m: int :type n: int :rtype: int """ dp = [1]*n dp = [dp]*m for i in range(m): for j in range(n): if i!=0 and j!=0: dp[i][j] = dp[i-1][j] + dp[i][j-1] return dp[m-1][n-1]
class Solution(object): def xxx(self, m, n): """ :type m: int :type n: int :rtype: int """ dp = [1] * n dp = [dp] * m for i in range(m): for j in range(n): if i != 0 and j != 0: dp[i][j] = dp[i - 1][j] + dp[i][j - 1] return dp[m - 1][n - 1]
# ................................................................................................................. level_dict["bombs"] = { "scheme": "red_scheme", "size": (9,9,9), "intro": "bombs", "help": ( "$scale(1.5)mission:\nget to the exit!\n\n" + \ "to get to the exit,\nuse the bombs", ), "player": { "position": (0,-4,0), }, "exits": [ { "name": "exit", "active": 1, "position": (0,2,0), }, ], "create": """ world.addObjectAtPos (KikiBomb(), world.decenter (0,-4,2)) world.addObjectAtPos (KikiBomb(), world.decenter (0,-4,-2)) world.addObjectAtPos (KikiBomb(), world.decenter (-3,-2,0)) """, }
level_dict['bombs'] = {'scheme': 'red_scheme', 'size': (9, 9, 9), 'intro': 'bombs', 'help': ('$scale(1.5)mission:\nget to the exit!\n\n' + 'to get to the exit,\nuse the bombs',), 'player': {'position': (0, -4, 0)}, 'exits': [{'name': 'exit', 'active': 1, 'position': (0, 2, 0)}], 'create': '\nworld.addObjectAtPos (KikiBomb(), world.decenter (0,-4,2))\nworld.addObjectAtPos (KikiBomb(), world.decenter (0,-4,-2))\nworld.addObjectAtPos (KikiBomb(), world.decenter (-3,-2,0))\n'}
class BaseDecoder(object): def __init__(self, name="BaseDecoder"): self.name = name print(name) def decode(self, **kwargs): """ Using for greedy decoding for a given input, may corresponding with gold target, return the log_probability of decoder steps. """ raise NotImplementedError def score(self, **kwargs): """ Used for teacher-forcing training, return the log_probability of <input,output>. """ raise NotImplementedError
class Basedecoder(object): def __init__(self, name='BaseDecoder'): self.name = name print(name) def decode(self, **kwargs): """ Using for greedy decoding for a given input, may corresponding with gold target, return the log_probability of decoder steps. """ raise NotImplementedError def score(self, **kwargs): """ Used for teacher-forcing training, return the log_probability of <input,output>. """ raise NotImplementedError
class Calculator: def __init__(self, socket): self.socket = socket def run(self): self.socket.emit('response', 'Here is your result')
class Calculator: def __init__(self, socket): self.socket = socket def run(self): self.socket.emit('response', 'Here is your result')
#import sys def interpret_bf_code(bf_code, memory_size = 30000): ''' (str, (int)) -> str This function interprets code in the BrainFuck language, which is passed in via bf_code parameter and returns the output of executing that code. If so specified in BrainFuck code, the function reads input from user. ''' instruction_PTR = 0 memory_PTR = memory_size // 2 memory = [0] * memory_size Output = "" while instruction_PTR < len(bf_code): ch = bf_code[instruction_PTR] if ch == '>': memory_PTR = (memory_PTR + 1) % memory_size; elif ch == '<': memory_PTR = (memory_PTR - 1) % memory_size; elif ch == '+': memory[memory_PTR] = memory[memory_PTR] + 1; elif ch == '-': memory[memory_PTR] = memory[memory_PTR] - 1; elif ch == '.': # chr(int) -> char converts int to a char with corresponding ASCII code out_ch = chr( memory[memory_PTR] ) Output = Output + out_ch elif ch == ',': # ord(char) -> int converts char to its corresponding ASCII code in_ch = input("Input 1 byte in form of a single character: ") memory[memory_PTR] = ord(in_ch[0]) elif ch == '[': if memory[memory_PTR] == 0: loops = 1 while loops > 0: instruction_PTR +=1 if bf_code[instruction_PTR] == '[': loops += 1 elif bf_code[instruction_PTR] == ']': loops -= 1 elif ch == ']': loops = 1 while loops > 0: instruction_PTR -=1 if bf_code[instruction_PTR] == '[': loops -= 1 elif bf_code[instruction_PTR] == ']': loops += 1 instruction_PTR -= 1 instruction_PTR +=1 print(Output) return Output #if len(sys.argv) >= 2: # bf_code = sys.argv[1] # interpret_bf_code(bf_code) if __name__ == "__main__": bf_test_code = input("Type in BrainFuck code: ") interpret_bf_code(bf_test_code)
def interpret_bf_code(bf_code, memory_size=30000): """ (str, (int)) -> str This function interprets code in the BrainFuck language, which is passed in via bf_code parameter and returns the output of executing that code. If so specified in BrainFuck code, the function reads input from user. """ instruction_ptr = 0 memory_ptr = memory_size // 2 memory = [0] * memory_size output = '' while instruction_PTR < len(bf_code): ch = bf_code[instruction_PTR] if ch == '>': memory_ptr = (memory_PTR + 1) % memory_size elif ch == '<': memory_ptr = (memory_PTR - 1) % memory_size elif ch == '+': memory[memory_PTR] = memory[memory_PTR] + 1 elif ch == '-': memory[memory_PTR] = memory[memory_PTR] - 1 elif ch == '.': out_ch = chr(memory[memory_PTR]) output = Output + out_ch elif ch == ',': in_ch = input('Input 1 byte in form of a single character: ') memory[memory_PTR] = ord(in_ch[0]) elif ch == '[': if memory[memory_PTR] == 0: loops = 1 while loops > 0: instruction_ptr += 1 if bf_code[instruction_PTR] == '[': loops += 1 elif bf_code[instruction_PTR] == ']': loops -= 1 elif ch == ']': loops = 1 while loops > 0: instruction_ptr -= 1 if bf_code[instruction_PTR] == '[': loops -= 1 elif bf_code[instruction_PTR] == ']': loops += 1 instruction_ptr -= 1 instruction_ptr += 1 print(Output) return Output if __name__ == '__main__': bf_test_code = input('Type in BrainFuck code: ') interpret_bf_code(bf_test_code)
# flatten 2D arrays into a single array A = [[1, 2, 3], [4], [5, 6]] # iterative version def flatten_iterative(A): result = [] for array in A: for element in array: result.append(element) return result print(flatten_iterative(A)) # recursively traverse 2 dimensional list out of order. def traverse_list(A): result = [] def traverse_list_rec(A, i, j): if i >= len(A) or j >= len(A[i]): return traverse_list_rec(A, i + 1, j) traverse_list_rec(A, i, j + 1) result.append(A[i][j]) traverse_list_rec(A, 0, 0) return result print(traverse_list(A)) # recursively traverse 2 dimensional list in order. def flatten(A): result = [] def flatten_recursive(A, i, j, result): if i == len(A): return if j == len(A[i]): flatten_recursive(A, i + 1, 0, result) return result.append(A[i][j]) flatten_recursive(A, i, j + 1, result) flatten_recursive(A, 0, 0, result) return result print(flatten(A))
a = [[1, 2, 3], [4], [5, 6]] def flatten_iterative(A): result = [] for array in A: for element in array: result.append(element) return result print(flatten_iterative(A)) def traverse_list(A): result = [] def traverse_list_rec(A, i, j): if i >= len(A) or j >= len(A[i]): return traverse_list_rec(A, i + 1, j) traverse_list_rec(A, i, j + 1) result.append(A[i][j]) traverse_list_rec(A, 0, 0) return result print(traverse_list(A)) def flatten(A): result = [] def flatten_recursive(A, i, j, result): if i == len(A): return if j == len(A[i]): flatten_recursive(A, i + 1, 0, result) return result.append(A[i][j]) flatten_recursive(A, i, j + 1, result) flatten_recursive(A, 0, 0, result) return result print(flatten(A))
# This class provides a way to drive a robot which has a drive train equipped # with separate motors powering the left and right sides of a robot. # Two different drive methods exist: # Arcade Drive: combines 2-axes of a joystick to control steering and driving speed. # Tank Drive: uses two joysticks to control motor speeds left and right. # A Pololu Maestro is used to send PWM signals to left and right motor controllers. # When using motor controllers, the maestro's speed setting can be used to tune the # responsiveness of the robot. Low values dampen acceleration, making for a more # stable robot. High values increase responsiveness, but can lead to a tippy robot. # Try values around 50 to 100. RESPONSIVENESS = 60 # this is also considered "speed" # These are the motor controller limits, measured in Maestro units. # These default values typically work fine and align with maestro's default limits. # Vaules should be adjusted so that center stops the motors and the min/max values # limit speed range you want for your robot. MIN = 4000 CENTER = 6000 MAX = 8000 class SimpleServo: # Pass the maestro controller object and the maestro channel numbers being used # for the left and right motor controllers. See maestro.py on how to instantiate maestro. def __init__(self, maestro, channel): self.maestro = maestro self.channel = channel # Init motor accel/speed params self.maestro.setAccel(self.channel, 0) self.maestro.setSpeed(self.channel, RESPONSIVENESS) # Motor min/center/max values self.min = MIN self.center = CENTER self.max = MAX # speed is -1.0 to 1.0 def drive(self, amount): # convert to servo units if (amount >= 0): target = int(self.center + (self.max - self.center) * amount) else: target = int(self.center + (self.center - self.min) * amount) self.maestro.setTarget(self.channel, target) # Set both motors to stopped (center) position def stop(self): self.maestro.setAccel(self.channel, self.center) # Close should be used when shutting down Drive object def close(self): self.stop()
responsiveness = 60 min = 4000 center = 6000 max = 8000 class Simpleservo: def __init__(self, maestro, channel): self.maestro = maestro self.channel = channel self.maestro.setAccel(self.channel, 0) self.maestro.setSpeed(self.channel, RESPONSIVENESS) self.min = MIN self.center = CENTER self.max = MAX def drive(self, amount): if amount >= 0: target = int(self.center + (self.max - self.center) * amount) else: target = int(self.center + (self.center - self.min) * amount) self.maestro.setTarget(self.channel, target) def stop(self): self.maestro.setAccel(self.channel, self.center) def close(self): self.stop()
""" ------------------------------------------------------------------------------- G E N E R A L I N F O R M A T I O N ------------------------------------------------------------------------------- This file contains general constants and information about the variables saved in the netCDF file needed for plotgen.py. The list variables sortPlots, plotNames and lines are sorted identically in order to relate the individual variables. """ #------------------------------------------------------------------------------- # C O N S T A N T S #------------------------------------------------------------------------------- DAY = 24 HOUR = 3600 KG = 1000. g_per_second_to_kg_per_day = 1. / (DAY * HOUR * KG) kg_per_second_to_kg_per_day = 1. / (DAY * HOUR) #------------------------------------------------------------------------------- # P L O T S #------------------------------------------------------------------------------- # Names of the variables sortPlots = ['theta_l', 'r_t', 'theta_l_flux', 'r_t_flux', 'cloudliq_frac', 'r_c', 'w_var', 'w3', 'theta_l_var', 'r_t_var', 'covar_thetal_rt', 'wobs', 'U', 'V', 'covar_uw', 'covar_vw', 'u_var', 'v_var',\ 'QR', 'QR_IP', 'QRP2', 'QRP2_QRIP', \ 'Nrm', 'Nrm_IP', 'Nrp2', 'Nrp2_NrmIP', \ 'Ncm', 'Ncm_IP', 'Ncp2', 'Ncp2_NcmIP', \ 'Ngm', 'Ngm_IP', 'Ngp2', 'Ngp2_NgmIP', \ 'Qgm', 'Qgm_IP', 'Qgp2', 'Qgp2_QgmIP', \ 'Qim', 'Qim_IP', 'Qip2', 'Qip2_QimIP', \ 'Nim', 'Nim_IP', 'Nip2', 'Nip2_NimIP', \ 'Qsm', 'Qsm_IP', 'Qsp2', 'Qsp2_QsmIP', \ 'Nsm', 'Nsm_IP', 'Nsp2', 'Nsp2_NsmIP', \ 'MicroFractions', 'Buoy_Flux', \ 'uprcp', 'uprtp', 'upthlp', \ 'vprcp', 'vprtp', 'vpthlp', \ ] # settings of each plot: # plot number, plot title, axis label plotNames = [\ ['Liquid Water Potential Temperature, theta_l', 'thetal [K]'],\ ['Total Water Mixing Ratio, r_t', 'rtm / qt [kg/kg]'],\ ['Turbulent Flux of theta_l', 'wpthlp / thflux(s) [K m/s]'],\ ['Turbulent Flux of r_t', 'wprtp / qtflux(s) [(kg/kg) m/s]'],\ ['Cloud Liquid Fraction', ' [%/100]'],\ ['Cloud Water Mixing Ratio, r_c', 'rcm / qcl [kg/kg]'],\ ['Variance of w', 'wp2 / w2 [m^2/s^2]'],\ ['Third-order Moment of w', 'wp3 / w3 [m^3/s^3]'],\ ['Variance of theta_l', 'thlp2 / tl2 [K^2]'],\ ['Variance of r_t', 'rtp2 / qtp2 [(kg/kg)^2]'],\ ['Covariance of r_t & theta_l', 'rtpthlp [(kg/kg) K]'],\ ['Vertical Wind Component, w (subsidence)', 'wobs [m/s]'],\ ['Zonal Wind Component, u', 'um / u [m/s]'],\ ['Meridonal Wind Component, v', 'vm / v [m/s]'],\ ['Covariance of u & w', 'upwp / uw [m^2/s^2]'],\ ['Covariance of v & w', 'vpwp / vw [m^2/s^2]'],\ ['Variance of u wind', 'up2 / u2 [m^2/s^2]'],\ ['Variance of v wind', 'vp2 / v2 [m^2/s^2]'],\ # Rain Water Mixing Ratio ['Rain Water Mixing Ratio', 'qrm [kg/kg]'],\ ['Rain Water Mixing Ratio in Rain', 'qrm_ip [kg/kg]'],\ ['Domain-wide Variance\nof Rain Water Mixing Ratio', 'qrp2 [(kg/kg)^2]'],\ ['Within-rain Variance\nof Rain Water Mixing Ratio', 'qrp2_ip / qrm_ip^2 [-]'],\ #Rain Drop Number Concentration ['Rain Drop Concentration', 'Nrm [num/kg]'],\ ['Rain Drop Concentration in Rain', 'Nrm_ip [num/kg]'],\ ['Domain-wide Variance\nof Rain Drop Concentration', 'Nrp2 [(num/kg)^2]'],\ ['Within-rain Variance\nof Rain Drop Concentration', 'Nrp2_ip / Nrm_ip^2 [-]'],\ #Cloud Droplet Number Concentration ['Cloud Droplet Number Concentration', 'Ncm [num/kg]'],\ ['Cloud Droplet Number Concentration in Cloud', 'Ncm_ip [num/kg]'],\ ['Domain-wide Variance\nof Cloud Droplet Number Concentration', 'Ncp2 [(#/kg)^2]'],\ ['Within-cloud Variance\nof Cloud Droplet Number Concentration', 'Ncp2_ip / Ncm_ip^2 [-]'],\ #Graupel Number Concentration ['Graupel Number Concentration', 'Ngm [kg/kg]'],\ ['Graupel Number Concentration in Graupel', 'Ngm_ip [num/kg]'],\ ['Domain-wide Variance\nof Graupel Number Concentration', 'Ngp2 [(kg/kg)^2]'],\ ['Within-graupel Variance\nof Graupel Number Concentration', 'Ngp2_ip / Ngm_ip^2 [-]'],\ #Graupel Mixing Ratio ['Graupel Mixing Ratio', 'qgm [kg/kg]'],\ ['Graupel Mixing Ratio in Graupel', 'qgm_ip [kg/kg]'],\ ['Domain-wide Variance\nof Graupel Mixing Ratio', 'qgp2 [(kg/kg)^2]'],\ ['Within-graupel Variance\nof Graupel Mixing Ratio', 'qgp2_ip / qgm_ip^2 [-]'],\ #Cloud Ice Mixing Ratio ['Cloud Ice Mixing Ratio', 'qim [kg/kg]'],\ ['Cloud Ice Mixing Ratio in Cloud Ice', 'qim_ip [kg/kg]'],\ ['Domain-wide Variance\nof Cloud Ice Mixing Ratio', 'qip2 [(kg/kg)^2]'],\ ['Within-cloud-ice Variance\nof Cloud Ice Mixing Ratio', 'qip2_ip / qim_ip^2 [-]'],\ #Cloud Ice Number Concentration ['Cloud Ice Concentration', 'Nim [num/kg]'],\ ['Cloud Ice Number Concentration in Cloud Ice', 'Ni_ip [num/kg]'],\ ['Domain-wide Variance\nof Cloud Ice Number Concentration', 'Nip2 [(num/kg)^2]'],\ ['Within-cloud-ice Variance\nof Cloud Ice Number Concentration', 'Nip2_ip / Nim_ip^2 [-]'],\ #Snow Mixing Ratio ['Snow Mixing Ratio ', 'qsm [kg/kg]'],\ ['Snow Mixing Ratio in Snow', 'qsm_ip [kg/kg]'],\ ['Domain-wide Variance\nof Snow Mixing Ratio', 'qsp2 [(kg/kg)^2]'],\ ['Within-snow Variance\nof Snow Mixing Ratio ', 'qsp2_ip / qsm_ip^2 [-]'],\ #Snow Number Concentration ['Snow Number Concentration', 'Nsm [num/kg]'],\ ['Snow Number Concentration in Snow', 'Nsm_ip [num/kg]'],\ ['Domain-wide Variance\nof Snow Number Concentration', 'Nsp2 [(#/kg)^2]'],\ ['Within-snow Variance\nof Snow Number Concentration', 'Nsp2_ip / Nsm_ip^2 [-]'],\ ['Micro Fractions', '[%/100]'],\ ['Buoyancy flux', 'wpthvp / tlflux [K m/s]'],\ #['Liquid Water Path', 'lwp [kg/m^2]'],\ #['Surface rainfall rate', 'rain_rate_sfc[mm/day]'],\ #['Density-Weighted Vertically Averaged wp2', 'wp2 / w2 [m^2/s^2]'],\ #['Cloud Ice Water Path', 'iwp [kg/m^2]'],\ #['Snow Water Path', 'swp [kg/m^2]'],\ # buoyancy sub-terms for parameterization in upwp budget ['Covariance of u & rc', 'uprcp / urc [m^2/s^2]'],\ ['Covariance of u & rt', 'uprtp / urt [m^2/s^2]'],\ ['Covariance of u & thl', 'upthlp / uthl [m^2/s^2]'],\ # buoyancy sub-terms for parameterization in upwp budget ['Covariance of v & rc', 'vprcp / urc [m^2/s^2]'],\ ['Covariance of v & rt', 'vprtp / urt [m^2/s^2]'],\ ['Covariance of v & thl', 'vpthlp / uthl [m^2/s^2]'],\ ] # lines of each plot: # variable name within python, shall this variable be plotted?, variable name in SAM output, conversion thetal = [\ # variables of thetal ['THETAL', False, 'THETAL', 1., 0],\ ['THETA', False, 'THETA', 1., 0],\ ['TABS', False, 'TABS', 1., 0],\ ['QI', False, 'QI', 1./KG, 0],\ ['THETAL', True, 'THETAL + 2500.4 * (THETA/TABS) * QI', 1., 0],\ ] rt = [\ # variables of rt ['QI', False, 'QI', 1., 0],\ ['QT', False, 'QT', 1., 0],\ ['RT', True, '(QT-QI)', 1./KG, 0],\ ] thetalflux = [\ # variables of thetalflux ['TLFLUX', False, 'TLFLUX', 1., 0],\ ['RHO', False, 'RHO', 1., 0],\ ['WPTHLP_SGS', False, 'WPTHLP_SGS', 1., 0],\ ['THETALFLUX', True, '((TLFLUX) / (RHO * 1004.)) + WPTHLP_SGS', 1., 0],\ ] rtflux = [\ # variables of rtflux ['QTFLUX', False, 'TLFLUX', 1., 0],\ ['RHO', False, 'RHO', 1., 0],\ ['WPRTP_SGS', False, 'WPRTP_SGS', 1., 0],\ ['RTFLUX', True, '(QTFLUX / (RHO * 2.5104e+6)) + WPRTP_SGS', 1., 0],\ ] cloudliqfrac = [\ # variables of cloudliqfrac ['cloudliq_frac_em6', True, 'cloudliq_frac_em6', 1., 0],\ ] qcl = [\ # variables of qcl ['QCL', True, 'QCL', 1./KG, 0],\ ] wVar = [\ # variables of wVar ['WP2_SGS', False, 'WP2_SGS', 1., 0],\ ['W2', False, 'W2', 1., 0],\ ['WVAR', True, 'WP2_SGS + W2', 1., 0],\ ] w3 = [\ # variables of wVar ['WP3_SGS', False, 'WP3_SGS', 1., 0],\ ['W3', False, 'W3', 1., 0],\ ['W3', True, 'WP3_SGS + W3', 1., 0],\ ] thetalVar = [\ # variables of thetalVar ['THLP2_SGS', False, 'THLP2_SGS', 1., 0],\ ['TL2', False, 'TL2', 1., 0],\ ['THETALVAR', True, 'THLP2_SGS + TL2', 1., 0],\ ] rtVar = [\ # variables of rtVar ['RTP2_SGS', False, 'RTP2_SGS', 1., 0],\ ['QT2', False, 'QT2', 1., 0],\ ['RTVAR', True, '(QT2 / 1e+6) + RTP2_SGS', 1., 0],\ ] covarThetalRt = [\ # variables of covarThetalRt ['CovarThetaLRT', True, 'RTPTHLP_SGS', 1., 0],\ ] wobs = [\ # variables of wobs ['WOBS', True, 'WOBS', 1., 0],\ ] U = [\ # variables of U ['U', True, 'U', 1., 0],\ ] V = [\ # variables of V ['V', True, 'V', 1., 0],\ ] covarUW = [\ # variables of covarUV ['UPWP_SGS', False, 'UPWP_SGS', 1., 0],\ ['UW', False, 'UW', 1., 0],\ ['UW', True, 'UW + UPWP_SGS', 1., 0],\ ] covarVW = [\ # variables of covarVW ['VPWP_SGS', False, 'VPWP_SGS', 1., 0],\ ['VW', False, 'VW', 1., 0],\ ['VW', True, 'VW + VPWP_SGS', 1., 0],\ ] uVar = [\ # variables of uVar ['UP2_SGS', False, 'UP2_SGS', 1., 0],\ ['U2', False, 'U2', 1., 0],\ ['UVAR', True, 'UP2_SGS + U2', 1., 0],\ ] vVar = [\ # variables of vVar ['VP2_SGS', False, 'VP2_SGS', 1., 0],\ ['V2', False, 'V2', 1., 0],\ ['VVAR', True, 'VP2_SGS + V2', 1., 0],\ ] # Rain Water Mixing Ratio QR = [\ # variables of QR ['QR', True, 'QR', 1./KG, 0],\ ] QRIP = [\ # variables of QRIP ['qrainm_ip', True, 'qrainm_ip', 1., 0],\ ] QRP2 = [\ # variables of QRP2 ['qrainp2', True, 'qrainp2', 1., 0],\ ] QRP2_QRIP = [\ # variables of QRP2_QRIP ['qrainp2_ip', False, 'qrainp2_ip', 1., 0],\ ['qrainm_ip', False, 'qrainm_ip', 1., 0],\ ['QRP2_QRIP', True, '(qrainp2_ip / (np.maximum(np.full(n,1e-5),qrainm_ip)**2))', 1., 0],\ ] #Rain Drop Number Concentration Nrm = [\ # variables of Nrm ['NR', False, 'NR', 1., 0],\ ['RHO', False, 'RHO', 1., 0],\ ['NRM', True, '(NR * 1e+6) / RHO', 1., 0],\ ] Nrm_IP = [\ # variables of Nrm_IP ['nrainm_ip', True, 'nrainm_ip', 1., 0],\ ] Nrp2 = [\ # variables of Nrp2 ['nrainp2', True, 'nrainp2', 1., 0],\ ] Nrp2_NrmIP = [\ # variables of Nrp2_NrmIP ['nrainp2_ip', False, 'nrainp2_ip', 1., 0],\ ['nrainm_ip', False, 'nrainm_ip', 1., 0],\ ['Nrp2_NrmIP', True, '(nrainp2_ip / (np.maximum(np.full(n,1e-5),nrainm_ip)**2))', 1., 0],\ ] #Cloud Droplet Number Concentration Ncm = [\ # variables of Ncm ['NC', False, 'NC', 1., 0],\ ['RHO', False, 'RHO', 1., 0],\ ['NCM', True, '(NC * 1e+6) / RHO', 1., 0],\ ] Ncm_IP = [\ # variables of Ncm_IP ['ncloudliqm_ip', True, 'ncloudliqm_ip', 1., 0],\ ] Ncp2 = [\ # variables of Ncp2 ['Ncp2', True, 'Ncp2', 1., 0],\ ] Ncp2_NcmIP = [\ # variables of Ncp2_NcmIP ['ncloudliqp2_ip', False, 'ncloudliqp2_ip', 1., 0],\ ['ncloudliqm_ip', False, 'ncloudliqm_ip', 1., 0],\ ['Ncp2_NcmIP', True, '(ncloudliqp2_ip / (np.maximum(np.full(n,1e-5),ncloudliqm_ip)**2))', 1., 0],\ ] #Graupel Number Concentration Ngm = [\ # variables of Ngm ['NG', False, 'NG', 1., 0],\ ['RHO', False, 'RHO', 1., 0],\ ['NGM', True, '(NG * 1e+6) / RHO', 1., 0],\ ] Ngm_IP = [\ # variables of Ngm_IP ['ngraupelm_ip', True, 'ngraupelm_ip', 1., 0],\ ] Ngp2 = [\ # variables of Ngp2 ['ngraupelp2', True, 'ngraupelp2', 1., 0],\ ] Ngp2_NgmIP = [\ # variables of Ngp2_NgmIP ['ngraupelp2_ip', False, 'ngraupelp2_ip', 1., 0],\ ['ngraupelm_ip', False, 'ngraupelm_ip', 1., 0],\ ['Ngp2_NgmIP', True, '(ngraupelp2_ip / (np.maximum(np.full(n,1e-5),ngraupelm_ip)**2))', 1., 0],\ ] #Graupel Mixing Ratio Qgm = [\ # variables of Qgm ['QG', True, 'QG', 1./KG, 0],\ ] Qgm_IP = [\ # variables of Qgm_IP ['qgraupelm_ip', True, 'qgraupelm_ip', 1., 0],\ ] Qgp2 = [\ # variables of Qgp2 ['qgraupelp2', True, 'qgraupelp2', 1., 0],\ ] Qgp2_QgmIP = [\ # variables of Qgp2_QgmIP ['qgraupelp2_ip', False, 'qgraupelp2_ip', 1., 0],\ ['qgraupelm_ip', False, 'qgraupelm_ip', 1., 0],\ ['Qgp2_QgmIP', True, '(qgraupelp2_ip / (np.maximum(np.full(n,1e-5),qgraupelm_ip)**2))', 1., 0],\ ] #Cloud Ice Mixing Ratio # Note: redundant, could not find variable in sam Qim = [\ # variables of Qim ['QG', True, 'QG', 1./KG, 0],\ ] Qim_IP = [\ # variables of Qim_IP ['qcloudicem_ip', True, 'qcloudicem_ip', 1., 0],\ ] Qip2 = [\ # variables of Qip2 ['qcloudicep2', True, 'qcloudicep2', 1., 0],\ ] Qip2_QimIP = [\ # variables of Qip2_QimIP ['qcloudicep2_ip', False, 'qcloudicep2_ip', 1., 0],\ ['qcloudicem_ip', False, 'qcloudicem_ip', 1., 0],\ ['Qip2_QimIP', True, '(qcloudicep2_ip / (np.maximum(np.full(n,1e-5),qcloudicem_ip)**2))', 1., 0],\ ] #Cloud Ice Number Concentration Nim = [\ # variables of Nim ['NI', False, 'NI', 1., 0],\ ['RHO', False, 'RHO', 1., 0],\ ['NIM', True, '(NI * 1e+6) / RHO', 1., 0],\ ] Nim_IP = [\ # variables of Nim_IP ['ncloudicem_ip', True, 'ncloudicem_ip', 1., 0],\ ] Nip2 = [\ # variables of Nip2 ['ncloudicep2', True, 'ncloudicep2', 1., 0],\ ] Nip2_NimIP = [\ # variables of Nip2_NimIP ['ncloudicep2_ip', False, 'ncloudicep2_ip', 1., 0],\ ['ncloudicem_ip', False, 'ncloudicem_ip', 1., 0],\ ['Nip2_NimIP', True, '(ncloudicep2_ip / (np.maximum(np.full(n,1e-5),ncloudicem_ip)**2))', 1., 0],\ ] #Snow Mixing Ratio Qsm = [\ # variables of Qsm ['QSM', True, 'QS', 1./KG, 0],\ ] Qsm_IP = [\ # variables of Qsm_IP ['qsnowm_ip', True, 'qsnowm_ip', 1., 0],\ ] Qsp2 = [\ # variables of Qsp2 ['qsnowp2', True, 'qsnowp2', 1., 0],\ ] Qsp2_QsmIP = [\ # variables of Qsp2_QsmIP ['qsnowp2_ip', False, 'qsnowp2_ip', 1., 0],\ ['qsnowm', False, 'qsnowm', 1., 0],\ ['Qsp2_QsmIP', True, '(qsnowp2_ip / (np.maximum(np.full(n,1e-5),qsnowm)**2))', 1., 0],\ ] #Snow Number Concentration Nsm = [\ # variables of Nsm ['NS', False, 'NS', 1., 0],\ ['RHO', False, 'RHO', 1., 0],\ ['NSM', True, '(NS * 1e+6) / RHO', 1., 0],\ ] Nsm_IP = [\ # variables of Nsm_IP ['nsnowm_ip', True, 'nsnowm_ip', 1., 0],\ ] Nsp2 = [\ # variables of Nsp2 ['nsnowp2', True, 'nsnowp2', 1., 0],\ ] Nsp2_NsmIP = [\ # variables of Nsp2_NsmIP ['nsnowp2_ip', False, 'nsnowp2_ip', 1., 0],\ ['nsnowm_ip', False, 'nsnowm_ip', 1., 0],\ ['Nsp2_NsmIP', True, '(nsnowp2_ip / (np.maximum(np.full(n,1e-5),nsnowm_ip)**2))', 1., 0],\ ] MicroFractions = [\ # variables of MicroFractions ['Cloud_liq', True, 'cloudliq_frac_em6', 1., 0],\ ['Rain', True, 'rain_frac_em6', 1., 0],\ ['Cloud_ice', True, 'cloudice_frac_em6', 1., 0],\ ['Snow', True, 'snow_frac_em6', 1., 0],\ ['Graupel', True, 'graupel_frac_em6', 1., 0],\ ] Buoy_Flux = [\ # variables of Buoy_Flux ['TVFLUX', False, 'TVFLUX', 1., 0],\ ['RHO', False, 'RHO', 1., 0],\ ['Buoy_Flux', True, 'TVFLUX / (RHO * 1004)', 1., 0],\ ] lwp = [\ # variables of lwp ['CWP', True, 'CWP', 1./KG, 0],\ ] PREC = [\ # variables of lwp ['PREC', True, 'PREC', 1., 0],\ ] WP2_W2 = [\ # variables of WP2_W2 ['NS', True, 'NS', 0., 0],\ ] IWP = [\ # variables of IWP ['IWP', True, 'IWP', 1./KG, 0],\ ] SWP = [\ # variables of SWP ['SWP', True, 'SWP', 1./KG, 0],\ ] uprcp = [\ ['UPRCP', True, 'UPRCP', 1., 0],\ ] uprtp = [\ ['UPRTP', True, 'UPRTP', 1., 0],\ ] upthlp = [\ ['UPTHLP', True, 'UPTHLP', 1., 0],\ ] vprcp = [\ ['VPRCP', True, 'VPRCP', 1., 0],\ ] vprtp = [\ ['VPRTP', True, 'VPRTP', 1., 0],\ ] vpthlp = [\ ['VPTHLP', True, 'VPTHLP', 1., 0],\ ] lines = [thetal, rt, thetalflux, rtflux, cloudliqfrac, qcl, wVar, w3, thetalVar, rtVar, covarThetalRt, wobs, U, V, covarUW, covarVW, uVar, vVar,\ QR, QRIP, QRP2, QRP2_QRIP, \ Nrm, Nrm_IP, Nrp2, Nrp2_NrmIP, \ Ncm, Ncm_IP, Ncp2, Ncp2_NcmIP, \ Ngm, Ngm_IP, Ngp2, Ngp2_NgmIP, \ Qgm, Qgm_IP, Qgp2, Qgp2_QgmIP, \ Qim, Qim_IP, Qip2, Qip2_QimIP, \ Nim, Nim_IP, Nip2, Nip2_NimIP, \ Qsm, Qsm_IP, Qsp2, Qsp2_QsmIP, \ Nsm, Nsm_IP, Nsp2, Nsp2_NsmIP, \ MicroFractions, Buoy_Flux, \ uprcp, uprtp, upthlp, \ vprcp, vprtp, vpthlp, \ ]
""" ------------------------------------------------------------------------------- G E N E R A L I N F O R M A T I O N ------------------------------------------------------------------------------- This file contains general constants and information about the variables saved in the netCDF file needed for plotgen.py. The list variables sortPlots, plotNames and lines are sorted identically in order to relate the individual variables. """ day = 24 hour = 3600 kg = 1000.0 g_per_second_to_kg_per_day = 1.0 / (DAY * HOUR * KG) kg_per_second_to_kg_per_day = 1.0 / (DAY * HOUR) sort_plots = ['theta_l', 'r_t', 'theta_l_flux', 'r_t_flux', 'cloudliq_frac', 'r_c', 'w_var', 'w3', 'theta_l_var', 'r_t_var', 'covar_thetal_rt', 'wobs', 'U', 'V', 'covar_uw', 'covar_vw', 'u_var', 'v_var', 'QR', 'QR_IP', 'QRP2', 'QRP2_QRIP', 'Nrm', 'Nrm_IP', 'Nrp2', 'Nrp2_NrmIP', 'Ncm', 'Ncm_IP', 'Ncp2', 'Ncp2_NcmIP', 'Ngm', 'Ngm_IP', 'Ngp2', 'Ngp2_NgmIP', 'Qgm', 'Qgm_IP', 'Qgp2', 'Qgp2_QgmIP', 'Qim', 'Qim_IP', 'Qip2', 'Qip2_QimIP', 'Nim', 'Nim_IP', 'Nip2', 'Nip2_NimIP', 'Qsm', 'Qsm_IP', 'Qsp2', 'Qsp2_QsmIP', 'Nsm', 'Nsm_IP', 'Nsp2', 'Nsp2_NsmIP', 'MicroFractions', 'Buoy_Flux', 'uprcp', 'uprtp', 'upthlp', 'vprcp', 'vprtp', 'vpthlp'] plot_names = [['Liquid Water Potential Temperature, theta_l', 'thetal [K]'], ['Total Water Mixing Ratio, r_t', 'rtm / qt [kg/kg]'], ['Turbulent Flux of theta_l', 'wpthlp / thflux(s) [K m/s]'], ['Turbulent Flux of r_t', 'wprtp / qtflux(s) [(kg/kg) m/s]'], ['Cloud Liquid Fraction', ' [%/100]'], ['Cloud Water Mixing Ratio, r_c', 'rcm / qcl [kg/kg]'], ['Variance of w', 'wp2 / w2 [m^2/s^2]'], ['Third-order Moment of w', 'wp3 / w3 [m^3/s^3]'], ['Variance of theta_l', 'thlp2 / tl2 [K^2]'], ['Variance of r_t', 'rtp2 / qtp2 [(kg/kg)^2]'], ['Covariance of r_t & theta_l', 'rtpthlp [(kg/kg) K]'], ['Vertical Wind Component, w (subsidence)', 'wobs [m/s]'], ['Zonal Wind Component, u', 'um / u [m/s]'], ['Meridonal Wind Component, v', 'vm / v [m/s]'], ['Covariance of u & w', 'upwp / uw [m^2/s^2]'], ['Covariance of v & w', 'vpwp / vw [m^2/s^2]'], ['Variance of u wind', 'up2 / u2 [m^2/s^2]'], ['Variance of v wind', 'vp2 / v2 [m^2/s^2]'], ['Rain Water Mixing Ratio', 'qrm [kg/kg]'], ['Rain Water Mixing Ratio in Rain', 'qrm_ip [kg/kg]'], ['Domain-wide Variance\nof Rain Water Mixing Ratio', 'qrp2 [(kg/kg)^2]'], ['Within-rain Variance\nof Rain Water Mixing Ratio', 'qrp2_ip / qrm_ip^2 [-]'], ['Rain Drop Concentration', 'Nrm [num/kg]'], ['Rain Drop Concentration in Rain', 'Nrm_ip [num/kg]'], ['Domain-wide Variance\nof Rain Drop Concentration', 'Nrp2 [(num/kg)^2]'], ['Within-rain Variance\nof Rain Drop Concentration', 'Nrp2_ip / Nrm_ip^2 [-]'], ['Cloud Droplet Number Concentration', 'Ncm [num/kg]'], ['Cloud Droplet Number Concentration in Cloud', 'Ncm_ip [num/kg]'], ['Domain-wide Variance\nof Cloud Droplet Number Concentration', 'Ncp2 [(#/kg)^2]'], ['Within-cloud Variance\nof Cloud Droplet Number Concentration', 'Ncp2_ip / Ncm_ip^2 [-]'], ['Graupel Number Concentration', 'Ngm [kg/kg]'], ['Graupel Number Concentration in Graupel', 'Ngm_ip [num/kg]'], ['Domain-wide Variance\nof Graupel Number Concentration', 'Ngp2 [(kg/kg)^2]'], ['Within-graupel Variance\nof Graupel Number Concentration', 'Ngp2_ip / Ngm_ip^2 [-]'], ['Graupel Mixing Ratio', 'qgm [kg/kg]'], ['Graupel Mixing Ratio in Graupel', 'qgm_ip [kg/kg]'], ['Domain-wide Variance\nof Graupel Mixing Ratio', 'qgp2 [(kg/kg)^2]'], ['Within-graupel Variance\nof Graupel Mixing Ratio', 'qgp2_ip / qgm_ip^2 [-]'], ['Cloud Ice Mixing Ratio', 'qim [kg/kg]'], ['Cloud Ice Mixing Ratio in Cloud Ice', 'qim_ip [kg/kg]'], ['Domain-wide Variance\nof Cloud Ice Mixing Ratio', 'qip2 [(kg/kg)^2]'], ['Within-cloud-ice Variance\nof Cloud Ice Mixing Ratio', 'qip2_ip / qim_ip^2 [-]'], ['Cloud Ice Concentration', 'Nim [num/kg]'], ['Cloud Ice Number Concentration in Cloud Ice', 'Ni_ip [num/kg]'], ['Domain-wide Variance\nof Cloud Ice Number Concentration', 'Nip2 [(num/kg)^2]'], ['Within-cloud-ice Variance\nof Cloud Ice Number Concentration', 'Nip2_ip / Nim_ip^2 [-]'], ['Snow Mixing Ratio ', 'qsm [kg/kg]'], ['Snow Mixing Ratio in Snow', 'qsm_ip [kg/kg]'], ['Domain-wide Variance\nof Snow Mixing Ratio', 'qsp2 [(kg/kg)^2]'], ['Within-snow Variance\nof Snow Mixing Ratio ', 'qsp2_ip / qsm_ip^2 [-]'], ['Snow Number Concentration', 'Nsm [num/kg]'], ['Snow Number Concentration in Snow', 'Nsm_ip [num/kg]'], ['Domain-wide Variance\nof Snow Number Concentration', 'Nsp2 [(#/kg)^2]'], ['Within-snow Variance\nof Snow Number Concentration', 'Nsp2_ip / Nsm_ip^2 [-]'], ['Micro Fractions', '[%/100]'], ['Buoyancy flux', 'wpthvp / tlflux [K m/s]'], ['Covariance of u & rc', 'uprcp / urc [m^2/s^2]'], ['Covariance of u & rt', 'uprtp / urt [m^2/s^2]'], ['Covariance of u & thl', 'upthlp / uthl [m^2/s^2]'], ['Covariance of v & rc', 'vprcp / urc [m^2/s^2]'], ['Covariance of v & rt', 'vprtp / urt [m^2/s^2]'], ['Covariance of v & thl', 'vpthlp / uthl [m^2/s^2]']] thetal = [['THETAL', False, 'THETAL', 1.0, 0], ['THETA', False, 'THETA', 1.0, 0], ['TABS', False, 'TABS', 1.0, 0], ['QI', False, 'QI', 1.0 / KG, 0], ['THETAL', True, 'THETAL + 2500.4 * (THETA/TABS) * QI', 1.0, 0]] rt = [['QI', False, 'QI', 1.0, 0], ['QT', False, 'QT', 1.0, 0], ['RT', True, '(QT-QI)', 1.0 / KG, 0]] thetalflux = [['TLFLUX', False, 'TLFLUX', 1.0, 0], ['RHO', False, 'RHO', 1.0, 0], ['WPTHLP_SGS', False, 'WPTHLP_SGS', 1.0, 0], ['THETALFLUX', True, '((TLFLUX) / (RHO * 1004.)) + WPTHLP_SGS', 1.0, 0]] rtflux = [['QTFLUX', False, 'TLFLUX', 1.0, 0], ['RHO', False, 'RHO', 1.0, 0], ['WPRTP_SGS', False, 'WPRTP_SGS', 1.0, 0], ['RTFLUX', True, '(QTFLUX / (RHO * 2.5104e+6)) + WPRTP_SGS', 1.0, 0]] cloudliqfrac = [['cloudliq_frac_em6', True, 'cloudliq_frac_em6', 1.0, 0]] qcl = [['QCL', True, 'QCL', 1.0 / KG, 0]] w_var = [['WP2_SGS', False, 'WP2_SGS', 1.0, 0], ['W2', False, 'W2', 1.0, 0], ['WVAR', True, 'WP2_SGS + W2', 1.0, 0]] w3 = [['WP3_SGS', False, 'WP3_SGS', 1.0, 0], ['W3', False, 'W3', 1.0, 0], ['W3', True, 'WP3_SGS + W3', 1.0, 0]] thetal_var = [['THLP2_SGS', False, 'THLP2_SGS', 1.0, 0], ['TL2', False, 'TL2', 1.0, 0], ['THETALVAR', True, 'THLP2_SGS + TL2', 1.0, 0]] rt_var = [['RTP2_SGS', False, 'RTP2_SGS', 1.0, 0], ['QT2', False, 'QT2', 1.0, 0], ['RTVAR', True, '(QT2 / 1e+6) + RTP2_SGS', 1.0, 0]] covar_thetal_rt = [['CovarThetaLRT', True, 'RTPTHLP_SGS', 1.0, 0]] wobs = [['WOBS', True, 'WOBS', 1.0, 0]] u = [['U', True, 'U', 1.0, 0]] v = [['V', True, 'V', 1.0, 0]] covar_uw = [['UPWP_SGS', False, 'UPWP_SGS', 1.0, 0], ['UW', False, 'UW', 1.0, 0], ['UW', True, 'UW + UPWP_SGS', 1.0, 0]] covar_vw = [['VPWP_SGS', False, 'VPWP_SGS', 1.0, 0], ['VW', False, 'VW', 1.0, 0], ['VW', True, 'VW + VPWP_SGS', 1.0, 0]] u_var = [['UP2_SGS', False, 'UP2_SGS', 1.0, 0], ['U2', False, 'U2', 1.0, 0], ['UVAR', True, 'UP2_SGS + U2', 1.0, 0]] v_var = [['VP2_SGS', False, 'VP2_SGS', 1.0, 0], ['V2', False, 'V2', 1.0, 0], ['VVAR', True, 'VP2_SGS + V2', 1.0, 0]] qr = [['QR', True, 'QR', 1.0 / KG, 0]] qrip = [['qrainm_ip', True, 'qrainm_ip', 1.0, 0]] qrp2 = [['qrainp2', True, 'qrainp2', 1.0, 0]] qrp2_qrip = [['qrainp2_ip', False, 'qrainp2_ip', 1.0, 0], ['qrainm_ip', False, 'qrainm_ip', 1.0, 0], ['QRP2_QRIP', True, '(qrainp2_ip / (np.maximum(np.full(n,1e-5),qrainm_ip)**2))', 1.0, 0]] nrm = [['NR', False, 'NR', 1.0, 0], ['RHO', False, 'RHO', 1.0, 0], ['NRM', True, '(NR * 1e+6) / RHO', 1.0, 0]] nrm_ip = [['nrainm_ip', True, 'nrainm_ip', 1.0, 0]] nrp2 = [['nrainp2', True, 'nrainp2', 1.0, 0]] nrp2__nrm_ip = [['nrainp2_ip', False, 'nrainp2_ip', 1.0, 0], ['nrainm_ip', False, 'nrainm_ip', 1.0, 0], ['Nrp2_NrmIP', True, '(nrainp2_ip / (np.maximum(np.full(n,1e-5),nrainm_ip)**2))', 1.0, 0]] ncm = [['NC', False, 'NC', 1.0, 0], ['RHO', False, 'RHO', 1.0, 0], ['NCM', True, '(NC * 1e+6) / RHO', 1.0, 0]] ncm_ip = [['ncloudliqm_ip', True, 'ncloudliqm_ip', 1.0, 0]] ncp2 = [['Ncp2', True, 'Ncp2', 1.0, 0]] ncp2__ncm_ip = [['ncloudliqp2_ip', False, 'ncloudliqp2_ip', 1.0, 0], ['ncloudliqm_ip', False, 'ncloudliqm_ip', 1.0, 0], ['Ncp2_NcmIP', True, '(ncloudliqp2_ip / (np.maximum(np.full(n,1e-5),ncloudliqm_ip)**2))', 1.0, 0]] ngm = [['NG', False, 'NG', 1.0, 0], ['RHO', False, 'RHO', 1.0, 0], ['NGM', True, '(NG * 1e+6) / RHO', 1.0, 0]] ngm_ip = [['ngraupelm_ip', True, 'ngraupelm_ip', 1.0, 0]] ngp2 = [['ngraupelp2', True, 'ngraupelp2', 1.0, 0]] ngp2__ngm_ip = [['ngraupelp2_ip', False, 'ngraupelp2_ip', 1.0, 0], ['ngraupelm_ip', False, 'ngraupelm_ip', 1.0, 0], ['Ngp2_NgmIP', True, '(ngraupelp2_ip / (np.maximum(np.full(n,1e-5),ngraupelm_ip)**2))', 1.0, 0]] qgm = [['QG', True, 'QG', 1.0 / KG, 0]] qgm_ip = [['qgraupelm_ip', True, 'qgraupelm_ip', 1.0, 0]] qgp2 = [['qgraupelp2', True, 'qgraupelp2', 1.0, 0]] qgp2__qgm_ip = [['qgraupelp2_ip', False, 'qgraupelp2_ip', 1.0, 0], ['qgraupelm_ip', False, 'qgraupelm_ip', 1.0, 0], ['Qgp2_QgmIP', True, '(qgraupelp2_ip / (np.maximum(np.full(n,1e-5),qgraupelm_ip)**2))', 1.0, 0]] qim = [['QG', True, 'QG', 1.0 / KG, 0]] qim_ip = [['qcloudicem_ip', True, 'qcloudicem_ip', 1.0, 0]] qip2 = [['qcloudicep2', True, 'qcloudicep2', 1.0, 0]] qip2__qim_ip = [['qcloudicep2_ip', False, 'qcloudicep2_ip', 1.0, 0], ['qcloudicem_ip', False, 'qcloudicem_ip', 1.0, 0], ['Qip2_QimIP', True, '(qcloudicep2_ip / (np.maximum(np.full(n,1e-5),qcloudicem_ip)**2))', 1.0, 0]] nim = [['NI', False, 'NI', 1.0, 0], ['RHO', False, 'RHO', 1.0, 0], ['NIM', True, '(NI * 1e+6) / RHO', 1.0, 0]] nim_ip = [['ncloudicem_ip', True, 'ncloudicem_ip', 1.0, 0]] nip2 = [['ncloudicep2', True, 'ncloudicep2', 1.0, 0]] nip2__nim_ip = [['ncloudicep2_ip', False, 'ncloudicep2_ip', 1.0, 0], ['ncloudicem_ip', False, 'ncloudicem_ip', 1.0, 0], ['Nip2_NimIP', True, '(ncloudicep2_ip / (np.maximum(np.full(n,1e-5),ncloudicem_ip)**2))', 1.0, 0]] qsm = [['QSM', True, 'QS', 1.0 / KG, 0]] qsm_ip = [['qsnowm_ip', True, 'qsnowm_ip', 1.0, 0]] qsp2 = [['qsnowp2', True, 'qsnowp2', 1.0, 0]] qsp2__qsm_ip = [['qsnowp2_ip', False, 'qsnowp2_ip', 1.0, 0], ['qsnowm', False, 'qsnowm', 1.0, 0], ['Qsp2_QsmIP', True, '(qsnowp2_ip / (np.maximum(np.full(n,1e-5),qsnowm)**2))', 1.0, 0]] nsm = [['NS', False, 'NS', 1.0, 0], ['RHO', False, 'RHO', 1.0, 0], ['NSM', True, '(NS * 1e+6) / RHO', 1.0, 0]] nsm_ip = [['nsnowm_ip', True, 'nsnowm_ip', 1.0, 0]] nsp2 = [['nsnowp2', True, 'nsnowp2', 1.0, 0]] nsp2__nsm_ip = [['nsnowp2_ip', False, 'nsnowp2_ip', 1.0, 0], ['nsnowm_ip', False, 'nsnowm_ip', 1.0, 0], ['Nsp2_NsmIP', True, '(nsnowp2_ip / (np.maximum(np.full(n,1e-5),nsnowm_ip)**2))', 1.0, 0]] micro_fractions = [['Cloud_liq', True, 'cloudliq_frac_em6', 1.0, 0], ['Rain', True, 'rain_frac_em6', 1.0, 0], ['Cloud_ice', True, 'cloudice_frac_em6', 1.0, 0], ['Snow', True, 'snow_frac_em6', 1.0, 0], ['Graupel', True, 'graupel_frac_em6', 1.0, 0]] buoy__flux = [['TVFLUX', False, 'TVFLUX', 1.0, 0], ['RHO', False, 'RHO', 1.0, 0], ['Buoy_Flux', True, 'TVFLUX / (RHO * 1004)', 1.0, 0]] lwp = [['CWP', True, 'CWP', 1.0 / KG, 0]] prec = [['PREC', True, 'PREC', 1.0, 0]] wp2_w2 = [['NS', True, 'NS', 0.0, 0]] iwp = [['IWP', True, 'IWP', 1.0 / KG, 0]] swp = [['SWP', True, 'SWP', 1.0 / KG, 0]] uprcp = [['UPRCP', True, 'UPRCP', 1.0, 0]] uprtp = [['UPRTP', True, 'UPRTP', 1.0, 0]] upthlp = [['UPTHLP', True, 'UPTHLP', 1.0, 0]] vprcp = [['VPRCP', True, 'VPRCP', 1.0, 0]] vprtp = [['VPRTP', True, 'VPRTP', 1.0, 0]] vpthlp = [['VPTHLP', True, 'VPTHLP', 1.0, 0]] lines = [thetal, rt, thetalflux, rtflux, cloudliqfrac, qcl, wVar, w3, thetalVar, rtVar, covarThetalRt, wobs, U, V, covarUW, covarVW, uVar, vVar, QR, QRIP, QRP2, QRP2_QRIP, Nrm, Nrm_IP, Nrp2, Nrp2_NrmIP, Ncm, Ncm_IP, Ncp2, Ncp2_NcmIP, Ngm, Ngm_IP, Ngp2, Ngp2_NgmIP, Qgm, Qgm_IP, Qgp2, Qgp2_QgmIP, Qim, Qim_IP, Qip2, Qip2_QimIP, Nim, Nim_IP, Nip2, Nip2_NimIP, Qsm, Qsm_IP, Qsp2, Qsp2_QsmIP, Nsm, Nsm_IP, Nsp2, Nsp2_NsmIP, MicroFractions, Buoy_Flux, uprcp, uprtp, upthlp, vprcp, vprtp, vpthlp]
if __name__ == '__main__': l = input().strip().split() data = [int(i) for i in l] n = int(input()) sum = [0 for i in range(0, len(data)+1)] sum[0] = data[0] for i in range(1, len(data)): sum[i] = sum[i-1] + data[i] # print(sum) found = False for length in range(0, len(data)): for t in range(length+1, len(data)): if sum[t] - sum[t-length-1] >= n: print(length+1) found = True # print(data[t], data[t-length]) break if found: break if not found: print("-1")
if __name__ == '__main__': l = input().strip().split() data = [int(i) for i in l] n = int(input()) sum = [0 for i in range(0, len(data) + 1)] sum[0] = data[0] for i in range(1, len(data)): sum[i] = sum[i - 1] + data[i] found = False for length in range(0, len(data)): for t in range(length + 1, len(data)): if sum[t] - sum[t - length - 1] >= n: print(length + 1) found = True break if found: break if not found: print('-1')
i = 1 while True: inp = input() if inp == "Hajj": inp = "Hajj-e-Akbar" elif inp == "Umrah": inp = "Hajj-e-Asghar" else: break print("Case {}: {}".format(i, inp)) i += 1
i = 1 while True: inp = input() if inp == 'Hajj': inp = 'Hajj-e-Akbar' elif inp == 'Umrah': inp = 'Hajj-e-Asghar' else: break print('Case {}: {}'.format(i, inp)) i += 1
class Report: def __init__(self, report): self.report = report @property def name(self): return self.report['name'] @property def filename(self): return self.report['filename'] @property def klass(self): return self.report['class'] @property def skip(self): return self.report['skip']
class Report: def __init__(self, report): self.report = report @property def name(self): return self.report['name'] @property def filename(self): return self.report['filename'] @property def klass(self): return self.report['class'] @property def skip(self): return self.report['skip']
def main_menu(): input_map = {'1': 'compute', '2': 'storage', '3': 'default', '4': 'exit'} print('\nSelect from the options below:') print(' 1. Set up or remove a compute service') print(' 2. Set up or remove a storage service') print(' 3. Change settings for compute or storage service (i.e. defaults)') print(' 4. Exit configuration') selection = input(f"{'/'.join(input_map)}> ") if selection not in input_map: raise Exception("Invalid selection") return input_map[selection] def main_service_menu(service): input_map = {'1': 'add', '2': 'remove'} print('\nDo you want to:') print(f' 1. Set up a new {service} service') print(f' 2. Remove a {service} service') selection = input(f"{'/'.join(input_map)}> ") if selection not in input_map: raise Exception("Invalid selection") return input_map[selection] def default_service_menu(): input_map = {'1': 'compute', '2': 'storage'} print('\nDo you want to:') print(f' 1. Change default compute service') print(f' 2. Change default storage service') selection = input(f"{'/'.join(input_map)}> ") if selection not in input_map: raise Exception("Invalid selection") return input_map[selection]
def main_menu(): input_map = {'1': 'compute', '2': 'storage', '3': 'default', '4': 'exit'} print('\nSelect from the options below:') print(' 1. Set up or remove a compute service') print(' 2. Set up or remove a storage service') print(' 3. Change settings for compute or storage service (i.e. defaults)') print(' 4. Exit configuration') selection = input(f"{'/'.join(input_map)}> ") if selection not in input_map: raise exception('Invalid selection') return input_map[selection] def main_service_menu(service): input_map = {'1': 'add', '2': 'remove'} print('\nDo you want to:') print(f' 1. Set up a new {service} service') print(f' 2. Remove a {service} service') selection = input(f"{'/'.join(input_map)}> ") if selection not in input_map: raise exception('Invalid selection') return input_map[selection] def default_service_menu(): input_map = {'1': 'compute', '2': 'storage'} print('\nDo you want to:') print(f' 1. Change default compute service') print(f' 2. Change default storage service') selection = input(f"{'/'.join(input_map)}> ") if selection not in input_map: raise exception('Invalid selection') return input_map[selection]
class Request: pass class DirectoryInfoRequest(Request): def __init__(self, path): super().__init__() self.path = path class AdditionalEntryPropertiesRequest(Request): def __init__(self, filepath): super().__init__() self.filepath = filepath
class Request: pass class Directoryinforequest(Request): def __init__(self, path): super().__init__() self.path = path class Additionalentrypropertiesrequest(Request): def __init__(self, filepath): super().__init__() self.filepath = filepath
######################## #######lecture 15####### ######################## class Node: def __init__(self , value=None): self.value = value self.next = None # def __str__(self): # return str(self.value) class Stack: def __init__(self , node=None): self.top = node def __str__(self): if self.top == None: return 'Stack is empty' else: output = '' while self.top != None: output += str(self.top) + '\n' self.top = self.top.next return output def push(self, value): if not self.top: self.top = Node(value) else: node = Node(value) node.next = self.top self.top = node def pop(self): if self.top == None: return None else: output = self.top self.top = self.top.next return output def peek(self): if self.top == None: return None else: return self.top.value def isEmpty(self): return self.top == None class Queue: def __init__(self , node=None): self.front= node self.rear = node def __str__(self): if self.front == None: return 'Queue is empty' else: output = '' while self.front != None: output += str(self.front) + '\n' self.front = self.front.next return output def enqueue(self, value): node = Node(value) if self.rear == None: self.rear = node self.front = node else: self.rear.next = node self.rear = node def dequeue(self): if self.front == None: return None else: output = self.front self.front = self.front.next return output def isEmpty(self): return self.front == None def peek(self): if self.front == None: return None else: return self.front.value class TNode: def __init__(self, value=None): self.value = value self.left = None self.right = None def __str__(self): return str(self.value) class BinaryTree: def __init__(self): self.root = None def pre_order(self): """"traverse tree recursively""" def traverse(root): # print the root node print(root.value) # traverse left & right subtree if root.left is not None: traverse(root.left) if root.right is not None: traverse(root.right) traverse(self.root) def in_order(self): """"traverse tree recursively""" def traverse(root): # print the root node # traverse left & right subtree if root.left is not None: traverse(root.left) print(root.value) if root.right is not None: traverse(root.right) traverse(self.root) def post_order(self): """"traverse tree recursively""" def traverse(root): # print the root node # traverse left & right subtree if root.left is not None: traverse(root.left) if root.right is not None: traverse(root.right) print(root.value) traverse(self.root) def pre_order_iterative(self): """traverse tree iteratively""" stack = Stack() stack.push(self.root) while not stack.isEmpty(): node = stack.pop() print(node.value) if node.value.right: stack.push(node.value.right) if node.value.left: stack.push(node.value.left) def breadth_First(self): """traverse tree breadth first""" queue = Queue() queue.enqueue(self.root) while not queue.isEmpty(): node = queue.dequeue() print(node.value) if node.left is not None: queue.enqueue(node.left) if node.right is not None: queue.enqueue(node.right) class BinarySearchTree(BinaryTree): def add(self, value): """Adds a value to the BST""" if self.root is None: self.root = TNode(value) else: current = self.root while current: if value < current.value: if current.left is None: current.left = TNode(value) return current = current.left else: if current.right is None: current.right = TNode(value) return current = current.right def contains(self, value): """Returns True if value is in the BST, False otherwise""" current = self.root while current: if current.value == value: return True if current.value > value: current = current.left else: current = current.right return False if __name__ == "__main__": # tree = BinaryTree() # tree.root = TNode("a") # tree.root.left = TNode("b") # tree.root.right = TNode("c") # tree.root.right.left = TNode("d") # tree.pre_order_iterative() # tree.pre_order() # tree.in_order() # tree.post_order() tree = BinarySearchTree() tree.add(20) tree.add(15) tree.add(10) tree.add(16) tree.add(30) tree.add(25) tree.add(35) print("pre_order") tree.pre_order() print("in_order") tree.in_order() print("post_order") tree.post_order() print("If tree contains value= 20 =>" ,tree.contains(20)) print("If tree contains value= 45 =>",tree.contains(45))
class Node: def __init__(self, value=None): self.value = value self.next = None class Stack: def __init__(self, node=None): self.top = node def __str__(self): if self.top == None: return 'Stack is empty' else: output = '' while self.top != None: output += str(self.top) + '\n' self.top = self.top.next return output def push(self, value): if not self.top: self.top = node(value) else: node = node(value) node.next = self.top self.top = node def pop(self): if self.top == None: return None else: output = self.top self.top = self.top.next return output def peek(self): if self.top == None: return None else: return self.top.value def is_empty(self): return self.top == None class Queue: def __init__(self, node=None): self.front = node self.rear = node def __str__(self): if self.front == None: return 'Queue is empty' else: output = '' while self.front != None: output += str(self.front) + '\n' self.front = self.front.next return output def enqueue(self, value): node = node(value) if self.rear == None: self.rear = node self.front = node else: self.rear.next = node self.rear = node def dequeue(self): if self.front == None: return None else: output = self.front self.front = self.front.next return output def is_empty(self): return self.front == None def peek(self): if self.front == None: return None else: return self.front.value class Tnode: def __init__(self, value=None): self.value = value self.left = None self.right = None def __str__(self): return str(self.value) class Binarytree: def __init__(self): self.root = None def pre_order(self): """"traverse tree recursively""" def traverse(root): print(root.value) if root.left is not None: traverse(root.left) if root.right is not None: traverse(root.right) traverse(self.root) def in_order(self): """"traverse tree recursively""" def traverse(root): if root.left is not None: traverse(root.left) print(root.value) if root.right is not None: traverse(root.right) traverse(self.root) def post_order(self): """"traverse tree recursively""" def traverse(root): if root.left is not None: traverse(root.left) if root.right is not None: traverse(root.right) print(root.value) traverse(self.root) def pre_order_iterative(self): """traverse tree iteratively""" stack = stack() stack.push(self.root) while not stack.isEmpty(): node = stack.pop() print(node.value) if node.value.right: stack.push(node.value.right) if node.value.left: stack.push(node.value.left) def breadth__first(self): """traverse tree breadth first""" queue = queue() queue.enqueue(self.root) while not queue.isEmpty(): node = queue.dequeue() print(node.value) if node.left is not None: queue.enqueue(node.left) if node.right is not None: queue.enqueue(node.right) class Binarysearchtree(BinaryTree): def add(self, value): """Adds a value to the BST""" if self.root is None: self.root = t_node(value) else: current = self.root while current: if value < current.value: if current.left is None: current.left = t_node(value) return current = current.left else: if current.right is None: current.right = t_node(value) return current = current.right def contains(self, value): """Returns True if value is in the BST, False otherwise""" current = self.root while current: if current.value == value: return True if current.value > value: current = current.left else: current = current.right return False if __name__ == '__main__': tree = binary_search_tree() tree.add(20) tree.add(15) tree.add(10) tree.add(16) tree.add(30) tree.add(25) tree.add(35) print('pre_order') tree.pre_order() print('in_order') tree.in_order() print('post_order') tree.post_order() print('If tree contains value= 20 =>', tree.contains(20)) print('If tree contains value= 45 =>', tree.contains(45))
version_info = (0, 0, '6a1') __version__ = '.'.join(map(str, version_info)) if __name__ == '__main__': print(__version__)
version_info = (0, 0, '6a1') __version__ = '.'.join(map(str, version_info)) if __name__ == '__main__': print(__version__)
# Python equivalent of an array is a list def reverse_array(a_list): """ https://www.hackerrank.com/challenges/01_arrays-ds/problem We can reverse an array by simply providing the step value in list slice parameters -1 means go backwards one by one """ return a_list[::-1]
def reverse_array(a_list): """ https://www.hackerrank.com/challenges/01_arrays-ds/problem We can reverse an array by simply providing the step value in list slice parameters -1 means go backwards one by one """ return a_list[::-1]
#!/usr/local/bin/python3 try: arquivo = open('pessoas.csv') for it in arquivo: print('Nome {}, Idade {}'.format(*it.strip().split(','))) finally: arquivo.close()
try: arquivo = open('pessoas.csv') for it in arquivo: print('Nome {}, Idade {}'.format(*it.strip().split(','))) finally: arquivo.close()
@authenticated def delete(self): model = self.db.query([model_name]).filter([delete_filter]).first() self.db.delete(model) self.db.commit() return JsonResponse(self, '000')
@authenticated def delete(self): model = self.db.query([model_name]).filter([delete_filter]).first() self.db.delete(model) self.db.commit() return json_response(self, '000')
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def longestZigZag(self, root: TreeNode) -> int: self.result = 0 self.dfs(root) return self.result def dfs(self, root): if root == None: return 0, 0 if root.left == None and root.right == None: return 0, 0 rootL, rootR = 0, 0 if root.left == None: rootL = 0 else: l, r = self.dfs(root.left) rootL = r + 1 if root.right == None: rootR = 0 else: l, r = self.dfs(root.right) rootR = l + 1 self.result = max(self.result, rootL, rootR) return rootL, rootR node1 = TreeNode(1) node2 = TreeNode(2) node3 = TreeNode(3) node4 = TreeNode(4) node5 = TreeNode(5) node6 = TreeNode(6) node7 = TreeNode(7) node8 = TreeNode(8) node1.right = node2 node2.left = node3 node2.right = node4 node4.left = node5 node4.right = node6 node5.right = node7 node7.right = node8 s = Solution() result = s.longestZigZag(node1) print(result)
class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def longest_zig_zag(self, root: TreeNode) -> int: self.result = 0 self.dfs(root) return self.result def dfs(self, root): if root == None: return (0, 0) if root.left == None and root.right == None: return (0, 0) (root_l, root_r) = (0, 0) if root.left == None: root_l = 0 else: (l, r) = self.dfs(root.left) root_l = r + 1 if root.right == None: root_r = 0 else: (l, r) = self.dfs(root.right) root_r = l + 1 self.result = max(self.result, rootL, rootR) return (rootL, rootR) node1 = tree_node(1) node2 = tree_node(2) node3 = tree_node(3) node4 = tree_node(4) node5 = tree_node(5) node6 = tree_node(6) node7 = tree_node(7) node8 = tree_node(8) node1.right = node2 node2.left = node3 node2.right = node4 node4.left = node5 node4.right = node6 node5.right = node7 node7.right = node8 s = solution() result = s.longestZigZag(node1) print(result)
def equal_slices(total, num, per_person): res = num * per_person if res <= total: return True return False foo = equal_slices(11, 11, 1) print(str(foo))
def equal_slices(total, num, per_person): res = num * per_person if res <= total: return True return False foo = equal_slices(11, 11, 1) print(str(foo))
class FileExtractorTimeoutException(Exception): pass class ParamsInvalidException(Exception): pass class NoProperExtractorFindException(Exception): def __init__(self): super().__init__('NoProperExtractorFind Exception')
class Fileextractortimeoutexception(Exception): pass class Paramsinvalidexception(Exception): pass class Noproperextractorfindexception(Exception): def __init__(self): super().__init__('NoProperExtractorFind Exception')
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Purpose: Agent API Methods ''' __author__ = 'Matt Joyce' __email__ = 'matt@joyce.nyc' __copyright__ = 'Copyright 2016, Symphony Communication Services LLC' class Base(object): def __init__(self, *args, **kwargs): super(Base, self).__init__(*args, **kwargs) def test_echo(self, test_string): ''' echo test ''' response, status_code = self.__agent__.Util.post_v1_util_echo( sessionToken=self.__session__, keyManagerToken=self.__keymngr__, echoInput={"message": test_string} ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response def create_datafeed(self): ''' create datafeed ''' response, status_code = self.__agent__.Datafeed.post_v4_datafeed_create( sessionToken=self.__session__, keyManagerToken=self.__keymngr__ ).result() # return the token self.logger.debug('%s: %s' % (status_code, response)) return status_code, response['id'] def read_datafeed(self, datafeed_id): ''' get datafeed ''' response, status_code = self.__agent__.Datafeed.get_v4_datafeed_id_read( sessionToken=self.__session__, keyManagerToken=self.__keymngr__, id=datafeed_id ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response def send_message(self, threadid, msgFormat, message): ''' send message to threadid/stream ''' # using deprecated v3 message create because of bug in codegen of v4 ( multipart/form-data ) response, status_code = self.__agent__.Messages.post_v3_stream_sid_message_create( sessionToken=self.__session__, keyManagerToken=self.__keymngr__, sid=threadid, message={"format": msgFormat, "message": message} ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response def read_stream(self, stream_id, since_epoch): ''' get datafeed ''' response, status_code = self.__agent__.Messages.get_v4_stream_sid_message( sessionToken=self.__session__, keyManagerToken=self.__keymngr__, sid=stream_id, since=since_epoch ).result() self.logger.debug('%s: %s' % (status_code, response)) return status_code, response
""" Purpose: Agent API Methods """ __author__ = 'Matt Joyce' __email__ = 'matt@joyce.nyc' __copyright__ = 'Copyright 2016, Symphony Communication Services LLC' class Base(object): def __init__(self, *args, **kwargs): super(Base, self).__init__(*args, **kwargs) def test_echo(self, test_string): """ echo test """ (response, status_code) = self.__agent__.Util.post_v1_util_echo(sessionToken=self.__session__, keyManagerToken=self.__keymngr__, echoInput={'message': test_string}).result() self.logger.debug('%s: %s' % (status_code, response)) return (status_code, response) def create_datafeed(self): """ create datafeed """ (response, status_code) = self.__agent__.Datafeed.post_v4_datafeed_create(sessionToken=self.__session__, keyManagerToken=self.__keymngr__).result() self.logger.debug('%s: %s' % (status_code, response)) return (status_code, response['id']) def read_datafeed(self, datafeed_id): """ get datafeed """ (response, status_code) = self.__agent__.Datafeed.get_v4_datafeed_id_read(sessionToken=self.__session__, keyManagerToken=self.__keymngr__, id=datafeed_id).result() self.logger.debug('%s: %s' % (status_code, response)) return (status_code, response) def send_message(self, threadid, msgFormat, message): """ send message to threadid/stream """ (response, status_code) = self.__agent__.Messages.post_v3_stream_sid_message_create(sessionToken=self.__session__, keyManagerToken=self.__keymngr__, sid=threadid, message={'format': msgFormat, 'message': message}).result() self.logger.debug('%s: %s' % (status_code, response)) return (status_code, response) def read_stream(self, stream_id, since_epoch): """ get datafeed """ (response, status_code) = self.__agent__.Messages.get_v4_stream_sid_message(sessionToken=self.__session__, keyManagerToken=self.__keymngr__, sid=stream_id, since=since_epoch).result() self.logger.debug('%s: %s' % (status_code, response)) return (status_code, response)
s = input() k1 = input() k2 = input() out = "" for c in s: found = False for i in range(len(k1)): if c == k1[i]: out += k2[i] found = True break elif c == k2[i]: out += k1[i] found = True break if not found: out += c print(out)
s = input() k1 = input() k2 = input() out = '' for c in s: found = False for i in range(len(k1)): if c == k1[i]: out += k2[i] found = True break elif c == k2[i]: out += k1[i] found = True break if not found: out += c print(out)
# This program converts the speeds 60 kph # through 130 kph (in 10 kph increments) # to mph. START_SPEED = 60 END_SPEED = 131 INCREMENT = 10 CONVERSION_FACTOR = 0.6214 # Print the table headings. print('KPH\tMPH') print('--------------') # Print the speeds for kph in range(START_SPEED, END_SPEED, INCREMENT): mph = kph * CONVERSION_FACTOR print(kph, '\t', format(mph, '.1f'))
start_speed = 60 end_speed = 131 increment = 10 conversion_factor = 0.6214 print('KPH\tMPH') print('--------------') for kph in range(START_SPEED, END_SPEED, INCREMENT): mph = kph * CONVERSION_FACTOR print(kph, '\t', format(mph, '.1f'))
d = dict() d['quincy'] = 1 d['beau'] = 5 d['kris'] = 9 for (k,i) in d.items(): print(k, i)
d = dict() d['quincy'] = 1 d['beau'] = 5 d['kris'] = 9 for (k, i) in d.items(): print(k, i)
# Africa 2010 # Problem A: Store Credit # Jon Hanson # # Declare Variables # ifile = 'input.txt' # simple input ofile = 'output.txt' # simple output #ifile = 'A-large-practice.in' # official input #ofile = 'A-large-practice.out' # official output caselist = [] # list containing cases # # Problem State (Case) Class # class CredCase(object): def __init__(self,credit,itemCount,items): # Initialize: self.credit = int(credit) # credit amount self.itemCount = int(itemCount) # item count self.items = list(map(int,items.split())) # item values list self.cost = -1 # total cost self.solution = [] # output list def trySolution(self,indices): cost = self.items[indices[0]] + self.items[indices[1]] if (cost <= self.credit) and (cost > self.cost): self.cost = cost self.solution = [x+1 for x in indices] # # Read Input File # with open(ifile) as f: cases = int(f.readline()) for n in range(0,cases): case = CredCase(f.readline(),f.readline(),f.readline()) caselist.append(case) # # Conduct Algorithm # for n in range(0,cases): case = caselist[n] for i in range(0,case.itemCount): for j in range( (i+1) , case.itemCount ): case.trySolution( [i,j] ) if case.credit == case.cost: break if case.credit == case.cost: break # # Write Output File # with open(ofile,'w') as f: for n in range(0,cases): case = caselist[n] casestr = 'Case #'+str(n+1)+': ' casestr = casestr+str(case.solution[0])+' '+str(case.solution[1])+'\n' checkstr = 'Check: Credit='+str(case.credit) checkstr += ' Cost='+str(case.cost) checkstr += ' Item'+str(case.solution[0])+'=' checkstr += str(case.items[case.solution[0]-1]) checkstr += ' Item'+str(case.solution[1])+'=' checkstr += str(case.items[case.solution[1]-1])+'\n' f.write(casestr) #f.write(checkstr)
ifile = 'input.txt' ofile = 'output.txt' caselist = [] class Credcase(object): def __init__(self, credit, itemCount, items): self.credit = int(credit) self.itemCount = int(itemCount) self.items = list(map(int, items.split())) self.cost = -1 self.solution = [] def try_solution(self, indices): cost = self.items[indices[0]] + self.items[indices[1]] if cost <= self.credit and cost > self.cost: self.cost = cost self.solution = [x + 1 for x in indices] with open(ifile) as f: cases = int(f.readline()) for n in range(0, cases): case = cred_case(f.readline(), f.readline(), f.readline()) caselist.append(case) for n in range(0, cases): case = caselist[n] for i in range(0, case.itemCount): for j in range(i + 1, case.itemCount): case.trySolution([i, j]) if case.credit == case.cost: break if case.credit == case.cost: break with open(ofile, 'w') as f: for n in range(0, cases): case = caselist[n] casestr = 'Case #' + str(n + 1) + ': ' casestr = casestr + str(case.solution[0]) + ' ' + str(case.solution[1]) + '\n' checkstr = 'Check: Credit=' + str(case.credit) checkstr += ' Cost=' + str(case.cost) checkstr += ' Item' + str(case.solution[0]) + '=' checkstr += str(case.items[case.solution[0] - 1]) checkstr += ' Item' + str(case.solution[1]) + '=' checkstr += str(case.items[case.solution[1] - 1]) + '\n' f.write(casestr)
class PodpingCustomJsonPayloadExceeded(RuntimeError): """Raise when the size of a json string exceeds the custom_json payload limit""" class TooManyCustomJsonsPerBlock(RuntimeError): """Raise when trying to write more than 5 custom_jsons in a single block"""
class Podpingcustomjsonpayloadexceeded(RuntimeError): """Raise when the size of a json string exceeds the custom_json payload limit""" class Toomanycustomjsonsperblock(RuntimeError): """Raise when trying to write more than 5 custom_jsons in a single block"""
# Version 1: build products of before and after i, Time: O(n), Space: O(n) class Solution: def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """ # scan from left to right to find products before i before_i = [i for i in range(len(nums))] prod = 1 for i in range(len(nums)): before_i[i] = prod prod *= nums[i] # scan from left to right to find products after i after_i = [i for i in range(len(nums))] prod = 1 for i in range(len(nums) - 1, -1, -1): after_i[i] = prod prod *= nums[i] return [before_i[i] * after_i[i] for i in range(len(nums))] # Version 2: save extra space, Time: O(n), Space: O(1) class Solution: def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """ products = [i for i in range(len(nums))] # scan from left to right to find products before i prod = 1 for i in range(len(nums)): products[i] = prod prod *= nums[i] # scan from left to right to mutiply products after i prod = 1 for i in range(len(nums) - 1, -1, -1): products[i] *= prod prod *= nums[i] return products
class Solution: def product_except_self(self, nums): """ :type nums: List[int] :rtype: List[int] """ before_i = [i for i in range(len(nums))] prod = 1 for i in range(len(nums)): before_i[i] = prod prod *= nums[i] after_i = [i for i in range(len(nums))] prod = 1 for i in range(len(nums) - 1, -1, -1): after_i[i] = prod prod *= nums[i] return [before_i[i] * after_i[i] for i in range(len(nums))] class Solution: def product_except_self(self, nums): """ :type nums: List[int] :rtype: List[int] """ products = [i for i in range(len(nums))] prod = 1 for i in range(len(nums)): products[i] = prod prod *= nums[i] prod = 1 for i in range(len(nums) - 1, -1, -1): products[i] *= prod prod *= nums[i] return products
def most_frequent(data): """ determines the most frequently occurring string in the sequence. """ # your code here max = 0 res = '' for each in data: if max < data.count(each): res = each max = data.count(each) return res if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for auto-testing assert most_frequent([ 'a', 'b', 'c', 'a', 'b', 'a' ]) == 'a' assert most_frequent(['a', 'a', 'bi', 'bi', 'bi']) == 'bi' print('Done')
def most_frequent(data): """ determines the most frequently occurring string in the sequence. """ max = 0 res = '' for each in data: if max < data.count(each): res = each max = data.count(each) return res if __name__ == '__main__': assert most_frequent(['a', 'b', 'c', 'a', 'b', 'a']) == 'a' assert most_frequent(['a', 'a', 'bi', 'bi', 'bi']) == 'bi' print('Done')
# Crie um programa que leia varios numeros # inteiros pelo teclado. O programa so # vai parar quando o usuario digitar o # valor 999, que eh a condicao de parada. # No final, mostre quantos numeros foram # digitados e qual foi a soma entre eles # (desconsiderando o flag). n = s = c = 0 while True: n = int(input('Digite um numero [999 para parar]: ')) if n == 999: break s += n c += 1 print(f'A soma dos numeros eh: {s}') print(f'A quantidade de numero digitada foi: {c}')
n = s = c = 0 while True: n = int(input('Digite um numero [999 para parar]: ')) if n == 999: break s += n c += 1 print(f'A soma dos numeros eh: {s}') print(f'A quantidade de numero digitada foi: {c}')
class AdapterError(Exception): pass class ServiceAPIError(Exception): pass
class Adaptererror(Exception): pass class Serviceapierror(Exception): pass
#!/usr/bin/env python problem4 = max(i*j for i in range(100, 1000+1) for j in range(i, 1000+1) \ if str(i*j) == str(i*j)[::-1]) print(problem4)
problem4 = max((i * j for i in range(100, 1000 + 1) for j in range(i, 1000 + 1) if str(i * j) == str(i * j)[::-1])) print(problem4)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Unit tests for dataset class.""" # import datetime # import os # import unittest # # from pma_api import db, create_app # from pma_api.db_models import Dataset # # from .config import TEST_STATIC_DIR # # # # TODO: incomplete # class TestDataset(unittest.TestCase): # """Test that the dataset class works. # # To run this test directly, issue this command from the root directory: # python -m test.test_dataset # """ # file_name = 'api_data-2018.03.19-v29-SAS.xlsx' # # def setUp(self): # """Set up: (1) Put Flask app in test mode, (2) Create temp DB.""" # # Continue from here next time # # 1 set up the test # import tempfile # app = create_app() # # TODO: Will this work? # self.db_fd, app.config['DATABASE'] = tempfile.mkstemp() # app.testing = True # self.app = app.test_client() # with app.app_context(): # # 2. new dataset object # new_dataset = Dataset( # file_path=TEST_STATIC_DIR + TestDataset.file_name) # # 3. write to db # db.session.add(new_dataset) # db.session.commit() # # def test_dataset(self): # """Create a new entry in 'dataset' table and read data.""" # # 4. read from the db # dataset_from_db = Dataset.query\ # .filter_by(dataset_display_name=TestDataset.file_name).first() # # # 5. make assertions # self.assertTrue(dataset_from_db.ID != '') # self.assertTrue(dataset_from_db.data != '') # self.assertTrue(dataset_from_db.dataset_display_name == # 'api_data-2018.03.19-v29-SAS.xlsx') # self.assertTrue(type(dataset_from_db.upload_date) == # datetime.date.today()) # self.assertTrue(dataset_from_db.version_number == 'v29') # self.assertTrue(dataset_from_db.dataset_type in # ('data', 'metadata', 'full')) # self.assertTrue(dataset_from_db.is_active_staging is False) # self.assertTrue(dataset_from_db.is_active_production is False) # # def tearDown(self): # """Tear down: (1) Close temp DB.""" # # 5: remove the stuff we wrote to the db # os.close(self.db_fd) # os.unlink(self.app.config['DATABASE']) # # # # TODO: Use this example from tutorial for the above test # class TestDB(unittest.TestCase): # """Test database functionality. # # Tutorial: http://flask.pocoo.org/docs/0.12/testing/ # """ # # def setUp(self): # """Set up: (1) Put Flask app in test mode, (2) Create temp DB.""" # import tempfile # from manage import initdb # self.db_fd, app.config['DATABASE'] = tempfile.mkstemp() # app.testing = True # self.app = app.test_client() # with app.app_context(): # initdb() # # def tearDown(self): # """Tear down: (1) Close temp DB.""" # os.close(self.db_fd) # os.unlink(app.config['DATABASE']) # # def test_empty_db(self): # """Test empty database.""" # resp = self.app.get('/') # assert b'No entries here so far' in resp.data
"""Unit tests for dataset class."""
#!/usr/bin/env python class Solution: def search(self, nums: 'List[int]', target: 'int') -> 'int': lo, hi = 0, len(nums)-1 while lo <= hi: mi = lo + (hi-lo)//2 if target == nums[mi]: return mi if nums[lo] <= nums[mi]: if nums[lo] <= target < nums[mi]: hi = mi-1 else: lo = mi+1 else: if nums[mi] < target <= nums[hi]: lo = mi+1 else: hi = mi-1 return -1 sol = Solution() nums = [] nums = [4,5,6,7,0,1,2] nums = [3,1] target = 1 for target in nums: print(sol.search(nums, target))
class Solution: def search(self, nums: 'List[int]', target: 'int') -> 'int': (lo, hi) = (0, len(nums) - 1) while lo <= hi: mi = lo + (hi - lo) // 2 if target == nums[mi]: return mi if nums[lo] <= nums[mi]: if nums[lo] <= target < nums[mi]: hi = mi - 1 else: lo = mi + 1 elif nums[mi] < target <= nums[hi]: lo = mi + 1 else: hi = mi - 1 return -1 sol = solution() nums = [] nums = [4, 5, 6, 7, 0, 1, 2] nums = [3, 1] target = 1 for target in nums: print(sol.search(nums, target))
def add_time(start, duration, day=None): time, period = start.split() initial_period = period hr_start, min_start = time.split(':') hr_duration, min_duration = duration.split(':') min_new = int(min_start) + int(min_duration) hr_new = int(hr_start) + int(hr_duration) periods_later = 0 days_later = 0 DAYS_OF_WEEK = [ "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" ] if min_new > 59: min_new -= 60 hr_new += 1 hr_new_period = hr_new while hr_new > 12: hr_new -= 12 while hr_new_period > 11: hr_new_period -= 12 period = "PM" if period == "AM" else "AM" periods_later += 1 if periods_later % 2 != 0: if initial_period == "PM": periods_later += 1 else: periods_later -= 1 days_later = periods_later / 2 new_time = f"{hr_new}:{str(min_new).zfill(2)} {period}" if day: day_index = DAYS_OF_WEEK.index(day.title()) new_day_index = int((day_index + days_later) % 7) new_time += f", {DAYS_OF_WEEK[new_day_index]}" if days_later == 1: new_time += " (next day)" if days_later > 1: new_time += f" ({int(days_later)} days later)" return new_time
def add_time(start, duration, day=None): (time, period) = start.split() initial_period = period (hr_start, min_start) = time.split(':') (hr_duration, min_duration) = duration.split(':') min_new = int(min_start) + int(min_duration) hr_new = int(hr_start) + int(hr_duration) periods_later = 0 days_later = 0 days_of_week = ['Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] if min_new > 59: min_new -= 60 hr_new += 1 hr_new_period = hr_new while hr_new > 12: hr_new -= 12 while hr_new_period > 11: hr_new_period -= 12 period = 'PM' if period == 'AM' else 'AM' periods_later += 1 if periods_later % 2 != 0: if initial_period == 'PM': periods_later += 1 else: periods_later -= 1 days_later = periods_later / 2 new_time = f'{hr_new}:{str(min_new).zfill(2)} {period}' if day: day_index = DAYS_OF_WEEK.index(day.title()) new_day_index = int((day_index + days_later) % 7) new_time += f', {DAYS_OF_WEEK[new_day_index]}' if days_later == 1: new_time += ' (next day)' if days_later > 1: new_time += f' ({int(days_later)} days later)' return new_time
# Histogram of life_exp, 15 bins plt.hist(life_exp, bins = 15) # Show and clear plot plt.show() plt.clf() # Histogram of life_exp1950, 15 bins plt.hist(life_exp1950, bins = 15) # Show and clear plot again plt.show() plt.clf()
plt.hist(life_exp, bins=15) plt.show() plt.clf() plt.hist(life_exp1950, bins=15) plt.show() plt.clf()
class Solution(object): def numberToWords(self, num): under_twenty = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"] under_hundred_above_twenty = ["Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety", "Hundred"] thousands = ["" , "Thousand", "Million", "Billion"] def printer(remainder): res_print = "" # Handle zero case if remainder == 0: return " " # Get the hundreds digit if remainder >= 100: res_print += str( under_twenty[int(remainder/100)]) + " Hundred " # Get tens and ones digit, accounting for zero tens = remainder%100 # Under 20 is a special case due to english diction if tens < 20: res_print += under_twenty[tens] + " " elif tens < 100: res_print += under_hundred_above_twenty[ int(tens/10) - 2 ] + " " res_print += under_twenty[tens%10] + " " return res_print # Handle edge case if num == 0: return "Zero" # We subdivide the number into every thousands res = "" thousand_count = 0 # 123000 has the same start as 123, thus we keep dividing by 1000 while float(num / 1000.0) > 0.00001: # Use a helper function to determine the suffix, and add it to the beginning suffix = printer(num%1000) if suffix != " ": res = printer(num % 1000) + thousands[thousand_count] + " " + res # Update the thousand_count thousand_count +=1 # Update num and round it num = int(num/1000) res = res.split() res = " ".join(res) return res.strip() z = Solution() num = 1000001000 print(z.numberToWords(num))
class Solution(object): def number_to_words(self, num): under_twenty = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'] under_hundred_above_twenty = ['Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety', 'Hundred'] thousands = ['', 'Thousand', 'Million', 'Billion'] def printer(remainder): res_print = '' if remainder == 0: return ' ' if remainder >= 100: res_print += str(under_twenty[int(remainder / 100)]) + ' Hundred ' tens = remainder % 100 if tens < 20: res_print += under_twenty[tens] + ' ' elif tens < 100: res_print += under_hundred_above_twenty[int(tens / 10) - 2] + ' ' res_print += under_twenty[tens % 10] + ' ' return res_print if num == 0: return 'Zero' res = '' thousand_count = 0 while float(num / 1000.0) > 1e-05: suffix = printer(num % 1000) if suffix != ' ': res = printer(num % 1000) + thousands[thousand_count] + ' ' + res thousand_count += 1 num = int(num / 1000) res = res.split() res = ' '.join(res) return res.strip() z = solution() num = 1000001000 print(z.numberToWords(num))
""" [9/10/2014] Challenge #179 [Intermediate] Roguelike - The traveller Game https://www.reddit.com/r/dailyprogrammer/comments/2g1c80/9102014_challenge_179_intermediate_roguelike_the/ #Description: So I was fooling around once with an idea to make a fun Rogue like game. If you do not know what a Rogue Like is check out [Wikipedia Article] (http://en.wikipedia.org/wiki/Roguelike) on what it is about. I got this really weak start at just trying to generate a more graphical approach than ASCII text. If you want to see my attempt. Check out my incomplete project [FORGE] (http://coderd00d.com/Forge/index.html) For this challenge you will have to develop a character moving in a rogue like environment. So the design requirements. * 1 Hero character who moves up/down/left/right in a box map. * Map must have boundary elements to contain it -- Walls/Water/Moutains/Whatever you come up with * Hero does not have to be a person. Could be a spaceship/sea creature/whatever - Just has to move up/down/left/right on a 2-D map * Map has to be 20x20. The boundary are some element which prevents passage like a wall, water or blackholes. Whatever fits your theme. * Your hero has 100 movement points. Each time they move up/down/left/right they lose 1 movement points. When they reach 0 movement points the game ends. * Random elements are generated in the room. Gold. Treasure. Plants. Towns. Caves. Whatever. When the hero reaches that point they score a point. You must have 100 random elements. * At the end of the game when your hero is out of movement. The score is based on how many elements you are able to move to. The higher the score the better. * Hero starts either in a fixed room spot or random spot. I leave it to you to decide. #input: Some keyboard/other method for moving a hero up/down/left/right and way to end the game like Q or Esc or whatever. #output: The 20x20 map with the hero updating if you can with moves. Show how much movement points you have and score. At the end of the game show some final score box. Good luck and have fun. #Example: ASCII Map might look like this. (This is not 20x20 but yours will be 20x20) * % = Wall * $ = Random element * @ = the hero A simple dungeon. %%%%%%%%%% %..$.....% %......$.% %...@....% %....$...% %.$......% %%%%%%%%%% Move: 100 Score: 0 #Creative Challenge: This is a creative challenge. You can use ASCII graphics or bmp graphics or more. You can add more elements to this. But regardless have fun trying to make this challenge work for you. """ def main(): pass if __name__ == "__main__": main()
""" [9/10/2014] Challenge #179 [Intermediate] Roguelike - The traveller Game https://www.reddit.com/r/dailyprogrammer/comments/2g1c80/9102014_challenge_179_intermediate_roguelike_the/ #Description: So I was fooling around once with an idea to make a fun Rogue like game. If you do not know what a Rogue Like is check out [Wikipedia Article] (http://en.wikipedia.org/wiki/Roguelike) on what it is about. I got this really weak start at just trying to generate a more graphical approach than ASCII text. If you want to see my attempt. Check out my incomplete project [FORGE] (http://coderd00d.com/Forge/index.html) For this challenge you will have to develop a character moving in a rogue like environment. So the design requirements. * 1 Hero character who moves up/down/left/right in a box map. * Map must have boundary elements to contain it -- Walls/Water/Moutains/Whatever you come up with * Hero does not have to be a person. Could be a spaceship/sea creature/whatever - Just has to move up/down/left/right on a 2-D map * Map has to be 20x20. The boundary are some element which prevents passage like a wall, water or blackholes. Whatever fits your theme. * Your hero has 100 movement points. Each time they move up/down/left/right they lose 1 movement points. When they reach 0 movement points the game ends. * Random elements are generated in the room. Gold. Treasure. Plants. Towns. Caves. Whatever. When the hero reaches that point they score a point. You must have 100 random elements. * At the end of the game when your hero is out of movement. The score is based on how many elements you are able to move to. The higher the score the better. * Hero starts either in a fixed room spot or random spot. I leave it to you to decide. #input: Some keyboard/other method for moving a hero up/down/left/right and way to end the game like Q or Esc or whatever. #output: The 20x20 map with the hero updating if you can with moves. Show how much movement points you have and score. At the end of the game show some final score box. Good luck and have fun. #Example: ASCII Map might look like this. (This is not 20x20 but yours will be 20x20) * % = Wall * $ = Random element * @ = the hero A simple dungeon. %%%%%%%%%% %..$.....% %......$.% %...@....% %....$...% %.$......% %%%%%%%%%% Move: 100 Score: 0 #Creative Challenge: This is a creative challenge. You can use ASCII graphics or bmp graphics or more. You can add more elements to this. But regardless have fun trying to make this challenge work for you. """ def main(): pass if __name__ == '__main__': main()
""" Selection sort. """ def selection_sort(A, unused_0=0, unused_1=1): for j in range(len(A)-1): iMin = j for i in range(j+1, len(A)): if A[i] < A[iMin]: iMin = i if iMin != j: A[j], A[iMin] = A[iMin], A[j]
""" Selection sort. """ def selection_sort(A, unused_0=0, unused_1=1): for j in range(len(A) - 1): i_min = j for i in range(j + 1, len(A)): if A[i] < A[iMin]: i_min = i if iMin != j: (A[j], A[iMin]) = (A[iMin], A[j])
""" This file is part of Totara Enterprise Extensions. Copyright (C) 2020 onwards Totara Learning Solutions LTD Totara Enterprise Extensions is provided only to Totara Learning Solutions LTD's customers and partners, pursuant to the terms and conditions of a separate agreement with Totara Learning Solutions LTD or its affiliate. If you do not have an agreement with Totara Learning Solutions LTD, you may not access, use, modify, or distribute this software. Please contact [licensing@totaralearning.com] for more information. @author Amjad Ali <amjad.ali@totaralearning.com> @package ml_recommender """ conf = { # Minimum number of users and items in interactions set for whom to run the recommendation engine in a tenant 'min_data': { 'min_users': 10, 'min_items': 10 }, # The L2 penalty on item features when item features are being used in the model 'item_alpha': 1e-6 } class Config: """ This is a conceptual representation of accessing the configuration elements from the conf object """ def __init__(self): """ The constructor method """ self._config = conf def get_property(self, property_name): """ This method accesses and returns the called item of the `conf` dictionary. The method returns `None` when the provided key does not match with any key of the `conf` dictionary :param property_name: A key from the keys of the `conf` dictionary :type property_name: str :return: An item from the `conf` dictionary whose key was used as input """ value = None if property_name in self._config.keys(): value = self._config[property_name] return value
""" This file is part of Totara Enterprise Extensions. Copyright (C) 2020 onwards Totara Learning Solutions LTD Totara Enterprise Extensions is provided only to Totara Learning Solutions LTD's customers and partners, pursuant to the terms and conditions of a separate agreement with Totara Learning Solutions LTD or its affiliate. If you do not have an agreement with Totara Learning Solutions LTD, you may not access, use, modify, or distribute this software. Please contact [licensing@totaralearning.com] for more information. @author Amjad Ali <amjad.ali@totaralearning.com> @package ml_recommender """ conf = {'min_data': {'min_users': 10, 'min_items': 10}, 'item_alpha': 1e-06} class Config: """ This is a conceptual representation of accessing the configuration elements from the conf object """ def __init__(self): """ The constructor method """ self._config = conf def get_property(self, property_name): """ This method accesses and returns the called item of the `conf` dictionary. The method returns `None` when the provided key does not match with any key of the `conf` dictionary :param property_name: A key from the keys of the `conf` dictionary :type property_name: str :return: An item from the `conf` dictionary whose key was used as input """ value = None if property_name in self._config.keys(): value = self._config[property_name] return value
#!/usr/bin/env python3.7 # -*- coding: utf-8 -*- # Source: https://youtu.be/6oL-0TdVy28 class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class BinaryTree(object): def __init__(self, root): self.root = Node(root) def print_tree(self, traversal_type): if traversal_type == "preorder": return self.preorder_print(tree.root, "") elif traversal_type == "inorder": return self.inorder_print(tree.root, "") elif traversal_type == "postorder": return self.postorder_print(tree.root, "") def preorder_print(self, start, traversal): """ Preorder traversal. Root -> Left -> Right """ if start: traversal += (str(start.value) + '-') traversal = self.preorder_print(start.left, traversal) traversal = self.preorder_print(start.right, traversal) return traversal def inorder_print(self, start, traversal): """ In-order traversal. Left -> Root - Right """ if start: traversal = self.inorder_print(start.left, traversal) traversal += (str(start.value) + '-') traversal = self.inorder_print(start.right, traversal) return traversal def postorder_print(self, start, traversal): """ Post-order traversal. Left -> Right -> Root """ if start: traversal = self.preorder_print(start.left, traversal) traversal = self.preorder_print(start.right, traversal) traversal += (str(start.value) + '-') return traversal # Tree representation. # 1 # / \ # 2 3 # / \ / \ # 4 5 6 7 # Pre-order: 1-2-4-5-3-6-7- # In-order: 4-2-5-1-6-3-7- # Post-order: 2-4-5-3-6-7-1- # It's all DFS Depth First Search # Binary tree setup. tree = BinaryTree(1) tree.root.left = Node(2) tree.root.right = Node(3) tree.root.left.left = Node(4) tree.root.left.right = Node(5) tree.root.right.left = Node(6) tree.root.right.right = Node(7) print(tree.print_tree('preorder')) print(tree.print_tree('inorder')) print(tree.print_tree('postorder'))
class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class Binarytree(object): def __init__(self, root): self.root = node(root) def print_tree(self, traversal_type): if traversal_type == 'preorder': return self.preorder_print(tree.root, '') elif traversal_type == 'inorder': return self.inorder_print(tree.root, '') elif traversal_type == 'postorder': return self.postorder_print(tree.root, '') def preorder_print(self, start, traversal): """ Preorder traversal. Root -> Left -> Right """ if start: traversal += str(start.value) + '-' traversal = self.preorder_print(start.left, traversal) traversal = self.preorder_print(start.right, traversal) return traversal def inorder_print(self, start, traversal): """ In-order traversal. Left -> Root - Right """ if start: traversal = self.inorder_print(start.left, traversal) traversal += str(start.value) + '-' traversal = self.inorder_print(start.right, traversal) return traversal def postorder_print(self, start, traversal): """ Post-order traversal. Left -> Right -> Root """ if start: traversal = self.preorder_print(start.left, traversal) traversal = self.preorder_print(start.right, traversal) traversal += str(start.value) + '-' return traversal tree = binary_tree(1) tree.root.left = node(2) tree.root.right = node(3) tree.root.left.left = node(4) tree.root.left.right = node(5) tree.root.right.left = node(6) tree.root.right.right = node(7) print(tree.print_tree('preorder')) print(tree.print_tree('inorder')) print(tree.print_tree('postorder'))
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2011, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Willow Garage, Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. def bonus(robot): # a nice bit of goodness from the turtlebot driver by Xuwen Cao and # Morgan Quigley song = ( (76, 16), (76, 16), (72, 8), (76, 16), (79, 32), (67, 32), (72, 24), (67, 24), (64, 24), (69, 16), (71, 16), (70, 8), (69, 16), (79, 16), (76, 16), (72, 8), (74, 16), (71, 24), (60, 16), (79, 8), (78, 8), (77, 8), (74, 8), (75, 8), (76, 16), (67, 8), (69, 8), (72, 16), (69, 8), (72, 8), (74, 8), (60, 16), (79, 8), (78, 8), (77, 8), (74, 8), (75, 8), (76, 16), (76, 4), (78, 4), (84, 16), (84, 8), (84, 16), (84, 16), (60, 16), (79, 8), (78, 8), (77, 8), (74, 8), (75, 8), (76, 16), (67, 8), (69, 8), (72, 16), (69, 8), (72, 8), (74, 16), (70, 4), (72, 4), (75, 16), (69, 4), (71, 4), (74, 16), (67, 4), (69, 4), (72, 16), (67, 8), (67, 16), (60, 24), ) # have to make sure robot is in full mode robot.sci.send([128, 132]) robot.sci.send([140, 1, len(song)]) for note in song: robot.sci.send(note) robot.sci.play_song(1) # From: http://www.harmony-central.com/MIDI/Doc/table2.html MIDI_TABLE = {'rest': 0, 'R': 0, 'pause': 0, 'G1': 31, 'G#1': 32, 'A1': 33, 'A#1': 34, 'B1': 35, 'C2': 36, 'C#2': 37, 'D2': 38, 'D#2': 39, 'E2': 40, 'F2': 41, 'F#2': 42, 'G2': 43, 'G#2': 44, 'A2': 45, 'A#2': 46, 'B2': 47, 'C3': 48, 'C#3': 49, 'D3': 50, 'D#3': 51, 'E3': 52, 'F3': 53, 'F#3': 54, 'G3': 55, 'G#3': 56, 'A3': 57, 'A#3': 58, 'B3': 59, 'C4': 60, 'C#4': 61, 'D4': 62, 'D#4': 63, 'E4': 64, 'F4': 65, 'F#4': 66, 'G4': 67, 'G#4': 68, 'A4': 69, 'A#4': 70, 'B4': 71, 'C5': 72, 'C#5': 73, 'D5': 74, 'D#5': 75, 'E5': 76, 'F5': 77, 'F#5': 78, 'G5': 79, 'G#5': 80, 'A5': 81, 'A#5': 82, 'B5': 83, 'C6': 84, 'C#6': 85, 'D6': 86, 'D#6': 87, 'E6': 88, 'F6': 89, 'F#6': 90, 'G6': 91, 'G#6': 92, 'A6': 93, 'A#6': 94, 'B6': 95, 'C7': 96, 'C#7': 97, 'D7': 98, 'D#7': 99, 'E7': 100, 'F7': 101, 'F#7': 102, 'G7': 103, 'G#7': 104, 'A7': 105, 'A#7': 106, 'B7': 107, 'C8': 108, 'C#8': 109, 'D8': 110, 'D#8': 111, 'E8': 112, 'F8': 113, 'F#8': 114, 'G8': 115, 'G#8': 116, 'A8': 117, 'A#8': 118, 'B8': 119, 'C9': 120, 'C#9': 121, 'D9': 122, 'D#9': 123, 'E9': 124, 'F9': 125, 'F#9': 126, 'G9': 127}
def bonus(robot): song = ((76, 16), (76, 16), (72, 8), (76, 16), (79, 32), (67, 32), (72, 24), (67, 24), (64, 24), (69, 16), (71, 16), (70, 8), (69, 16), (79, 16), (76, 16), (72, 8), (74, 16), (71, 24), (60, 16), (79, 8), (78, 8), (77, 8), (74, 8), (75, 8), (76, 16), (67, 8), (69, 8), (72, 16), (69, 8), (72, 8), (74, 8), (60, 16), (79, 8), (78, 8), (77, 8), (74, 8), (75, 8), (76, 16), (76, 4), (78, 4), (84, 16), (84, 8), (84, 16), (84, 16), (60, 16), (79, 8), (78, 8), (77, 8), (74, 8), (75, 8), (76, 16), (67, 8), (69, 8), (72, 16), (69, 8), (72, 8), (74, 16), (70, 4), (72, 4), (75, 16), (69, 4), (71, 4), (74, 16), (67, 4), (69, 4), (72, 16), (67, 8), (67, 16), (60, 24)) robot.sci.send([128, 132]) robot.sci.send([140, 1, len(song)]) for note in song: robot.sci.send(note) robot.sci.play_song(1) midi_table = {'rest': 0, 'R': 0, 'pause': 0, 'G1': 31, 'G#1': 32, 'A1': 33, 'A#1': 34, 'B1': 35, 'C2': 36, 'C#2': 37, 'D2': 38, 'D#2': 39, 'E2': 40, 'F2': 41, 'F#2': 42, 'G2': 43, 'G#2': 44, 'A2': 45, 'A#2': 46, 'B2': 47, 'C3': 48, 'C#3': 49, 'D3': 50, 'D#3': 51, 'E3': 52, 'F3': 53, 'F#3': 54, 'G3': 55, 'G#3': 56, 'A3': 57, 'A#3': 58, 'B3': 59, 'C4': 60, 'C#4': 61, 'D4': 62, 'D#4': 63, 'E4': 64, 'F4': 65, 'F#4': 66, 'G4': 67, 'G#4': 68, 'A4': 69, 'A#4': 70, 'B4': 71, 'C5': 72, 'C#5': 73, 'D5': 74, 'D#5': 75, 'E5': 76, 'F5': 77, 'F#5': 78, 'G5': 79, 'G#5': 80, 'A5': 81, 'A#5': 82, 'B5': 83, 'C6': 84, 'C#6': 85, 'D6': 86, 'D#6': 87, 'E6': 88, 'F6': 89, 'F#6': 90, 'G6': 91, 'G#6': 92, 'A6': 93, 'A#6': 94, 'B6': 95, 'C7': 96, 'C#7': 97, 'D7': 98, 'D#7': 99, 'E7': 100, 'F7': 101, 'F#7': 102, 'G7': 103, 'G#7': 104, 'A7': 105, 'A#7': 106, 'B7': 107, 'C8': 108, 'C#8': 109, 'D8': 110, 'D#8': 111, 'E8': 112, 'F8': 113, 'F#8': 114, 'G8': 115, 'G#8': 116, 'A8': 117, 'A#8': 118, 'B8': 119, 'C9': 120, 'C#9': 121, 'D9': 122, 'D#9': 123, 'E9': 124, 'F9': 125, 'F#9': 126, 'G9': 127}
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSubtree(self, root: TreeNode, subRoot: TreeNode) -> bool: if not root: return False return self.isEqualtree(root, subRoot) or self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot) def isEqualtree(self, root1, root2): if not root1 and not root2: return True if not root1 or not root2: return False if root1.val != root2.val: return False return self.isEqualtree(root1.left, root2.left) and self.isEqualtree(root1.right, root2.right)
class Solution: def is_subtree(self, root: TreeNode, subRoot: TreeNode) -> bool: if not root: return False return self.isEqualtree(root, subRoot) or self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot) def is_equaltree(self, root1, root2): if not root1 and (not root2): return True if not root1 or not root2: return False if root1.val != root2.val: return False return self.isEqualtree(root1.left, root2.left) and self.isEqualtree(root1.right, root2.right)
'''Helper to filter sets of data''' class SetFilter: '''Helper class to filter list''' @staticmethod def diff(a_set, b_set): '''Filter by not intersection''' return not set(b_set).intersection(set(a_set)) @staticmethod def exact(a_set, b_set): '''Filter by eq''' return set(a_set) == set(b_set) @staticmethod def subset(a_set, b_set): '''Filter by intersection''' return set(a_set).intersection(set(b_set))
"""Helper to filter sets of data""" class Setfilter: """Helper class to filter list""" @staticmethod def diff(a_set, b_set): """Filter by not intersection""" return not set(b_set).intersection(set(a_set)) @staticmethod def exact(a_set, b_set): """Filter by eq""" return set(a_set) == set(b_set) @staticmethod def subset(a_set, b_set): """Filter by intersection""" return set(a_set).intersection(set(b_set))
code_begin = """#!/usr/bin/env bash curl""" code_header = """ --header "{header}:{value}" """ code_proxy = " -x {proxy}" code_post = """ --data "{data}" """ code_search = """ | egrep --color " {search_string} |$" """ code_nosearch = """ -v --request {method} {url} {headers} --include"""
code_begin = '#!/usr/bin/env bash\ncurl' code_header = ' --header "{header}:{value}" ' code_proxy = ' -x {proxy}' code_post = ' --data "{data}" ' code_search = ' | egrep --color " {search_string} |$" ' code_nosearch = ' -v --request {method} {url} {headers} --include'
# Solution to Exercise #1 # ... env = MultiAgentArena() obs = env.reset() while True: # Compute actions separately for each agent. a1 = dummy_trainer.compute_action(obs["agent1"]) a2 = dummy_trainer.compute_action(obs["agent2"]) # Send the action-dict to the env. obs, rewards, dones, _ = env.step({"agent1": a1, "agent2": a2}) # Get a rendered image from the env. out.clear_output(wait=True) env.render() time.sleep(0.1) if dones["agent1"]: break
env = multi_agent_arena() obs = env.reset() while True: a1 = dummy_trainer.compute_action(obs['agent1']) a2 = dummy_trainer.compute_action(obs['agent2']) (obs, rewards, dones, _) = env.step({'agent1': a1, 'agent2': a2}) out.clear_output(wait=True) env.render() time.sleep(0.1) if dones['agent1']: break
#!/usr/bin/env python # -*- coding: utf-8 -*- count = 0 while count < 10: count += 1 if count % 2 == 0: continue print(count, end=" ")
count = 0 while count < 10: count += 1 if count % 2 == 0: continue print(count, end=' ')
def bubble_sort(arr): length = len(arr) for i in range(length): for j in range(0, length - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] def main(): random_list = [12, 4, 5, 6, 25, 14, 15] bubble_sort(random_list) print(random_list) if __name__ == "__main__": main()
def bubble_sort(arr): length = len(arr) for i in range(length): for j in range(0, length - i - 1): if arr[j] > arr[j + 1]: (arr[j], arr[j + 1]) = (arr[j + 1], arr[j]) def main(): random_list = [12, 4, 5, 6, 25, 14, 15] bubble_sort(random_list) print(random_list) if __name__ == '__main__': main()
def bowling_score(frames): frames = [list(r) for r in frames.split(' ')] points = 0 for f in range(0, 8): if frames[f][0] == 'X': points += 10 if frames[f+1][0] == 'X': points += 10 if frames[f+2][0] == 'X': points += 10 else: points += int(frames[f+2][0]) elif frames[f+1][1] == '/': points += 10 else: points += int(frames[f+1][0]) + int(frames[f+1][1]) elif frames[f][1] == '/': points += 10 if frames[f+1][0] == 'X': points += 10 else: points += int(frames[f+1][0]) else: points += int(frames[f][0]) + int(frames[f][1]) if frames[8][0] == 'X': points += 10 if frames[9][0] == 'X': points += 10 if frames[9][1] == 'X': points += 10 else: points += int(frames[9][1]) elif frames[9][1] == '/': points += 10 else: points += int(frames[9][0]) + int(frames[9][1]) elif frames[8][1] == '/': points += 10 if frames[9][0] == 'X': points += 10 else: points += int(frames[9][0]) else: points += int(frames[8][0]) + int(frames[8][1]) if frames[9][0] == 'X': points += 10 if frames[9][1] == 'X': points += 10 if frames[9][2] == 'X': points += 10 else: points += int(frames[9][2]) elif frames[9][2] == '/': points += 10 else: points += int(frames[9][1]) + int(frames[9][2]) elif frames[9][1] == '/': points += 10 if frames[9][2] == 'X': points += 10 else: points += int(frames[9][2]) else: points += int(frames[9][0]) + int(frames[9][1]) return points if __name__ == '__main__': print(bowling_score('11 11 11 11 11 11 11 11 11 11')) print(bowling_score('X X X X X X X X X XXX')) print(bowling_score('00 5/ 4/ 53 33 22 4/ 5/ 45 XXX')) print(bowling_score('5/ 4/ 3/ 2/ 1/ 0/ X 9/ 4/ 8/8')) print(bowling_score('5/ 4/ 3/ 2/ 1/ 0/ X 9/ 4/ 7/2'))
def bowling_score(frames): frames = [list(r) for r in frames.split(' ')] points = 0 for f in range(0, 8): if frames[f][0] == 'X': points += 10 if frames[f + 1][0] == 'X': points += 10 if frames[f + 2][0] == 'X': points += 10 else: points += int(frames[f + 2][0]) elif frames[f + 1][1] == '/': points += 10 else: points += int(frames[f + 1][0]) + int(frames[f + 1][1]) elif frames[f][1] == '/': points += 10 if frames[f + 1][0] == 'X': points += 10 else: points += int(frames[f + 1][0]) else: points += int(frames[f][0]) + int(frames[f][1]) if frames[8][0] == 'X': points += 10 if frames[9][0] == 'X': points += 10 if frames[9][1] == 'X': points += 10 else: points += int(frames[9][1]) elif frames[9][1] == '/': points += 10 else: points += int(frames[9][0]) + int(frames[9][1]) elif frames[8][1] == '/': points += 10 if frames[9][0] == 'X': points += 10 else: points += int(frames[9][0]) else: points += int(frames[8][0]) + int(frames[8][1]) if frames[9][0] == 'X': points += 10 if frames[9][1] == 'X': points += 10 if frames[9][2] == 'X': points += 10 else: points += int(frames[9][2]) elif frames[9][2] == '/': points += 10 else: points += int(frames[9][1]) + int(frames[9][2]) elif frames[9][1] == '/': points += 10 if frames[9][2] == 'X': points += 10 else: points += int(frames[9][2]) else: points += int(frames[9][0]) + int(frames[9][1]) return points if __name__ == '__main__': print(bowling_score('11 11 11 11 11 11 11 11 11 11')) print(bowling_score('X X X X X X X X X XXX')) print(bowling_score('00 5/ 4/ 53 33 22 4/ 5/ 45 XXX')) print(bowling_score('5/ 4/ 3/ 2/ 1/ 0/ X 9/ 4/ 8/8')) print(bowling_score('5/ 4/ 3/ 2/ 1/ 0/ X 9/ 4/ 7/2'))
# -*- coding: utf-8 -*- __soap_format = ( '<?xml version="1.0" encoding="UTF-8"?>\n' '<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ' 'xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" ' 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' 'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' 'xmlns:ns1="{url}">' '<SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' '<ns1:{action}>{params}</ns1:{action}>' '</SOAP-ENV:Body>' '</SOAP-ENV:Envelope>' ) __headers = { 'User-Agent': 'BSPlayer/2.x (1022.12362)', 'Content-Type': 'text/xml; charset=utf-8', 'Connection': 'close', } __subdomains = [1, 2, 3, 4, 5, 6, 7, 8, 101, 102, 103, 104, 105, 106, 107, 108, 109] def __get_url(core, service_name): context = core.services[service_name].context if not context.subdomain: time_seconds = core.datetime.now().second context.subdomain = __subdomains[time_seconds % len(__subdomains)] return "http://s%s.api.bsplayer-subtitles.com/v1.php" % context.subdomain def __validate_response(core, service_name, request, response, retry=True): if not retry: return None def get_retry_request(): core.time.sleep(2) request['validate'] = lambda response: __validate_response(core, service_name, request, response, retry=False) return request if response is None: return get_retry_request() if response.status_code != 200: return get_retry_request() response = __parse_response(core, service_name, response.text) if response is None: return None status_code = response.find('result/result') if status_code is None: status_code = response.find('result') if status_code.text != '200' and status_code.text != '402': return get_retry_request() results = response.findall('data/item') if not results: return get_retry_request() if len(results) == 0: return get_retry_request() return None def __get_request(core, service_name, action, params): url = __get_url(core, service_name) headers = __headers.copy() headers['SOAPAction'] = '"%s#%s"' % (url, action) request = { 'method': 'POST', 'url': url, 'data': __soap_format.format(url=url, action=action, params=params), 'headers': headers, 'validate': lambda response: __validate_response(core, service_name, request, response) } return request def __parse_response(core, service_name, response): try: tree = core.ElementTree.fromstring(response.strip()) return tree.find('.//return') except Exception as exc: core.logger.error('%s - %s' % (service_name, exc)) return None def __logout(core, service_name): context = core.services[service_name].context if not context.token: return action = 'logOut' params = '<handle>%s</handle>' % context.token request = __get_request(core, service_name, action, params) def logout(): core.request.execute(core, request) context.token = None thread = core.threading.Thread(target=logout) thread.start() def build_auth_request(core, service_name): action = 'logIn' params = ( '<username></username>' '<password></password>' '<AppID>BSPlayer v2.72</AppID>' ) return __get_request(core, service_name, action, params) def parse_auth_response(core, service_name, response): response = __parse_response(core, service_name, response) if response is None: return if response.find('result').text == '200': token = response.find('data').text core.services[service_name].context.token = token def build_search_requests(core, service_name, meta): token = core.services[service_name].context.token if not token: return [] action = 'searchSubtitles' params = ( '<handle>{token}</handle>' '<movieHash>{filehash}</movieHash>' '<movieSize>{filesize}</movieSize>' '<languageId>{lang_ids}</languageId>' '<imdbId>{imdb_id}</imdbId>' ).format( token=token, filesize=meta.filesize if meta.filesize else '0', filehash=meta.filehash if meta.filehash else '0', lang_ids=','.join(core.utils.get_lang_ids(meta.languages)), imdb_id=meta.imdb_id[2:] ) return [__get_request(core, service_name, action, params)] def parse_search_response(core, service_name, meta, response): __logout(core, service_name) service = core.services[service_name] response = __parse_response(core, service_name, response.text) if response is None: return [] if response.find('result/result').text != '200': return [] results = response.findall('data/item') if not results: return [] lang_ids = core.utils.get_lang_ids(meta.languages) def map_result(result): name = result.find('subName').text lang_id = result.find('subLang').text rating = result.find('subRating').text try: lang = meta.languages[lang_ids.index(lang_id)] except: lang = lang_id return { 'service_name': service_name, 'service': service.display_name, 'lang': lang, 'name': name, 'rating': int(round(float(rating) / 2)) if rating else 0, 'lang_code': core.kodi.xbmc.convertLanguage(lang, core.kodi.xbmc.ISO_639_1), 'sync': 'true' if meta.filehash else 'false', 'impaired': 'false', 'color': 'gold', 'action_args': { 'url': result.find('subDownloadLink').text, 'lang': lang, 'filename': name, 'gzip': True } } return list(map(map_result, results)) def build_download_request(core, service_name, args): request = { 'method': 'GET', 'url': args['url'] } return request
__soap_format = '<?xml version="1.0" encoding="UTF-8"?>\n<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:ns1="{url}"><SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><ns1:{action}>{params}</ns1:{action}></SOAP-ENV:Body></SOAP-ENV:Envelope>' __headers = {'User-Agent': 'BSPlayer/2.x (1022.12362)', 'Content-Type': 'text/xml; charset=utf-8', 'Connection': 'close'} __subdomains = [1, 2, 3, 4, 5, 6, 7, 8, 101, 102, 103, 104, 105, 106, 107, 108, 109] def __get_url(core, service_name): context = core.services[service_name].context if not context.subdomain: time_seconds = core.datetime.now().second context.subdomain = __subdomains[time_seconds % len(__subdomains)] return 'http://s%s.api.bsplayer-subtitles.com/v1.php' % context.subdomain def __validate_response(core, service_name, request, response, retry=True): if not retry: return None def get_retry_request(): core.time.sleep(2) request['validate'] = lambda response: __validate_response(core, service_name, request, response, retry=False) return request if response is None: return get_retry_request() if response.status_code != 200: return get_retry_request() response = __parse_response(core, service_name, response.text) if response is None: return None status_code = response.find('result/result') if status_code is None: status_code = response.find('result') if status_code.text != '200' and status_code.text != '402': return get_retry_request() results = response.findall('data/item') if not results: return get_retry_request() if len(results) == 0: return get_retry_request() return None def __get_request(core, service_name, action, params): url = __get_url(core, service_name) headers = __headers.copy() headers['SOAPAction'] = '"%s#%s"' % (url, action) request = {'method': 'POST', 'url': url, 'data': __soap_format.format(url=url, action=action, params=params), 'headers': headers, 'validate': lambda response: __validate_response(core, service_name, request, response)} return request def __parse_response(core, service_name, response): try: tree = core.ElementTree.fromstring(response.strip()) return tree.find('.//return') except Exception as exc: core.logger.error('%s - %s' % (service_name, exc)) return None def __logout(core, service_name): context = core.services[service_name].context if not context.token: return action = 'logOut' params = '<handle>%s</handle>' % context.token request = __get_request(core, service_name, action, params) def logout(): core.request.execute(core, request) context.token = None thread = core.threading.Thread(target=logout) thread.start() def build_auth_request(core, service_name): action = 'logIn' params = '<username></username><password></password><AppID>BSPlayer v2.72</AppID>' return __get_request(core, service_name, action, params) def parse_auth_response(core, service_name, response): response = __parse_response(core, service_name, response) if response is None: return if response.find('result').text == '200': token = response.find('data').text core.services[service_name].context.token = token def build_search_requests(core, service_name, meta): token = core.services[service_name].context.token if not token: return [] action = 'searchSubtitles' params = '<handle>{token}</handle><movieHash>{filehash}</movieHash><movieSize>{filesize}</movieSize><languageId>{lang_ids}</languageId><imdbId>{imdb_id}</imdbId>'.format(token=token, filesize=meta.filesize if meta.filesize else '0', filehash=meta.filehash if meta.filehash else '0', lang_ids=','.join(core.utils.get_lang_ids(meta.languages)), imdb_id=meta.imdb_id[2:]) return [__get_request(core, service_name, action, params)] def parse_search_response(core, service_name, meta, response): __logout(core, service_name) service = core.services[service_name] response = __parse_response(core, service_name, response.text) if response is None: return [] if response.find('result/result').text != '200': return [] results = response.findall('data/item') if not results: return [] lang_ids = core.utils.get_lang_ids(meta.languages) def map_result(result): name = result.find('subName').text lang_id = result.find('subLang').text rating = result.find('subRating').text try: lang = meta.languages[lang_ids.index(lang_id)] except: lang = lang_id return {'service_name': service_name, 'service': service.display_name, 'lang': lang, 'name': name, 'rating': int(round(float(rating) / 2)) if rating else 0, 'lang_code': core.kodi.xbmc.convertLanguage(lang, core.kodi.xbmc.ISO_639_1), 'sync': 'true' if meta.filehash else 'false', 'impaired': 'false', 'color': 'gold', 'action_args': {'url': result.find('subDownloadLink').text, 'lang': lang, 'filename': name, 'gzip': True}} return list(map(map_result, results)) def build_download_request(core, service_name, args): request = {'method': 'GET', 'url': args['url']} return request
ACCEL_FSR_2G = 0 ACCEL_FSR_4G = 1 ACCEL_FSR_8G = 2 ACCEL_FSR_16G = 3
accel_fsr_2_g = 0 accel_fsr_4_g = 1 accel_fsr_8_g = 2 accel_fsr_16_g = 3
SUCCESS = 0 FAILURE = 1 # NOTE: click.abort() uses this # for when tests are already running ALREADY_RUNNING = 2
success = 0 failure = 1 already_running = 2
karman_line_earth = 100_000*m // km karman_line_mars = 80_000*m // km karman_line_venus = 250_000*m // km
karman_line_earth = 100000 * m // km karman_line_mars = 80000 * m // km karman_line_venus = 250000 * m // km
def extractWLTranslations(item): """ # 'WL Translations' """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None if 'Chapter Releases' in item['tags'] and ('OSI' in item['tags'] or item['title'].startswith('OSI Chapter')): return buildReleaseMessageWithType(item, 'One Sword to Immortality', vol, chp, frag=frag, postfix=postfix) return False
def extract_wl_translations(item): """ # 'WL Translations' """ (vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None if 'Chapter Releases' in item['tags'] and ('OSI' in item['tags'] or item['title'].startswith('OSI Chapter')): return build_release_message_with_type(item, 'One Sword to Immortality', vol, chp, frag=frag, postfix=postfix) return False
class Car: def __init__(self, make, petrol_consumption): self.make = make self.petrol_consumption = petrol_consumption def petrol_calculation(self, price = 22.5): return self.petrol_consumption * price ford = Car("ford", 10) money = ford.petrol_calculation() print(money)
class Car: def __init__(self, make, petrol_consumption): self.make = make self.petrol_consumption = petrol_consumption def petrol_calculation(self, price=22.5): return self.petrol_consumption * price ford = car('ford', 10) money = ford.petrol_calculation() print(money)
# Mouse Move # # November 12, 2018 # By Robin Nash [c,r] = [int(i) for i in input().split(" ") if i != " "] x,y = 0,0 while True: pair = [int(i) for i in input().split(" ") if i != " "] if pair == [0,0]: break x += pair[0] y += pair[1] pair = [x,y] for i in range(2): if pair[i] > [c,r][i]: pair[i] = [c,r][i] if pair[i] < 0: pair[i] = 0 [x,y] = pair print(x,y) #1541983052.0
[c, r] = [int(i) for i in input().split(' ') if i != ' '] (x, y) = (0, 0) while True: pair = [int(i) for i in input().split(' ') if i != ' '] if pair == [0, 0]: break x += pair[0] y += pair[1] pair = [x, y] for i in range(2): if pair[i] > [c, r][i]: pair[i] = [c, r][i] if pair[i] < 0: pair[i] = 0 [x, y] = pair print(x, y)
class Solution: def thirdMax(self, nums: List[int]) -> int: hq = [] for x in nums: if x not in hq: if len(hq) < 3: heapq.heappush(hq, x) else: heapq.heappushpop(hq, x) if len(hq) < 3: return hq[-1] return hq[0]
class Solution: def third_max(self, nums: List[int]) -> int: hq = [] for x in nums: if x not in hq: if len(hq) < 3: heapq.heappush(hq, x) else: heapq.heappushpop(hq, x) if len(hq) < 3: return hq[-1] return hq[0]
s = input() k = int(input()) ans = set() for i in range(len(s)): for j in range(1, k+1): ans.add(s[i:i+j]) # print(ans) print(sorted(list(ans))[k-1])
s = input() k = int(input()) ans = set() for i in range(len(s)): for j in range(1, k + 1): ans.add(s[i:i + j]) print(sorted(list(ans))[k - 1])
""" File: copyfile.py Project 7.3 Copies the text from a given input file to a given output file. """ # Take the inputs inName = input("Enter the input file name: ") outName = input("Enter the output file name: ") # Open the input file and read the text inputFile = open(inName, 'r') text = inputFile.read() # Open the output file and write the text outFile = open(outName, 'w') outFile.write(text) outFile.close()
""" File: copyfile.py Project 7.3 Copies the text from a given input file to a given output file. """ in_name = input('Enter the input file name: ') out_name = input('Enter the output file name: ') input_file = open(inName, 'r') text = inputFile.read() out_file = open(outName, 'w') outFile.write(text) outFile.close()