content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Solution: # my solution def removeDuplicates(self, nums: List[int]) -> int: i = 1 # while i < len(nums): for j in range(len(nums)-1): if nums[j] != nums[j+1]: nums[i] = nums[j+1] i += 1 return i
class Solution: def remove_duplicates(self, nums: List[int]) -> int: i = 1 for j in range(len(nums) - 1): if nums[j] != nums[j + 1]: nums[i] = nums[j + 1] i += 1 return i
load("@io_bazel_rules_docker//container:providers.bzl", "PushInfo") def _run_deployment_impl(ctx): registry = ctx.attr.image_push[PushInfo].registry repository = ctx.attr.image_push[PushInfo].repository image = "%s/%s" % (registry, repository) deploy_deps_string = "\n".join([ label[DefaultInfo...
load('@io_bazel_rules_docker//container:providers.bzl', 'PushInfo') def _run_deployment_impl(ctx): registry = ctx.attr.image_push[PushInfo].registry repository = ctx.attr.image_push[PushInfo].repository image = '%s/%s' % (registry, repository) deploy_deps_string = '\n'.join([label[DefaultInfo].files_to...
""" SPIFlash.py Contains code needed to emulate SPI flash memory. Copyright (c) 2018, wchill All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above c...
""" SPIFlash.py Contains code needed to emulate SPI flash memory. Copyright (c) 2018, wchill All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above c...
class Solution: def trap(self, height: List[int]) -> int: if not height: return 0 s = [] result = 0 for i in range(len(height)): while s and height[i] > height[s[-1]]: top = s.pop() if not s: break distance = i - s[-1] - ...
class Solution: def trap(self, height: List[int]) -> int: if not height: return 0 s = [] result = 0 for i in range(len(height)): while s and height[i] > height[s[-1]]: top = s.pop() if not s: break ...
""" Search in a rotated sorted array - Distinct There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1]...
""" Search in a rotated sorted array - Distinct There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1]...
def test_i8(): i: i8 i = 5 print(i) def test_i16(): i: i16 i = 4 print(i) def test_i32(): i: i32 i = 3 print(i) def test_i64(): i: i64 i = 2 print(i)
def test_i8(): i: i8 i = 5 print(i) def test_i16(): i: i16 i = 4 print(i) def test_i32(): i: i32 i = 3 print(i) def test_i64(): i: i64 i = 2 print(i)
class MyQueue: def __init__(self): self.queue = [] self.behind = -1 self.front = -1 def push(self, x: int) -> None: self.queue.append(x) self.behind = self.behind + 1 def pop(self) -> int: popResult = self.queue.pop(0) self.front = self.front + 1 ...
class Myqueue: def __init__(self): self.queue = [] self.behind = -1 self.front = -1 def push(self, x: int) -> None: self.queue.append(x) self.behind = self.behind + 1 def pop(self) -> int: pop_result = self.queue.pop(0) self.front = self.front + 1 ...
def age_assignment(*args, **kwargs): result = {} for n in args: result[n] = kwargs[n[0]] return result
def age_assignment(*args, **kwargs): result = {} for n in args: result[n] = kwargs[n[0]] return result
hrs = input("Enter Hours:") h = float(hrs) rate = input("Enter rate: ") r = float(rate) if h <= 40: pay = h * r else: pay = r * 40 + (r * 1.5) * (h - 40) print(pay)
hrs = input('Enter Hours:') h = float(hrs) rate = input('Enter rate: ') r = float(rate) if h <= 40: pay = h * r else: pay = r * 40 + r * 1.5 * (h - 40) print(pay)
f = open("/home/gangserver/dev/data/new.txt", 'r') while True: line = f.readline() if not line: break print(line) f.close() print("*" * 30) f = open("/home/gangserver/dev/data/new.txt", 'r') lines = f.readlines() for line in lines: print(line) f.close() print("*" * 30) f = open("/home/gangserver/dev...
f = open('/home/gangserver/dev/data/new.txt', 'r') while True: line = f.readline() if not line: break print(line) f.close() print('*' * 30) f = open('/home/gangserver/dev/data/new.txt', 'r') lines = f.readlines() for line in lines: print(line) f.close() print('*' * 30) f = open('/home/gangserver...
s = input() answer = [] for e in s: if not e in ["a", "i", "u", "e", "o"]: answer.append(e) print("".join(answer))
s = input() answer = [] for e in s: if not e in ['a', 'i', 'u', 'e', 'o']: answer.append(e) print(''.join(answer))
#inheritance class Employee: def __init__(self): self.__id=10 self._name="ABC" self.salary=100 class Student(Employee): def Display(self): #print(self.__id) unavailable to object print(self._name) print(self.salary) ob=Student() ob.Display() print(ob...
class Employee: def __init__(self): self.__id = 10 self._name = 'ABC' self.salary = 100 class Student(Employee): def display(self): print(self._name) print(self.salary) ob = student() ob.Display() print(ob._name, ob.salary)
""" Date: 06/06/2021 Name: Rio Weil Title: errors.py Description: Custom errors for project. """ """ Base class for other exceptions """ class Error(Exception): pass """ Error raised when initializing board with zero space or bombs """ class ZeroException(Error): pass """ Error raised when more bombs than po...
""" Date: 06/06/2021 Name: Rio Weil Title: errors.py Description: Custom errors for project. """ '\nBase class for other exceptions\n' class Error(Exception): pass '\nError raised when initializing board with zero space or bombs\n' class Zeroexception(Error): pass '\nError raised when more bombs than possible...
#Slicing Strings """ b = "hello, word!" print(b[2:5]) """ """ b = "hello, word!" print(b[2:5]) """ """ b = "hello, word!" print(b[2:]) """ b = "hello, word!" print(b[-5:-2])
""" b = "hello, word!" print(b[2:5]) """ '\nb = "hello, word!"\nprint(b[2:5])\n' '\nb = "hello, word!"\nprint(b[2:])\n' b = 'hello, word!' print(b[-5:-2])
""" A function which formats a duration, given as a number of seconds, in a human-friendly way. """ # Created by Egor Kostan. # GitHub: https://github.com/ikostan # LinkedIn: https://www.linkedin.com/in/egor-kostan/ def format_duration(seconds: int) -> str: """ A function which formats a duration, given a...
""" A function which formats a duration, given as a number of seconds, in a human-friendly way. """ def format_duration(seconds: int) -> str: """ A function which formats a duration, given as a number of seconds, in a human-friendly way. The resulting expression is made of components like 4 seconds, ...
def normalize(state): temp_state = [] temp_state.append(0.001*state[0]) temp_state.append((state[1]-2478330.0752)/188151.0787) temp_state.append((state[2]-9696.347622)/14234.47008) temp_state.append((state[3]-2515.821571)/2615.29795) temp_state.append(0.01*state[4]) temp_state.append(0.01*st...
def normalize(state): temp_state = [] temp_state.append(0.001 * state[0]) temp_state.append((state[1] - 2478330.0752) / 188151.0787) temp_state.append((state[2] - 9696.347622) / 14234.47008) temp_state.append((state[3] - 2515.821571) / 2615.29795) temp_state.append(0.01 * state[4]) temp_stat...
#!/usr/bin/env python3 inp = "(((())))()((((((((())()(()))(()((((()(()(((()((()((()(()()()()()))(((()(()((((((((((())(()()((())()(((())))()(()(()((()(()))(()()()()((()((()(((()()(((((((()()())()((((()()(((((()(())()(())((())()()))()(((((((())(()())(()(((())(()))((())))(()((()())))()())((((())))(()(((((()(())(((()()(((...
inp = '(((())))()((((((((())()(()))(()((((()(()(((()((()((()(()()()()()))(((()(()((((((((((())(()()((())()(((())))()(()(()((()(()))(()()()()((()((()(((()()(((((((()()())()((((()()(((((()(())()(())((())()()))()(((((((())(()())(()(((())(()))((())))(()((()())))()())((((())))(()(((((()(())(((()()((()((()((((((((((())(()())...
# -*- coding: utf-8 -*- """ exceptions in xalpha packages """ class XalphaException(Exception): pass class FundTypeError(XalphaException): """ The code mismatches the fund type obj, fundinfo/mfundinfo """ pass class FundNotExistError(XalphaException): """ There is no fund with given c...
""" exceptions in xalpha packages """ class Xalphaexception(Exception): pass class Fundtypeerror(XalphaException): """ The code mismatches the fund type obj, fundinfo/mfundinfo """ pass class Fundnotexisterror(XalphaException): """ There is no fund with given code """ pass class ...
INPUT_DIR = "/mnt/input" OUTPUT_DIR = "/mnt/output" CONFIG_FILE_NAME = 'config.yml' CONFIG_SECTION = 'fc_survival_svm'
input_dir = '/mnt/input' output_dir = '/mnt/output' config_file_name = 'config.yml' config_section = 'fc_survival_svm'
if __name__ == '__main__': for _ in range(int(input())): a = int(input()) A = set(map(int,input().split())) b = int(input()) B = set(map(int,input().split())) # if len(A-B) == 0: # print(True) # else: # print(False) # print(not bool(A.difference(B))) # print( A.intersection(B) == A) pr...
if __name__ == '__main__': for _ in range(int(input())): a = int(input()) a = set(map(int, input().split())) b = int(input()) b = set(map(int, input().split())) print(A.issubset(B))
class Node: def __init__(self, val): self.val = val self.next = None class SinglyLinkedList: def __init__(self): self.head = None def add(self, val): curNode = self.head while(curNode.next != None): curNode = curNode.next curNode.next = Node(val)...
class Node: def __init__(self, val): self.val = val self.next = None class Singlylinkedlist: def __init__(self): self.head = None def add(self, val): cur_node = self.head while curNode.next != None: cur_node = curNode.next curNode.next = node(v...
"""Rules for StringTemplate 4.""" def _impl(ctx): if not ctx.attr.controller and not ctx.attr.data and not ctx.attr.json: fail("Missing template data. Provide at least one of \"controller\", \"data\" or \"json\" attributes.") output = ctx.actions.declare_file(ctx.attr.out) deps = depset(transitive...
"""Rules for StringTemplate 4.""" def _impl(ctx): if not ctx.attr.controller and (not ctx.attr.data) and (not ctx.attr.json): fail('Missing template data. Provide at least one of "controller", "data" or "json" attributes.') output = ctx.actions.declare_file(ctx.attr.out) deps = depset(transitive=[d...
# Reversing linked list. class Node: def __init__(self, cargo=None, next=None): self.cargo = cargo self.next = next def __str__(self): return str(self.cargo) class SimpleLinkedList: def __init__(self, init_values=[]): self.length = 0 self.head = None if ...
class Node: def __init__(self, cargo=None, next=None): self.cargo = cargo self.next = next def __str__(self): return str(self.cargo) class Simplelinkedlist: def __init__(self, init_values=[]): self.length = 0 self.head = None if len(init_values) > 0: ...
''' Facebook error classes also see http://fbdevwiki.com/wiki/Error_codes#User_Permission_Errors ''' class OpenFacebookException(Exception): ''' BaseClass for all open facebook errors ''' @classmethod def codes_list(cls): ''' Returns the codes as a list of instructions ''...
""" Facebook error classes also see http://fbdevwiki.com/wiki/Error_codes#User_Permission_Errors """ class Openfacebookexception(Exception): """ BaseClass for all open facebook errors """ @classmethod def codes_list(cls): """ Returns the codes as a list of instructions """ ...
def add_native_methods(clazz): def SCardEstablishContext__int__(a0): raise NotImplementedError() def SCardListReaders__long__(a0): raise NotImplementedError() def SCardConnect__long__java_lang_String__int__int__(a0, a1, a2, a3): raise NotImplementedError() def SCardTransmit__l...
def add_native_methods(clazz): def s_card_establish_context__int__(a0): raise not_implemented_error() def s_card_list_readers__long__(a0): raise not_implemented_error() def s_card_connect__long__java_lang__string__int__int__(a0, a1, a2, a3): raise not_implemented_error() def ...
def check_ticket(char, string, integer): if integer == 20: print(f'ticket "{string}" - {integer/2:.0f}{char} Jackpot!') return True left_part = string[:10] right_part = string[10:] is_found = False left_counter = 0 right_counter = 0 for el in left_part: # 2 "for" ...
def check_ticket(char, string, integer): if integer == 20: print(f'ticket "{string}" - {integer / 2:.0f}{char} Jackpot!') return True left_part = string[:10] right_part = string[10:] is_found = False left_counter = 0 right_counter = 0 for el in left_part: if el == cha...
""" We need to divide our data set Get a pivot point recursively sort each half of the array """ def particion(arr, low, high): i = (low-1) pivot = arr[high] for j in range(low, high): if arr[j]<= pivot: i = i+1 arr[i], arr[j] = arr[j], arr[i] arr[i+1], arr[high] = arr[high], arr...
""" We need to divide our data set Get a pivot point recursively sort each half of the array """ def particion(arr, low, high): i = low - 1 pivot = arr[high] for j in range(low, high): if arr[j] <= pivot: i = i + 1 (arr[i], arr[j]) = (arr[j], arr[i]) (arr[i + 1], arr[hig...
# Time: O(nlogn) # Space: O(1) # 1231 biweekly contest 11 10/19/2019 # You have one chocolate bar that consists of some chunks. Each chunk has its own sweetness given by the array sweetness. # # You want to share the chocolate with your K friends so you start cutting the chocolate bar into K+1 pieces using # K cuts, ...
class Solution(object): def maximize_sweetness(self, sweetness, K): """ :type sweetness: List[int] :type K: int :rtype: int """ def check(K, x): (curr, cuts) = (0, 0) for s in sweetness: curr += s if curr >= x:...
class BaseModelConfig(object): scheduler: dict concurrency_limiter: dict early_stopping: dict score_function: dict reporter: dict tune_best_trial: dict stopper: dict tune_run: dict optuna_search: dict = {} # used for creating groups during train/val split in hp optimizat...
class Basemodelconfig(object): scheduler: dict concurrency_limiter: dict early_stopping: dict score_function: dict reporter: dict tune_best_trial: dict stopper: dict tune_run: dict optuna_search: dict = {} essential_properties: list model_setup: dict transformer_specs: li...
""" Generated Loss CLI parsers """ def binary_crossentropyConfig(argument_parser): """ Set CLI arguments :param argument_parser: argument parser :type argument_parser: ```ArgumentParser``` :returns: argument_parser :rtype: ```ArgumentParser``` """ argument_parser.description = """Com...
""" Generated Loss CLI parsers """ def binary_crossentropy_config(argument_parser): """ Set CLI arguments :param argument_parser: argument parser :type argument_parser: ```ArgumentParser``` :returns: argument_parser :rtype: ```ArgumentParser``` """ argument_parser.description = 'Compu...
name = input() def foo(name): print("Hello, world! Hello, "+name) foo(name)
name = input() def foo(name): print('Hello, world! Hello, ' + name) foo(name)
""" Problem 3: What is the largest prime factor of the number 600851475143 ? """ def is_prime(n): for i in range(2, n // 2 + 1): if n % 2 == 0: return False return True class Prime: def __init__(self): self.curr = 1 def __next__(self): new_next = self.cur...
""" Problem 3: What is the largest prime factor of the number 600851475143 ? """ def is_prime(n): for i in range(2, n // 2 + 1): if n % 2 == 0: return False return True class Prime: def __init__(self): self.curr = 1 def __next__(self): new_next = self.curr...
n = int(input()) flag = True if n == 1 or n == 2: flag = True if n % 2 == 0: flag = False else: i = 3 while i*i <= n: if n % i == 0: flag = False break i += 2 if flag == True: print("N") else: print("S")
n = int(input()) flag = True if n == 1 or n == 2: flag = True if n % 2 == 0: flag = False else: i = 3 while i * i <= n: if n % i == 0: flag = False break i += 2 if flag == True: print('N') else: print('S')
def greet(val): return 'Hello, ' + val + '!' print(greet('pah'))
def greet(val): return 'Hello, ' + val + '!' print(greet('pah'))
# import libraries here ... model = """ data { int<lower=0> K; // Number of cluster int<lower=0> N; // Number of observations real y[N]; // observations real<lower=0> alpha_shape; real<lower=0> alpha_rate; real<lower=0> sigma_shape; real<lower=0> sigma_rate; } parameters { real mu[K]; // cluster me...
model = '\ndata {\n int<lower=0> K; // Number of cluster\n int<lower=0> N; // Number of observations\n real y[N]; // observations\n real<lower=0> alpha_shape;\n real<lower=0> alpha_rate;\n real<lower=0> sigma_shape;\n real<lower=0> sigma_rate;\n}\n\nparameters {\n real mu[K]; // cluster means\n // real <low...
class MyCircularQueue: def __init__(self, k): """ Initialize your data structure here. Set the size of the queue to be k. """ self.q = [None] * (k+1) self.front, self.rear = -1, -1 def enQueue(self, value): """ Insert an element into the circular queue. ...
class Mycircularqueue: def __init__(self, k): """ Initialize your data structure here. Set the size of the queue to be k. """ self.q = [None] * (k + 1) (self.front, self.rear) = (-1, -1) def en_queue(self, value): """ Insert an element into the circular ...
class Events: ALWAYS = "ALWAYS" ON_LOGIN = "ON_LOGIN" ON_ITEM_DONE = "ON_ITEM_DONE"
class Events: always = 'ALWAYS' on_login = 'ON_LOGIN' on_item_done = 'ON_ITEM_DONE'
# # PySNMP MIB module HM2-DNS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HM2-DNS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:18:37 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 0...
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, value_size_constraint, constraints_intersection, single_value_constraint, constraints_union) ...
"""Exceptions when there is a problem with a call to the LBRY daemons.""" def print_request(request): """Print a prepared request to give the user info as to what they're sending. :param request.PreparedRequest request: PreparedRequest object to be printed :return: Nothing """ start = "----------...
"""Exceptions when there is a problem with a call to the LBRY daemons.""" def print_request(request): """Print a prepared request to give the user info as to what they're sending. :param request.PreparedRequest request: PreparedRequest object to be printed :return: Nothing """ start = '-----------...
class Node: def __init__(self,key): self.key = key self.parent = None self.right = None self.left = None class Tree: def __init__(self): self.root = None self.node = Node(self.root) self.find_node = None def add(self,key): if (self.root ==...
class Node: def __init__(self, key): self.key = key self.parent = None self.right = None self.left = None class Tree: def __init__(self): self.root = None self.node = node(self.root) self.find_node = None def add(self, key): if self.root ==...
if __name__ == '__main__': with open('train.csv', 'w') as f: for i in range(1, 451): f.write(f'/workspace/data/VCTK-Corpus/wav48/p239/p239_{i:03d}.wav,/workspace/data/VCTK-Corpus/txt/p239/p239_{i:03d}.txt\n') with open('val.csv', 'w') as f: for i in range(451, 476): f.write(f'/workspace/data/VCTK-Corpus/w...
if __name__ == '__main__': with open('train.csv', 'w') as f: for i in range(1, 451): f.write(f'/workspace/data/VCTK-Corpus/wav48/p239/p239_{i:03d}.wav,/workspace/data/VCTK-Corpus/txt/p239/p239_{i:03d}.txt\n') with open('val.csv', 'w') as f: for i in range(451, 476): f.wri...
number = int(input()) for a in range(1, 9 + 1): for b in range(1, 9 + 1): for c in range(1, 9 + 1): for d in range(1, 9 + 1): if a + b == c + d and number % (a +b) == 0: print('{0}{1}{2}{3}'.format(a, b, c, d), end=" ")
number = int(input()) for a in range(1, 9 + 1): for b in range(1, 9 + 1): for c in range(1, 9 + 1): for d in range(1, 9 + 1): if a + b == c + d and number % (a + b) == 0: print('{0}{1}{2}{3}'.format(a, b, c, d), end=' ')
class DataProcessor(object): def get_train_examples(self, data_dir): raise NotImplementedError() def get_dev_examples(self, data_dir): raise NotImplementedError() def get_test_examples(self, data_dir, data_file_name): raise NotImplementedError() def get_labels(self): ...
class Dataprocessor(object): def get_train_examples(self, data_dir): raise not_implemented_error() def get_dev_examples(self, data_dir): raise not_implemented_error() def get_test_examples(self, data_dir, data_file_name): raise not_implemented_error() def get_labels(self): ...
"""Same name 2.0 This program has only one variable. Attributes: eggs (str): String denoting global variable. """ eggs = 'global' def spam() -> None: """Spam Reassigns global variable called eggs. Returns: None. """ global eggs eggs = 'spam' #: Reassign global variable. de...
"""Same name 2.0 This program has only one variable. Attributes: eggs (str): String denoting global variable. """ eggs = 'global' def spam() -> None: """Spam Reassigns global variable called eggs. Returns: None. """ global eggs eggs = 'spam' def main(): spam() print(eg...
""" coding: utf-8 Created on 11/11/2020 @author: github.com/edrmonteiro From: Hackerrank challenges Language: Python Title: Minimum Swaps 2 You are given an unordered array consisting of consecutive integers [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements. You need to find the mini...
""" coding: utf-8 Created on 11/11/2020 @author: github.com/edrmonteiro From: Hackerrank challenges Language: Python Title: Minimum Swaps 2 You are given an unordered array consisting of consecutive integers [1, 2, 3, ..., n] without any duplicates. You are allowed to swap any two elements. You need to find the mini...
def my_func(name): print(f"this function is {name}") return "ha ha ha" my_func("Carlos's") the_input = int(input("Tell me something: ")) print(the_input + 2)
def my_func(name): print(f'this function is {name}') return 'ha ha ha' my_func("Carlos's") the_input = int(input('Tell me something: ')) print(the_input + 2)
def get_item_by_name(self, item_name): for item in self.items: if item.item_name == item_name: return item return None def get_item_list_by_name(self, item_name): for item_list in self.item_lists: if item_list.item_name == item_name: return item_list return None...
def get_item_by_name(self, item_name): for item in self.items: if item.item_name == item_name: return item return None def get_item_list_by_name(self, item_name): for item_list in self.item_lists: if item_list.item_name == item_name: return item_list return None
# -*- coding: utf-8 -*- """ Config parser of the shunt connector. Copyright 2021 Christian Doppler Laboratory for Embedded Machine Learning 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 ...
""" Config parser of the shunt connector. Copyright 2021 Christian Doppler Laboratory for Embedded Machine Learning 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/licens...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jan 22 18:10:02 2022 @author: victor """ fav_numbers = {'eric': 17, 'ever': 4} for name, number in fav_numbers.items(): print(name + ' loves ' + str(number))
""" Created on Sat Jan 22 18:10:02 2022 @author: victor """ fav_numbers = {'eric': 17, 'ever': 4} for (name, number) in fav_numbers.items(): print(name + ' loves ' + str(number))
EXAMPLES = { "pyxel": [], "pygame": [], "cli": [], "matplotlib": [], "pyglet": [], "streamlit": [], "kivy": [], } class TestExamples: def test_all_examples_were_registered(self): ... class BaseRunner: def run(self, file): """ Run file """ class T...
examples = {'pyxel': [], 'pygame': [], 'cli': [], 'matplotlib': [], 'pyglet': [], 'streamlit': [], 'kivy': []} class Testexamples: def test_all_examples_were_registered(self): ... class Baserunner: def run(self, file): """ Run file """ class Testpyxelexample: ...
#characterization of a linguistic value #it has a belonging function and possibly its inverse function class fuzzy_linguistic_value: #builder (belonging function and its inverse) def __init__(self, function, inverse_function = None): self.function = function self.inverse_function = inverse_func...
class Fuzzy_Linguistic_Value: def __init__(self, function, inverse_function=None): self.function = function self.inverse_function = inverse_function def defuzzy_function(function, maximum, x): return min(maximum, function(x)) class Fuzzy_Variable: def __init__(self, initial_value, domain...
s = input() ans = 0 for i in range(len(s) // 2): if s[i] != s[len(s) - 1 - i]: ans += 1 print(ans)
s = input() ans = 0 for i in range(len(s) // 2): if s[i] != s[len(s) - 1 - i]: ans += 1 print(ans)
# test basic await expression # adapted from PEP0492 async def abinary(n): print(n) if n <= 0: return 1 l = await abinary(n - 1) r = await abinary(n - 1) return l + 1 + r o = abinary(4) try: while True: o.send(None) except StopIteration: print('finished')
async def abinary(n): print(n) if n <= 0: return 1 l = await abinary(n - 1) r = await abinary(n - 1) return l + 1 + r o = abinary(4) try: while True: o.send(None) except StopIteration: print('finished')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- print('[+] First Read') with open('file.txt', 'r') as file: print(file.read()) print('\n[+] Second Read') with open('file.txt', 'r') as file: while True: line = file.readline() print(line, end='') if not line: break print('\n...
print('[+] First Read') with open('file.txt', 'r') as file: print(file.read()) print('\n[+] Second Read') with open('file.txt', 'r') as file: while True: line = file.readline() print(line, end='') if not line: break print('\n\n[+] Third Read') with open('file.txt', 'r') as fi...
rows =13 mid=int(rows/2) for row in range(rows): if row <=mid: for blank in range(mid-row): print(" ",end="") for star in range(2*row+1): print("*",end="") else: for blank in range(row-mid): print(" ",end="") for star in range(rows-2*(row-mid)...
rows = 13 mid = int(rows / 2) for row in range(rows): if row <= mid: for blank in range(mid - row): print(' ', end='') for star in range(2 * row + 1): print('*', end='') else: for blank in range(row - mid): print(' ', end='') for star in range(...
#!/usr/bin/env python # # Cloudlet Infrastructure for Mobile Computing # # Author: Kiryong Ha <krha@cmu.edu> # Zhuo Chen <zhuoc@cs.cmu.edu> # # Copyright (C) 2011-2013 Carnegie Mellon University # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in com...
class Protocol_Client(object): json_key_control_message = 'control' json_key_result_message = 'result' json_key_frame_id = 'frame_id' json_key_engine_id = 'engine_id' json_key_token_inject = 'token_inject' json_key_train = 'training' json_key_add_person = 'add_person' json_key_rm_person ...
# -*- coding: utf-8 -*- z = 'watevah' def blah(a,k='b'): def blorp(b): print(b) #3 print(a) #4 print(z) #5 print(__name__) #6 l = lambda x: x #def l(x): return x print(l("zoom!")) #1 print(a,k) #2 blorp("boom") blah("floom")
z = 'watevah' def blah(a, k='b'): def blorp(b): print(b) print(a) print(z) print(__name__) l = lambda x: x print(l('zoom!')) print(a, k) blorp('boom') blah('floom')
class Solution: """ @param numbers: Give an array numbers of n integer @param target: An integer @return: return the sum of the three integers, the sum closest target. """ def threeSumClosest(self, numbers, target): if len(numbers) < 3: return 0 numbers.sort() ...
class Solution: """ @param numbers: Give an array numbers of n integer @param target: An integer @return: return the sum of the three integers, the sum closest target. """ def three_sum_closest(self, numbers, target): if len(numbers) < 3: return 0 numbers.sort() ...
#max(x,y) = (x+y+|x-y|)/2 #max(x,y,z) = max(x,max(y,z)) def AlgebraicallyFindMaxTwo(x,y): return(x+y+abs(x-y))/2 AlgebraicallyFindMaxTwo(3,4) def AlgebraicallyFindMaxThree(x,y,z): print (AlgebraicallyFindMaxTwo(AlgebraicallyFindMaxTwo(x,y), z)) AlgebraicallyFindMaxThree(3,4,5)
def algebraically_find_max_two(x, y): return (x + y + abs(x - y)) / 2 algebraically_find_max_two(3, 4) def algebraically_find_max_three(x, y, z): print(algebraically_find_max_two(algebraically_find_max_two(x, y), z)) algebraically_find_max_three(3, 4, 5)
# common values for app boards MESSAGE_FIELD_SIZE = 8000 BOARD_NAME_SIZE = 30 DESCRIPTION_SIZE = 100 TOPIC_SUBJECT_SIZE = 255 POSTS_PER_PAGE = 2 TOPICS_PER_PAGE = 10 HAS_MANY_PAGES_LIMIT = 3 POST_SUBJECT_SIZE = 255 EXCLUDE_USERS = ['default_user', 'moderator'] MAX_SYMBOLS_ALLOWED = 20 # common values for app newsfeed ...
message_field_size = 8000 board_name_size = 30 description_size = 100 topic_subject_size = 255 posts_per_page = 2 topics_per_page = 10 has_many_pages_limit = 3 post_subject_size = 255 exclude_users = ['default_user', 'moderator'] max_symbols_allowed = 20 delay_factor = 35 min_chars = 350 banner_length = 150 help_arrows...
# # PySNMP MIB module ADTRAN-AOS-MEDIAGATEWAY-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-AOS-MEDIAGATEWAY-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:14:04 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python versio...
(ad_gen_aos_voice,) = mibBuilder.importSymbols('ADTRAN-AOS', 'adGenAOSVoice') (ad_identity, ad_shared) = mibBuilder.importSymbols('ADTRAN-MIB', 'adIdentity', 'adShared') (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuild...
# -*- coding: utf-8 -*- def find_floor(string: str) -> int: floor = 0 for direction in string: if direction == '(': floor += 1 else: floor -= 1 return floor def find_position(string: str) -> int: floor = 0 for i, s in enumerate(string): floor = flo...
def find_floor(string: str) -> int: floor = 0 for direction in string: if direction == '(': floor += 1 else: floor -= 1 return floor def find_position(string: str) -> int: floor = 0 for (i, s) in enumerate(string): floor = floor + find_floor(s) ...
def get_input(): with open("input.txt") as f: lines = f.read().splitlines() food_list = [] for line in lines: split = line.split("(") ingredients = set(split[0].split()) allergens = set(split[1][9:-1].split(", ")) food_list.append((ingredients,...
def get_input(): with open('input.txt') as f: lines = f.read().splitlines() food_list = [] for line in lines: split = line.split('(') ingredients = set(split[0].split()) allergens = set(split[1][9:-1].split(', ')) food_list.append((ingredients,...
a = int(input()) b = 1 for i in range(1, a + 1): b *= i print(b)
a = int(input()) b = 1 for i in range(1, a + 1): b *= i print(b)
# wczytanie slow with open('../dane/dane.txt') as f: data = [] for line in f.readlines(): data.append(line[:-1]) # licznik liczb parzystych even = 0 for word in data: # zamieniam na male litery, potem na system dziesietny # i wtedy sprawdzam czy jest podzielne przez 2 if int(word.lower(), ...
with open('../dane/dane.txt') as f: data = [] for line in f.readlines(): data.append(line[:-1]) even = 0 for word in data: if int(word.lower(), base=16) % 2 == 0: even += 1 answer = f'6 b) Ilosc parzystych liczb: {even}' print(answer)
"""Version file.""" VERSION_INFO = (0, 1, 0, "dev0") __version__ = ".".join((str(version) for version in VERSION_INFO))
"""Version file.""" version_info = (0, 1, 0, 'dev0') __version__ = '.'.join((str(version) for version in VERSION_INFO))
range_start = 367479 range_stop = 893698 def isvalid(n): ns = str(n) if not len(ns) == 6: return False has_same = False for pos in range(len(ns) - 1): if ns[pos] > ns[pos + 1]: return False if ns[pos] == ns[pos + 1]: has_same = True return has_same ...
range_start = 367479 range_stop = 893698 def isvalid(n): ns = str(n) if not len(ns) == 6: return False has_same = False for pos in range(len(ns) - 1): if ns[pos] > ns[pos + 1]: return False if ns[pos] == ns[pos + 1]: has_same = True return has_same co...
x = f"There are {10} types of people." binary = 'binary' do_not = "don't" y = "Those who know {binary} adn those who {do_not}." print(x) print(y) print('I said: {x}.') print('I also said: {y}') hilarious = False joke_evaluation = f"Isn't that joke so funny?! {hilarious}" print(joke_evaluation) w = ...
x = f'There are {10} types of people.' binary = 'binary' do_not = "don't" y = 'Those who know {binary} adn those who {do_not}.' print(x) print(y) print('I said: {x}.') print('I also said: {y}') hilarious = False joke_evaluation = f"Isn't that joke so funny?! {hilarious}" print(joke_evaluation) w = 'This is the left sid...
def romanToInt(s): roman_val = {'I' : 1, 'V': 5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} int_val = 0 for i in range(len(s)): print(s, i, s[i], roman_val[s[i]], roman_val[s[i - 1]]) if i > 0 and roman_val[s[i]] > roman_val[s[i - 1]]: int_val += roman_val[s[i]] - 2 * roma...
def roman_to_int(s): roman_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} int_val = 0 for i in range(len(s)): print(s, i, s[i], roman_val[s[i]], roman_val[s[i - 1]]) if i > 0 and roman_val[s[i]] > roman_val[s[i - 1]]: int_val += roman_val[s[i]] - 2 * roma...
class Loan: 'Base class for all loans.' LoanCount = 0 def __init__(self, m, y, v, r, score, term): LoanCount += 1 self.PolicyNumber = LoanCount self.OriginMonth = m self.OriginYear = y self.OriginValue = v self.PrincipalValue = v self.Balance = v ...
class Loan: """Base class for all loans.""" loan_count = 0 def __init__(self, m, y, v, r, score, term): loan_count += 1 self.PolicyNumber = LoanCount self.OriginMonth = m self.OriginYear = y self.OriginValue = v self.PrincipalValue = v self.Balance = ...
# 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 isSymmetric(self, root: TreeNode) -> bool: def find(r,l): if(r == None and ...
class Solution: def is_symmetric(self, root: TreeNode) -> bool: def find(r, l): if r == None and l == None: return True if r != None and l != None and (r.val == l.val): return find(r.right, l.left) and find(r.left, l.right) return find(root.r...
def pattern_elevan(strings): '''Pattern elevan K A T H M A N D U A T H M A N D U T H M A N D U H M A N D U M A N D U A N D U N D U D U U ''' if not str(strings).isalpha(): strings = str(strings) # If provided i...
def pattern_elevan(strings): """Pattern elevan K A T H M A N D U A T H M A N D U T H M A N D U H M A N D U M A N D U A N D U N D U D U U """ if not str(strings).isalpha(): strings = str(strings) for x in range(len(strings))...
# Created by Egor Kostan. # GitHub: https://github.com/ikostan # LinkedIn: https://www.linkedin.com/in/egor-kostan/ class EpidemicTestData: def __init__(self, tm, n, s0, i0, b, a, expected): self.__tm = tm self.__n = n self.__s0 = s0 self.__i0 = i0 self.__b = b self.__a = a self.__expected = expect...
class Epidemictestdata: def __init__(self, tm, n, s0, i0, b, a, expected): self.__tm = tm self.__n = n self.__s0 = s0 self.__i0 = i0 self.__b = b self.__a = a self.__expected = expected @property def tm(self): return self.__tm @property ...
class Solution: def solve(self, lst1, lst2): lst1.sort() lst2.sort() n = len(lst1)-1 m = len(lst2)-1 i = 0 j = 0 ans = float('inf') while i <= n and j <= m: ans = min(abs(lst1[i]-lst2[j]),ans) if lst1[i] < lst2[j]: ...
class Solution: def solve(self, lst1, lst2): lst1.sort() lst2.sort() n = len(lst1) - 1 m = len(lst2) - 1 i = 0 j = 0 ans = float('inf') while i <= n and j <= m: ans = min(abs(lst1[i] - lst2[j]), ans) if lst1[i] < lst2[j]: ...
n = int(input()) arr = list(map(int, input().split())) b=max(arr) while max(arr)==b: arr.remove(max(arr)) print(max(arr))
n = int(input()) arr = list(map(int, input().split())) b = max(arr) while max(arr) == b: arr.remove(max(arr)) print(max(arr))
class GraphQlVariable(object): """A GraphQL variable definition. Public attributes: object default_value - A Python object indicating the default value of the variable, if any. basestring name - The name of the variable. GraphQlType variable_type - The type of the variable. """ de...
class Graphqlvariable(object): """A GraphQL variable definition. Public attributes: object default_value - A Python object indicating the default value of the variable, if any. basestring name - The name of the variable. GraphQlType variable_type - The type of the variable. """ de...
# https://docs.python.org/3/library/__main__.html if __name__ == "__main__": pass
if __name__ == '__main__': pass
print('Enter the three sides of the triangle') a = float(input('Enter first side: ')) b = float(input('Enter second side: ')) c = float(input('Enter third side: ')) s = (a + b + c) / 2 area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 print('Area of the triangle = %0.3f' %area)
print('Enter the three sides of the triangle') a = float(input('Enter first side: ')) b = float(input('Enter second side: ')) c = float(input('Enter third side: ')) s = (a + b + c) / 2 area = (s * (s - a) * (s - b) * (s - c)) ** 0.5 print('Area of the triangle = %0.3f' % area)
def transform_test_oa18_to_oa11_kinetics(oa18_test_stacks, oa11_kinetics_test_stacks): cls_to_new_class = {2:1, 3:2, 4:3, 5:4, 7:5, 9:6, 11:7, 13:8, 15:9, 17:10, 18:11} lines = [] with open(oa18_test_stacks) as fr: for line in...
def transform_test_oa18_to_oa11_kinetics(oa18_test_stacks, oa11_kinetics_test_stacks): cls_to_new_class = {2: 1, 3: 2, 4: 3, 5: 4, 7: 5, 9: 6, 11: 7, 13: 8, 15: 9, 17: 10, 18: 11} lines = [] with open(oa18_test_stacks) as fr: for line in fr: (fname, starting, cls) = line.split() ...
n, l = map(int, input().split()) list = [str(input()) for i in range(n)] list.sort() s = ''.join(list) print(s)
(n, l) = map(int, input().split()) list = [str(input()) for i in range(n)] list.sort() s = ''.join(list) print(s)
def lcs(s1,s2): l1 = len(s1) l2 = len(s2) memo = [[-1] * (l1+1) for x in range(l2+1)] sol = [[None for x in range(l1+1)] for x in range(l2+1)] for i in range(l1): for j in range(l2): if i == 0 or j == 0: q = 0 memo[i][j] = 0 sol[i]...
def lcs(s1, s2): l1 = len(s1) l2 = len(s2) memo = [[-1] * (l1 + 1) for x in range(l2 + 1)] sol = [[None for x in range(l1 + 1)] for x in range(l2 + 1)] for i in range(l1): for j in range(l2): if i == 0 or j == 0: q = 0 memo[i][j] = 0 ...
class Tile: def __init__(self, tile_type): self.tyle_type = tile_type
class Tile: def __init__(self, tile_type): self.tyle_type = tile_type
# Copyright (c) 2021. # The copyright lies with Timo Hirsch-Hoffmann, the further use is only permitted with reference to source class ChampionMastery: champion_id: int champion_level: int champion_points: int last_play_time: int champion_points_since_last_level: int champion_points_until_nex...
class Championmastery: champion_id: int champion_level: int champion_points: int last_play_time: int champion_points_since_last_level: int champion_points_until_next_level: int chest_granted: bool tokens_earned: int summoner_id: str def __init__(self, champion_id: int, champion_...
def mode(): tally = {} M = nums[0] for x in nums: tally[x] = tally.get(x, 0) + 1 if tally[x] > tally[M]: M = x return M def max(nums): M = nums[0] for x in nums: if x > M: M = x return M def min(nums): M = nums[0] for x in nums: if x < M: M =x return M def mean(nums): if len(nums) == 0: ...
def mode(): tally = {} m = nums[0] for x in nums: tally[x] = tally.get(x, 0) + 1 if tally[x] > tally[M]: m = x return M def max(nums): m = nums[0] for x in nums: if x > M: m = x return M def min(nums): m = nums[0] for x in nums: ...
NODE_SIGNING_KEY = NotImplemented SENTRY_DSN = None SENTRY_EVENT_LEVEL = 'WARNING' NODE_NETWORK_ADDRESSES: list[str] = [] NODE_PORT = 8555 APPEND_AUTO_DETECTED_NETWORK_ADDRESS = True NODE_FEE = 4 IN_DOCKER = False NODE_LIST_JSON_PATH = None SYNC_BATCH_SIZE = 10 SCHEDULE_CAPACITY = 20 SUPPRESS_WARNINGS_TB = True LO...
node_signing_key = NotImplemented sentry_dsn = None sentry_event_level = 'WARNING' node_network_addresses: list[str] = [] node_port = 8555 append_auto_detected_network_address = True node_fee = 4 in_docker = False node_list_json_path = None sync_batch_size = 10 schedule_capacity = 20 suppress_warnings_tb = True lock_de...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next #Approach : ''' Put Node2.next which is n3->n4->...nn into Node1.next Now put entire Node1 which is n1-n3-n4... into Node2.next . with this step n1 and n2 are swapped....
""" Put Node2.next which is n3->n4->...nn into Node1.next Now put entire Node1 which is n1-n3-n4... into Node2.next . with this step n1 and n2 are swapped. In the first iteration save the pointer of new 2nd node which is node1. This pointer node keeps the link between Pari1..Pari2...Pair3....etc. From the second itera...
for t in range(int(input())): wordList=(" ".join(input())).split(" ") numOfHy=int(input()) locOfHy=list(map(int,input().split())) numOfHyEachLoc=[0 for i in range(len(wordList)+1)] for i in locOfHy: numOfHyEachLoc[i]+=1 print(f"#{t+1}",numOfHyEachLoc[0]*"-",end="") for i in range(len...
for t in range(int(input())): word_list = ' '.join(input()).split(' ') num_of_hy = int(input()) loc_of_hy = list(map(int, input().split())) num_of_hy_each_loc = [0 for i in range(len(wordList) + 1)] for i in locOfHy: numOfHyEachLoc[i] += 1 print(f'#{t + 1}', numOfHyEachLoc[0] * '-', end=...
""" for i in range(size): c = buf[i] enc += table[(c // 10) * 16 + c % 10] """ with open("babyrev.exe", "rb") as f: f.seek(0x8fb0) table = f.read(0x100) with open("enc.txt", "rb") as f: cipher = f.read() flag = "" for i, c in enumerate(cipher): for x in range(0x100): if table[(x // 10)...
""" for i in range(size): c = buf[i] enc += table[(c // 10) * 16 + c % 10] """ with open('babyrev.exe', 'rb') as f: f.seek(36784) table = f.read(256) with open('enc.txt', 'rb') as f: cipher = f.read() flag = '' for (i, c) in enumerate(cipher): for x in range(256): if table[x // 10 * 16 +...
# -*- coding: utf-8 -*- class NotRecognizeCommandException(Exception): pass class NotRecognizeProtocolException(Exception): pass
class Notrecognizecommandexception(Exception): pass class Notrecognizeprotocolexception(Exception): pass
# # @lc app=leetcode id=765 lang=python3 # # [765] Couples Holding Hands # # @lc code=start class Solution: def minSwapsCouples(self, row: List[int]) -> int: d, swap={}, 0 for i, x in enumerate(row): d[x]=i for i in range(0, len(row), 2): partner=row[i]+1 if row[i]%2...
class Solution: def min_swaps_couples(self, row: List[int]) -> int: (d, swap) = ({}, 0) for (i, x) in enumerate(row): d[x] = i for i in range(0, len(row), 2): partner = row[i] + 1 if row[i] % 2 == 0 else row[i] - 1 j = d[partner] if j - i != 1...
# -*- coding: utf-8 -*- '''package requirements are checked at runtime and installation time''' #----------------------------------------------------------------------------- # Copyright (c) 2013-2020, NeXpy Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the ...
"""package requirements are checked at runtime and installation time""" pkg_requirements = ['numpy>=1.16', 'scipy', 'h5py', 'versioneer']
# multiple.py def fail(exception_cls): raise exception_cls("Ooops") try: fail(ValueError) except Exception as exc: print("Can catch ValueError as Exception.") print(exc.__class__) except ValueError as exc: print("Can catch ValueError as ValueError.") print(exc.__class__) try: fail(Value...
def fail(exception_cls): raise exception_cls('Ooops') try: fail(ValueError) except Exception as exc: print('Can catch ValueError as Exception.') print(exc.__class__) except ValueError as exc: print('Can catch ValueError as ValueError.') print(exc.__class__) try: fail(ValueError) except Value...
#!/usr/bin/env python """ Fraunhofer IML Department Automation and Embedded Systems Tabsize : 4 Charset : UTF-8 """ __author__ = "Dennis Luensch" __maintainer__ = "Dennis Luensch" __email__ = "dennis.luensch@iml.fraunhofer.de" TP_EXCEPTION_PATH_ALREADY_EXISTS = "Path to vertex alreay ...
""" Fraunhofer IML Department Automation and Embedded Systems Tabsize : 4 Charset : UTF-8 """ __author__ = 'Dennis Luensch' __maintainer__ = 'Dennis Luensch' __email__ = 'dennis.luensch@iml.fraunhofer.de' tp_exception_path_already_exists = 'Path to vertex alreay exists!' class Topolog...
# https://www.hackerrank.com/challenges/python-string-formatting/problem def print_formatted(number): for i in range(1, number + 1): pad = number.bit_length() print(f"{i:{pad}d} {i:{pad}o} {i:{pad}X} {i:{pad}b}")
def print_formatted(number): for i in range(1, number + 1): pad = number.bit_length() print(f'{i:{pad}d} {i:{pad}o} {i:{pad}X} {i:{pad}b}')
# Generic CPREF_COMPONENT = "([0-9A-Z-]|%2F|%23)+" NUMERIC_COMPONENT = "(0|[1-9]\d*)" GS3A3_CHAR = "((%[0-9a-fA-F])|([a-zA-Z0-9!'()*+,-.:;=_]))" GS3A3_COMPONENT = f"{GS3A3_CHAR}+" PADDED_NUMERIC_COMPONENT = "\d+" PADDED_NUMERIC_COMPONENT_OR_EMPTY = "\d*" VERIFY_GS3A3_CHARS = "[a-zA-Z0-9!'()*+,-.:;=_\"%&/<>?]+" GS1_ELEM...
cpref_component = '([0-9A-Z-]|%2F|%23)+' numeric_component = '(0|[1-9]\\d*)' gs3_a3_char = "((%[0-9a-fA-F])|([a-zA-Z0-9!'()*+,-.:;=_]))" gs3_a3_component = f'{GS3A3_CHAR}+' padded_numeric_component = '\\d+' padded_numeric_component_or_empty = '\\d*' verify_gs3_a3_chars = '[a-zA-Z0-9!\'()*+,-.:;=_"%&/<>?]+' gs1_elem_cha...
#Code to check a string has unique charecters #using hash_map def is_unique(inp_str): c_dict = {} for c in inp_str: if c in inp_str: return False else: c_dict[c]=1 return True #no data structure , bruteforce def is_unique_bf(inp_str): for i in range(len(inp_str)-1): for j in range(i+1,len(inp_str))...
def is_unique(inp_str): c_dict = {} for c in inp_str: if c in inp_str: return False else: c_dict[c] = 1 return True def is_unique_bf(inp_str): for i in range(len(inp_str) - 1): for j in range(i + 1, len(inp_str)): if inp_str[i] == inp_str[j]: ...
string = 'afassdfasdfa' start = maxLength = 0 mydict = {} for i, c in enumerate(string): if c in mydict and start <= mydict[c]: start = mydict[c] + 1 else: maxLength = max(maxLength, i-start+1) mydict[c] = i print(mydict) print(maxLength, mydict )
string = 'afassdfasdfa' start = max_length = 0 mydict = {} for (i, c) in enumerate(string): if c in mydict and start <= mydict[c]: start = mydict[c] + 1 else: max_length = max(maxLength, i - start + 1) mydict[c] = i print(mydict) print(maxLength, mydict)
{ "targets": [ { "target_name": "addon", "sources": [ "SensorFusion_Addon.cpp", "SensorFusion.cpp", "Vector3D.cpp" ], "include_dirs": [ "/usr/include/upm/","/usr/include/mraa/" ], "libraries": [ "/usr/lib/libupm-lsm9ds0.so" ], "cflags": [ "-...
{'targets': [{'target_name': 'addon', 'sources': ['SensorFusion_Addon.cpp', 'SensorFusion.cpp', 'Vector3D.cpp'], 'include_dirs': ['/usr/include/upm/', '/usr/include/mraa/'], 'libraries': ['/usr/lib/libupm-lsm9ds0.so'], 'cflags': ['-fexceptions'], 'cflags_cc': ['-fexceptions']}]}
def update_session_credentials(config, session_credentials, profile): if not config.has_section(profile): config.add_section(profile) config.set(profile, "aws_access_key_id", session_credentials.access_key) config.set(profile, "aws_secret_access_key", session_credentials.secret_key) config.set...
def update_session_credentials(config, session_credentials, profile): if not config.has_section(profile): config.add_section(profile) config.set(profile, 'aws_access_key_id', session_credentials.access_key) config.set(profile, 'aws_secret_access_key', session_credentials.secret_key) config.set(p...
student = { "Name": "Shantanu", "Age": 21, "feedback": None } student["lastName"] = "Kamath" try: lastName = student["lastName"] new_var = 3 + student["lastName"] except KeyError: print("Error finding last name") except TypeError as error: print("Cant add these two together...
student = {'Name': 'Shantanu', 'Age': 21, 'feedback': None} student['lastName'] = 'Kamath' try: last_name = student['lastName'] new_var = 3 + student['lastName'] except KeyError: print('Error finding last name') except TypeError as error: print('Cant add these two together', error) except Exception: ...