content
stringlengths
7
1.05M
''' Created on 1.12.2016 @author: Darren ''' ''' Given a binary search tree and a node in it, find the in-order successor of that node in the BST. Note: If the given node has no in-order successor in the tree, return null. '''
def printCommands(): print("Congratulations! You're running Ryan's Task list program.") print("What would you like to do next?") print("1. List all tasks.") print("2. Add a task to the list.") print("3. Delete a task.") print("q. To quit the program") printCommands() aTaskListArray = ["bob", "dave"] userSelection = input('Enter a command: ') if userSelection == "1": for itemList in aTaskListArray: print(itemList) userSelection = input('Enter a command: ') if userSelection == "2": newTask = input("What would you like to add? ") aTaskListArray.append(newTask) userSelection = input("Enter a command: ") if userSelection == "3": newTask = input("What would you like to remove? ") aTaskListArray.remove(newTask) userSelection = input("Enter a command: ") if userSelection == "q": quit() else: print("Not a command") print(aTaskListArray)
data = open("input.txt", "r") data = data.read().split(",") check = True index = 0 while check is True: section = data[index] firstNum = int(data[int(data[index + 1])]) secondNum = int(data[int(data[index + 2])]) if section == "1": total = firstNum + secondNum if section == "2": total = firstNum * secondNum data[int(data[index + 3])] = str(total) if data[index + 4] == "99": check = False index = index + 4 print("Your answer is... " + data[0])
mod = 10**9 + 7 n = int(input()) a = list(map(int, input().split())) answer = 0 sumation = sum(a) for i in range(n-1): sumation -= a[i] answer += a[i]*sumation answer %= mod print(answer)
{ "targets": [ { "target_name": "sharedMemory", "include_dirs": [ "<!(node -e \"require('napi-macros')\")" ], "sources": [ "./src/sharedMemory.cpp" ], "libraries": [], }, { "target_name": "messaging", "include_dirs": [ "<!(node -e \"require('napi-macros')\")" ], "sources": [ "./src/messaging.cpp" ], "libraries": [], } ] }
def protected(func): def wrapper(password): if password=='platzi': return func() else: print('Contrasena invalida') return wrapper @protected def protected_func(): print('To contrasena es correcta') if __name__ == "__main__": password=str(raw_input('Ingresa tu contrasena: ')) # wrapper=protected(protected_func) # wrapper(password) protected_func(password)
s=input() if s[-1] in '24579': print('hon') elif s[-1] in '0168': print('pon') else: print('bon')
# Text Type: str # Numeric Types: int, float, complex # Sequence Types: list, tuple, range # Mapping Type: dict # Set Types: set, frozenset # Boolean Type: bool # Binary Types: bytes, bytearray, memoryview x = float(1) # x will be 1.0 y = float(2.8) # y will be 2.8 z = float("3") # z will be 3.0 w = float("4.2") # w will be 4.2 print("--------------------------------------------------------") num =6 print(num) print(str(num)+ " is my num") # print(num + "my num") # print(num + "my num") - will not work print("--------------------------------------------------------")
"""Extended Euclidean Algorithm ============================== GCD of two numbers is the largest number that divides both of them. A simple way to find GCD is to factorize both numbers and multiply common factors. GCD(a,b) = ax + by If we can find the value of x and y then we can easily find the value of GCD(a,b) by replacing (x,y) with their respective values. """ def gcdFunction(a, b, x, y): if a == 0: x = 0 y = 1 return b x1 = 0; y1 = 0 gcd = gcdFunction(b % a, a, x1, y1) x = y1 - int(b / a) * x1 y = x1 return gcd a = 98; b = 21 x = 0; y = 0 print("GCD of numbers " + str(a) + " and " + str(b) + " is " + str(gcdFunction(a, b, x, y))) ''' Output GCD of numbers 98 and 21 is 7 '''
TRAIN_DATA_PATH = "data/processed/train_folds.csv" TEST_DATA_PATH = "data/processed/test.csv" MODEL_PATH = "models/" NUM_FOLDS = 5 SEED = 23 VERBOSE = 0 FEATURE_COLS = [ "Pclass", "Sex", "Age", "SibSp", "Parch", "Ticket", "Fare", "Cabin", "Embarked", "Title", "Surname", "Family_Size", ] TARGET_COL = "Survived"
""" author: Alice Francener problem: 1082 - Connected Components description: https://www.urionlinejudge.com.br/judge/en/problems/view/1082 """ '''Problema: quantos grafos conexos existem''' class DisjointSets: def __init__(self, n): self.rank = [0] * n self.parent = [] for i in range(0, n): self.parent.append(i) def find(self, u): if u != self.parent[u]: self.parent[u] = self.find(self.parent[u]) return self.parent[u] def union(self, x, y): x = self.find(x) y = self.find(y) if self.rank[x] > self.rank[y]: self.parent[y] = x else: self.parent[x] = y if self.rank[x] == self.rank[y]: self.rank[y] = self.rank[y] + 1 '''input: 1. numero de casos, 2. numero de nos & numero de arestas, 3. arestas''' n_casos = int(input()) for caso in range(n_casos): entrada = input().split() n_nodes = int(entrada[0]) n_edges = int(entrada[1]) alfabeto = DisjointSets(n_nodes) for e in range(n_edges): edge = input().split() alfabeto.union(ord(edge[0])-97, ord(edge[1])-97) for i in range(0, n_nodes): alfabeto.find(i) print("Case #{}:".format(caso+1)) connected = 0 for i in range(0, len(alfabeto.parent)): graph = '' if alfabeto.parent[i] != -1: graph = graph + chr(i+97) + ',' for j in range(i+1, len(alfabeto.parent)): if alfabeto.parent[i] == alfabeto.parent[j]: graph = graph + chr(j+97) + ',' alfabeto.parent[j] = -1 if len(graph): print(graph) connected = connected + 1 print('{} connected components\n'.format(connected))
def parse_ninja(): f = open('out/peerconnection_client.ninja', 'r') for line in f.readlines(): lines = line.split(" ") for l in lines: print(l) f.close() def create_list_of_libs(): f = open('out/client_libs.txt', 'r') for line in f.readlines(): segments = line.strip().split('/') print('PUBLIC ' + segments[len(segments)-1].split('.')[0].upper()) f.close() def main(): create_list_of_libs() if __name__ == '__main__': main()
#(n-1)%M = x - 1 #(n-1)%N = y - 1 gcd = lambda a,b: gcd(b,a%b) if b else a def finder(M,N,x,y): for i in range(N//gcd(M,N)): if (x-1+i*M)%N==y-1: return x+i*M return -1 for _ in range(int(input())): M,N,x,y = map(int,input().split()) print(finder(M,N,x,y))
# while循环,语法如下 # while 条件表达式: # 循环体 print("求数,三三数之剩二,五五数之剩三,七七数之剩二") found = False number = 0 while not found: number += 1 if number % 3 == 2 and number % 5 == 3 and number % 7 == 2: print("数字为", str(number)) found = True # for循环,语法如下 # for 迭代变量 in 对象: # 循环体 print("计算1+2+3+···+100=?") result = 0 # range内置函数,用于生成一系列连续的整数,语法:range(start,end,step) # range函数中start可省略(默认为0),step可省略(默认为1),end不可省略(生成的数据不包括end) for i in range(101): result += i print("结果为", result) # 使用range函数输出10以内的奇数,print时使用end=' '将内容打印在一行,不换行 for i in range(1, 10, 2): print(i, end=' ') print("\n再求数,三三数之剩二,五五数之剩三,七七数之剩二") for value in range(100): if value % 3 == 2 and value % 5 == 3 and value % 7 == 2: print("数字为", value) # 变量字符串 content = "LOVE" print(content) for char in content: print(char) # 嵌套循环,for循环和while循环可以互相嵌套 # 打印九九乘法表 for row in range(10): for col in range(1, row + 1): print(str(row) + "*" + str(col) + "=" + str(row * col) + "\t", end='') print("")
norm_cfg = dict(type='GN', num_groups=32, requires_grad=True) model = dict( type='PoseDetDetector', pretrained='pretrained/dla34-ba72cf86.pth', # pretrained='open-mmlab://msra/hrnetv2_w32', backbone=dict( type='DLA', return_levels=True, levels=[1, 1, 1, 2, 2, 1], channels=[16, 32, 64, 128, 256, 512], ouput_indice=[3,4,5,6], ), neck=dict( type='FPN', in_channels=[64, 128, 256, 512], out_channels=128, start_level=1, add_extra_convs='on_input', num_outs=4, # num_outs=3, norm_cfg=norm_cfg,), bbox_head=dict( # type='PoseDetHead', type='PoseDetHeadHeatMapMl', norm_cfg=norm_cfg, num_classes=1, in_channels=128, feat_channels=128, embedding_feat_channels=128, init_convs=3, refine_convs=2, cls_convs=2, gradient_mul=0.1, dcn_kernel=(1,17), refine_num=1, point_strides=[8, 16, 32, 64], point_base_scale=4, num_keypoints=17, loss_cls=dict( type='FocalLoss', use_sigmoid=True, gamma=2.0, alpha=0.25, loss_weight=1.0), loss_keypoints_init=dict(type='KeypointsLoss', d_type='L2', weight=.1, stage='init', normalize_factor=1, ), loss_keypoints_refine=dict(type='KeypointsLoss', d_type='L2', weight=.2, stage='refine', normalize_factor=1, ), loss_heatmap=dict(type='HeatmapLoss', weight=.1, with_sigmas=False), ) ) # training and testing settings train_cfg = dict( init=dict( assigner=dict(type='KeypointsAssigner', scale=4, pos_num=1, number_keypoints_thr=3, num_keypoints=17, center_type='keypoints', # center_type='box' ), allowed_border=-1, pos_weight=-1, debug=False), refine=dict( assigner=dict( type='OksAssigner', pos_PD_thr=0.7, neg_PD_thr=0.7, min_pos_iou=0.52, ignore_iof_thr=-1, match_low_quality=True, num_keypoints=17, number_keypoints_thr=3, # ), allowed_border=-1, pos_weight=-1, debug=False ), cls=dict( assigner=dict( type='OksAssigner', pos_PD_thr=0.6, neg_PD_thr=0.5, min_pos_iou=0.5, ignore_iof_thr=-1, match_low_quality=False, num_keypoints=17, number_keypoints_thr=3, ), allowed_border=-1, pos_weight=-1, debug=False ), ) test_cfg = dict( nms_pre=500, min_bbox_size=0, score_thr=0.05, nms=dict(type='keypoints_nms', iou_thr=0.2), max_per_img=100)
"""top-level pytest config options can only be defined here, not in binderhub/tests/conftest.py """ def pytest_addoption(parser): parser.addoption( "--helm", action="store_true", default=False, help="Run tests marked with pytest.mark.helm", )
# Exceptions class SequenceFieldException(Exception): pass
try: x = int(input("X: ")) except ValueError: print("That is not an int!") exit() try: y = int(input("Y: ")) except ValueError: print("That is not an int!") exit() print (x + y)
# Design Linked List class ListNode: def __init__(self, x): self.value = x self.next = None class LinkedList: def __init__(self): self.size = 0 self.head = ListNode(0) # Sentinel Node as psuedo-head # add at head def addAtHead(self, val): self.addAtHead(0, val) # add at tail def addAtTail(self, val): self.addAtTail(self.size, val) # add at index def addAtIndex(self, index, val): if index > self.size: return if index < 0: index = 0 self.size += 1 # predecessor of the node prd = self.head for _ in range(index): prd = prd.next # node to be added to_add = ListNode(val) # Insert to_add.next = prd.next prd.next = to_add # delete at index def delAtIndex(self,index): if index < 0 or index >= index.size: return self.size -= 1 prd = self.head for _ in range(index): prd = prd.next prd.next = prd.next.next # get element def getElement(self,index): if index < 0 or index >= self.size: return -1 curr = self.head for _ in range(index + 1): curr = curr.next return curr.val
# -*- coding:utf-8 -*- pizza = { 'crust': 'thick', 'toppings': ['mushrooms', 'extra cheese'], }
''' 1) 파일 열기(open) 2) 파일 읽기(read)/쓰기(write) 3) 파일 닫기(close) ''' # 파일 열기 f = open('test.txt', 'w', encoding ='utf-8') # 파일에 텍스트를 씀 for i in range(1,11): f.write(f'{i}번째 줄...\n') # 파일 닫기 f.close() # with 구문 : 리소스를 사용한 후 close() 메소드를 자동으로 호출 # with ...as 변수: # 실행문 with open('test2.txt', mode='w', encoding='utf-8') as f: f.write('Hello, Python!\n') f.write('점심 식사는 맛있게 하셨나요?\n') f.write('0123456789\n')
# You may remember by now that while loops use the condition to check when # to exit. The body of the while loop needs to make sure that the condition begin # checked will change. If it doesn't change, the loop may never finish and we get # what's called an infinite loop, a loop that keeps executing and never stops. # Check out this example. It uses the modulo operator that we saw a while back. # This cycle will finish for positive and negative values of x. But what would # happen if x was zero? The remainder of 0 divided by 2 is 0, so the condition # would be true. The result of dividing 0 by 2 would also be zero, so the value of # x wouldn't change. This loop would go on for ever, and so we'd get an infinite # loop. If our code was called with x having the value of zero, the computer # would just waster resources doing a division that would never lead to the loop # stopping. The program would be stuck in an infinite loop circling background # endlessly, and we don't want that. All that looping might make your computer # dizzy. To avoid this, we need to think about what needs to be different than zero. # So we could nest this while loop inside an if statement just like this. With this # approach, the while loop is executed only when x is not zero. Alternatively, we # could add the condition directly to the loop using a logical operator like in this # example. This makes sure we only enter the body of the loop for values of x # that are both different than zero and even. Talking about infinite loop reminds # me of one of the first times I used while loops myself. I wrote a script that # emailed me as a way of verifying that the code worked, and while some # condition was true, I forgot to exit the loop. Turns out those e-mails get sent # faster than once per second. As you can imagine, I got about 500 e-mails # before I realized what was going on. Infinitely grateful for that little lesson. # When you're done laughing at my story, remember, when you're writing loops, # it's a good idea to take a moment to consider the different values a variable # can take. This helps you make sure your loop won't get stuck, If you see that # your program is running forever without finishing, have a second look at your # loops to check there's no infinite loop hiding somewhere in the code. While # you need to watch out for infinite loops, they are not always a bad thing. # Sometimes you actually want your program to execute continuously until # some external condition is met. If you've used the ping utility on Linux or # macOS system, or ping-t on a Windows system, you've seen an infinite loop in # action. This tool will keep sending packets and printing the results to the # terminal unless you send it the interrupt signal, usually pressing Ctrl+C. If you # were looking at the program source code you'll see that it uses an infinite loop # to do hits with a block of code with instructions to keep sending the packets # forever. One thing to call out is it should always be possible to break the loop # by sending a certain signal. In the ping example, that signal is the user pressing # Ctrl+C. In other cases, it could be that the user pressed the button on a # graphical application, or that another program sent a specific signal, or even # that a time limit was reached. In your code, you could have an infinite loop that # looks something like this. In Python, we use the break keyword which you can # see here to signal that the current loop should stop running. We can use it not # only to stop infinite loops but also to stop a loop early if the code has already # achieved what's needed. So quick refresh. How do you avoid the most # common pitfalls when writing while loops? First, remember to initialize your # variables, and second, check that your loops won't run forever. Wow, All this # talk of loops is making me feel a little loopy. I'm going to have to go and lie # down while you do the next practice quiz. Best of luck, and meet me over in # the next video when you're done. # The following code causes an infinite loop. Can you figure out what's missing # and how to fix it? def print_range(start, end): # Loop through the numbers from stand to end n = start while n <= end: print(n) n += 1 print_range(1, 5) # Should print 1 2 3 4 5 (each number on its own line)
""" *Sounding State* A type describing state of data soundness. """ class SoundingState( StatefulPhantomClass, ): pass
""" Top level of MQTT IO package. """ VERSION = "2.1.4"
DOMAIN = "audiconnect" CONF_VIN = "vin" CONF_CARNAME = "carname" CONF_ACTION = "action" MIN_UPDATE_INTERVAL = 5 DEFAULT_UPDATE_INTERVAL = 10 CONF_SPIN = "spin" CONF_REGION = "region" CONF_SERVICE_URL = "service_url" CONF_MUTABLE = "mutable" SIGNAL_STATE_UPDATED = "{}.updated".format(DOMAIN) TRACKER_UPDATE = f"{DOMAIN}_tracker_update" RESOURCES = [ "position", "last_update_time", "mileage", "range", "service_inspection_time", "service_inspection_distance", "oil_change_time", "oil_change_distance", "oil_level", "charging_state", "max_charge_current", "engine_type1", "engine_type2", "parking_light", "any_window_open", "any_door_unlocked", "any_door_open", "trunk_unlocked", "trunk_open", "hood_open", "tank_level", "state_of_charge", "remaining_charging_time", "plug_state", "sun_roof", "doors_trunk_status", ] COMPONENTS = { "sensor": "sensor", "binary_sensor": "binary_sensor", "lock": "lock", "device_tracker": "device_tracker", "switch": "switch", }
def first_last6(list1: list) -> bool: """Return True if either/both first and last element are assigned a value of 6 >>> first_last6(test_list1) False >>> first_last6(test_list2) True >>> first_last6(test_list3) True """ if list1[0] or list1[5] == 6: return True else: return False test_list1 = [0, 1, 2, 3, 4, 5] test_list2 = [6, 1, 2, 3, 4, 9] test_list3 = [6, 1, 2, 3, 4, 6] print(first_last6(test_list1)) print(first_last6(test_list2)) print(first_last6(test_list3))
class Mouse: __slots__=( '_system_cursor', 'has_mouse' ) def __init__(self): self._system_cursor = ez.window.panda_winprops.get_cursor_filename() self.has_mouse = ez.panda_showbase.mouseWatcherNode.has_mouse def hide(self): ez.window.panda_winprops.set_cursor_hidden(True) ez.panda_showbase.win.request_properties(ez.window.panda_winprops) def show(self): ez.window.panda_winprops.set_cursor_hidden(False) ez.panda_showbase.win.request_properties(ez.window.panda_winprops) @property def cursor(self): return ez.window.panda_winprops.get_cursor_filename() ez.panda_showbase.win.request_properties(ez.window.panda_winprops) @cursor.setter def cursor(self, cursor): if cursor: ez.window.panda_winprops.set_cursor_filename(cursor) else: ez.window.panda_winprops.set_cursor_filename(self._system_cursor) ez.panda_showbase.win.request_properties(ez.window.panda_winprops) @property def mouse_pos(self): return ez.panda_showbase.mouseWatcherNode.get_mouse() @property def pos(self): # Convert mouse coordinates to aspect2D coordinates: mpos = ez.panda_showbase.mouseWatcherNode.get_mouse() pos = aspect2d.get_relative_point(render, (mpos.x, mpos.y, 0)) return pos.xy @pos.setter def pos(self, pos): # Have to convert aspect2D position to window coordinates: x, y = pos w, h = ez.panda_showbase.win.get_size() cpos = ez.panda_showbase.camera2d.get_pos() L, R, T, B = ez.window.get_aspect2D_edges() # Get aspect2D size: aw = R-L ah = T-B # Get mouse pos equivalent to window cordinates: mx = x+R my = abs(y+B) # Convert the mouse pos to window position: x = mx/aw*w y = my/ah*h ez.panda_showbase.win.move_pointer(0, round(x), round(y))
n = int(input()) s = set(map(int, input().split())) for i in range(int(input())): f = input().split() if (f[0] == "pop"): s.pop() elif (f[0] == "remove"): s.remove(int(f[-1])) else: s.discard(int(f[-1])) print(sum(s))
# ------------------------------------------------------------------------------------ # Tutorial: Learn how to use Dictionaries in Python # ------------------------------------------------------------------------------------ # Dictionaries are a collection of key-value pairs. # Keys can only appear once in a dictionary but can be of any type. # Dictionaries are unordered. # Values can appear in any number of keys. # Keys can be of almost any type, values can be of any type. # Defining a dictionary # Dictionaries are assigned using a pair of curly brackets. # Key pair values are assigned within the curly brackets with a : between the key and value # Each pair is separated by a comma my_dict = { 'my_key': 'my value', 'your_key': 42, 5: 10, 'speed': 20.0, } # Assigning key-value pairs # Adding key pairs to an existing dictionary my_dict['their_key'] = 3.142 # Retreiving a value retrieved = my_dict['my_key'] print("Value of 'my_key': " + str(retrieved)) # Should print "Value of 'my_key': my value" retrieved = my_dict.get('your_key') print("Value of 'your_key': " + str(retrieved)) # Should print "Value of 'your_key': 42" # With either of the above options Python will throw a key error if the key doesn't exist. # To fix this dictionary.get() can be used to return a default value if no key exists retrieved = my_dict.get('non_existent_key', 'Not here.') print("Value of 'non_existent_key': " + str(retrieved)) # Should print "Value of 'non_existent_key' not here" print("") # ------------------------------------------------------------------------------------ # Challenge: Create a dictionary called person. # The person dictionary should contain the following keys: # name, height, age # With the following values: # 'Sally', 154.9, 15 # Add a key called occupation with value 'student' # Update the value of age to 18 # Remember to uncomment the print lines # You should see the output # Person is called Sally # Person is 18 # Person is 154.9cm # Person is student # ------------------------------------------------------------------------------------ # Define person dictionary here # Add occupation key here # Increase the age to 18 here # Uncomment the lines below once you have completed the challenge # print("Person is called " + str(person.get("name", "Unnamed"))) # print("Person is " + str(person.get("age", "Ageless"))) # print("Person is " + str(person.get("height", "Tiny")) + "cm") # print("Person is " + str(person.get("occupation", "Unemployed")))
def setup(): noLoop() size(500, 500) noStroke() smooth() def draw(): background(50) fill(94, 206, 40, 100) ellipse(250, 100, 160, 160) fill(94, 206, 40, 150) ellipse(250, 200, 160, 160) fill(94, 206, 40, 200) ellipse(250, 300, 160, 160) fill(94, 206, 40, 250) ellipse(250, 400, 160, 160)
def test_get_condition_new(): scraper = Scraper('Apple', 3000, 'new') result = scraper.condition_code assert result == 1000 def test_get_condition_used(): scraper = Scraper('Apple', 3000, 'used') result = scraper.condition_code assert result == 3000 def test_get_condition_error(): scraper = Scraper('Apple', 3000, 'something else') with pytest.raises(KeyError): scraper.condition_code def test_get_brand_id_apple(): scraper = Scraper('Apple', 3000, 'used') result = scraper.brand_id assert result == 319682 def test_get_brand_id_lg(): scraper = Scraper('LG', 3000, 'used') result = scraper.brand_id assert result == 353985 def test_get_brand_id_huawei(): scraper = Scraper('Huawei', 3000, 'used') result = scraper.brand_id assert result == 349965 def test_get_brand_id_samsung(): scraper = Scraper('Samsung', 3000, 'used') result = scraper.brand_id assert result == 352130 def test_get_brand_id_error(): scraper = Scraper('Something else', 3000, 'new') with pytest.raises(KeyError): scraper.brand_id def test_get_num_of_pages_true(): scraper = Scraper('Apple', 48, 'new') result = scraper.num_of_pages assert result == 1 def test_get_num_of_pages_error(): scraper = Scraper('Something else', '3000', 'new') with pytest.raises(TypeError): scraper.num_of_pages
""" Hao Ren 11 October, 2021 495. Teemo Attacking """ class Solution(object): def findPoisonedDuration(self, timeSeries, duration): """ :type timeSeries: List[int] :type duration: int :rtype: int """ time = 0 length = len(timeSeries) for i in range(length - 1): time += min(timeSeries[i + 1] - timeSeries[i], duration) return time + duration
def get_median( arr ): size = len(arr) mid_pos = size // 2 if size % 2 == 0: # size is even median = ( arr[mid_pos-1] + arr[mid_pos] ) / 2 else: # size is odd median = arr[mid_pos] return (median) def collect_Q1_Q2_Q3( arr ): # Preprocessing # in-place sorting arr.sort() Q2 = get_median( arr ) size = len(arr) mid = size // 2 if size % 2 == 0: # size is even Q1 = get_median( arr[:mid] ) Q3 = get_median( arr[mid:] ) else: # size is odd Q1 = get_median( arr[:mid] ) Q3 = get_median( arr[mid+1:] ) return (Q1, Q2, Q3) def expand_to_flat_list( element_arr, freq_arr ): flat_list = [] for index in range( len(element_arr) ): cur_element = element_arr[ index ] cur_freq = freq_arr[ index ] # repeat current element with cur_freq times cur_list = [ cur_element ] * cur_freq flat_list += cur_list return flat_list def get_interquartile_range( arr ): Q1, Q2, Q3 = collect_Q1_Q2_Q3( arr ) return (Q3-Q1) if __name__ == '__main__': # Enter your code here. Read input from STDIN. Print output to STDOUT n = int( input() ) element_arr = list( map(int, input().strip().split() ) ) frequency_arr = list( map(int, input().strip().split() ) ) flat_list = expand_to_flat_list( element_arr, frequency_arr) inter_quartile_range = get_interquartile_range( flat_list ) print( "%.1f" % inter_quartile_range )
class YamboSpectra(): """ Class to show optical absorption spectra """ def __init__(self,energies,data): self.energies = energies self.data = data
def vowelCount(str): count = 0 for i in str: if i == "a" or i == "e" or i == "u" or i == "i" or i == "o": count += 1 print(count) exString = "Count the vowels in me!" vowelCount(exString)
def test_add_two_params(): expected = 5 actual = add(2, 3) assert expected == actual def test_add_three_params(): expected = 9 actual = add(2, 3, 4) assert expected == actual def add(a, b, c=None): if c is None: return a + b else: return a + b + c
# pylint: disable=R0903 """test __init__ return """ __revision__ = 'yo' class MyClass(object): """dummy class""" def __init__(self): return 1 class MyClass2(object): """dummy class""" def __init__(self): return class MyClass3(object): """dummy class""" def __init__(self): return None class MyClass4(object): """dummy class""" def __init__(self): yield None class MyClass5(object): """dummy class""" def __init__(self): self.callable = lambda: (yield None)
l = [58, 60, 67, 72, 76, 74, 79] s = '[' for ll in l: s += ' %i' % (ll + 9) s += ' ]' print(s)
# -*- coding: utf-8 -*- # @Time: 2020/6/22 22:33 # @Author: GraceKoo # @File: interview_26.py # @Desc: https://leetcode-cn.com/problems/ # er-cha-sou-suo-shu-yu-shuang-xiang-lian-biao-lcof/ """ # Definition for a Node. class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right """ class Solution: # 中序遍历 def zhongxu(self, root): if not root: return [] return self.zhongxu(root.left) + [root] + self.zhongxu(root.right) # 将中序遍历结果进行连接 def treeToDoublyList(self, root: "Node") -> "Node": list_result = self.zhongxu(root) if len(list_result) == 0 or len(list_result) == 1: return root for i in range(len(list_result) - 1): list_result[i].right = list_result[i + 1] list_result[i + 1].left = list_result[i] return list_result[0]
''' Estruturas Lógicas: and, or, not, is. Operadores unários: -not, is. Operadores binários: - and, or Regras de funcionamento: Para o and ambos os valores pecisam serem verdadeiros (True) Para o 'or', um ou outro valor precisa ser verdadeiro (True) ara o 'not', o valor do boolenao é invertido, ou seja, se for True vira False, se for False vira True ''' # and ativo = True logado = True if ativo and logado: print('Bem vindo usuário!') else: print('Você precisa ativar sua conta. Por favor, cheque o seu e-mail!') # or ativo = False logado = True if ativo or logado: print('Bem vindo usuário!') else: print('Você precisa ativar sua conta. Por favor, cheque o seu e-mail!') # not ativo = True logado = False # Se não estiver ativo faça isto: if not ativo: print('Bem vindo usuário!') else: print('Você precisa ativar sua conta. Por favor, cheque o seu e-mail!') # ativo é falso? print(ativo is False)
{ "variables": { "GTK_Root%": "c:\\gtk", "conditions": [ [ "OS == 'mac'", { "pkg_env": "PKG_CONFIG_PATH=/opt/X11/lib/pkgconfig" }, { "pkg_env": "" }] ] }, "targets": [ { "target_name": "rsvg", "sources": [ "src/Rsvg.cc", "src/Enums.cc", "src/Autocrop.cc" ], "include_dirs": [ "<!(node -e \"require('nan')\")" ], "variables": { "packages": "librsvg-2.0 cairo-png cairo-pdf cairo-svg", "conditions": [ [ "OS!='win'", { "libraries": "<!(<(pkg_env) pkg-config --libs-only-l <(packages))", "ldflags": "<!(<(pkg_env) pkg-config --libs-only-L --libs-only-other <(packages))", "cflags": "<!(<(pkg_env) pkg-config --cflags <(packages))" }, { # else OS!='win' "include_dirs": "<!(<(python) tools/include_dirs.py <(GTK_Root) <(packages))" } ] ] }, "conditions": [ [ "OS!='mac' and OS!='win'", { "cflags": [ "<@(cflags)", "-std=c++0x" ], "ldflags": [ "<@(ldflags)" ], "libraries": [ "<@(libraries)" ], } ], [ "OS=='mac'", { "xcode_settings": { "OTHER_CFLAGS": [ "<@(cflags)" ], "OTHER_LDFLAGS": [ "<@(ldflags)" ] }, "libraries": [ "<@(libraries)" ], } ], [ "OS=='win'", { "sources+": [ "src/win32-math.cc" ], "include_dirs": [ "<@(include_dirs)" ], "libraries": [ 'librsvg-2.dll.a', 'glib-2.0.lib', 'gobject-2.0.lib', 'cairo.lib' ], "msvs_settings": { 'VCCLCompilerTool': { 'AdditionalOptions': [ "/EHsc" ] } }, "msbuild_settings": { "Link": { "AdditionalLibraryDirectories": [ "<(GTK_Root)\\lib" ], "ImageHasSafeExceptionHandlers": "false" } } } ] ] } ] }
def is_even_with_return(i): print('with return') remainder = i % 2 return remainder == 0 print(is_even_with_return(132)) def is_even(i): return i % 2 == 0 print("All numbers between 0 and 20: even or not") for i in range(20): if is_even(i): print(i, "even") else: print(i, "odd") def func_a(): print('inside func_a') def func_b(y): print('inside func_b') return y def func_c(z): print('inside func_c') return z() print(func_c(func_a)) def f(): def x(a, b): return a+b return x val = f()(3,4) print(val)
class gbXMLBuildingOperatingSchedule(Enum,IComparable,IFormattable,IConvertible): """ Enumerations for gbXML (Green Building XML) format,used for energy analysis,schema version 0.34. enum gbXMLBuildingOperatingSchedule,values: DefaultOperatingSchedule (0),KindergartenThruTwelveGradeSchool (7),NoOfOperatingScheduleEnums (11),TheaterPerformingArts (9),TwelveHourFiveDayFacility (6),TwelveHourSevenDayFacility (4),TwelveHourSixDayFacility (5),TwentyFourHourHourFiveDayFacility (3),TwentyFourHourHourSixDayFacility (2),TwentyFourHourSevenDayFacility (1),Worship (10),YearRoundSchool (8) """ def __eq__(self,*args): """ x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """ pass def __format__(self,*args): """ __format__(formattable: IFormattable,format: str) -> str """ pass def __ge__(self,*args): pass def __gt__(self,*args): pass def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __le__(self,*args): pass def __lt__(self,*args): pass def __ne__(self,*args): pass def __reduce_ex__(self,*args): pass def __str__(self,*args): pass DefaultOperatingSchedule=None KindergartenThruTwelveGradeSchool=None NoOfOperatingScheduleEnums=None TheaterPerformingArts=None TwelveHourFiveDayFacility=None TwelveHourSevenDayFacility=None TwelveHourSixDayFacility=None TwentyFourHourHourFiveDayFacility=None TwentyFourHourHourSixDayFacility=None TwentyFourHourSevenDayFacility=None value__=None Worship=None YearRoundSchool=None
class Solution: def firstBadVersion(self, n): if n == 1: return 1 l, r = 2, n while l <= r: mid = (l + r) // 2 if isBadVersion(mid) and not isBadVersion(mid - 1): return mid elif isBadVersion(mid): r = mid - 1 else: l = mid + 1 return 1
class Solution: def wordPatternMatch(self, pattern, text): """ :type pattern: str :type str: str :rtype: bool { "a": asd } asdasdasd 3 "" """ return self._find_match(pattern, text, 0, 0, {}, set()) def _find_match(self, pattern, text, start_text, curr_pattern_index, pattern_mapping, used_patterns): if start_text >= len(text): return curr_pattern_index >= len(pattern) if curr_pattern_index >= len(pattern): return start_text >= len(text) if pattern[curr_pattern_index] not in pattern_mapping: # select a prefix prefix = "" for i in range(start_text, len(text)): prefix += text[i] if prefix in used_patterns: continue pattern_mapping[pattern[curr_pattern_index]] = prefix used_patterns.add(prefix) if self._find_match(pattern, text, i+1, curr_pattern_index+1, pattern_mapping, used_patterns): return True used_patterns.remove(prefix) del pattern_mapping[pattern[curr_pattern_index]] else: expected_prefix = pattern_mapping[pattern[curr_pattern_index]] if start_text+len(expected_prefix) > len(text): return False prefix = text[start_text: start_text+len(expected_prefix)] if prefix == expected_prefix: return self._find_match(pattern, text, start_text+len(expected_prefix), curr_pattern_index+1, pattern_mapping, used_patterns) return False
for i in range(10): if i%2==0: continue print(i) #1 3 5 7 9 numbers=[10,20,0,5,0,30] for n in numbers: if n==0: print("Hey how we can divide with zero…pagal ho gya kya") continue print('100/{}={}'.format(n,100/n)) #---100/10=10.0 100/20=5.0 hey how we can devide with zero……..
""" Time utilities for lux analysis and replay """ # Sunrise sunset data for Sunnyvale, CA, 2016. # From http://aa.usno.navy.mil/cgi-bin/aa_rstablew.pl?ID=AA&year=2016&task=0&state=CA&place=Sunnyvale # Eventually use ephem (https://pypi.python.org/pypi/pyephem/) to # compute the sunrise/sunset. sunrise_sunset_data =\ """01 0722 1701 0712 1732 0638 1803 0553 1831 0512 1858 0449 1924 0451 1933 0513 1915 0539 1836 0604 1750 0633 1709 0704 1650 02 0723 1702 0711 1733 0637 1804 0551 1832 0511 1859 0449 1924 0452 1933 0514 1914 0540 1835 0605 1749 0635 1708 0705 1650 03 0723 1703 0710 1734 0636 1805 0550 1833 0510 1900 0448 1925 0452 1932 0515 1913 0541 1833 0606 1747 0636 1707 0706 1650 04 0723 1703 0709 1735 0634 1806 0548 1834 0509 1901 0448 1925 0453 1932 0516 1912 0542 1832 0607 1746 0637 1706 0707 1650 05 0723 1704 0708 1737 0633 1807 0547 1835 0508 1902 0448 1926 0453 1932 0516 1911 0542 1830 0608 1744 0638 1705 0708 1650 06 0723 1705 0707 1738 0631 1808 0545 1836 0507 1903 0448 1927 0454 1932 0517 1910 0543 1829 0608 1743 0639 1704 0709 1650 07 0723 1706 0706 1739 0630 1808 0544 1837 0506 1904 0447 1927 0455 1931 0518 1909 0544 1827 0609 1742 0640 1704 0710 1650 08 0723 1707 0705 1740 0629 1809 0543 1838 0505 1905 0447 1928 0455 1931 0519 1908 0545 1826 0610 1740 0641 1703 0710 1650 09 0723 1708 0704 1741 0627 1810 0541 1839 0504 1906 0447 1928 0456 1931 0520 1907 0546 1824 0611 1739 0642 1702 0711 1650 10 0723 1709 0703 1742 0626 1811 0540 1839 0503 1906 0447 1929 0456 1930 0521 1905 0547 1822 0612 1737 0643 1701 0712 1650 11 0722 1710 0702 1743 0624 1812 0538 1840 0502 1907 0447 1929 0457 1930 0521 1904 0547 1821 0613 1736 0644 1700 0713 1651 12 0722 1711 0701 1744 0623 1813 0537 1841 0501 1908 0447 1930 0458 1930 0522 1903 0548 1819 0614 1734 0645 1659 0713 1651 13 0722 1712 0700 1745 0621 1814 0535 1842 0500 1909 0447 1930 0458 1929 0523 1902 0549 1818 0615 1733 0646 1659 0714 1651 14 0722 1713 0659 1746 0620 1815 0534 1843 0500 1910 0447 1930 0459 1929 0524 1901 0550 1816 0616 1732 0647 1658 0715 1651 15 0721 1714 0658 1747 0618 1816 0533 1844 0459 1911 0447 1931 0500 1928 0525 1859 0551 1815 0617 1730 0648 1657 0716 1652 16 0721 1715 0656 1748 0617 1817 0531 1845 0458 1912 0447 1931 0501 1928 0526 1858 0551 1813 0618 1729 0649 1657 0716 1652 17 0721 1716 0655 1749 0615 1818 0530 1846 0457 1912 0447 1931 0501 1927 0527 1857 0552 1812 0619 1728 0650 1656 0717 1652 18 0720 1717 0654 1751 0614 1819 0529 1847 0456 1913 0447 1932 0502 1926 0527 1856 0553 1810 0620 1726 0651 1655 0717 1653 19 0720 1718 0653 1752 0612 1820 0527 1848 0456 1914 0447 1932 0503 1926 0528 1854 0554 1809 0620 1725 0652 1655 0718 1653 20 0719 1719 0652 1753 0611 1821 0526 1848 0455 1915 0448 1932 0503 1925 0529 1853 0555 1807 0621 1724 0653 1654 0718 1654 21 0719 1720 0650 1754 0609 1821 0525 1849 0454 1916 0448 1932 0504 1924 0530 1852 0556 1806 0622 1722 0654 1654 0719 1654 22 0718 1721 0649 1755 0608 1822 0523 1850 0454 1916 0448 1932 0505 1924 0531 1850 0556 1804 0623 1721 0655 1653 0719 1655 23 0718 1722 0648 1756 0606 1823 0522 1851 0453 1917 0448 1933 0506 1923 0532 1849 0557 1803 0624 1720 0656 1653 0720 1655 24 0717 1723 0647 1757 0605 1824 0521 1852 0453 1918 0449 1933 0507 1922 0532 1847 0558 1801 0625 1719 0657 1652 0720 1656 25 0717 1724 0645 1758 0603 1825 0520 1853 0452 1919 0449 1933 0507 1921 0533 1846 0559 1759 0626 1717 0658 1652 0721 1657 26 0716 1726 0644 1759 0602 1826 0518 1854 0451 1919 0449 1933 0508 1921 0534 1845 0600 1758 0627 1716 0659 1652 0721 1657 27 0715 1727 0643 1800 0600 1827 0517 1855 0451 1920 0450 1933 0509 1920 0535 1843 0601 1756 0628 1715 0700 1651 0721 1658 28 0715 1728 0641 1801 0559 1828 0516 1856 0450 1921 0450 1933 0510 1919 0536 1842 0602 1755 0629 1714 0701 1651 0722 1659 29 0714 1729 0640 1802 0557 1829 0515 1857 0450 1922 0451 1933 0511 1918 0537 1840 0602 1753 0630 1713 0702 1651 0722 1659 30 0713 1730 0556 1830 0514 1857 0450 1922 0451 1933 0511 1917 0537 1839 0603 1752 0631 1712 0703 1651 0722 1700 31 0712 1731 0554 1830 0449 1923 0512 1916 0538 1837 0632 1711 0722 1701""" DST_START=(3,13) DST_END=(11,6) SUNRISE_SUNSET_TABLE=[[None for d in range(31)] for m in range(12)] def parse_sunrise_sunset_table(): day = 1 for line in sunrise_sunset_data.split('\n'): assert day==int(line[0:2]) for m in range(12): start = (m*11)+4 sunrise = line[start:start+4] sunset = line[start+5:start+10] month = m+1 if (month>DST_START[0] and month<DST_END[0]) or \ (month==DST_START[0] and day>=DST_START[1]) or \ (month==DST_END[0] and day<DST_END[1]): dst = 60 else: dst = 0 if sunrise!=" ": sunrise_minutes = int(sunrise[0:2])*60+int(sunrise[2:4]) + dst sunset_minutes = int(sunset[0:2])*60+int(sunset[2:4]) + dst SUNRISE_SUNSET_TABLE[m][day-1] = (sunrise_minutes, sunset_minutes) #print("%d day %d, sunrise=%s [%d], sunset=%s [%d]" % # (m+1, day, sunrise, sunrise_minutes, sunset, sunset_minutes)) day += 1 parse_sunrise_sunset_table() def get_sunrise_sunset(month, day): return SUNRISE_SUNSET_TABLE[month-1][day-1] # # We divide the day into "zones" based on a rough idea of the amount of sunlight. def time_of_day_to_zone(minutes, sunrise, sunset): if minutes < sunrise: return 0 # early morning elif minutes <= (sunset-30): return 1 # daytime elif minutes <= max(sunset+60,21.5*60): return 2 # evening else: return 3 # later evening NUM_ZONES=4 def dt_to_minutes(dt): return dt.time().hour*60 + dt.time().minute def minutes_to_time(minutes): hrs = int(minutes/60) mins = minutes-(hrs*60) assert mins<60 return (hrs, mins)
class Obstacle: def __init__(self, clearance): self.x = 10 self.y = 10 self.clearance = clearance self.robot_radius = 0.354 / 2 self.clearance = self.robot_radius + self.clearance self.dynamic_Obstacle = False # self.rect1_corner1_x = 3 # self.rect1_corner1_y = 0 self.rect1_corner1_x = 0 self.rect1_corner1_y = 2.75 self.rect1_length = 3 self.rect1_width = 0.01 # self.rect2_corner1_x = 6 # self.rect2_corner1_y = 0 self.rect2_corner1_x = 0 self.rect2_corner1_y = 6.25 self.rect2_length = 3 self.rect2_width = 0.01 def isInObstacleSpace(self, x, y): if (x < 1 or x > 9 or y < 1 or y > 9): #print('Out of boundary !') return 1 #rectangle obstacle 1 x1 = self.rect1_corner1_x - self.clearance x2 = x1 + self.rect1_length + 2*self.clearance y1 = self.rect1_corner1_y - self.clearance y2 = y1 + self.rect1_width + 2*self.clearance if (x >= x1 and x <= x2 and y >= y1 and y <= y2): #print('Inside rectangle 1, avoid') return 1 #rectangle obstacle 2 x1 = self.rect2_corner1_x - self.clearance x2 = x1 + self.rect2_length + 2*self.clearance y1 = self.rect2_corner1_y - self.clearance y2 = y1 + self.rect2_width + 2*self.clearance if (x >= x1 and x <= x2 and y >= y1 and y <= y2): #print('Inside rectangle 1, avoid') return 1 if self.dynamic_Obstacle == True: x1 = self.dynamic_obs_corner_x - self.clearance x2 = x1 + self.dynamic_obs_length + 2*self.clearance y1 = self.dynamic_obs_corner_y - self.clearance y2 = y1 + self.dynamic_obs_width + 2*self.clearance if (x >= x1 and x <= x2 and y >= y1 and y <= y2): # print('Hitting new dynamic obstacle') return 1 return 0 def addNewObstacle(self, x, y, length, width): self.dynamic_obs_corner_x = x self.dynamic_obs_corner_y = y self.dynamic_obs_length = length self.dynamic_obs_width = width self.dynamic_Obstacle = True
""" Problem Given a list of integers, find the largest product you could make from 3 integers in the list Requirements You can assume that the list will always have at least 3 integers """ def get_largest_product(lst): if len(lst) < 3: raise ValueError("List is too short") high = max(lst[0], lst[1]) low = min(lst[0], lst[1]) high_prod_2 = lst[0] * lst[1] low_prod_2 = lst[0] * lst[1] high_prod_3 = lst[0] * lst[1] * lst[2] for num in lst[2:]: high_prod_3 = max(high_prod_3, num * high_prod_2, num * low_prod_2) high_prod_2 = max(high_prod_2, num * high, num * low) low_prod_2 = min(low_prod_2, num * high, num * low) high = max(high, num) low = min(low, num) return high_prod_3 if __name__ == '__main__': lp = get_largest_product([1, 3, 4, 6, 7, 2, 8, 9, 4, 2, 3, 4, 6, 7]) print(lp)
"""Project metadata Information describing the project. """ # The package name, which is also the so-called "UNIX name" for the project. package = 'ecs' project = "Entity-Component-System" project_no_spaces = project.replace(' ', '') version = '0.1' description = 'An entity/component system library for games' authors = ['Sean Fisk', 'Kevin Ward'] authors_string = ', '.join(authors) emails = ['sean@seanfisk.com', 'antiomiae@gmail.com'] license = 'MIT' copyright = '2013 ' + authors_string url = 'https://github.com/seanfisk/ecs'
def f(*, b): return b def f(a, *, b): return a + b def f(a, *, b, c): return a + b + c def f(a, *, b=c): return a + b def f(a, *, b=c, c): return a + b + c def f(a, *, b=c, c=d): return a + b + c def f(a, *, b=c, c, d=e): return a + b + c + d def f(a=None, *, b=None): return a + b
# Sort the entries of medals: medals_sorted medals_sorted = medals.sort_index(level=0) # Print the number of Bronze medals won by Germany print(medals_sorted.loc[('bronze','Germany')]) # Print data about silver medals print(medals_sorted.loc['silver']) # Create alias for pd.IndexSlice: idx idx = pd.IndexSlice # Print all the data on medals won by the United Kingdom print(medals_sorted.loc[idx[:,'United Kingdom'],:])
class WebSocketDefine: Uri = "wss://sdstream.binance.com/stream" # testnet new spec # Uri = "wss://sdstream.binancefuture.com/stream" class RestApiDefine: Url = "https://dapi.binance.com" # testnet # Url = "https://testnet.binancefuture.com"
s = input() y, m, d = map(int, s.split('/')) f = False ( Heisei, TBD, )= ( 'Heisei', 'TBD', ) if y < 2019: print(Heisei) elif y == 2019: if(m < 4): print(Heisei) elif m == 4: if(d <= 30): print(Heisei) else : print(TBD) else : print(TBD) else : print(TBD)
""" The meat. Things to do: TaskFinder - querys a (file|db) for what sort of tasks to run Task - initialize from task data pulled by TaskFinder - enumerate the combination of args and kwargs to sent to this task - provide a function which takes *args and **kwargs to execute the task - specify the type of schedule to be used for this task ScopeFinder - querys a (file|db) for the set of parameter combinations to send to the task Scheduler - initialize from schedule data pulled by ScheduleFinder - determine if a task and arguement combination should run Registry - manage the state of all jobs in progress """
rfm69SpiBus = 0 rfm69NSS = 5 # GPIO5 == pin 7 rfm69D0 = 9 # GPIO9 == pin 12 rfm69RST = 8 # GPIO8 == pin 11 am2302 = 22 # GPIO22 == pin 29 voltADC = 26 # GPIO26 == pin 31
class persona: edad=0 id = -1 id_padre=0 id_madre=0 def __init__(self, nombre,edad,id,id_padre,id_madre): self.nombre=nombre self.edad = edad self.id = id self.id_padre=id_padre self.id_madre=id_madre personas=[] for i in range (0,1000): personas.append(persona) def crear_persona(): acabado=False n=str(input('Elija un nombre:')) e=int(input('Cual es su edad:')) id_p=int(input('Id del padre (si no tiene introduzca el valor 0):')) id_m=int(input('Id de la madre (si no tiene introduzca el valor 0):')) while(acabado==False): id=int(input('Introduzca el id que desea:')) if(id!=persona.id or persona.id==-1): personas.append(persona(n,e,id,id_p,id_m)) acabado=True else: print('Elija un id nuevo') def sumar_edad(): for i in range (0,1000): if(persona.id!=-1): persona.edad=persona.edad+1 else: i=i+1 fin=False while(fin==False): r1=str(input('Quieres crear una nueva persona?:')) if(r1=='s'or r1=='S'): crear_persona() if(r1=='n'or r1=='N'): fin=True else: print('Introduzca una S o una N') fin2=False while(fin2==False): r2=str(input('Quieres sumarle 1 año a todas las personas de la lista?:')) if(r2=='s'or r2=='S'): sumar_edad() if(r2=='n'or r2=='N'): fin=True else: print('Introduzca una S o una N')
# # @lc app=leetcode.cn id=400 lang=python3 # # [400] 第N个数字 # class Solution: def findNthDigit(self, n: int) -> int: if n < 10: return n i = 1 length = 0 cnt = 9 while length + cnt * i < n: length += cnt * i cnt *= 10 i += 1 num = pow(10, i-1) - 1 + (n - length + 1) // i index = (n - length - 1) % i return int(str(num)[index])
# Hack 3: create your own math function # Function is superfactorial: superfactorial is product of all factorials until n. # OOP method class superFactorial(): def __init__(self,n): self.n = n def factorial(self,y): y = self.n if y is None else y product = 1 for x in range(1,y+1): product*=x return product def __call__(self): product = 1 for x in range(1,self.n+1): product*= self.factorial(x) return product # Imperative Method def superfac(): x = int(input("What number should we use? ")) product = 1 for y in range(1,x+1): secondProd = 1 for z in range(1,y+1): secondProd*= z product*=secondProd print(product) if __name__ == "__main__": sfac = superFactorial(3) print(sfac()) print(superfac())
class Settings(): "A class to store all settings for Football game." def __init__(self): """Initialize the game's settings.""" # Screen settings. self.screen_width = 1200 self.screen_height = 700 self.bg_color = (50, 205, 50) self.attacker_speed_factor = 1.5 # Attacker settings. self.ball_speed_factor = 2 self.balls_allowed = 1 self.attackers_limit = 3 # Defender settings. self.defender_speed_factor = 1 self.defense_move_speed = 10 # defense_direction of 1 represent up : -1 represents down. self.defense_direction = 1
#条件分岐によるbreak(終了)とcontinue(スキップ) for num in range(10): #0~10未満(9まで)の値を順にnumに代入 if num == 1: #numが1の時、 continue #これより下の処理をスキップし、繰り返し処理に戻る(printもスキップされる) if num == 5: #numが5の時、 break #終了 print(num) #for文の組み合わせ(for_4.pyに続く…)
#declaração variaveis idade_med = 0 idade_maior = -1 quant_menor = 0 #laço for para pegar os dados for c in range(1, 5): print('-----{}ª pessoa-----'.format(c)) nome = str(input('Nome: ')).upper() idade = int(input('Idade: ')) genero = str(input('Gênero [M/F]: ')).upper() #calcular média de idade idade_med += idade #calcular homem mais velho if idade > idade_maior and genero == 'M': idade_maior = idade homem_velho = nome.capitalize() #calcular número de mulheres menores de idade if idade < 18 and genero == 'F': quant_menor += 1 idade_med = idade_med / 4 #mostrar resultados na tela print('A média de idade é {}'.format(idade_med)) print('O homem mais velho tem {} anos e se chama {}'.format(idade_maior, homem_velho)) print('Tem {} mulheres menores de idade'.format(quant_menor))
# -*- coding: utf-8 -*- # ------------- Funciones en listas ------------- #Pop en listas print ("Lista A") listaA = [1, 2, 3, 4] print (listaA) elem_borrado = listaA.pop(1) print ("Eliminaste el elemento:", elem_borrado) #listaA.pop(0) #Elimina primer elemento print ("POP", listaA.pop(0)) print (listaA) #La función del sirve para eliminar elementos de una lista print ("Lista B") listaB = [3, 4, 5, 6] print (listaB) del(listaB[3]) print ("DEL [2]") print (listaB) #Insertando elementos en la lista print ("INSERT 5") listaB.insert(3, 15) print ("INSERT 15") listaB.insert(4, 1) print (listaB) listaB.insert(0, 10) print (listaB)
# -*- Mode:Python;indent-tabs-mode:nil; -*- # # File: psaExceptions.py # Created: 05/09/2014 # Author: BSC # # Description: # Custom execption class to manage error in the PSC # class psaExceptions( object ): class confRetrievalFailed( Exception ): pass
class CategoryDefinition: """ Defines a category for labeling texts.""" def __init__(self, name): self.name = name class NamedEntityDefinition: """ Defines a named entity for annotating texts.""" def __init__(self, code, key_sequence = None, maincolor = None, backcolor = None, forecolor= None): self.code = code self.key_sequence = key_sequence self.maincolor = maincolor self.backcolor = backcolor self.forecolor = forecolor
# multiply a list by a number def mul(row, num): return [x * num for x in row] # subtract one row from another def sub(row_left, row_right): return [a - b for (a, b) in zip(row_left, row_right)] # calculate the row echelon form of the matrix def echelonify(rw, i, m): for j, row in enumerate(m[(i+1):]): j += 1 # print("rw[i]:", rw[i]) if rw[i] != 0: m[j+i] = sub(row, mul(rw, row[i] / rw[i])) return rw def row_echelon(m): for i in range(len(m)): # len(m) == m x n active_row = m[i] echelonify(active_row, i, m) # close to zero m = [[(0 if (0.0000000001 > x > -0.0000000001) else x) for x in row]for row in m] return m if __name__ == '__main__': print("Enter number of rows and columns") m, n = map(int, input().split()) # m = row and n = column M = [] for _ in range(m): row = list(map(int, input().split()))[:n] M.append(row) mat = row_echelon(M) for row in mat: print(' '.join((str(x) for x in row))) # The output can be printed by dividing each element of each row by the first non-zero element of the respective row in order to get 1
ans = 0 a=input() for _ in range(int(input())): s=input() for start in range(10): for j in range(len(a)): if a[j] != s[(start+j)%10]: break else: ans+=1 break print(ans)
#!/usr/bin/env python3 """ Problem : Double-Degree Array URL : http://rosalind.info/problems/ddeg/ Author : David P. Perkins """ if __name__=="__main__": with open("ddegIn.txt", "r") as infile, open("ddegOut.txt", "w") as outfile: nodeCount = int(infile.readline().split()[0]) adjl = {x:set() for x in range(1, nodeCount+1)} ddegl = list() for line in infile: a, b = [int(x) for x in line.split()] adjl.setdefault(a, set()).add(b) adjl.setdefault(b, set()).add(a) for node in sorted(adjl): ddeg = sum([len(adjl[x]) for x in adjl[node]]) ddegl.append(ddeg) print(*ddegl, file=outfile)
# Easy # Runtime: 32 ms, faster than 73.01% of Python3 online submissions for Count and Say. # Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Count and Say. class Solution: def countAndSay(self, n: int) -> str: def count_and_say(n): if n == 1: return '1' cur_s = '' idx = 0 cur_sum = 0 s = count_and_say(n - 1) for i, ch in enumerate(s): if ch != s[idx]: cur_s += str(cur_sum) + s[idx] cur_sum = 1 idx = i else: cur_sum += 1 cur_s += str(cur_sum) + s[idx] return cur_s return count_and_say(n)
class IBeacon(): def __init__(self, driver_instace) -> None: self.ble_driver_instace = driver_instace def setUUID(self, uuid : str) -> None: "uuid is 16 bytes should be represented as a string of hex-decimal format: XX XX XX XX ..." self.uuid = uuid def setMajor(self, major : str) -> None: "major is 2 bytes should be represented as string of hex-decimal format: XX XX" self.major = major def setMinor(self, minor : str) -> None: "minor is 2 bytes should be represented as string of hex-decimal format: XX XX" self.minor = minor def setTXPower(self, txpower : str) -> None: "txpower used to measure RSSI loss" self.txpower = txpower def __makeIBeaconMessage(self): # As from the IBeacon spec: # 02 01 1A 1A FF 4C 00 02 15 - IBeacon 9 byte prefix for Apple, inc. Please, # refer to a IBeacon frame spec to get more details. # UUID 16-18 bytes. We fix as 16 # Major # Minor # 1E - length of the message for driver # 02 01 06 - BLE discoverable mode # 1A - length of the content # FF - custom manufacturer data # 4C 00 - Apple's Bluetooth code # 02 - Apple's iBeacon type of custom data # 15 - length of rest IBeacon data return "1E 02 01 06 1A FF 4C 00 02 15 " + self.uuid + " " + self.major + " " + self.minor + " " + self.txpower def up(self) -> None: """ start transmission """ self.ble_driver_instace.init() self.ble_driver_instace.up() self.ble_driver_instace.setAdvertisingMode() self.ble_driver_instace.setSanningState(False) self.ble_driver_instace.sendRawData(self.__makeIBeaconMessage()) def down(self): """ Start transmission """ self.ble_driver_instace.down()
input("как вас зовут? ") # типы переменных int \ float \ bool \ None - пустой тип \ str name = "Mike" print(type(name)) bul_type = True print(type(bul_type)) date = "22" print(type(date)) date = int(date) print(type(date)) new_date = str(date) + " число" print(type(new_date)) # ####################### # print + sep= - разделитель, end= - замена окончания, \n - с новой строки print("text", "is", "here", sep="\n") print("w", end=" ") print("t", end="/") print("f", end=" ") ############################ new_name = input("введите имя") new_age = int(input("ваш возраст")) ############################# # ПРИ ДЕЛЕНИИ ВСЕГДА ПОЛУЧАЕТСЯ float print(5 // 2) # целая часть от деления print(5 % 2) # остаток от деления print(2 ** 3) # возведение в степень # == != >= <= > < and or not num += 1 ##################### while True: number = int(input("введите число")) if number > 0 or number < 10: print("верное число", number) break else: # elif print("неверное число, введите пложительное число меньше 10") # continue - начинает цикл заново не доходя до конца # else для while - выполняется если while стал ложью # ###### СТРОКИ name = "Mike Sboev" sybmol_2 = name[1] # i sybmol_last = name[-1] # v symbols_middle = name[5:7] # символы с какой по какой, [:3] = Mike , [-5:] number = len(name) ############################## name = "Mike Sboev" print(len(name)) # len - МЕТОД считающий сколько символов в строке print(name.find("Sbo")) # find - ФУНКЦИЯ (пишется через точку), показывает в каком месте начинается подстрока, # в противном случае выдает -1 if name.find("a") == -1: print("такой буквы нет", name.find("a")) # in (также можно not in ) - позволяет получить булевое значение при поиске, напримере предыдущего: if "a" in name: print("буква есть") else: print("буквы нет") print(name.split()) # разбивает строку на нассив из строк через пробел, если слова в строке разделены например : то # print(name.split(".")) - поможет айти места разделения. например для даты 01.01.2021 - разделитель "." print(name.isdigit()) # проверяет состоит ли строка только из цифр, булевое значение print(name.lower()) # upper - делает все символы верним \ нижним регистром # форматирование строк name = "Leo" age = 30 hello_str = "Привет %s тебе %d лет" % (name, age) # s - str , d - digit print(hello_str) hello_str = "Привет {} тебе {} лет".format(name, age) print(hello_str) result = f'{name} {age}' print(result)
class PlannerEventHandler(object): pass def ProblemNotImplemented(self): return False def StartedPlanning(self): return True def SubmittedPipeline(self, pipeline): return True def RunningPipeline(self, pipeline): return True def CompletedPipeline(self, pipeline, result): return True def StartExecutingPipeline(self, pipeline): return True def ExecutedPipeline(self, pipeline, result): return True def EndedPlanning(self): return True
def minSubArrayLen(target, nums): length = list() for i in range(len(nums)): remain = target - nums[i] if remain <= 0: length.append(1) continue for j in range(i+1, len(nums)): remain = remain - nums[j] if remain <= 0: length.append(j-i+1) break if not length: return 0 return min(length) if __name__ == '__main__': # print(minSubArrayLen(1, [1,1,1,1,1,1,1,1])) # print(minSubArrayLen(7, [2,3,1,2,4,3])) print(minSubArrayLen(11, [1, 2, 3, 4, 5]))
''' Created on Apr 23, 2021 @author: Jimmy Palomino ''' def Region(main): """This function creates the region and set the boundaries to the machine analysis by FEM. Args: main (Dic): Main Dictionary than contain the necessary information. Returns: Dic: unmodified main dictionary. """ oEditor = main['ANSYS']['oEditor'] oDesign = main['ANSYS']['oDesign'] RegionName = main['ANSYS']['Region']['RegionName'] oModule = oDesign.GetModule("BoundarySetup") OffsetPercent = main['ANSYS']['Region']['OffsetPercent'] # Drawing the Region oEditor.CreateCircle( [ "NAME:CircleParameters", "IsCovered:=" , True, "XCenter:=" , "0mm", "YCenter:=" , "0mm", "ZCenter:=" , "0mm", "Radius:=" , "DiaYoke/2"+'*'+str(1+OffsetPercent/100), "WhichAxis:=" , "Z", "NumSegments:=" , "0" ], [ "NAME:Attributes", "Name:=" , RegionName, "Flags:=" , "", "Color:=" , "(143 175 143)", "Transparency:=" , 0.75, "PartCoordinateSystem:=", "Global", "UDMId:=" , "", "MaterialValue:=" , "\"vacuum\"", "SurfaceMaterialValue:=", "\"\"", "SolveInside:=" , True, "ShellElement:=" , False, "ShellElementThickness:=", "0mm", "IsMaterialEditable:=" , True, "UseMaterialAppearance:=", False, "IsLightweight:=" , False ] ) # Boundaries setting Edges = oEditor.GetEdgeIDsFromObject(RegionName) oModule.AssignVectorPotential( [ "NAME:VectorPotential1", "Edges:=" , [int(Edges[0])], "Value:=" , "0", "CoordinateSystem:=" , "" ] ) oEditor.FitAll() return main
# -*- coding: UTF-8 -*- class Shared(object): ''' Class used for /hana/shared attributes. Attributes and methods are passed to other LVM Classes. ''' name = 'shared' vg_physical_extent_size = '-s 1M' vg_data_alignment = '--dataalignment 1M' vg_args = vg_physical_extent_size + ' ' + vg_data_alignment lv_size = '-l 100%VG' lv_args = lv_size fs_block_size = '-b size=4096' fs_sector_size = '-s size=4096' fs_type = 'xfs' fs_mount_point = '/hana/shared' fs_args = fs_block_size + ' ' + fs_sector_size def __init__(self): super(Shared, self).__init__()
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: shortest = min(strs, key=len) longest_common = "" for idx, char in enumerate(shortest): for word in strs: if word[idx] != char: return longest_common longest_common += char # Case where they pass us nothing return longest_common
class Solution: def uniqueOccurrences(self, arr: List[int]) -> bool: dict = {} for i in arr : if i in dict : dict[i] += 1 else : dict[i] = 1 count = 0 s = set(dict.values()) ns = len(s) nl = len(dict.values()) if nl != ns : return False else : return True
test = { 'name': 'q1d', 'points': 1, 'suites': [ { 'cases': [ {'code': ">>> species_by_island.labels == ('species', 'Biscoe', 'Dream', 'Torgersen')\nTrue", 'hidden': False, 'locked': False}, {'code': ">>> np.all(species_by_island.column('Biscoe') == np.array([44, 0, 119]))\nTrue", 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]}
# objects here will be mixed into the dynamically created asset type classes # based on name. # This lets us extend certain asset types without having to give up the generic # dynamic meta implementation class Attachment(object): def set_blob(self, blob): return self._v1_v1meta.set_attachment_blob(self, blob) def get_blob(self): return self._v1_v1meta.get_attachment_blob(self) file_data = property(get_blob, set_blob) # the special_classes mapping will be used to lookup mixins by asset type name. special_classes = locals()
def input_journal(path: str): journal = {} count = int(input("Введите количество записей: ")) for i in range(count): name = input("Введите Имя и Фамилию: ") mark = int(input(f"Введите оценку для {name}: ")) journal[name] = mark with open(path, "w") as file: file.write(str(journal)) def update_dict(my_dict: dict, key, value: str): if key in my_dict.keys() and isinstance(my_dict[key], list): my_dict[key].append(value) if key in my_dict.keys() and not isinstance(my_dict[key], list): my_dict[key] = [my_dict[key], value] if key not in my_dict.keys(): my_dict[key] = value if __name__ == '__main__': input_journal("test3.txt") d = {"1": 1} update_dict(d, "1", "10") update_dict(d, "1", "qwerty") update_dict(d, "2", "xxx") print(d)
LOG_EPOCH = 'epoch' LOG_TRAIN_LOSS = 'train_loss' LOG_TRAIN_ACC = 'train_acc' LOG_VAL_LOSS = 'val_loss' LOG_VAL_ACC = 'val_acc' LOG_FIELDS = [LOG_EPOCH, LOG_TRAIN_LOSS, LOG_TRAIN_ACC, LOG_VAL_LOSS, LOG_VAL_ACC] LOG_COLOR_HEADER = '\033[95m' LOG_COLOR_OKBLUE = '\033[94m' LOG_COLOR_OKCYAN = '\033[96m' LOG_COLOR_OKGREEN = '\033[92m' LOG_COLOR_WARNING = '\033[93m' LOG_COLOR_FAIL = '\033[91m' LOG_COLOR_ENDC = '\033[0m' LOG_COLOR_BOLD = '\033[1m' LOG_COLOR_UNDERLINE = '\033[4m'
""" Test module for learning python packaging. """ def my_sum(arg): """ Sums the arguments and returns the sum. """ total = 0 for val in arg: total += val return total class MySum(object): # pylint: disable=too-few-public-methods """ MySum class """ @staticmethod def my_sum(arg): """ Sums the arguments and returns the sum. """ return my_sum(arg)
def load(h): return ({'abbr': 1, 'code': 1, 'title': 'PRES Pressure [hPa]'}, {'abbr': 2, 'code': 2, 'title': 'psnm Pressure reduced to MSL [hPa]'}, {'abbr': 3, 'code': 3, 'title': 'tsps Pressure tendency [Pa/s]'}, {'abbr': 4, 'code': 4, 'title': 'var4 undefined'}, {'abbr': 5, 'code': 5, 'title': 'var5 undefined'}, {'abbr': 6, 'code': 6, 'title': 'geop Geopotential [dam]'}, {'abbr': 7, 'code': 7, 'title': 'zgeo Geopotential height [gpm]'}, {'abbr': 8, 'code': 8, 'title': 'gzge Geometric height [m]'}, {'abbr': 9, 'code': 9, 'title': 'var9 undefined'}, {'abbr': 10, 'code': 10, 'title': 'var10 undefined'}, {'abbr': 11, 'code': 11, 'title': 'temp ABSOLUTE TEMPERATURE [K]'}, {'abbr': 12, 'code': 12, 'title': 'vtmp VIRTUAL TEMPERATURE [K]'}, {'abbr': 13, 'code': 13, 'title': 'ptmp POTENTIAL TEMPERATURE [K]'}, {'abbr': 14, 'code': 14, 'title': 'psat PSEUDO-ADIABATIC POTENTIAL TEMPERATURE [K]'}, {'abbr': 15, 'code': 15, 'title': 'mxtp MAXIMUM TEMPERATURE [K]'}, {'abbr': 16, 'code': 16, 'title': 'mntp MINIMUM TEMPERATURE [K]'}, {'abbr': 17, 'code': 17, 'title': 'tpor DEW POINT TEMPERATURE [K]'}, {'abbr': 18, 'code': 18, 'title': 'dptd DEW POINT DEPRESSION [K]'}, {'abbr': 19, 'code': 19, 'title': 'lpsr LAPSE RATE [K/m]'}, {'abbr': 20, 'code': 20, 'title': 'var20 undefined'}, {'abbr': 21, 'code': 21, 'title': 'rds1 RADAR SPECTRA(1) [non-dim]'}, {'abbr': 22, 'code': 22, 'title': 'rds2 RADAR SPECTRA(2) [non-dim]'}, {'abbr': 23, 'code': 23, 'title': 'rds3 RADAR SPECTRA(3) [non-dim]'}, {'abbr': 24, 'code': 24, 'title': 'var24 undefined'}, {'abbr': 25, 'code': 25, 'title': 'tpan TEMPERATURE ANOMALY [K]'}, {'abbr': 26, 'code': 26, 'title': 'psan PRESSURE ANOMALY [Pa hPa]'}, {'abbr': 27, 'code': 27, 'title': 'zgan GEOPOT HEIGHT ANOMALY [m]'}, {'abbr': 28, 'code': 28, 'title': 'wvs1 WAVE SPECTRA(1) [non-dim]'}, {'abbr': 29, 'code': 29, 'title': 'wvs2 WAVE SPECTRA(2) [non-dim]'}, {'abbr': 30, 'code': 30, 'title': 'wvs3 WAVE SPECTRA(3) [non-dim]'}, {'abbr': 31, 'code': 31, 'title': 'wind WIND DIRECTION [deg]'}, {'abbr': 32, 'code': 32, 'title': 'wins WIND SPEED [m/s]'}, {'abbr': 33, 'code': 33, 'title': 'uvel ZONAL WIND (U) [m/s]'}, {'abbr': 34, 'code': 34, 'title': 'vvel MERIDIONAL WIND (V) [m/s]'}, {'abbr': 35, 'code': 35, 'title': 'fcor STREAM FUNCTION [m2/s]'}, {'abbr': 36, 'code': 36, 'title': 'potv VELOCITY POTENTIAL [m2/s]'}, {'abbr': 37, 'code': 37, 'title': 'var37 undefined'}, {'abbr': 38, 'code': 38, 'title': 'sgvv SIGMA COORD VERT VEL [sec/sec]'}, {'abbr': 39, 'code': 39, 'title': 'omeg OMEGA [Pa/s]'}, {'abbr': 40, 'code': 40, 'title': 'omg2 VERTICAL VELOCITY [m/s]'}, {'abbr': 41, 'code': 41, 'title': 'abvo ABSOLUTE VORTICITY [10**5/sec]'}, {'abbr': 42, 'code': 42, 'title': 'abdv ABSOLUTE DIVERGENCE [10**5/sec]'}, {'abbr': 43, 'code': 43, 'title': 'vort VORTICITY [1/s]'}, {'abbr': 44, 'code': 44, 'title': 'divg DIVERGENCE [1/s]'}, {'abbr': 45, 'code': 45, 'title': 'vucs VERTICAL U-COMP SHEAR [1/sec]'}, {'abbr': 46, 'code': 46, 'title': 'vvcs VERT V-COMP SHEAR [1/sec]'}, {'abbr': 47, 'code': 47, 'title': 'dirc DIRECTION OF CURRENT [deg]'}, {'abbr': 48, 'code': 48, 'title': 'spdc SPEED OF CURRENT [m/s]'}, {'abbr': 49, 'code': 49, 'title': 'ucpc U-COMPONENT OF CURRENT [m/s]'}, {'abbr': 50, 'code': 50, 'title': 'vcpc V-COMPONENT OF CURRENT [m/s]'}, {'abbr': 51, 'code': 51, 'title': 'umes SPECIFIC HUMIDITY [kg/kg]'}, {'abbr': 52, 'code': 52, 'title': 'umrl RELATIVE HUMIDITY [no Dim]'}, {'abbr': 53, 'code': 53, 'title': 'hmxr HUMIDITY MIXING RATIO [kg/kg]'}, {'abbr': 54, 'code': 54, 'title': 'agpl INST. PRECIPITABLE WATER [Kg/m2]'}, {'abbr': 55, 'code': 55, 'title': 'vapp VAPOUR PRESSURE [Pa hpa]'}, {'abbr': 56, 'code': 56, 'title': 'sadf SATURATION DEFICIT [Pa hPa]'}, {'abbr': 57, 'code': 57, 'title': 'evap EVAPORATION [Kg/m2/day]'}, {'abbr': 58, 'code': 58, 'title': 'var58 undefined'}, {'abbr': 59, 'code': 59, 'title': 'prcr PRECIPITATION RATE [kg/m2/day]'}, {'abbr': 60, 'code': 60, 'title': 'thpb THUNDER PROBABILITY [%]'}, {'abbr': 61, 'code': 61, 'title': 'prec TOTAL PRECIPITATION [Kg/m2/day]'}, {'abbr': 62, 'code': 62, 'title': 'prge LARGE SCALE PRECIPITATION [Kg/m2/day]'}, {'abbr': 63, 'code': 63, 'title': 'prcv CONVECTIVE PRECIPITATION [Kg/m2/day]'}, {'abbr': 64, 'code': 64, 'title': 'neve SNOWFALL [Kg/m2/day]'}, {'abbr': 65, 'code': 65, 'title': 'wenv WAT EQUIV ACC SNOW DEPTH [kg/m2]'}, {'abbr': 66, 'code': 66, 'title': 'nvde SNOW DEPTH [cm]'}, {'abbr': 67, 'code': 67, 'title': 'mxld MIXED LAYER DEPTH [m cm]'}, {'abbr': 68, 'code': 68, 'title': 'tthd TRANS THERMOCLINE DEPTH [m cm]'}, {'abbr': 69, 'code': 69, 'title': 'mthd MAIN THERMOCLINE DEPTH [m cm]'}, {'abbr': 70, 'code': 70, 'title': 'mtha MAIN THERMOCLINE ANOM [m cm]'}, {'abbr': 71, 'code': 71, 'title': 'cbnv CLOUD COVER [0-1]'}, {'abbr': 72, 'code': 72, 'title': 'cvnv CONVECTIVE CLOUD COVER [0-1]'}, {'abbr': 73, 'code': 73, 'title': 'lwnv LOW CLOUD COVER [0-1]'}, {'abbr': 74, 'code': 74, 'title': 'mdnv MEDIUM CLOUD COVER [0-1]'}, {'abbr': 75, 'code': 75, 'title': 'hinv HIGH CLOUD COVER [0-1]'}, {'abbr': 76, 'code': 76, 'title': 'wtnv CLOUD WATER [kg/m2]'}, {'abbr': 77, 'code': 77, 'title': 'bli BEST LIFTED INDEX (TO 500 HPA) [K]'}, {'abbr': 78, 'code': 78, 'title': 'var78 undefined'}, {'abbr': 79, 'code': 79, 'title': 'var79 undefined'}, {'abbr': 80, 'code': 80, 'title': 'var80 undefined'}, {'abbr': 81, 'code': 81, 'title': 'lsmk LAND SEA MASK [0,1]'}, {'abbr': 82, 'code': 82, 'title': 'dslm DEV SEA_LEV FROM MEAN [m]'}, {'abbr': 83, 'code': 83, 'title': 'zorl ROUGHNESS LENGTH [m]'}, {'abbr': 84, 'code': 84, 'title': 'albe ALBEDO [%]'}, {'abbr': 85, 'code': 85, 'title': 'dstp DEEP SOIL TEMPERATURE [K]'}, {'abbr': 86, 'code': 86, 'title': 'soic SOIL MOISTURE CONTENT [Kg/m2]'}, {'abbr': 87, 'code': 87, 'title': 'vege VEGETATION [%]'}, {'abbr': 88, 'code': 88, 'title': 'var88 undefined'}, {'abbr': 89, 'code': 89, 'title': 'dens DENSITY [kg/m3]'}, {'abbr': 90, 'code': 90, 'title': 'var90 Undefined'}, {'abbr': 91, 'code': 91, 'title': 'icec ICE CONCENTRATION [fraction]'}, {'abbr': 92, 'code': 92, 'title': 'icet ICE THICKNESS [m]'}, {'abbr': 93, 'code': 93, 'title': 'iced DIRECTION OF ICE DRIFT [deg]'}, {'abbr': 94, 'code': 94, 'title': 'ices SPEED OF ICE DRIFT [m/s]'}, {'abbr': 95, 'code': 95, 'title': 'iceu U-COMP OF ICE DRIFT [m/s]'}, {'abbr': 96, 'code': 96, 'title': 'icev V-COMP OF ICE DRIFT [m/s]'}, {'abbr': 97, 'code': 97, 'title': 'iceg ICE GROWTH [m]'}, {'abbr': 98, 'code': 98, 'title': 'icdv ICE DIVERGENCE [sec/sec]'}, {'abbr': 99, 'code': 99, 'title': 'var99 undefined'}, {'abbr': 100, 'code': 100, 'title': 'shcw SIG HGT COM WAVE/SWELL [m]'}, {'abbr': 101, 'code': 101, 'title': 'wwdi DIRECTION OF WIND WAVE [deg]'}, {'abbr': 102, 'code': 102, 'title': 'wwsh SIG HGHT OF WIND WAVES [m]'}, {'abbr': 103, 'code': 103, 'title': 'wwmp MEAN PERIOD WIND WAVES [sec]'}, {'abbr': 104, 'code': 104, 'title': 'swdi DIRECTION OF SWELL WAVE [deg]'}, {'abbr': 105, 'code': 105, 'title': 'swsh SIG HEIGHT SWELL WAVES [m]'}, {'abbr': 106, 'code': 106, 'title': 'swmp MEAN PERIOD SWELL WAVES [sec]'}, {'abbr': 107, 'code': 107, 'title': 'prwd PRIMARY WAVE DIRECTION [deg]'}, {'abbr': 108, 'code': 108, 'title': 'prmp PRIM WAVE MEAN PERIOD [s]'}, {'abbr': 109, 'code': 109, 'title': 'swdi SECOND WAVE DIRECTION [deg]'}, {'abbr': 110, 'code': 110, 'title': 'swmp SECOND WAVE MEAN PERIOD [s]'}, {'abbr': 111, 'code': 111, 'title': 'ocas SHORT WAVE ABSORBED AT GROUND [W/m2]'}, {'abbr': 112, 'code': 112, 'title': 'slds NET LONG WAVE AT BOTTOM [W/m2]'}, {'abbr': 113, 'code': 113, 'title': 'nswr NET SHORT-WAV RAD(TOP) [W/m2]'}, {'abbr': 114, 'code': 114, 'title': 'role OUTGOING LONG WAVE AT TOP [W/m2]'}, {'abbr': 115, 'code': 115, 'title': 'lwrd LONG-WAV RAD [W/m2]'}, {'abbr': 116, 'code': 116, 'title': 'swea SHORT WAVE ABSORBED BY EARTH/ATMOSPHERE [W/m2]'}, {'abbr': 117, 'code': 117, 'title': 'glbr GLOBAL RADIATION [W/m2 ]'}, {'abbr': 118, 'code': 118, 'title': 'var118 undefined'}, {'abbr': 119, 'code': 119, 'title': 'var119 undefined'}, {'abbr': 120, 'code': 120, 'title': 'var120 undefined'}, {'abbr': 121, 'code': 121, 'title': 'clsf LATENT HEAT FLUX FROM SURFACE [W/m2]'}, {'abbr': 122, 'code': 122, 'title': 'cssf SENSIBLE HEAT FLUX FROM SURFACE [W/m2]'}, {'abbr': 123, 'code': 123, 'title': 'blds BOUND LAYER DISSIPATION [W/m2]'}, {'abbr': 124, 'code': 124, 'title': 'var124 undefined'}, {'abbr': 125, 'code': 125, 'title': 'var125 undefined'}, {'abbr': 126, 'code': 126, 'title': 'var126 undefined'}, {'abbr': 127, 'code': 127, 'title': 'imag IMAGE [image^data]'}, {'abbr': 128, 'code': 128, 'title': 'tp2m 2 METRE TEMPERATURE [K]'}, {'abbr': 129, 'code': 129, 'title': 'dp2m 2 METRE DEWPOINT TEMPERATURE [K]'}, {'abbr': 130, 'code': 130, 'title': 'u10m 10 METRE U-WIND COMPONENT [m/s]'}, {'abbr': 131, 'code': 131, 'title': 'v10m 10 METRE V-WIND COMPONENT [m/s]'}, {'abbr': 132, 'code': 132, 'title': 'topo TOPOGRAPHY [m]'}, {'abbr': 133, 'code': 133, 'title': 'gsfp GEOMETRIC MEAN SURFACE PRESSURE [hPa]'}, {'abbr': 134, 'code': 134, 'title': 'lnsp LN SURFACE PRESSURE [hPa]'}, {'abbr': 135, 'code': 135, 'title': 'pslc SURFACE PRESSURE [hPa]'}, {'abbr': 136, 'code': 136, 'title': 'pslm M S L PRESSURE (MESINGER METHOD) [hPa]'}, {'abbr': 137, 'code': 137, 'title': 'mask MASK [-/+]'}, {'abbr': 138, 'code': 138, 'title': 'mxwu MAXIMUM U-WIND [m/s]'}, {'abbr': 139, 'code': 139, 'title': 'mxwv MAXIMUM V-WIND [m/s]'}, {'abbr': 140, 'code': 140, 'title': 'cape CONVECTIVE AVAIL. POT.ENERGY [m2/s2]'}, {'abbr': 141, 'code': 141, 'title': 'cine CONVECTIVE INHIB. ENERGY [m2/s2]'}, {'abbr': 142, 'code': 142, 'title': 'lhcv CONVECTIVE LATENT HEATING [K/s]'}, {'abbr': 143, 'code': 143, 'title': 'mscv CONVECTIVE MOISTURE SOURCE [1/s]'}, {'abbr': 144, 'code': 144, 'title': 'scvm SHALLOW CONV. MOISTURE SOURCE [1/s]'}, {'abbr': 145, 'code': 145, 'title': 'scvh SHALLOW CONVECTIVE HEATING [K/s]'}, {'abbr': 146, 'code': 146, 'title': 'mxwp MAXIMUM WIND PRESS. LVL [hPa]'}, {'abbr': 147, 'code': 147, 'title': 'ustr STORM MOTION U-COMPONENT [m/s]'}, {'abbr': 148, 'code': 148, 'title': 'vstr STORM MOTION V-COMPONENT [m/s]'}, {'abbr': 149, 'code': 149, 'title': 'cbnt MEAN CLOUD COVER [0-1]'}, {'abbr': 150, 'code': 150, 'title': 'pcbs PRESSURE AT CLOUD BASE [hPa]'}, {'abbr': 151, 'code': 151, 'title': 'pctp PRESSURE AT CLOUD TOP [hPa]'}, {'abbr': 152, 'code': 152, 'title': 'fzht FREEZING LEVEL HEIGHT [m]'}, {'abbr': 153, 'code': 153, 'title': 'fzrh FREEZING LEVEL RELATIVE HUMIDITY [%]'}, {'abbr': 154, 'code': 154, 'title': 'fdlt FLIGHT LEVELS TEMPERATURE [K]'}, {'abbr': 155, 'code': 155, 'title': 'fdlu FLIGHT LEVELS U-WIND [m/s]'}, {'abbr': 156, 'code': 156, 'title': 'fdlv FLIGHT LEVELS V-WIND [m/s]'}, {'abbr': 157, 'code': 157, 'title': 'tppp TROPOPAUSE PRESSURE [hPa]'}, {'abbr': 158, 'code': 158, 'title': 'tppt TROPOPAUSE TEMPERATURE [K]'}, {'abbr': 159, 'code': 159, 'title': 'tppu TROPOPAUSE U-WIND COMPONENT [m/s]'}, {'abbr': 160, 'code': 160, 'title': 'tppv TROPOPAUSE v-WIND COMPONENT [m/s]'}, {'abbr': 161, 'code': 161, 'title': 'var161 undefined'}, {'abbr': 162, 'code': 162, 'title': 'gvdu GRAVITY WAVE DRAG DU/DT [m/s2]'}, {'abbr': 163, 'code': 163, 'title': 'gvdv GRAVITY WAVE DRAG DV/DT [m/s2]'}, {'abbr': 164, 'code': 164, 'title': 'gvus GRAVITY WAVE DRAG SFC ZONAL STRESS [Pa]'}, {'abbr': 165, 'code': 165, 'title': 'gvvs GRAVITY WAVE DRAG SFC MERIDIONAL STRESS [Pa]'}, {'abbr': 166, 'code': 166, 'title': 'var166 undefined'}, {'abbr': 167, 'code': 167, 'title': 'dvsh DIVERGENCE OF SPECIFIC HUMIDITY [1/s]'}, {'abbr': 168, 'code': 168, 'title': 'hmfc HORIZ. MOISTURE FLUX CONV. [1/s]'}, {'abbr': 169, 'code': 169, 'title': 'vmfl VERT. INTEGRATED MOISTURE FLUX CONV. [kg/(m2*s)]'}, {'abbr': 170, 'code': 170, 'title': 'vadv VERTICAL MOISTURE ADVECTION [kg/(kg*s)]'}, {'abbr': 171, 'code': 171, 'title': 'nhcm NEG. HUM. CORR. MOISTURE SOURCE [kg/(kg*s)]'}, {'abbr': 172, 'code': 172, 'title': 'lglh LARGE SCALE LATENT HEATING [K/s]'}, {'abbr': 173, 'code': 173, 'title': 'lgms LARGE SCALE MOISTURE SOURCE [1/s]'}, {'abbr': 174, 'code': 174, 'title': 'smav SOIL MOISTURE AVAILABILITY [0-1]'}, {'abbr': 175, 'code': 175, 'title': 'tgrz SOIL TEMPERATURE OF ROOT ZONE [K]'}, {'abbr': 176, 'code': 176, 'title': 'bslh BARE SOIL LATENT HEAT [Ws/m2]'}, {'abbr': 177, 'code': 177, 'title': 'evpp POTENTIAL SFC EVAPORATION [m]'}, {'abbr': 178, 'code': 178, 'title': 'rnof RUNOFF [kg/m2/s)]'}, {'abbr': 179, 'code': 179, 'title': 'pitp INTERCEPTION LOSS [W/m2]'}, {'abbr': 180, 'code': 180, 'title': 'vpca VAPOR PRESSURE OF CANOPY AIR SPACE [mb]'}, {'abbr': 181, 'code': 181, 'title': 'qsfc SURFACE SPEC HUMIDITY [kg/kg]'}, {'abbr': 182, 'code': 182, 'title': 'ussl SOIL WETNESS OF SURFACE [0-1]'}, {'abbr': 183, 'code': 183, 'title': 'uzrs SOIL WETNESS OF ROOT ZONE [0-1]'}, {'abbr': 184, 'code': 184, 'title': 'uzds SOIL WETNESS OF DRAINAGE ZONE [0-1]'}, {'abbr': 185, 'code': 185, 'title': 'amdl STORAGE ON CANOPY [m]'}, {'abbr': 186, 'code': 186, 'title': 'amsl STORAGE ON GROUND [m]'}, {'abbr': 187, 'code': 187, 'title': 'tsfc SURFACE TEMPERATURE [K]'}, {'abbr': 188, 'code': 188, 'title': 'tems SURFACE ABSOLUTE TEMPERATURE [K]'}, {'abbr': 189, 'code': 189, 'title': 'tcas TEMPERATURE OF CANOPY AIR SPACE [K]'}, {'abbr': 190, 'code': 190, 'title': 'ctmp TEMPERATURE AT CANOPY [K]'}, {'abbr': 191, 'code': 191, 'title': 'tgsc GROUND/SURFACE COVER TEMPERATURE [K]'}, {'abbr': 192, 'code': 192, 'title': 'uves SURFACE ZONAL WIND (U) [m/s]'}, {'abbr': 193, 'code': 193, 'title': 'usst SURFACE ZONAL WIND STRESS [Pa]'}, {'abbr': 194, 'code': 194, 'title': 'vves SURFACE MERIDIONAL WIND (V) [m/s]'}, {'abbr': 195, 'code': 195, 'title': 'vsst SURFACE MERIDIONAL WIND STRESS [Pa]'}, {'abbr': 196, 'code': 196, 'title': 'suvf SURFACE MOMENTUM FLUX [W/m2]'}, {'abbr': 197, 'code': 197, 'title': 'iswf INCIDENT SHORT WAVE FLUX [W/m2]'}, {'abbr': 198, 'code': 198, 'title': 'ghfl TIME AVE GROUND HT FLX [W/m2]'}, {'abbr': 199, 'code': 199, 'title': 'var199 undefined'}, {'abbr': 200, 'code': 200, 'title': 'lwbc NET LONG WAVE AT BOTTOM (CLEAR) [W/m2]'}, {'abbr': 201, 'code': 201, 'title': 'lwtc OUTGOING LONG WAVE AT TOP (CLEAR) [W/m2]'}, {'abbr': 202, 'code': 202, 'title': 'swec SHORT WV ABSRBD BY EARTH/ATMOS (CLEAR) [W/m2]'}, {'abbr': 203, 'code': 203, 'title': 'ocac SHORT WAVE ABSORBED AT GROUND (CLEAR) [W/m2]'}, {'abbr': 204, 'code': 204, 'title': 'var204 undefined'}, {'abbr': 205, 'code': 205, 'title': 'lwrh LONG WAVE RADIATIVE HEATING [K/s]'}, {'abbr': 206, 'code': 206, 'title': 'swrh SHORT WAVE RADIATIVE HEATING [K/s]'}, {'abbr': 207, 'code': 207, 'title': 'olis DOWNWARD LONG WAVE AT BOTTOM [W/m2]'}, {'abbr': 208, 'code': 208, 'title': 'olic DOWNWARD LONG WAVE AT BOTTOM (CLEAR) [W/m2]'}, {'abbr': 209, 'code': 209, 'title': 'ocis DOWNWARD SHORT WAVE AT GROUND [W/m2]'}, {'abbr': 210, 'code': 210, 'title': 'ocic DOWNWARD SHORT WAVE AT GROUND (CLEAR) [W/m2]'}, {'abbr': 211, 'code': 211, 'title': 'oles UPWARD LONG WAVE AT BOTTOM [W/m2]'}, {'abbr': 212, 'code': 212, 'title': 'oces UPWARD SHORT WAVE AT GROUND [W/m2]'}, {'abbr': 213, 'code': 213, 'title': 'swgc UPWARD SHORT WAVE AT GROUND (CLEAR) [W/m2]'}, {'abbr': 214, 'code': 214, 'title': 'roce UPWARD SHORT WAVE AT TOP [W/m2]'}, {'abbr': 215, 'code': 215, 'title': 'swtc UPWARD SHORT WAVE AT TOP (CLEAR) [W/m2]'}, {'abbr': 216, 'code': 216, 'title': 'var216 undefined'}, {'abbr': 217, 'code': 217, 'title': 'var217 undefined'}, {'abbr': 218, 'code': 218, 'title': 'hhdf HORIZONTAL HEATING DIFFUSION [K/s]'}, {'abbr': 219, 'code': 219, 'title': 'hmdf HORIZONTAL MOISTURE DIFFUSION [1/s]'}, {'abbr': 220, 'code': 220, 'title': 'hddf HORIZONTAL DIVERGENCE DIFFUSION [1/s2]'}, {'abbr': 221, 'code': 221, 'title': 'hvdf HORIZONTAL VORTICITY DIFFUSION [1/s2]'}, {'abbr': 222, 'code': 222, 'title': 'vdms VERTICAL DIFF. MOISTURE SOURCE [1/s]'}, {'abbr': 223, 'code': 223, 'title': 'vdfu VERTICAL DIFFUSION DU/DT [m/s2]'}, {'abbr': 224, 'code': 224, 'title': 'vdfv VERTICAL DIFFUSION DV/DT [m/s2]'}, {'abbr': 225, 'code': 225, 'title': 'vdfh VERTICAL DIFFUSION HEATING [K/s]'}, {'abbr': 226, 'code': 226, 'title': 'umrs SURFACE RELATIVE HUMIDITY [no Dim]'}, {'abbr': 227, 'code': 227, 'title': 'vdcc VERTICAL DIST TOTAL CLOUD COVER [no Dim]'}, {'abbr': 228, 'code': 228, 'title': 'var228 undefined'}, {'abbr': 229, 'code': 229, 'title': 'var229 undefined'}, {'abbr': 230, 'code': 230, 'title': 'usmt TIME MEAN SURFACE ZONAL WIND (U) [m/s]'}, {'abbr': 231, 'code': 231, 'title': 'vsmt TIME MEAN SURFACE MERIDIONAL WIND (V) [m/s]'}, {'abbr': 232, 'code': 232, 'title': 'tsmt TIME MEAN SURFACE ABSOLUTE TEMPERATURE [K]'}, {'abbr': 233, 'code': 233, 'title': 'rsmt TIME MEAN SURFACE RELATIVE HUMIDITY [no Dim]'}, {'abbr': 234, 'code': 234, 'title': 'atmt TIME MEAN ABSOLUTE TEMPERATURE [K]'}, {'abbr': 235, 'code': 235, 'title': 'stmt TIME MEAN DEEP SOIL TEMPERATURE [K]'}, {'abbr': 236, 'code': 236, 'title': 'ommt TIME MEAN DERIVED OMEGA [Pa/s]'}, {'abbr': 237, 'code': 237, 'title': 'dvmt TIME MEAN DIVERGENCE [1/s]'}, {'abbr': 238, 'code': 238, 'title': 'zhmt TIME MEAN GEOPOTENTIAL HEIGHT [m]'}, {'abbr': 239, 'code': 239, 'title': 'lnmt TIME MEAN LOG SURFACE PRESSURE [ln(cbar)]'}, {'abbr': 240, 'code': 240, 'title': 'mkmt TIME MEAN MASK [-/+]'}, {'abbr': 241, 'code': 241, 'title': 'vvmt TIME MEAN MERIDIONAL WIND (V) [m/s]'}, {'abbr': 242, 'code': 242, 'title': 'omtm TIME MEAN OMEGA [cbar/s]'}, {'abbr': 243, 'code': 243, 'title': 'ptmt TIME MEAN POTENTIAL TEMPERATURE [K]'}, {'abbr': 244, 'code': 244, 'title': 'pcmt TIME MEAN PRECIP. WATER [kg/m2]'}, {'abbr': 245, 'code': 245, 'title': 'rhmt TIME MEAN RELATIVE HUMIDITY [%]'}, {'abbr': 246, 'code': 246, 'title': 'mpmt TIME MEAN SEA LEVEL PRESSURE [hPa]'}, {'abbr': 247, 'code': 247, 'title': 'simt TIME MEAN SIGMADOT [1/s]'}, {'abbr': 248, 'code': 248, 'title': 'uemt TIME MEAN SPECIFIC HUMIDITY [kg/kg]'}, {'abbr': 249, 'code': 249, 'title': 'fcmt TIME MEAN STREAM FUNCTION| m2/s]'}, {'abbr': 250, 'code': 250, 'title': 'psmt TIME MEAN SURFACE PRESSURE [hPa]'}, {'abbr': 251, 'code': 251, 'title': 'tmmt TIME MEAN SURFACE TEMPERATURE [K]'}, {'abbr': 252, 'code': 252, 'title': 'pvmt TIME MEAN VELOCITY POTENTIAL [m2/s]'}, {'abbr': 253, 'code': 253, 'title': 'tvmt TIME MEAN VIRTUAL TEMPERATURE [K]'}, {'abbr': 254, 'code': 254, 'title': 'vtmt TIME MEAN VORTICITY [1/s]'}, {'abbr': None, 'code': 255, 'title': 'uvmt TIME MEAN ZONAL WIND (U) [m/s]'})
class Settings: params = () def __init__(self, params): self.params = params
urlChatAdd = '/chat/add' urlUserAdd = '/chat/adduser' urlGetUsers = '/chat/getusers/' urlGetChats = '/chat/chats' urlPost = '/chat/post' urlHist = '/chat/hist' urlAuth = '/chat/auth'
""" This module contains the definitions for Bike and its subclasses Bicycle and Motorbike. """ class Bike: """ Class defining a bike that can be ridden and have its gear changed. Attributes: seats: number of seats the bike has gears: number of gears the bike has """ def __init__(self, seats, gears): """ Creates a new Bike object. Args: seats: number of seats the bike has gears: number of gears the bike has """ self.seats = seats self.gears = gears self._curr_gear = 1 # current gear, private self._riding = False # bike is per default not ridden @property def curr_gear(self): """ Purpose of this function is to enable the user to check the gear status, but is only able to change it with a specific method. (was not necessary to implement it this way) """ return self._curr_gear def start_ride(self): """ Starts a bike ride. Returns: True if successful. False if bike is already on a ride. """ # can't ride a bike if already ridden if self._riding: return False self._riding = True return True def end_ride(self): """ Ends a bike ride. Returns: True if successful. False if bike is not currently ridden. """ # can't stop a bike ride if the bike is already standing if not self._riding: return False self._riding = False return True def change_gear(self, new_gear): """ Changes bike gear to a new gear. Args: new_gear: gear to be changed to Returns: True if gear was successfully changed. Raises: ValueError if current gear is same as new gear or new gear is <= 0 or not in range of available gears. """ if self._curr_gear == new_gear or not 0 < new_gear <= self.gears: raise ValueError("Already in this gear or invalid gear number.") self._curr_gear = new_gear return True class Bicycle(Bike): """ Class defining a Bicycle (extending Bike) that can be ridden, have its gear changed and has a bell that can be rung. Attributes: seats: number of seats the bike has gears: number of gears the bike has bell_sound: sound the bell makes when rung """ def __init__(self, seats=1, gears=7, bell_sound="ring ring"): """ Creates a new Bike object. Args: seats: number of seats the bicycle has, defaults to 1 gears: number of gears the bicycle has, defaults to 7 bell_sound: sound the bell makes when rung """ super().__init__(seats, gears) self.bell_sound = bell_sound def ring_bell(self): """ Rings bicycle bell.""" print(self.bell_sound) class Motorbike(Bike): """ Class defining a Motorbike (extending Bike) that can be ridden, have its gear changed and has a tank that can be filled. Attributes: seats: number of seats the bike has gears: number of gears the bike has """ def __init__(self, seats=2, gears=5): """ Creates a new Motorbike object. Args: seats: number of seats the motorbike has, defaults to 2 gears: number of gears the motorbike has, defaults to 5 """ super().__init__(seats, gears) # True means full tank. Private so it can only be changed in # a controlled manner self._tank = True @property def tank(self): """ Purpose of this function is to enable the user to check the tank status, but is only able to fill/empty the tank with specific methods. This was not necessary to implement. """ return self._tank def start_ride(self): """ Starts a motorbike ride. Returns: True if successful. False if motorbike is already on a ride or tank is empty """ # can't ride a motorbike if tank is empty or it is already ridden if not self._tank or not super().start_ride(): return False return True def end_ride(self): """ Ends a motorbike ride and empties tank. Returns: True if successful. False if motorbike is not currently ridden. """ if not super().end_ride(): return False self._tank = False # tank is empty after riding return True # the following method was not necessary to implement, but we want to be # able to ride more than once. def fill_tank(self): """ Fills motorbike tank with fuel. Returns: True if successful. False if tank already full. """ # can't fill tank if already full if self._tank: return False self._tank = True return True
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. names = { 'Cisco': 'cwom' } mappings = { 'cwom': { '1.0': '5.8.3.1', '1.1': '5.9.1', '1.1.3': '5.9.3', '1.2.0': '6.0.3', '1.2.1': '6.0.6', '1.2.2': '6.0.9', '1.2.3': '6.0.11.1', '2.0.0': '6.1.1', '2.0.1': '6.1.6', '2.0.2': '6.1.8', '2.0.3': '6.1.12', '2.1.0': '6.2.2', '2.1.1': '6.2.7.1', '2.1.2': '6.2.10', '2.2': '6.3.2', '2.2.1': '6.3.5.0.1', '2.2.2': '6.3.7', '2.2.3': '6.3.7.1', '2.2.4': '6.3.10', '2.2.5': '6.3.13', '2.3.0': '6.4.2', '2.3.1': '6.4.5', '2.3.2': '6.4.6', '2.3.3': '6.4.7', '2.3.4': '6.4.8', '2.3.5': '6.4.9', '2.3.6': '6.4.10', '2.3.7': '6.4.11', '2.3.8': '6.4.12', '2.3.9': '6.4.13', '2.3.10': '6.4.14', '2.3.11': '6.4.15', '2.3.12': '6.4.16', '2.3.13': '6.4.17', '2.3.14': '6.4.18', '2.3.15': '6.4.19', '2.3.16': '6.4.20', '2.3.17': '6.4.21', '2.3.18': '6.4.22', '2.3.19': '6.4.23', '2.3.20': '6.4.24', '2.3.21': '6.4.25', '2.3.22': '6.4.26', '2.3.23': '6.4.27', '2.3.24': '6.4.28', '2.3.25': '6.4.29', '2.3.26': '6.4.30', '2.3.27': '6.4.31', '2.3.28': '6.4.32', '2.3.29': '6.4.33', '2.3.30': '6.4.34', '2.3.31': '6.4.35', '2.3.32': '6.4.36', '2.3.33': '6.4.37', '2.3.34': '6.4.38', '3.0.1': '8.2.1' } }
try: with open('../../../assets/img_cogwheel_argb.bin','rb') as f: cogwheel_img_data = f.read() except: try: with open('images/img_cogwheel_rgb565.bin','rb') as f: cogwheel_img_data = f.read() except: print("Could not find binary img_cogwheel file") # create the cogwheel image data cogwheel_img_dsc = lv.img_dsc_t( { "header": {"always_zero": 0, "w": 100, "h": 100, "cf": lv.img.CF.TRUE_COLOR_ALPHA}, "data": cogwheel_img_data, "data_size": len(cogwheel_img_data), } ) # Create an image using the decoder img1 = lv.img(lv.scr_act(),None) lv.img.cache_set_size(2) img1.align(lv.scr_act(), lv.ALIGN.CENTER, 0, -50) img1.set_src(cogwheel_img_dsc) img2 = lv.img(lv.scr_act(), None) img2.set_src(lv.SYMBOL.OK+"Accept") img2.align(img1, lv.ALIGN.OUT_BOTTOM_MID, 0, 20)
class Solution(object): def calculate(self, s): """ :type s: str :rtype: int """ if not s: return 0 s = s.replace(" ", "") n = len(s) stack = [] num = 0 sign = '+' for i in range(n): if s[i].isdigit(): num = num * 10 + int(s[i]) if not s[i].isdigit() or i == n - 1: if sign == '-': stack.append(-num) elif sign == '+': stack.append(num) elif sign == '*': stack.append(stack.pop() * num) elif sign == '/': d = stack.pop() r = d // num if r < 0 and d % num != 0: r += 1 stack.append(r) sign = s[i] num = 0 res = 0 for i in stack: res += i return res s = Solution() print(s.calculate("")) print(s.calculate("123")) print(s.calculate("3+2*2")) print(s.calculate(" 3/2 ")) print(s.calculate("3+5 / 2")) print(s.calculate("14/3*2")) print(s.calculate("14-3/2")) print(s.calculate("10000-1000/10+100*1"))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Feb 23 13:11:49 2020 @author: abdulroqeeb """ host = "127.0.0.1" port = 7497 ticktypes = { 66: "Bid", 67: "Ask", 68: "Last", 69: "Bid Size", 70: "Ask Size", 71: "Last Size", 72: "High", 73: "Low", 74: "Volume", 75: "Prior Close", 76: "Prior Open", 88: "Timestamp", } account_details_params = [ 'AccountCode', 'AccountType', 'AccruedCash', 'AvailableFunds', 'BuyingPower', 'CashBalance', 'NetLiquidation' ] port_chart_lim = 600 #minutes states = {1: 'Long', 0: 'Flat', -1: 'Short'}
int1 = int(input('informe o inteiro 1 ')) int2 = int(input('informe o inteiro 2 ')) real = float(input('informe o real ')) print('a %2.f' %((int1*2)*(int2/2))) print('b %2.f' %((int1*3)+(real))) print('c %2.f' %(real**3))
data = ( 'ruk', # 0x00 'rut', # 0x01 'rup', # 0x02 'ruh', # 0x03 'rweo', # 0x04 'rweog', # 0x05 'rweogg', # 0x06 'rweogs', # 0x07 'rweon', # 0x08 'rweonj', # 0x09 'rweonh', # 0x0a 'rweod', # 0x0b 'rweol', # 0x0c 'rweolg', # 0x0d 'rweolm', # 0x0e 'rweolb', # 0x0f 'rweols', # 0x10 'rweolt', # 0x11 'rweolp', # 0x12 'rweolh', # 0x13 'rweom', # 0x14 'rweob', # 0x15 'rweobs', # 0x16 'rweos', # 0x17 'rweoss', # 0x18 'rweong', # 0x19 'rweoj', # 0x1a 'rweoc', # 0x1b 'rweok', # 0x1c 'rweot', # 0x1d 'rweop', # 0x1e 'rweoh', # 0x1f 'rwe', # 0x20 'rweg', # 0x21 'rwegg', # 0x22 'rwegs', # 0x23 'rwen', # 0x24 'rwenj', # 0x25 'rwenh', # 0x26 'rwed', # 0x27 'rwel', # 0x28 'rwelg', # 0x29 'rwelm', # 0x2a 'rwelb', # 0x2b 'rwels', # 0x2c 'rwelt', # 0x2d 'rwelp', # 0x2e 'rwelh', # 0x2f 'rwem', # 0x30 'rweb', # 0x31 'rwebs', # 0x32 'rwes', # 0x33 'rwess', # 0x34 'rweng', # 0x35 'rwej', # 0x36 'rwec', # 0x37 'rwek', # 0x38 'rwet', # 0x39 'rwep', # 0x3a 'rweh', # 0x3b 'rwi', # 0x3c 'rwig', # 0x3d 'rwigg', # 0x3e 'rwigs', # 0x3f 'rwin', # 0x40 'rwinj', # 0x41 'rwinh', # 0x42 'rwid', # 0x43 'rwil', # 0x44 'rwilg', # 0x45 'rwilm', # 0x46 'rwilb', # 0x47 'rwils', # 0x48 'rwilt', # 0x49 'rwilp', # 0x4a 'rwilh', # 0x4b 'rwim', # 0x4c 'rwib', # 0x4d 'rwibs', # 0x4e 'rwis', # 0x4f 'rwiss', # 0x50 'rwing', # 0x51 'rwij', # 0x52 'rwic', # 0x53 'rwik', # 0x54 'rwit', # 0x55 'rwip', # 0x56 'rwih', # 0x57 'ryu', # 0x58 'ryug', # 0x59 'ryugg', # 0x5a 'ryugs', # 0x5b 'ryun', # 0x5c 'ryunj', # 0x5d 'ryunh', # 0x5e 'ryud', # 0x5f 'ryul', # 0x60 'ryulg', # 0x61 'ryulm', # 0x62 'ryulb', # 0x63 'ryuls', # 0x64 'ryult', # 0x65 'ryulp', # 0x66 'ryulh', # 0x67 'ryum', # 0x68 'ryub', # 0x69 'ryubs', # 0x6a 'ryus', # 0x6b 'ryuss', # 0x6c 'ryung', # 0x6d 'ryuj', # 0x6e 'ryuc', # 0x6f 'ryuk', # 0x70 'ryut', # 0x71 'ryup', # 0x72 'ryuh', # 0x73 'reu', # 0x74 'reug', # 0x75 'reugg', # 0x76 'reugs', # 0x77 'reun', # 0x78 'reunj', # 0x79 'reunh', # 0x7a 'reud', # 0x7b 'reul', # 0x7c 'reulg', # 0x7d 'reulm', # 0x7e 'reulb', # 0x7f 'reuls', # 0x80 'reult', # 0x81 'reulp', # 0x82 'reulh', # 0x83 'reum', # 0x84 'reub', # 0x85 'reubs', # 0x86 'reus', # 0x87 'reuss', # 0x88 'reung', # 0x89 'reuj', # 0x8a 'reuc', # 0x8b 'reuk', # 0x8c 'reut', # 0x8d 'reup', # 0x8e 'reuh', # 0x8f 'ryi', # 0x90 'ryig', # 0x91 'ryigg', # 0x92 'ryigs', # 0x93 'ryin', # 0x94 'ryinj', # 0x95 'ryinh', # 0x96 'ryid', # 0x97 'ryil', # 0x98 'ryilg', # 0x99 'ryilm', # 0x9a 'ryilb', # 0x9b 'ryils', # 0x9c 'ryilt', # 0x9d 'ryilp', # 0x9e 'ryilh', # 0x9f 'ryim', # 0xa0 'ryib', # 0xa1 'ryibs', # 0xa2 'ryis', # 0xa3 'ryiss', # 0xa4 'rying', # 0xa5 'ryij', # 0xa6 'ryic', # 0xa7 'ryik', # 0xa8 'ryit', # 0xa9 'ryip', # 0xaa 'ryih', # 0xab 'ri', # 0xac 'rig', # 0xad 'rigg', # 0xae 'rigs', # 0xaf 'rin', # 0xb0 'rinj', # 0xb1 'rinh', # 0xb2 'rid', # 0xb3 'ril', # 0xb4 'rilg', # 0xb5 'rilm', # 0xb6 'rilb', # 0xb7 'rils', # 0xb8 'rilt', # 0xb9 'rilp', # 0xba 'rilh', # 0xbb 'rim', # 0xbc 'rib', # 0xbd 'ribs', # 0xbe 'ris', # 0xbf 'riss', # 0xc0 'ring', # 0xc1 'rij', # 0xc2 'ric', # 0xc3 'rik', # 0xc4 'rit', # 0xc5 'rip', # 0xc6 'rih', # 0xc7 'ma', # 0xc8 'mag', # 0xc9 'magg', # 0xca 'mags', # 0xcb 'man', # 0xcc 'manj', # 0xcd 'manh', # 0xce 'mad', # 0xcf 'mal', # 0xd0 'malg', # 0xd1 'malm', # 0xd2 'malb', # 0xd3 'mals', # 0xd4 'malt', # 0xd5 'malp', # 0xd6 'malh', # 0xd7 'mam', # 0xd8 'mab', # 0xd9 'mabs', # 0xda 'mas', # 0xdb 'mass', # 0xdc 'mang', # 0xdd 'maj', # 0xde 'mac', # 0xdf 'mak', # 0xe0 'mat', # 0xe1 'map', # 0xe2 'mah', # 0xe3 'mae', # 0xe4 'maeg', # 0xe5 'maegg', # 0xe6 'maegs', # 0xe7 'maen', # 0xe8 'maenj', # 0xe9 'maenh', # 0xea 'maed', # 0xeb 'mael', # 0xec 'maelg', # 0xed 'maelm', # 0xee 'maelb', # 0xef 'maels', # 0xf0 'maelt', # 0xf1 'maelp', # 0xf2 'maelh', # 0xf3 'maem', # 0xf4 'maeb', # 0xf5 'maebs', # 0xf6 'maes', # 0xf7 'maess', # 0xf8 'maeng', # 0xf9 'maej', # 0xfa 'maec', # 0xfb 'maek', # 0xfc 'maet', # 0xfd 'maep', # 0xfe 'maeh', # 0xff )
class PHPWriter: def __init__(self, constants): self.constants = constants def write(self, out): out.write("<?php\n") out.write("/* This file was generated by generate_constants. */\n\n") for enum in self.constants.enum_values.values(): out.write("\n") for name, value in enum.items(): out.write("define('{}', {});\n".format(name, value)) for name, value in self.constants.constant_values.items(): out.write("define('{}', {});\n".format(name, value))
__version__ = "170130" __authors__ = "Ryo KOBAYASHI" __email__ = "kobayashi.ryo@nitech.ac.jp" class Machine(): """ Parent class of any other machine classes. """ QUEUES = { 'batch': {'num_nodes': 12, 'default_sec': 86400, 'limit_sec': 604800}, 'default':{'num_nodes': 12, 'default_sec': 86400, 'limit_sec': 604800}, } SCHEDULER = 'pbs' def __init__(self): pass class FUJITSU_FX100(Machine): """ Class for the specific super computer at Nagoya University, Fujitsu FX100. """ # Resource groups and their nums of nodes and time limits QUEUES = { 'fx-debug': {'num_nodes': 32, 'default_sec': 3600, 'limit_sec': 3600}, 'fx-small': {'num_nodes': 16, 'default_sec':86400, 'limit_sec':604800}, 'fx-middle':{'num_nodes': 96, 'default_sec':86400, 'limit_sec':259200}, 'fx-large': {'num_nodes':192, 'default_sec':86400, 'limit_sec':259200}, 'fx-xlarge':{'num_nodes':864, 'default_sec':86400, 'limit_sec': 86400}, } SCHEDULER = 'fujitsu' class MIKE(Machine): """ Class for the specific machine in Ogata Lab. at NITech.ac.jp """ SCHEDULER = 'pbs' #...Currently it is hard to specify nodes to use, so this queues are #...like the greatest commond divider QUEUES = { 'batch': {'num_nodes': 12, 'default_sec': 86400, 'limit_sec': 604800}, 'default':{'num_nodes': 12, 'default_sec': 86400, 'limit_sec': 604800}, }
Amount = float BenefitName = str Email = str Donor = Email PaymentId = str def isnotemptyinstance(value, type): if not isinstance(value, type): return False # None returns false if isinstance(value, str): return (len(value.strip()) != 0) elif isinstance(value, int): return (value != 0) elif isinstance(value, float): return (value != 0.0) else: raise NotImplementedError
# model settings model = dict( type='ImageClassifier', backbone=dict( type='SVT', arch='base', in_channels=3, out_indices=(3, ), qkv_bias=True, norm_cfg=dict(type='LN'), norm_after_stage=[False, False, False, True], drop_rate=0.0, attn_drop_rate=0., drop_path_rate=0.3), neck=dict(type='GlobalAveragePooling'), head=dict( type='LinearClsHead', num_classes=1000, in_channels=768, loss=dict( type='LabelSmoothLoss', label_smooth_val=0.1, mode='original'), cal_acc=False), init_cfg=[ dict(type='TruncNormal', layer='Linear', std=0.02, bias=0.), dict(type='Constant', layer='LayerNorm', val=1., bias=0.) ], train_cfg=dict(augments=[ dict(type='BatchMixup', alpha=0.8, num_classes=1000, prob=0.5), dict(type='BatchCutMix', alpha=1.0, num_classes=1000, prob=0.5) ]))
nome = input('Digite seu nome: ') def saudar(x): print(f'Bem-vindo, {x}!') saudar(nome)
"""Anagram utilities""" def find_anagrams(word: str, candidates: list) -> list: """Detect anagrams on a list against a reference word Args: word: the reference word candidates: the list of words to be compared Returns: A new list with the anagrams found. """ low_word = sorted(word.lower()) return [candidate for candidate in candidates if is_anagram(low_word, candidate)] def is_anagram(low_sort_word: str, candidate: str) -> bool: """Determine whether two words are anagrams of each other. Args: low_sort_words: the original word, sorted and lowered. candidate: the word to be compared Returns: A boolean True if the two words have the same letters in different order.""" return sorted(candidate.lower()) == low_sort_word and candidate.lower() != low_sort_word
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: sq_nums = [] for num in nums: sq_nums.append(num ** 2) sq_nums.sort() return sq_nums
class Stack(object): def __init__(self): self.items = [] self.min_value = None def push(self, item): if not self.min_value or self.min_value > item: self.min_value = item self.items.append(item) def pop(self): self.items.pop() def get_min_value(self): return self.min_value stack = Stack() stack.push(4) stack.push(6) stack.push(2) print(stack.get_min_value()) stack.push(1) print(stack.get_min_value())