content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def counting_sort(x): N = len(x) M = max(x) + 1 a = [0] * M for v in x: a[v] += 1 res = [] for i in range(M): for j in range(a[i]): res.append(i) return res def counting_sort2(x): N = len(x) M = max(x) + 1 c = [0] * M for v in x: c[v] += ...
def counting_sort(x): n = len(x) m = max(x) + 1 a = [0] * M for v in x: a[v] += 1 res = [] for i in range(M): for j in range(a[i]): res.append(i) return res def counting_sort2(x): n = len(x) m = max(x) + 1 c = [0] * M for v in x: c[v] += 1...
class Solution: def countSubstrings(self, s): dp = [[0] * len(s) for i in range(len(s))] res = 0 for r in range(len(s)): for l in range(r+1): if s[r] == s[l]: if r == l or r+1 == l or dp[l+1][r-1] == 1: dp[l][r] = 1 ...
class Solution: def count_substrings(self, s): dp = [[0] * len(s) for i in range(len(s))] res = 0 for r in range(len(s)): for l in range(r + 1): if s[r] == s[l]: if r == l or r + 1 == l or dp[l + 1][r - 1] == 1: dp[l][r...
# projecteuler.net/problem=52 def main(): answer = PermutatedMul() print("Answer: {}".format(answer)) def PermutatedMul(): i = 1 muls = [2,3,4,5,6] while True: found = True i += 1 si = list(str(i)) ops = list(map(lambda x: x * i, muls)) for...
def main(): answer = permutated_mul() print('Answer: {}'.format(answer)) def permutated_mul(): i = 1 muls = [2, 3, 4, 5, 6] while True: found = True i += 1 si = list(str(i)) ops = list(map(lambda x: x * i, muls)) for num in ops: if len(str(i)) != ...
YEAR_IN_S = 31557600. GEV_IN_KEV = 1.e6 C_KMSEC = 299792.458 NUCLEON_MASS = 0.938272 # Nucleon mass in GeV P_MAGMOM = 2.793 # proton magnetic moment, PDG Live N_MAGMOM = -1.913 # neutron magnetic moment, PDG Live NUCLEAR_MASSES = { 'xenon': 122.298654871, 'germanium': 67.663731424, 'argon': 37.2113263068,...
year_in_s = 31557600.0 gev_in_kev = 1000000.0 c_kmsec = 299792.458 nucleon_mass = 0.938272 p_magmom = 2.793 n_magmom = -1.913 nuclear_masses = {'xenon': 122.298654871, 'germanium': 67.663731424, 'argon': 37.2113263068, 'silicon': 26.1614775455, 'sodium': 21.4140502327, 'iodine': 118.206437626, 'fluorine': 17.6969003039...
def get_version(testbed: str): path = [e for e in testbed.split(" ") if e.find("/") > -1][0] full_name = path.split("/")[-1] return full_name.replace(".jar", "") def parse_engine_name(testbed: str): return get_version(testbed).split("-")[0]
def get_version(testbed: str): path = [e for e in testbed.split(' ') if e.find('/') > -1][0] full_name = path.split('/')[-1] return full_name.replace('.jar', '') def parse_engine_name(testbed: str): return get_version(testbed).split('-')[0]
def predict(text, with_neu=True): # requires string input. start_at = time.time() x_test = pad_sequences(tokenizer.texts_to_sequences([text]), maxlen=seq_len) score = model.predict([x_test])[0] label = decode_sentiment(score, with_neu=with_neu) score = float(score) return {print(f"label: {label}...
def predict(text, with_neu=True): start_at = time.time() x_test = pad_sequences(tokenizer.texts_to_sequences([text]), maxlen=seq_len) score = model.predict([x_test])[0] label = decode_sentiment(score, with_neu=with_neu) score = float(score) return {print(f'label: {label}, score: {score}, calcula...
def get_session_attributes(previous_intent = "", previous_intent_attributes = "", requested_value = "", previous_requested_value = "", questions_urls = [], question_now_id = 0, question_name = "", answers_ids = [], answer_now_id = 0, comments_ids = [], comment_now_id = 0, complete_answer = [], complete_code = [], comp...
def get_session_attributes(previous_intent='', previous_intent_attributes='', requested_value='', previous_requested_value='', questions_urls=[], question_now_id=0, question_name='', answers_ids=[], answer_now_id=0, comments_ids=[], comment_now_id=0, complete_answer=[], complete_code=[], complete_code_now_id=0): se...
STATS = [ { "num_node_expansions": 0, "search_time": 0.0929848, "total_time": 0.206795, "plan_length": 209, "plan_cost": 209, "objects_used": 145, "objects_total": 253, "neural_net_time": 0.09392738342285156, "num_replanning_steps": 0, ...
stats = [{'num_node_expansions': 0, 'search_time': 0.0929848, 'total_time': 0.206795, 'plan_length': 209, 'plan_cost': 209, 'objects_used': 145, 'objects_total': 253, 'neural_net_time': 0.09392738342285156, 'num_replanning_steps': 0, 'wall_time': 0.9533143043518066}, {'num_node_expansions': 0, 'search_time': 0.0644765,...
# Copyright (c) 2020 Trail of Bits, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is di...
class Colors: class C: green = '\x1b[92m' yellow = '\x1b[93m' red = '\x1b[91m' magneta = '\x1b[95m' bg_yellow = '\x1b[43m' orange = '\x1b[38;5;202m' reset = '\x1b[0m' def get_result_color(total, success): if total == 0: return Colors.c.magneta if...
# container.py - Creates META-INF/content.xml within the epub file def create_container(epub_file): epub_file.writestr('META-INF/container.xml', '''<?xml version="1.0"?> <container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container"> <rootfiles> <rootfile full-path="OEBPS/cont...
def create_container(epub_file): epub_file.writestr('META-INF/container.xml', '<?xml version="1.0"?>\n<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">\n <rootfiles>\n <rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>\n </rootfiles>\n</...
APP_MIN_WIDTH = 1024 APP_MIN_HEIGHT = 800 APP_NAME = 'Fractals' APP_FONT = 12
app_min_width = 1024 app_min_height = 800 app_name = 'Fractals' app_font = 12
s = input() ans = [] i=0 while i<len(s): if s[i]=='.': ans.append('0') else: if s[i+1]=='.': ans.append('1') else: ans.append('2') i=i+1 i+=1 for j in ans: print(j,end='')
s = input() ans = [] i = 0 while i < len(s): if s[i] == '.': ans.append('0') else: if s[i + 1] == '.': ans.append('1') else: ans.append('2') i = i + 1 i += 1 for j in ans: print(j, end='')
def usersagein_Sec(): users_age = int(input("Enter user age in years")) agein_sec = users_age *12 *365 * 24 print(f"Age in sec is {agein_sec}") print("Welcome to function project 1 ") usersagein_Sec() # Never use same name in anywhere inside a function program. else going to get error. friends ...
def usersagein__sec(): users_age = int(input('Enter user age in years')) agein_sec = users_age * 12 * 365 * 24 print(f'Age in sec is {agein_sec}') print('Welcome to function project 1 ') usersagein__sec() friends = [] def friend(): friends.append('Ram') friend() friend() friend() print(friends)
def test_non_standard_default_desired_privilege_level(iosxe_conn): # purpose of this test is to ensure that when a user sets a non-standard default desired priv # level, that there is nothing in genericdriver/networkdriver that will prevent that from # actually being set as the default desired priv level ...
def test_non_standard_default_desired_privilege_level(iosxe_conn): iosxe_conn.close() iosxe_conn.default_desired_privilege_level = 'configuration' iosxe_conn.open() current_prompt = iosxe_conn.get_prompt() assert current_prompt == 'csr1000v(config)#' iosxe_conn.close()
# Mac address of authentication server AUTH_SERVER_MAC = "b8:ae:ed:7a:05:3b" # IP address of authentication server AUTH_SERVER_IP = "192.168.1.42" # Switch port authentication server is facing AUTH_SERVER_PORT = 3 #CTL_REST_IP = "192.168.1.39" CTL_REST_IP = "10.0.1.8" CTL_REST_PORT = "8080" CTL_MAC = "b8:27:eb:b0:1d...
auth_server_mac = 'b8:ae:ed:7a:05:3b' auth_server_ip = '192.168.1.42' auth_server_port = 3 ctl_rest_ip = '10.0.1.8' ctl_rest_port = '8080' ctl_mac = 'b8:27:eb:b0:1d:6b' gateway_mac = '24:09:95:79:31:7e' gateway_port = 1 whitelist = [(AUTH_SERVER_MAC, CTL_MAC), (CTL_MAC, AUTH_SERVER_MAC), (GATEWAY_MAC, '00:1d:a2:80:60:6...
running = True # Global Options SIZES = {'small': [7.58, 0], 'medium': [9.69, 1], 'large': [12.09, 2], 'jumbo': [17.99, 3], 'party': [20.29, 4]} # [Price, ID] TOPPINGS = {'pepperoni': [0, False], 'bacon': [0, True], 'sausage': [0, False], 'mushroom': [1, False], 'black olive': [1, False], 'green pepper': [1, False]} #...
running = True sizes = {'small': [7.58, 0], 'medium': [9.69, 1], 'large': [12.09, 2], 'jumbo': [17.99, 3], 'party': [20.29, 4]} toppings = {'pepperoni': [0, False], 'bacon': [0, True], 'sausage': [0, False], 'mushroom': [1, False], 'black olive': [1, False], 'green pepper': [1, False]} topping_prices = [[1.6, 2.05, 2.3...
# # PySNMP MIB module EdgeSwitch-QOS-AUTOVOIP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EdgeSwitch-QOS-AUTOVOIP-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:10:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python versio...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_intersection, constraints_union, value_size_constraint, single_value_constraint) ...
def reverse(my_list): if type(my_list) != list: return f"{my_list} is not a list" elif len(my_list) ==0: return 'list should not be empty' reversed_list = my_list[::-1] return reversed_list if __name__ == "__main__": riddle_index = 0
def reverse(my_list): if type(my_list) != list: return f'{my_list} is not a list' elif len(my_list) == 0: return 'list should not be empty' reversed_list = my_list[::-1] return reversed_list if __name__ == '__main__': riddle_index = 0
class _dafny: def print(value): if type(value) == bool: print("true" if value else "false", end="") elif type(value) == property: print(value.fget(), end="") else: print(value, end="")
class _Dafny: def print(value): if type(value) == bool: print('true' if value else 'false', end='') elif type(value) == property: print(value.fget(), end='') else: print(value, end='')
limit=int(input("enter the limit")) no=int(input("enter the no")) for i in range(1,limit+1,1): multi=no*i print(no,"*",i,"=",multi)
limit = int(input('enter the limit')) no = int(input('enter the no')) for i in range(1, limit + 1, 1): multi = no * i print(no, '*', i, '=', multi)
class Arithmetic: def __init__(self, command): self.text = command def operation(self): return self.text.strip() class MemoryAccess: def __init__(self, command): self.op, self.seg, self.idx = tuple(command.split()) def operation(self): return self.op def segmen...
class Arithmetic: def __init__(self, command): self.text = command def operation(self): return self.text.strip() class Memoryaccess: def __init__(self, command): (self.op, self.seg, self.idx) = tuple(command.split()) def operation(self): return self.op def segme...
N = int(input()) pokemons = [] while (N != 0): Name = input() pokemons.append(Name) N-= 1 print('Falta(m) {} pomekon(s).'.format(151 - len(set(pokemons))))
n = int(input()) pokemons = [] while N != 0: name = input() pokemons.append(Name) n -= 1 print('Falta(m) {} pomekon(s).'.format(151 - len(set(pokemons))))
def count_salutes(hallway): count=hallway.count("<") total=0 for i in hallway: count-=i=="<" if i==">": total+=count*2 return total
def count_salutes(hallway): count = hallway.count('<') total = 0 for i in hallway: count -= i == '<' if i == '>': total += count * 2 return total
# Python - 3.6.0 Test.assert_equals(catch_sign_change([1, 3, 4, 5]), 0) Test.assert_equals(catch_sign_change([1, -3, -4, 0, 5]), 2) Test.assert_equals(catch_sign_change([]), 0) Test.assert_equals(catch_sign_change([-47, 84, -30, -11, -5, 74, 77]), 3)
Test.assert_equals(catch_sign_change([1, 3, 4, 5]), 0) Test.assert_equals(catch_sign_change([1, -3, -4, 0, 5]), 2) Test.assert_equals(catch_sign_change([]), 0) Test.assert_equals(catch_sign_change([-47, 84, -30, -11, -5, 74, 77]), 3)
{ 'targets': [ { 'target_name': 'murmurhash3', 'sources': ['src/MurmurHash3.cpp', 'src/node_murmurhash3.cc'], 'cflags': ['-fexceptions'], 'cflags_cc': ['-fexceptions'], 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exception'], "include_dirs" : [ "<!(node...
{'targets': [{'target_name': 'murmurhash3', 'sources': ['src/MurmurHash3.cpp', 'src/node_murmurhash3.cc'], 'cflags': ['-fexceptions'], 'cflags_cc': ['-fexceptions'], 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exception'], 'include_dirs': ['<!(node -e "require(\'nan\')")'], 'conditions': [['OS=="win"', {'msvs_...
def create_desktop_file_KDE(): path="/usr/share/applications/klusta_process_manager.desktop" text=["[Desktop Entry]", "Version=0.1", "Name=klusta_process_manager", "Comment=GUI", "Exec=klusta_process_manager", "Icon=eyes", "Terminal=False", "Type=Application", "Categories=Applications;...
def create_desktop_file_kde(): path = '/usr/share/applications/klusta_process_manager.desktop' text = ['[Desktop Entry]', 'Version=0.1', 'Name=klusta_process_manager', 'Comment=GUI', 'Exec=klusta_process_manager', 'Icon=eyes', 'Terminal=False', 'Type=Application', 'Categories=Applications;'] with open(path,...
class BinarySearchTreeNode: def __init__(self,data): self.data=data self.left=None self.right=None def add_child(self,data): if data == self.data: return if data <self.data: #add on the left side of the subtree if self.left: ...
class Binarysearchtreenode: def __init__(self, data): self.data = data self.left = None self.right = None def add_child(self, data): if data == self.data: return if data < self.data: if self.left: self.left.add_child(data) ...
# -*- coding: utf-8 -*- # Scrapy settings for cosme project # # For simplicity, this file contains only the most important settings by # default. All the other settings are documented here: # # http://doc.scrapy.org/en/latest/topics/settings.html # BOT_NAME = 'cosme' SPIDER_MODULES = ['cosme.spiders'] NEWSPIDER_...
bot_name = 'cosme' spider_modules = ['cosme.spiders'] newspider_module = 'cosme.spiders' download_delay = 1.5 cookies_enables = False item_pipelines = {'cosme.pipelines.ProductDetailPipeline': 1} (host, db, user, pwd) = ('127.0.0.1', 'cosme', 'root', '123456')
# Time: O(n) # Space: O(h), h is height of binary tree # 129 # Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. # # An example is the root-to-leaf path 1->2->3 which represents the number 123. # # Find the total sum of all root-to-leaf numbers. # # For example, # # ...
class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def sum_numbers(self, root: TreeNode) -> int: ans = 0 stack = [(root, 0)] while stack: (node, v) = stack.pop() if node: ...
task = int(input()) points = int(input()) course = input() if task == 1: if course == 'Basics': points = points * 0.08 - (0.2 * (points * 0.08)) elif course == 'Fundamentals': points = points * 0.11 elif course == 'Advanced': points = points * 0.14 + (0.2 * (points * 0.14)) elif ta...
task = int(input()) points = int(input()) course = input() if task == 1: if course == 'Basics': points = points * 0.08 - 0.2 * (points * 0.08) elif course == 'Fundamentals': points = points * 0.11 elif course == 'Advanced': points = points * 0.14 + 0.2 * (points * 0.14) elif task == ...
# Given a number N, print the odd digits in the number(space seperated) or print -1 if there is no odd digit in the given number. number = int(input('')) array = list(str(number)) flag = 0 for digit in range(0, len(array)-1): if(int(array[digit]) % 2 == 0): print(' ', end='') else: print(array...
number = int(input('')) array = list(str(number)) flag = 0 for digit in range(0, len(array) - 1): if int(array[digit]) % 2 == 0: print(' ', end='') else: print(array[digit], end='') flag = flag + 1 if int(array[len(array) - 1]) % 2 == 0: print('', end='') else: print(int(array[le...
t5_generation_config = { "do_sample": True, "num_beams": 2, "repetition_penalty": 5.0, "length_penalty": 1.0, "num_return_sequences": 1, } GPT2_generation_config = { "do_sample": True, "num_beams": 2, "repetition_penalty": 5.0, "length_penalty": 1.0, }
t5_generation_config = {'do_sample': True, 'num_beams': 2, 'repetition_penalty': 5.0, 'length_penalty': 1.0, 'num_return_sequences': 1} gpt2_generation_config = {'do_sample': True, 'num_beams': 2, 'repetition_penalty': 5.0, 'length_penalty': 1.0}
while True: number = int(input('Enter a number: ')) while number != 1: if number % 2 == 0: number //= 2 else: number = number * 3 + 1 print(number) print()
while True: number = int(input('Enter a number: ')) while number != 1: if number % 2 == 0: number //= 2 else: number = number * 3 + 1 print(number) print()
#Conditional if x = 22 y = 100 if y < x: print("This is True, y is not greater than x!") elif y == x: print("This is True, y is greater than x!") else: print("Anything else!") print("Completed")
x = 22 y = 100 if y < x: print('This is True, y is not greater than x!') elif y == x: print('This is True, y is greater than x!') else: print('Anything else!') print('Completed')
#import sys #sys.stdin = open('rectangles.in', 'r') #sys.stdout = open('rectangles.out', 'w') n, m, k = map(int, input().split()) a = [[100000, 0, 100000, 0] for i in range(k)] field = [] for i in range(n): field.append(list(map(int, input().split()))) field.reverse() for i in range(n): for j in range(m): ...
(n, m, k) = map(int, input().split()) a = [[100000, 0, 100000, 0] for i in range(k)] field = [] for i in range(n): field.append(list(map(int, input().split()))) field.reverse() for i in range(n): for j in range(m): if field[i][j] > 0: v = field[i][j] - 1 a[v][0] = min(a[v][0], j)...
def _cc_injected_toolchain_header_library_impl(ctx): hdrs = ctx.files.hdrs transitive_cc_infos = [dep[CcInfo] for dep in ctx.attr.deps] compilation_ctx = cc_common.create_compilation_context(headers = depset(hdrs)) info = cc_common.merge_cc_infos( cc_infos = transitive_cc_infos + [CcInfo(compila...
def _cc_injected_toolchain_header_library_impl(ctx): hdrs = ctx.files.hdrs transitive_cc_infos = [dep[CcInfo] for dep in ctx.attr.deps] compilation_ctx = cc_common.create_compilation_context(headers=depset(hdrs)) info = cc_common.merge_cc_infos(cc_infos=transitive_cc_infos + [cc_info(compilation_context...
# # PySNMP MIB module TRAPEZE-NETWORKS-REGISTRATION-DEVICES-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRAPEZE-NETWORKS-REGISTRATION-DEVICES-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:27:22 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user da...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_constraint, value_range_constraint, constraints_union, single_value_constraint) ...
class Solution: def searchMatrix(self, matrix, target): i = 0 m = len(matrix) while i < m and matrix[i][0] <= target: i = i + 1 i = i - 1 return target in matrix[i] if __name__ == '__main__': matrix = [[1]] target = 1 ans = Solution().searchMatrix(mat...
class Solution: def search_matrix(self, matrix, target): i = 0 m = len(matrix) while i < m and matrix[i][0] <= target: i = i + 1 i = i - 1 return target in matrix[i] if __name__ == '__main__': matrix = [[1]] target = 1 ans = solution().searchMatrix(ma...
# Basic type checking: no types necessary x = 3 x + 'a' def return_type() -> float: return 'a' return_type(9) def argument_type(x: float): return argument_type()
x = 3 x + 'a' def return_type() -> float: return 'a' return_type(9) def argument_type(x: float): return argument_type()
def sudoku(board, rows, columns): return helper(board, 0, 0, columns, rows) def helper(board, r, c, rows, columns): def inbound(r, c): return (0 <= r < rows) and (0 <= c < columns) # Out of bounds: # We filled all blank cells and, thus, a valid solution if not inbound(r, c): return True nr, nc = ...
def sudoku(board, rows, columns): return helper(board, 0, 0, columns, rows) def helper(board, r, c, rows, columns): def inbound(r, c): return 0 <= r < rows and 0 <= c < columns if not inbound(r, c): return True (nr, nc) = next_pos(r, c, rows, columns) if board[r][c] != 0: r...
'''Print multiplication table of given number''' n=int(input("Enter the no:")) print("Multiplication table is:") for i in range(1,11): print(i*n)
"""Print multiplication table of given number""" n = int(input('Enter the no:')) print('Multiplication table is:') for i in range(1, 11): print(i * n)
# CONVERT DB_DATA TO STRING FOR SELF-MESSAGE def format_to_writeable_db_data(db_data: list) -> str: writeable_data = "" for user in db_data: listed_mangoes = "" for manga in user['mangoes']: listed_mangoes += f"{manga}>(u*u)>" writeable_data = f"{writeable_data}{user['name']...
def format_to_writeable_db_data(db_data: list) -> str: writeable_data = '' for user in db_data: listed_mangoes = '' for manga in user['mangoes']: listed_mangoes += f'{manga}>(u*u)>' writeable_data = f"{writeable_data}{user['name']}:{listed_mangoes}\n" return writeable_dat...
class SuperList(list): def __len__(self): return 1000 super_list1 = SuperList() print((len(super_list1))) super_list1.append(5) print(super_list1[0]) print(issubclass(SuperList, list)) # true print(issubclass(list, object))
class Superlist(list): def __len__(self): return 1000 super_list1 = super_list() print(len(super_list1)) super_list1.append(5) print(super_list1[0]) print(issubclass(SuperList, list)) print(issubclass(list, object))
def reverse(SA): reverse = [0] * len(SA) for i in range(len(SA)): reverse[SA[i] - 1] = i + 1 return reverse def prefix_doubling(text, n): '''Computes suffix array using Karp-Miller-Rosenberg algorithm''' text += '$' mapping = {v: i + 1 for i, v in enumerate(sorted(set(text[1:])))} R, k = [mapping[v] ...
def reverse(SA): reverse = [0] * len(SA) for i in range(len(SA)): reverse[SA[i] - 1] = i + 1 return reverse def prefix_doubling(text, n): """Computes suffix array using Karp-Miller-Rosenberg algorithm""" text += '$' mapping = {v: i + 1 for (i, v) in enumerate(sorted(set(text[1:])))} ...
N, M = map(int, input().split()) case = [i for i in range(1, N+1)] disk = [] for _ in range(M): disk.append(int(input())) now = 0 for d in disk: if d == now: continue i = case.index(d) tmp = case[i] case[i] = now now = tmp for c in case: print(c)
(n, m) = map(int, input().split()) case = [i for i in range(1, N + 1)] disk = [] for _ in range(M): disk.append(int(input())) now = 0 for d in disk: if d == now: continue i = case.index(d) tmp = case[i] case[i] = now now = tmp for c in case: print(c)
def maximum(): A = input('Enter the 1st number:') B = input('Enter the 2nd number:') if A > B: print("%d The highest num than %d"%(A,B)) else: print('The highest num is:' ,B) print("Optised max",max(A,B)) def minimum(): A1 = input('Enter the 1st number:') B1 = input('Enter ...
def maximum(): a = input('Enter the 1st number:') b = input('Enter the 2nd number:') if A > B: print('%d The highest num than %d' % (A, B)) else: print('The highest num is:', B) print('Optised max', max(A, B)) def minimum(): a1 = input('Enter the 1st number:') b1 = input('En...
stores = [] command = input() while command != 'END': tokens = command.split('->') store_name = tokens[1] if tokens[0] == 'Add': items = tokens[2].split(',') if len([x for x in stores if x[0] == store_name]) > 0: idx = stores.index([x for x in stores if x[0] == store_name...
stores = [] command = input() while command != 'END': tokens = command.split('->') store_name = tokens[1] if tokens[0] == 'Add': items = tokens[2].split(',') if len([x for x in stores if x[0] == store_name]) > 0: idx = stores.index([x for x in stores if x[0] == store_name][0]) ...
# This is a great place to put your bot's version number. __version__ = "0.1.0" # You'll want to change this. GUILD_ID = 845688627265536010
__version__ = '0.1.0' guild_id = 845688627265536010
#dictionary and for statements with values method linguagens = { 'lea': 'python', 'sara': 'c', 'eddie': 'java', 'phil': 'python', } for linguagem in linguagens.values(): #values method shows us the values of a dictionary print(linguagem.title())
linguagens = {'lea': 'python', 'sara': 'c', 'eddie': 'java', 'phil': 'python'} for linguagem in linguagens.values(): print(linguagem.title())
class EmitterTypeError(Exception): pass class EmitterValidationError(Exception): pass
class Emittertypeerror(Exception): pass class Emittervalidationerror(Exception): pass
class BSTNode(): def __init__(self, Key, Value=None): self.key = Key self.Value = Value self.left = None self.right = None self.parent = None @staticmethod def remove_none(lst): return [x for x in lst if x is not None] def check_BSTNode(self): if...
class Bstnode: def __init__(self, Key, Value=None): self.key = Key self.Value = Value self.left = None self.right = None self.parent = None @staticmethod def remove_none(lst): return [x for x in lst if x is not None] def check_bst_node(self): if...
LSM9DS1_MAG_ADDRESS = 0x1C #Would be 0x1E if SDO_M is HIGH LSM9DS1_ACC_ADDRESS = 0x6A LSM9DS1_GYR_ADDRESS = 0x6A #Would be 0x6B if SDO_AG is HIGH #///////////////////////////////////////// #// LSM9DS1 Accel/Gyro (XL/G) Registers // #///////////////////////////////////////// LSM9DS1_ACT_THS = 0x04 LSM9DS1_ACT...
lsm9_ds1_mag_address = 28 lsm9_ds1_acc_address = 106 lsm9_ds1_gyr_address = 106 lsm9_ds1_act_ths = 4 lsm9_ds1_act_dur = 5 lsm9_ds1_int_gen_cfg_xl = 6 lsm9_ds1_int_gen_ths_x_xl = 7 lsm9_ds1_int_gen_ths_y_xl = 8 lsm9_ds1_int_gen_ths_z_xl = 9 lsm9_ds1_int_gen_dur_xl = 10 lsm9_ds1_reference_g = 11 lsm9_ds1_int1_ctrl = 12 l...
n = int(input('digite um numero: ')) n2 = int(input('digite um numero: ')) def soma (): s = n + n2 print(soma)
n = int(input('digite um numero: ')) n2 = int(input('digite um numero: ')) def soma(): s = n + n2 print(soma)
# noinspection PyUnusedLocal # skus = unicode string def checkout(skus): sd = dict() for sku in skus: if sku in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': if sku in sd: sd[sku] += 1 else: sd[sku] = 1 else: return -1 na = sd.get('A', 0...
def checkout(skus): sd = dict() for sku in skus: if sku in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': if sku in sd: sd[sku] += 1 else: sd[sku] = 1 else: return -1 na = sd.get('A', 0) p = int(na / 5) * 200 na %= 5 p += int(na ...
def test_upgrade_atac_alignment_enrichment_quality_metric_1_2( upgrader, atac_alignment_enrichment_quality_metric_1 ): value = upgrader.upgrade( 'atac_alignment_enrichment_quality_metric', atac_alignment_enrichment_quality_metric_1, current_version='1', target_version='2', ) ...
def test_upgrade_atac_alignment_enrichment_quality_metric_1_2(upgrader, atac_alignment_enrichment_quality_metric_1): value = upgrader.upgrade('atac_alignment_enrichment_quality_metric', atac_alignment_enrichment_quality_metric_1, current_version='1', target_version='2') assert value['schema_version'] == '2' ...
PREVIEW_CHOICES = [ ('slider', 'Slider'), ('pre-order', 'Pre-order'), ('new', 'New'), ('offer', 'Offer'), ('hidden', 'Hidden'), ] CATEGORY_CHOICES = [ ('accesory', 'Accesory'), ('bottom', 'Bottoms'), ('hoodie', 'Hoodies'), ('outerwear', 'Outerwears'), ('sneaker', 'Sneakers'), ...
preview_choices = [('slider', 'Slider'), ('pre-order', 'Pre-order'), ('new', 'New'), ('offer', 'Offer'), ('hidden', 'Hidden')] category_choices = [('accesory', 'Accesory'), ('bottom', 'Bottoms'), ('hoodie', 'Hoodies'), ('outerwear', 'Outerwears'), ('sneaker', 'Sneakers'), ('t-shirt', 'T-Shirts')]
class Estereo: def __init__(self, marca) -> None: self.marca = marca self.estado = 'apagado'
class Estereo: def __init__(self, marca) -> None: self.marca = marca self.estado = 'apagado'
list = [2, 4, 6, 8] sum = 0 for num in list: sum = sum + num print("The sum is:", sum)
list = [2, 4, 6, 8] sum = 0 for num in list: sum = sum + num print('The sum is:', sum)
class RDBMSHost: def __init__(self, host: str, port: int, db_name: str, db_schema: str, db_user: str, db_password: str): self.host: str = host self.port: int = port self.db_name: str = db_name self.db_schema: str = db_schema self.db_user: str = db_user self.db_passwor...
class Rdbmshost: def __init__(self, host: str, port: int, db_name: str, db_schema: str, db_user: str, db_password: str): self.host: str = host self.port: int = port self.db_name: str = db_name self.db_schema: str = db_schema self.db_user: str = db_user self.db_passwo...
grid = [input() for _ in range(323)] width = len(grid[0]) height = len(grid) trees = 0 i, j = 0, 0 while (i := i + 1) < height: j = (j + 3) % width if grid[i][j] == '#': trees += 1 print(trees)
grid = [input() for _ in range(323)] width = len(grid[0]) height = len(grid) trees = 0 (i, j) = (0, 0) while (i := (i + 1)) < height: j = (j + 3) % width if grid[i][j] == '#': trees += 1 print(trees)
def test_root_redirect(client): r_root = client.get("/") assert r_root.status_code == 302 assert r_root.headers["Location"].endswith("/overview/")
def test_root_redirect(client): r_root = client.get('/') assert r_root.status_code == 302 assert r_root.headers['Location'].endswith('/overview/')
'''8. Write a Python program to split a given list into two parts where the length of the first part of the list is given. Original list: [1, 1, 2, 3, 4, 4, 5, 1] Length of the first part of the list: 3 Splited the said list into two parts: ([1, 1, 2], [3, 4, 4, 5, 1]) ''' def split_two_parts(n_list, L): return n...
"""8. Write a Python program to split a given list into two parts where the length of the first part of the list is given. Original list: [1, 1, 2, 3, 4, 4, 5, 1] Length of the first part of the list: 3 Splited the said list into two parts: ([1, 1, 2], [3, 4, 4, 5, 1]) """ def split_two_parts(n_list, L): return (...
n = int(input()) for i in range(n): row, base, number = map(int, input().split()) remains = list() while number > 0: remain = number % base number = number // base remains.append(remain) sumOfRemains = 0 for i in range(len(remains)): remains[i] = remains[i] ** 2 ...
n = int(input()) for i in range(n): (row, base, number) = map(int, input().split()) remains = list() while number > 0: remain = number % base number = number // base remains.append(remain) sum_of_remains = 0 for i in range(len(remains)): remains[i] = remains[i] ** 2 ...
with open("110000.dat","r") as fi: with open("110000num.dat","w") as fo: i=1 for l in fi.readlines(): if i%100 == 0: fo.write(l.strip()+" #"+str(i)+"\n") else: fo.write(l) i = i+1
with open('110000.dat', 'r') as fi: with open('110000num.dat', 'w') as fo: i = 1 for l in fi.readlines(): if i % 100 == 0: fo.write(l.strip() + ' #' + str(i) + '\n') else: fo.write(l) i = i + 1
class Person(object): # This definition hasn't changed from part 1! def __init__(self, fn, ln, em, age, occ): self.firstName = fn self.lastName = ln self.email = em self.age = age self.occupation = occ class Occupation(object): def __init__(self, name, location): self.name = name sel...
class Person(object): def __init__(self, fn, ln, em, age, occ): self.firstName = fn self.lastName = ln self.email = em self.age = age self.occupation = occ class Occupation(object): def __init__(self, name, location): self.name = name self.location = lo...
#!/usr/bin/python3 class Face(object): def __init__(self, bbox, aligned_face_img, confidence, key_points): self._bbox = bbox # [x_min, y_min, x_max, y_max] self._aligned_face_img = aligned_face_img self._confidence = confidence self._key_points = key_points @property ...
class Face(object): def __init__(self, bbox, aligned_face_img, confidence, key_points): self._bbox = bbox self._aligned_face_img = aligned_face_img self._confidence = confidence self._key_points = key_points @property def bbox(self): return self._bbox @property...
start_house, end_house = map(int, input().split()) left_tree, right_tree = map(int, input().split()) number_of_apples, number_of_oranges = map(int, input().split()) apple_distances = map(int, input().split()) orange_distances = map(int, input().split()) apple_count = 0 orange_count = 0 for distance in apple_distances:...
(start_house, end_house) = map(int, input().split()) (left_tree, right_tree) = map(int, input().split()) (number_of_apples, number_of_oranges) = map(int, input().split()) apple_distances = map(int, input().split()) orange_distances = map(int, input().split()) apple_count = 0 orange_count = 0 for distance in apple_dista...
def countInversions(nums): #Our recursive base case, if our list is of size 1 we know there's no inversion and that it's already sorted if len(nums) == 1: return nums, 0 #We run our function recursively on it's left and right halves left, leftInversions = countInversions(nums[:len(nums) // 2]) righ...
def count_inversions(nums): if len(nums) == 1: return (nums, 0) (left, left_inversions) = count_inversions(nums[:len(nums) // 2]) (right, right_inversions) = count_inversions(nums[len(nums) // 2:]) inversions = leftInversions + rightInversions sorted_nums = [] i = j = 0 while i < len...
# find highest grade of an assignment def highest_SRQs_grade(queryset): queryset = queryset.order_by('-assignment', 'SRQs_grade') dict_q = {} for each in queryset: dict_q[each.assignment] = each result = [] for assignment in dict_q.values(): result.append(assignment) return resu...
def highest_sr_qs_grade(queryset): queryset = queryset.order_by('-assignment', 'SRQs_grade') dict_q = {} for each in queryset: dict_q[each.assignment] = each result = [] for assignment in dict_q.values(): result.append(assignment) return result
def f(x): if x: return if x: return elif y: return if x: return else: return if x: return elif y: return else: return if x: return elif y: return elif z: return else: return ...
def f(x): if x: return if x: return elif y: return if x: return else: return if x: return elif y: return else: return if x: return elif y: return elif z: return else: return ...
# Iterative approach using stack # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: ...
class Solution: def merge_trees(self, root1: TreeNode, root2: TreeNode) -> TreeNode: if root1 == None: return root2 stack = [] stack.append([root1, root2]) while stack: node = stack.pop() if node[0] == None or node[1] == None: cont...
# 26.05.2019 # Working with BitwiseOperators and different kind of String Outputs. print(f"Working with Bitwise Operators and different kind of String Outputs.") var1 = 13 # 13 in Binary: 1101 var2 = 5 # 5 in Binary: 0101 # AND Operator with format String # 1101 13 # 0101 5 # ---- A...
print(f'Working with Bitwise Operators and different kind of String Outputs.') var1 = 13 var2 = 5 print('AND & Operator {}'.format(var1 & var2)) print(f'OR | operator {var1 | var2}') print('XOR ^ operator %d' % (var1 ^ var2)) print('Left Shift << operator {}'.format(var1 << 1)) print(f'Right Shift >> operator {var1 >> ...
class Solution: def numTilings(self, n: int) -> int: MOD = 1000000007 if n <= 2: return n previous = 1 result = 2 current = 1 for k in range(3, n + 1): tmp = result result = (result + previous + 2 * current) % MOD curren...
class Solution: def num_tilings(self, n: int) -> int: mod = 1000000007 if n <= 2: return n previous = 1 result = 2 current = 1 for k in range(3, n + 1): tmp = result result = (result + previous + 2 * current) % MOD curr...
# 4. Caesar Cipher # Write a program that returns an encrypted version of the same text. # Encrypt the text by shifting each character with three positions forward. # For example A would be replaced by D, B would become E, and so on. Print the encrypted text. text = input() encrypted_text = [chr(ord(character) + 3) ...
text = input() encrypted_text = [chr(ord(character) + 3) for character in text] print(''.join(encrypted_text))
ies = [] ies.append({ "ie_type" : "Node ID", "ie_value" : "Node ID", "presence" : "M", "instance" : "0", "comment" : "This IE shall contain the unique identifier of the sending Node."}) ies.append({ "ie_type" : "F-SEID", "ie_value" : "CP F-SEID", "presence" : "M", "instance" : "0", "comment" : "This IE shall contain th...
ies = [] ies.append({'ie_type': 'Node ID', 'ie_value': 'Node ID', 'presence': 'M', 'instance': '0', 'comment': 'This IE shall contain the unique identifier of the sending Node.'}) ies.append({'ie_type': 'F-SEID', 'ie_value': 'CP F-SEID', 'presence': 'M', 'instance': '0', 'comment': 'This IE shall contain the unique ide...
# https://www.codechef.com/problems/MISSP for T in range(int(input())): a=[] for n in range(int(input())): k=int(input()) if(k not in a): a.append(k) else: a.remove(k) print(a[0])
for t in range(int(input())): a = [] for n in range(int(input())): k = int(input()) if k not in a: a.append(k) else: a.remove(k) print(a[0])
def check_subtree(t2, t1): if t1 is None or t2 is None: return False if t1.val == t2.val: # potential subtree if subtree_equality(t2, t1): return True return check_subtree(t2, t1.left) or check_subtree(t2, t1.right) def subtree_equality(t2, t1): if t2 is None and t1 is Non...
def check_subtree(t2, t1): if t1 is None or t2 is None: return False if t1.val == t2.val: if subtree_equality(t2, t1): return True return check_subtree(t2, t1.left) or check_subtree(t2, t1.right) def subtree_equality(t2, t1): if t2 is None and t1 is None: return True...
# Sky Jewel box (2002016) | Treasure Room of Queen (926000010) eleska = 3935 skyJewel = 4031574 reactor.incHitCount() if reactor.getHitCount() >= 3: if sm.hasQuest(eleska) and not sm.hasItem(skyJewel): sm.dropItem(skyJewel, sm.getPosition(objectID).getX(), sm.getPosition(objectID).getY()) sm.removeReactor()
eleska = 3935 sky_jewel = 4031574 reactor.incHitCount() if reactor.getHitCount() >= 3: if sm.hasQuest(eleska) and (not sm.hasItem(skyJewel)): sm.dropItem(skyJewel, sm.getPosition(objectID).getX(), sm.getPosition(objectID).getY()) sm.removeReactor()
a[-1] a[-2:] a[:-2] a[::-1] a[1::-1] a[:-3:-1] a[-3::-1] point_coords = coords[i, :] main(sys.argv[1:])
a[-1] a[-2:] a[:-2] a[::-1] a[1::-1] a[:-3:-1] a[-3::-1] point_coords = coords[i, :] main(sys.argv[1:])
''' for a in range(3,1000): for b in range(a+1,999): csquared= a**2+b**2 c=csquared**0.5 if a+b+c==1000: product= a*b*c print(product) print(c) break ''' def compute(): PERIMETER = 1000 for a in range(1, PERIMETER + 1): for b in range(a + 1...
""" for a in range(3,1000): for b in range(a+1,999): csquared= a**2+b**2 c=csquared**0.5 if a+b+c==1000: product= a*b*c print(product) print(c) break """ def compute(): perimeter = 1000 for a in range(1, PERIMETER + 1): for b i...
# Language: Python # Level: 8kyu # Name of Problem: DNA to RNA Conversion # Instructions: Deoxyribonucleic acid, DNA is the primary information storage molecule in biological systems. # It is composed of four nucleic acid bases Guanine ('G'), Cytosine ('C'), Adenine ('A'), and Thymine ('T'). # Ribonucleic acid, RNA, ...
def dn_ato_rna(dna): return dna.replace('T', 'U')
data = ( 'Kay ', # 0x00 'Kayng ', # 0x01 'Ke ', # 0x02 'Ko ', # 0x03 'Kol ', # 0x04 'Koc ', # 0x05 'Kwi ', # 0x06 'Kwi ', # 0x07 'Kyun ', # 0x08 'Kul ', # 0x09 'Kum ', # 0x0a 'Na ', # 0x0b 'Na ', # 0x0c 'Na ', # 0x0d 'La ', # 0x0e 'Na ', # 0x0f 'Na ', ...
data = ('Kay ', 'Kayng ', 'Ke ', 'Ko ', 'Kol ', 'Koc ', 'Kwi ', 'Kwi ', 'Kyun ', 'Kul ', 'Kum ', 'Na ', 'Na ', 'Na ', 'La ', 'Na ', 'Na ', 'Na ', 'Na ', 'Na ', 'Nak ', 'Nak ', 'Nak ', 'Nak ', 'Nak ', 'Nak ', 'Nak ', 'Nan ', 'Nan ', 'Nan ', 'Nan ', 'Nan ', 'Nan ', 'Nam ', 'Nam ', 'Nam ', 'Nam ', 'Nap ', 'Nap ', 'Nap ', ...
class Sol(object): def __init__(self): self.suc = None def in_order(self, head, num): if not head: return None int = [] def helper(head): nonlocal int if head: self.helper(head.left) int.append(head.val) ...
class Sol(object): def __init__(self): self.suc = None def in_order(self, head, num): if not head: return None int = [] def helper(head): nonlocal int if head: self.helper(head.left) int.append(head.val) ...
# OpenWeatherMap API Key weather_api_key = "Insert your own key" # Google API Key g_key = "Insert your own key"
weather_api_key = 'Insert your own key' g_key = 'Insert your own key'
class Solution: def countGoodSubstrings(self, s: str) -> int: count, i, end = 0, 2, len(s) while i < end: a, b, c = s[i-2], s[i-1], s[i] if a == b == c: i += 2 continue count += a != b and b != c and a != c i += 1 ...
class Solution: def count_good_substrings(self, s: str) -> int: (count, i, end) = (0, 2, len(s)) while i < end: (a, b, c) = (s[i - 2], s[i - 1], s[i]) if a == b == c: i += 2 continue count += a != b and b != c and (a != c) ...
( XL_CELL_EMPTY, #0 XL_CELL_TEXT, #1 XL_CELL_NUMBER, #2 XL_CELl_DATE, #3 XL_CELL_BOOLEAN,#4 XL_CELL_ERROR, #5 XL_CELL_BLANK, #6 ) = range(7) ctype_text = { XL_CELL_EMPTY: 'empty', XL_CELL_TEXT:'text', XL_CELL_NUMBER:'number', XL_CELl_DATE:'date', XL_CELL_BOOLEAN:'...
(xl_cell_empty, xl_cell_text, xl_cell_number, xl_ce_ll_date, xl_cell_boolean, xl_cell_error, xl_cell_blank) = range(7) ctype_text = {XL_CELL_EMPTY: 'empty', XL_CELL_TEXT: 'text', XL_CELL_NUMBER: 'number', XL_CELl_DATE: 'date', XL_CELL_BOOLEAN: 'boolean', XL_CELL_ERROR: 'error', XL_CELL_BLANK: 'blank'}
def sum6(n): nums = [i for i in range(1, n + 1)] return sum(nums) N = 10 S = sum6(N) print(S)
def sum6(n): nums = [i for i in range(1, n + 1)] return sum(nums) n = 10 s = sum6(N) print(S)
def solve(): s = sum((x ** x for x in range(1, 1001))) print(str(s)[-10:]) if __name__ == '__main__': solve()
def solve(): s = sum((x ** x for x in range(1, 1001))) print(str(s)[-10:]) if __name__ == '__main__': solve()
listaDePalavras = ('Aprender','Programar','Linguagem','Python','Curso','Gratis', 'Estudar','Praticar','Trabalhar','Mercado','Programador', 'Futuro') for palavras in listaDePalavras: print(f'\n A palavra {palavras} temos', end=' ') for letras in palavras: if letras.l...
lista_de_palavras = ('Aprender', 'Programar', 'Linguagem', 'Python', 'Curso', 'Gratis', 'Estudar', 'Praticar', 'Trabalhar', 'Mercado', 'Programador', 'Futuro') for palavras in listaDePalavras: print(f'\n A palavra {palavras} temos', end=' ') for letras in palavras: if letras.lower() in 'aeiou': ...
x = 1 y = 'Hello' z = 10.123 d = x + z print(d) print(type(x)) print(type(y)) print(y.upper()) print(y.lower()) print(type(z)) a = [1,2,3,4,5,6,6,7,8] print(len(a)) print(a.count(6)) b = list(range(10,100,10)) print(b) stud_marks = {"Madhan":90, "Raj":25,"Mani":80} print(stud_marks.keys()) print(stud_marks.va...
x = 1 y = 'Hello' z = 10.123 d = x + z print(d) print(type(x)) print(type(y)) print(y.upper()) print(y.lower()) print(type(z)) a = [1, 2, 3, 4, 5, 6, 6, 7, 8] print(len(a)) print(a.count(6)) b = list(range(10, 100, 10)) print(b) stud_marks = {'Madhan': 90, 'Raj': 25, 'Mani': 80} print(stud_marks.keys()) print(stud_mark...
# Generate .travis.yml automatically # Configuration for Linux configs = [ # OS, OS version, compiler, build type, task ("ubuntu", "18.04", "gcc", "DefaultDebug", "Test"), ("ubuntu", "18.04", "gcc", "DefaultRelease", "Test"), ("debian", "9", "gcc", "DefaultDebug", "Test"), ("debian", "9", "gcc", "D...
configs = [('ubuntu', '18.04', 'gcc', 'DefaultDebug', 'Test'), ('ubuntu', '18.04', 'gcc', 'DefaultRelease', 'Test'), ('debian', '9', 'gcc', 'DefaultDebug', 'Test'), ('debian', '9', 'gcc', 'DefaultRelease', 'Test'), ('debian', '10', 'gcc', 'DefaultDebug', 'Test'), ('debian', '10', 'gcc', 'DefaultRelease', 'Test'), ('ubu...
######################### # # # Developer: Luis Regus # # Date: 11/24/15 # # # ######################### NORTH = "north" EAST = "east" SOUTH = "south" WEST = "west" class Robot: ''' Custom object used to represent a robot ''' def __init__(self, ...
north = 'north' east = 'east' south = 'south' west = 'west' class Robot: """ Custom object used to represent a robot """ def __init__(self, direction=NORTH, x_coord=0, y_coord=0): self.coordinates = (x_coord, y_coord) self.bearing = direction def turn_right(self): dire...
class ToolBoxBaseException(Exception): status_code = 500 error_name = 'base_exception' def __init__(self, message): self.message = message def to_dict(self): return dict(error_name=self.error_name, message=self.message) class UnknownError(ToolBoxBaseException): status_code = 500 ...
class Toolboxbaseexception(Exception): status_code = 500 error_name = 'base_exception' def __init__(self, message): self.message = message def to_dict(self): return dict(error_name=self.error_name, message=self.message) class Unknownerror(ToolBoxBaseException): status_code = 500 ...
''' lab 8 functions ''' #3.1 def count_words(input_str): return len(input_str.split()) #print(count_words('This is a string')) #3.2 demo_str = 'Hello World!' print(count_words(demo_str)) #3.3 def find_min(num_list): min_item = num_list[0] for num in num_list: if type(num) is not str: ...
""" lab 8 functions """ def count_words(input_str): return len(input_str.split()) demo_str = 'Hello World!' print(count_words(demo_str)) def find_min(num_list): min_item = num_list[0] for num in num_list: if type(num) is not str: if min_item >= num: min_item = num r...
users = { 'name': 'Elena', 'age': 100, 'town': 'Varna' } for key, value in users.items(): print(key, value) for key in users.keys(): print(key) for value in users.values(): print(value)
users = {'name': 'Elena', 'age': 100, 'town': 'Varna'} for (key, value) in users.items(): print(key, value) for key in users.keys(): print(key) for value in users.values(): print(value)
class Solution: def getSum(self, a: int, b: int) -> int: # 32 bits integer max and min MAX = 0x7FFFFFFF MIN = 0x80000000 mask = 0xFFFFFFFF while b != 0: carry = a & b a, b = (a ^ b) & mask, (carry << 1) & mask ret...
class Solution: def get_sum(self, a: int, b: int) -> int: max = 2147483647 min = 2147483648 mask = 4294967295 while b != 0: carry = a & b (a, b) = ((a ^ b) & mask, carry << 1 & mask) return a if a <= MAX else ~(a ^ mask)
CONFIG = { "main_dir": "./tests/", "results_dir": "results/", "manips_dir": "manips/", "parameters_dir": "parameters/", "tikz_dir": "tikz/" }
config = {'main_dir': './tests/', 'results_dir': 'results/', 'manips_dir': 'manips/', 'parameters_dir': 'parameters/', 'tikz_dir': 'tikz/'}
stack = [] while True: print("1. Insert Element in the stack") print("2. Remove element from stack") print("3. Display elements in stack") print("4. Exit") choice = int(input("Enter your Choice: ")) if choice == 1: if len(stack) == 5: print("Sorry, stack is already full")...
stack = [] while True: print('1. Insert Element in the stack') print('2. Remove element from stack') print('3. Display elements in stack') print('4. Exit') choice = int(input('Enter your Choice: ')) if choice == 1: if len(stack) == 5: print('Sorry, stack is already full') ...
# Operations on Sets ? # Consider the following set: S = {1,8,2,3} # Len(s) : Returns 4, the length of the set S = {1,8,2,3} print(len(S)) #Length of the Set # remove(8) : Updates the set S and removes 8 from S S = {1,8,2,3} S.remove(8) #Remove of the Set print(S) # pop() : Removes an arbitrary element fro...
s = {1, 8, 2, 3} s = {1, 8, 2, 3} print(len(S)) s = {1, 8, 2, 3} S.remove(8) print(S) s = {1, 8, 2, 3} print(S.pop()) s = {1, 8, 2, 3} print(S.clear()) s = {1, 8, 2, 3} print(S.union()) s = {1, 8, 2, 3} print(S.intersection())
idade = str(input("idade :")) if not idade.isnumeric(): print("oi") else: print("passou")
idade = str(input('idade :')) if not idade.isnumeric(): print('oi') else: print('passou')