content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class NoteGroup : def __init__(self, noteList) : self._noteList = noteList def clone(self) : other = NoteGroup([]) for note in self._noteList : other._noteList.append(note.clone()) return other def getNoteList(self) : return self._noteList def increaseOctave(self, delta) : for note in self._noteLi...
class Notegroup: def __init__(self, noteList): self._noteList = noteList def clone(self): other = note_group([]) for note in self._noteList: other._noteList.append(note.clone()) return other def get_note_list(self): return self._noteList def increa...
print('') senha = int(input('Qual sua senha: ')) print('') t = 0 while t != senha: t=int(input('Digite a senha novamente: ')) print('') if t != senha: print('Senha incorreta. Tente novamente') print('') print('Senha confirmada com sucesso!') print('')
print('') senha = int(input('Qual sua senha: ')) print('') t = 0 while t != senha: t = int(input('Digite a senha novamente: ')) print('') if t != senha: print('Senha incorreta. Tente novamente') print('') print('Senha confirmada com sucesso!') print('')
# coding=utf-8 crawler_start = object() crawler_shutdown = object() request_scheduled = object() request_ignored = object() response_received = object() item_scraped = object() item_ignored = object()
crawler_start = object() crawler_shutdown = object() request_scheduled = object() request_ignored = object() response_received = object() item_scraped = object() item_ignored = object()
class Persona: def __init__(self, nombre, edad): self.nombre = nombre self.edad = edad def calcular(self): if self.edad>18: print(f'{self.nombre} eres mayor de edad') else: print(f'{self.nombre} eres un crio aun') obj1 = Persona('Haroun',12) obj1.calcu...
class Persona: def __init__(self, nombre, edad): self.nombre = nombre self.edad = edad def calcular(self): if self.edad > 18: print(f'{self.nombre} eres mayor de edad') else: print(f'{self.nombre} eres un crio aun') obj1 = persona('Haroun', 12) obj1.calc...
def convert_matrix_to_image(m, shape): """Convert a column matrix of pixels to a 3D image given by shape. The number of channels is taken from m, not shape. If shape has length 2, the matrix is returned unchanged. This is the inverse of convert_image_to_matrix: im == convert_matrix_to_image(conve...
def convert_matrix_to_image(m, shape): """Convert a column matrix of pixels to a 3D image given by shape. The number of channels is taken from m, not shape. If shape has length 2, the matrix is returned unchanged. This is the inverse of convert_image_to_matrix: im == convert_matrix_to_image(conve...
n=int(input("Enter the year")) if n%4==0: print("Leap year") if n%100==0: print("Not Leap Year") if n%400==0: print("Leap year") else: print("Not Leap year")
n = int(input('Enter the year')) if n % 4 == 0: print('Leap year') if n % 100 == 0: print('Not Leap Year') if n % 400 == 0: print('Leap year') else: print('Not Leap year')
class Session(object): def __init__(self): self.start = None self.end = None self.scenarios = {} def add_run(self, run): if run.details_loaded and run.score == 0: # When a run is exited early via the "Restart Challenge" or # "Cancel Challenge" menu item i...
class Session(object): def __init__(self): self.start = None self.end = None self.scenarios = {} def add_run(self, run): if run.details_loaded and run.score == 0: return if not self.start or run.timestamp < self.start: self.start = run.timestamp ...
# 1493. Longest Subarray of 1's After Deleting One Element # User Accepted:3497 # User Tried:3867 # Total Accepted:3616 # Total Submissions:6849 # Difficulty:Medium # Given a binary array nums, you should delete one element from it. # Return the size of the longest non-empty subarray containing only 1's in the resultin...
class Solution: def longest_subarray(self, nums: List[int]) -> int: if sum(nums) == len(nums): return sum(nums) - 1 def helper(nums): cnt = 0 res = 0 for i in range(len(nums)): if nums[i] == 1: cnt += 1 ...
def solve(): s = input() cpos = s.find('C') if cpos < 0: print('No') return fpos = s[cpos:].find('F') if fpos >= 0: print('Yes') else: print('No') solve()
def solve(): s = input() cpos = s.find('C') if cpos < 0: print('No') return fpos = s[cpos:].find('F') if fpos >= 0: print('Yes') else: print('No') solve()
args_get = { 'filter_all': {'type': int, 'choices': [0, 1]} } args_put_or_post = { 'user_id': {'type': int}, 'username': {'type': str} }
args_get = {'filter_all': {'type': int, 'choices': [0, 1]}} args_put_or_post = {'user_id': {'type': int}, 'username': {'type': str}}
#weights dictionary having all weights of any layer as a value..preloaded #relu is a function return max(input_data,0).means relu is an activation function.. def predict_with_network(input_data): # Calculate node 0 in the first hidden layer node_0_0_input = (input_data * weights["node_0_0"]).sum() node_0_0_...
def predict_with_network(input_data): node_0_0_input = (input_data * weights['node_0_0']).sum() node_0_0_output = relu(node_0_0_input) node_0_1_input = (input_data * weights['node_0_1']).sum() node_0_1_output = relu(node_0_1_input) hidden_0_outputs = np.array([node_0_0_output, node_0_1_output]) ...
#!/usr/bin/env python3 class Shape(object): LIZT = [] def __init__(self): Shape.LIZT.append(self) def __str__(self): return('SHAPE:from __str__: {}'.format(Shape.LIZT)) def __repr__(self): return('SHAPE: from __repr__: {} {}'.format(self,Shape.LIZT)) class Circle(Shape): ...
class Shape(object): lizt = [] def __init__(self): Shape.LIZT.append(self) def __str__(self): return 'SHAPE:from __str__: {}'.format(Shape.LIZT) def __repr__(self): return 'SHAPE: from __repr__: {} {}'.format(self, Shape.LIZT) class Circle(Shape): def __init__(self, radi...
# -*- coding: utf-8 -*- """ 979. Distribute Coins in Binary Tree Given the root of a binary tree with N nodes, each node in the tree has node.val coins, and there are N coins total. In one move, we may choose two adjacent nodes and move one coin from one node to another. (The move may be from parent to child, or fro...
""" 979. Distribute Coins in Binary Tree Given the root of a binary tree with N nodes, each node in the tree has node.val coins, and there are N coins total. In one move, we may choose two adjacent nodes and move one coin from one node to another. (The move may be from parent to child, or from child to parent.) Ret...
def clean_line(line): instruction, argument = line.strip().split() return instruction, int(argument) with open('in') as f: data = list(map(clean_line, f.readlines())) def exec_code(program): acc = 0 index = 0 executed = [False] * len(data) while not executed[index]: executed[in...
def clean_line(line): (instruction, argument) = line.strip().split() return (instruction, int(argument)) with open('in') as f: data = list(map(clean_line, f.readlines())) def exec_code(program): acc = 0 index = 0 executed = [False] * len(data) while not executed[index]: executed[ind...
inputs = [1.2, 5.1, 2.1] weights = [3.1, 2.1, 8.7] bias = 3 output = inputs[0]*weights[0] + inputs[1]*weights[1] + inputs[2]*weights[2] + bias print(output)
inputs = [1.2, 5.1, 2.1] weights = [3.1, 2.1, 8.7] bias = 3 output = inputs[0] * weights[0] + inputs[1] * weights[1] + inputs[2] * weights[2] + bias print(output)
"""Support module for looking up drivers by name The driver model (see ``docs/driver-model.rst``) requires us to be able to resolve driver names to classes; this module provides support for building and querying lookup tables for this. Any class which wishes to be exposed via this interface should: 1. Inherit, direc...
"""Support module for looking up drivers by name The driver model (see ``docs/driver-model.rst``) requires us to be able to resolve driver names to classes; this module provides support for building and querying lookup tables for this. Any class which wishes to be exposed via this interface should: 1. Inherit, direc...
# Function to find and list all substrings in a string def find_all(string, x): index_list = [] start = 0 while True: index = string.find(x, start) if index != -1: index_list.append(index) start = index+1 else: if start==0: return -...
def find_all(string, x): index_list = [] start = 0 while True: index = string.find(x, start) if index != -1: index_list.append(index) start = index + 1 elif start == 0: return -1 else: return index_list if __name__ == '__main__'...
# -*- coding: utf-8 -*- USER_AGENT_LIST = [ \ "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1", \ "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11", \ "Mozilla/5.0 (Windows NT 6.1; WO...
user_agent_list = ['Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1', 'Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) C...
def my_gen(): n = 1 print('This is printed first') # Generator function contains yield statements yield n n += 1 print('This is printed second') yield n n += 1 print('This is printed at last') yield n class GeneratorFunctions: def __init__(self): print('no this i...
def my_gen(): n = 1 print('This is printed first') yield n n += 1 print('This is printed second') yield n n += 1 print('This is printed at last') yield n class Generatorfunctions: def __init__(self): print('no this is printed first.')
__author__ = 'Harsh Gupta' __email__ = 'working@example.com' __version__ = '0.0.1' __version_info__ = tuple(__version__.split('.'))
__author__ = 'Harsh Gupta' __email__ = 'working@example.com' __version__ = '0.0.1' __version_info__ = tuple(__version__.split('.'))
score = input("Enter score:") s = float(score) if s < 0.6: print("F") elif s >= 0.6: if s < 0.7: print("E") elif s >= 0.7: if s < 0.8: print("C") elif s >= 0.8: if s < 0.9: print("B") elif s >= 0.9: print("A")
score = input('Enter score:') s = float(score) if s < 0.6: print('F') elif s >= 0.6: if s < 0.7: print('E') elif s >= 0.7: if s < 0.8: print('C') elif s >= 0.8: if s < 0.9: print('B') elif s >= 0.9: print('A')
t = int(input()) answer = [] ans = [] counter = 0 for a in range(t): counter = 0 n = int(input()) ans = [0 for d in range(n)] line = list(input()) for b in range(len(line)-n+1): current = [line[c] for c in range(b, b+n)] #print(current) check = int(ans[counter])|int(current[c...
t = int(input()) answer = [] ans = [] counter = 0 for a in range(t): counter = 0 n = int(input()) ans = [0 for d in range(n)] line = list(input()) for b in range(len(line) - n + 1): current = [line[c] for c in range(b, b + n)] check = int(ans[counter]) | int(current[counter]) ...
numbers = [5, 6, 7, 12, 29] med = 0 out = None if(len(numbers) != 0): for n in numbers: med += n out = med/len(numbers)
numbers = [5, 6, 7, 12, 29] med = 0 out = None if len(numbers) != 0: for n in numbers: med += n out = med / len(numbers)
# Define a class Employee having members id, name, department, salary. Create a subclass called manager with member bonus. Define methods accept and display in both the classes. Create n objects of the manager class and display the details of the manager having the maximum total salary (salary+bonus). class Employee:...
class Employee: def __init__(self, id, name, department, salary): self.id = id self.name = name self.department = department self.salary = salary def accept(self): self.id = int(input('Enter id: ')) self.name = input('Enter name: ') self.department = inp...
class Transform(object,IComparable[Transform],IEquatable[Transform]): """ Transform(diagonalValue: float) """ @staticmethod def ChangeBasis(*__args): """ ChangeBasis(initialBasisX: Vector3d,initialBasisY: Vector3d,initialBasisZ: Vector3d,finalBasisX: Vector3d,finalBasisY: Vector3d,finalBasisZ: Vector3d) -> ...
class Transform(object, IComparable[Transform], IEquatable[Transform]): """ Transform(diagonalValue: float) """ @staticmethod def change_basis(*__args): """ ChangeBasis(initialBasisX: Vector3d,initialBasisY: Vector3d,initialBasisZ: Vector3d,finalBasisX: Vector3d,finalBasisY: Vector3d,finalBasisZ:...
class NodoAVL: def __init__(self, element): self.__element = element self.__right = None self.__left = None self.__factor = 1 def set_left(self, left): self.__left = left def get_left(self): return self.__left def set_right(self, right): self.__...
class Nodoavl: def __init__(self, element): self.__element = element self.__right = None self.__left = None self.__factor = 1 def set_left(self, left): self.__left = left def get_left(self): return self.__left def set_right(self, right): self._...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- __license__ = "BSD" __credits__ = ["Stephone White"] __version__ = "0.1.0" __status__ = "development" def main(): """Entry point for the application script""" print("Call your main application code here")
__license__ = 'BSD' __credits__ = ['Stephone White'] __version__ = '0.1.0' __status__ = 'development' def main(): """Entry point for the application script""" print('Call your main application code here')
# # PySNMP MIB module SUNSTORAGEAGENT-NOTIFICATION-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SUNSTORAGEAGENT-NOTIFICATION-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:04:29 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Pyt...
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, value_range_constraint, constraints_union, constraints_intersection, single_value_constraint) ...
INSTALLED_APPS += [ 'userservice', 'rc_django' ] MIDDLEWARE += [ 'userservice.user.UserServiceMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'debug': True, 'context_processors...
installed_apps += ['userservice', 'rc_django'] middleware += ['userservice.user.UserServiceMiddleware'] templates = [{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': {'debug': True, 'context_processors': ['django.template.context_processors.debug', 'django.template.context_pro...
class Solution: # @param num, a list of integers # @return an integer def majorityElement(self, num): count = 0 isMajority = False whatIsMajority = 0 for index in xrange(0,len(num)): if not isMajority: whatIsMajority = num[index] ...
class Solution: def majority_element(self, num): count = 0 is_majority = False what_is_majority = 0 for index in xrange(0, len(num)): if not isMajority: what_is_majority = num[index] count += 1 is_majority = True ...
n=input() k=input().strip() count=0 for i in range(len(n)): if(n[i]==k): count=count+1 print(count)
n = input() k = input().strip() count = 0 for i in range(len(n)): if n[i] == k: count = count + 1 print(count)
def fib(n): """ Returns a list of all the even terms in the Fibonacci sequence that are less than n. """ ls = [] a, b = 0, 1 while b < n: if b % 2 == 0: ls.append(b) a, b = b, a+b return ls if __name__ == '__main__': n = int(input("Enter max numb...
def fib(n): """ Returns a list of all the even terms in the Fibonacci sequence that are less than n. """ ls = [] (a, b) = (0, 1) while b < n: if b % 2 == 0: ls.append(b) (a, b) = (b, a + b) return ls if __name__ == '__main__': n = int(input('Enter max number: ...
#!/usr/bin/python # -*- coding: utf-8 -*- """ @project:Explaining-and-Harnessing-Adversarial-Examples @author: Kevin Leung @file:model.py @interpreter: Python3.6 @ide:PyCharm @time:2019-02-20 16:57:12 """
""" @project:Explaining-and-Harnessing-Adversarial-Examples @author: Kevin Leung @file:model.py @interpreter: Python3.6 @ide:PyCharm @time:2019-02-20 16:57:12 """
# -*- encoding:utf-8 -*- """ Author: Yijie.Wu Email: 1694517106@qq.com Date: 2020/5/16 15:17 """
""" Author: Yijie.Wu Email: 1694517106@qq.com Date: 2020/5/16 15:17 """
# import pandas as pd # results=[] # draft1=pd.read_table('sample.tsv') # print(draft1) # for row in draft1: # results.append(row) # print(results) l = 'https://github.com/msirrele/dc-metro-proxy' a=l.split('/') print(a[-1])
l = 'https://github.com/msirrele/dc-metro-proxy' a = l.split('/') print(a[-1])
class Vertex(object): def __init__(self, key): self.id = key self.connectedTo = {} def addNeighbor(self, nbr, w): self.connectedTo[nbr] = w def getConnections(self): return self.connectedTo.keys() def getId(self): return self.id def getWeight(self, nbr): ...
class Vertex(object): def __init__(self, key): self.id = key self.connectedTo = {} def add_neighbor(self, nbr, w): self.connectedTo[nbr] = w def get_connections(self): return self.connectedTo.keys() def get_id(self): return self.id def get_weight(self, nb...
#!/usr/bin/env python3 """ Module Docstring """ __author__ = "Your Name" __version__ = "0.1.0" __license__ = "MIT" def read_profile(infile): """ Reads contents of an airfoil definition file such as the ones found here: http://m-selig.ae.illinois.edu/ads/coord_database.html Many have an airfo...
""" Module Docstring """ __author__ = 'Your Name' __version__ = '0.1.0' __license__ = 'MIT' def read_profile(infile): """ Reads contents of an airfoil definition file such as the ones found here: http://m-selig.ae.illinois.edu/ads/coord_database.html Many have an airfoil name, followed by 2 va...
n = int(input()) pos = [] for i in range(n): x, y = map(int, input().split()) pos.append((x, y)) pos.sort(key=lambda x:(x[0], x[1])) for p in pos: print(p[0], p[1])
n = int(input()) pos = [] for i in range(n): (x, y) = map(int, input().split()) pos.append((x, y)) pos.sort(key=lambda x: (x[0], x[1])) for p in pos: print(p[0], p[1])
#!/usr/bin/env python # -*- coding: utf-8 -*- owner_users = {'email': 'prozorroytenderowner@gmail.com', 'password': '123456'} provider_users = {'prozorroyprovider1@gmail.com': '123456', 'prozorroyprovider2@gmail.com': '123456', 'uaceseller1@mail.ru': 'andriy85', ...
owner_users = {'email': 'prozorroytenderowner@gmail.com', 'password': '123456'} provider_users = {'prozorroyprovider1@gmail.com': '123456', 'prozorroyprovider2@gmail.com': '123456', 'uaceseller1@mail.ru': 'andriy85', 'uaceseller2@mail.ru': 'andriy85'} broker = {'url': 'http://utender.com.ua'} login_button = '#nav-w2 > ...
def binary_search(l,x,start,end): if start==end: if l[start]==x: return start else: return -1 else: mid=int((start+end)/2) if l[mid]==x: return mid elif l[mid]>x: return binary_search(l,x,start,mid-1) else: ...
def binary_search(l, x, start, end): if start == end: if l[start] == x: return start else: return -1 else: mid = int((start + end) / 2) if l[mid] == x: return mid elif l[mid] > x: return binary_search(l, x, start, mid - 1) ...
# Golomb sequence def findGolomb(n): if (n == 1): return 1 return 1 + findGolomb(n - findGolomb(findGolomb(n - 1))) def printGolomb(n): for i in range(1, n + 1): print(findGolomb(i), end=" ") n = 19 printGolomb(n)
def find_golomb(n): if n == 1: return 1 return 1 + find_golomb(n - find_golomb(find_golomb(n - 1))) def print_golomb(n): for i in range(1, n + 1): print(find_golomb(i), end=' ') n = 19 print_golomb(n)
# https://www.hackerrank.com/challenges/luck-balance/problem?isFullScreen=true def luckBalance(k, contests): # Write your code here luck_importance_array = [item[0] for item in contests if item[1]==1] luck_value_array = [item[0] for item in contests] luck_sum = sum(luck_value_array) luck_...
def luck_balance(k, contests): luck_importance_array = [item[0] for item in contests if item[1] == 1] luck_value_array = [item[0] for item in contests] luck_sum = sum(luck_value_array) luck_value_array.sort() luck_importance_array.sort() for i in range(len(luck_importance_array) - k): lu...
# -*- coding: utf-8 -*- # # Copyright (c) 2020~2999 - Cologler <skyoflw@gmail.com> # ---------- # # ---------- class GLinkError(Exception): 'the base error for glink' def __init__(self, message: str) -> None: self.message = message class LocalFileRemovedError(GLinkError): pass class RemoteFil...
class Glinkerror(Exception): """the base error for glink""" def __init__(self, message: str) -> None: self.message = message class Localfileremovederror(GLinkError): pass class Remotefileremovederror(GLinkError): pass class Conflicterror(GLinkError): pass class Missingdataerror(GLinkErr...
def update_base(): return True def show_base(): return True
def update_base(): return True def show_base(): return True
''' Problem statement : Given two numbers M and N, the task is to check if the M-th and N-th Fibonacci numbers perfectly divide each other or not. Approach : A naive approach will be to find the N-th and M-th Fibonacci numbers and check if they are perfectly divisible or not. An efficient approach is to use the Fibona...
""" Problem statement : Given two numbers M and N, the task is to check if the M-th and N-th Fibonacci numbers perfectly divide each other or not. Approach : A naive approach will be to find the N-th and M-th Fibonacci numbers and check if they are perfectly divisible or not. An efficient approach is to use the Fibona...
""" The `river.tree.nodes` module includes learning and split node implementations for the hoeffding trees. """
""" The `river.tree.nodes` module includes learning and split node implementations for the hoeffding trees. """
class ChoiceTemplates: genericMoscow = [{'text': 'Must have', 'priority': 100}, {'text': 'Should have', 'priority': 200}, {'text': 'Could have', 'priority': 300}, {'text': 'Wishlist', 'priority': 400}] genericYesNo = [{'text': 'Yes', 'priority': 1...
class Choicetemplates: generic_moscow = [{'text': 'Must have', 'priority': 100}, {'text': 'Should have', 'priority': 200}, {'text': 'Could have', 'priority': 300}, {'text': 'Wishlist', 'priority': 400}] generic_yes_no = [{'text': 'Yes', 'priority': 100}, {'text': 'No', 'priority': 200}] generic1to5 = [{'tex...
n=int(input()) l=[] for i in range(n): l.append(int(input())) m=max(l) r=0 for i in range(2,m+1): c=0 for j in range(0,len(l)): if l[j]%i==0: c+=1 if c==len(l): r+=1 print(r)
n = int(input()) l = [] for i in range(n): l.append(int(input())) m = max(l) r = 0 for i in range(2, m + 1): c = 0 for j in range(0, len(l)): if l[j] % i == 0: c += 1 if c == len(l): r += 1 print(r)
# A class is a code template for creating objects. # Objects have member variables and have behaviour associated with them. I class myClass(): def method1(obj): print ("myClass method1") def method2(obj, sth): print ("myClass method2: " + sth) class anotherClass(myClass): def method2(obj): ...
class Myclass: def method1(obj): print('myClass method1') def method2(obj, sth): print('myClass method2: ' + sth) class Anotherclass(myClass): def method2(obj): print('anotherClass method2') def method1(obj): myClass.method1(obj) print('anotherClass method1')...
els = [1,2,3,3,4,4,4,4,5,5,5,6,6] search = int(input("Enter the number to search: ")) count = 0 for el in els: if el == search: count += 1 print(search,"occurred in the list",count,"times")
els = [1, 2, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6] search = int(input('Enter the number to search: ')) count = 0 for el in els: if el == search: count += 1 print(search, 'occurred in the list', count, 'times')
#CASE_IEEE30 Power flow data for IEEE 30 bus test case. # Please see CASEFORMAT for details on the case file format. # This data was converted from IEEE Common Data Format # (ieee30cdf.txt) on 15-Oct-2014 by cdf2matp, rev. 2393 # See end of file for warnings generated during conversion. # # Converted from IE...
def return_data(): base_mva = 100 bus = [[1, 3, 0, 0, 0, 0, 1, 1.06, 0, 132, 1, 1.06, 0.94], [2, 2, 21.7, 12.7, 0, 0, 1, 1.043, -5.48, 132, 1, 1.06, 0.94], [3, 1, 2.4, 1.2, 0, 0, 1, 1.021, -7.96, 132, 1, 1.06, 0.94], [4, 1, 7.6, 1.6, 0, 0, 1, 1.012, -9.62, 132, 1, 1.06, 0.94], [5, 2, 94.2, 19, 0, 0, 1, 1.01, -1...
class Solution: MAX_NUM = (2 ** 31) - 1 MIN_NUM = -(2 ** 31) def reverse(self, x): """ :type x: int :rtype: int """ ret = 0 str_string = str(x).split('-') negative = False if len(str_string) == 2: negative = True for i in r...
class Solution: max_num = 2 ** 31 - 1 min_num = -2 ** 31 def reverse(self, x): """ :type x: int :rtype: int """ ret = 0 str_string = str(x).split('-') negative = False if len(str_string) == 2: negative = True for i in range...
__mixed = getattr(None, '') __f = open('/dev/null') def load(f): return __mixed load(__f) def loads(s): return __mixed loads('') def dump(o, f): return dump(__mixed, __f) def dumps(o): return '' dumps(__mixed)
__mixed = getattr(None, '') __f = open('/dev/null') def load(f): return __mixed load(__f) def loads(s): return __mixed loads('') def dump(o, f): return dump(__mixed, __f) def dumps(o): return '' dumps(__mixed)
""" JMOSS Python implementation for public release Jurado-McGehee Online Self Survey (JMOSS) Version 6.0 January 2021 Written by Juan Jurado, Clark McGehee Based on: Jurado, Juan D., and Clark C. McGehee. "Complete Online Algorithm for Air Data System Calibration." Journal of Aircraft 56.2 (2019):...
""" JMOSS Python implementation for public release Jurado-McGehee Online Self Survey (JMOSS) Version 6.0 January 2021 Written by Juan Jurado, Clark McGehee Based on: Jurado, Juan D., and Clark C. McGehee. "Complete Online Algorithm for Air Data System Calibration." Journal of Aircraft 56.2 (2019):...
#Project Euler Question 53 #Combinatoric selections def factorial(x): if x > 1: return x * factorial(x - 1) else: return 1 comb_list = [] for x in range(1, 101): for y in range(1, 101): if y > x: break combinations = int(factorial(x) / (factorial(y) * factorial...
def factorial(x): if x > 1: return x * factorial(x - 1) else: return 1 comb_list = [] for x in range(1, 101): for y in range(1, 101): if y > x: break combinations = int(factorial(x) / (factorial(y) * factorial(x - y))) if combinations > 1000000: ...
""" DBError +-- EntityDoesNotExistError """ __all__ = [ 'DBError', 'EntityDoesNotExistError' ] class DBError(Exception): """ Common DB exception. """ class EntityDoesNotExistError(DBError): """ Raised if the searched entity does not exist in the database. """
""" DBError +-- EntityDoesNotExistError """ __all__ = ['DBError', 'EntityDoesNotExistError'] class Dberror(Exception): """ Common DB exception. """ class Entitydoesnotexisterror(DBError): """ Raised if the searched entity does not exist in the database. """
p = ('double dragon', 'fifa', 'mario bros', 'final fight', 'street fighter', 'alien', 'castle of ilusions', 'quack shot', 'sunset riders', 'flashback') for c in p: print(f'\nA palavra {c.upper()} temos as vogais', end = ' - ') for letra in c: if letra in 'aeiou': print(letra, end = ' ')...
p = ('double dragon', 'fifa', 'mario bros', 'final fight', 'street fighter', 'alien', 'castle of ilusions', 'quack shot', 'sunset riders', 'flashback') for c in p: print(f'\nA palavra {c.upper()} temos as vogais', end=' - ') for letra in c: if letra in 'aeiou': print(letra, end=' ')
''' Configuration options for RegGNN pipeline. ''' class Config: # SYSTEM OPTIONS DATA_FOLDER = './simulated_data/' # path to the folder data will be written to and read from RESULT_FOLDER = './' # path to the folder data will be written to and read from # SIMULATED DATA OPTIONS CONNECTOME_MEAN...
""" Configuration options for RegGNN pipeline. """ class Config: data_folder = './simulated_data/' result_folder = './' connectome_mean = 0.0 connectome_std = 1.0 score_mean = 90.0 score_std = 10.0 n_subjects = 30 roi = 116 spd = True k_folds = 5 class Reggnn: num_e...
Import("env") upload_protocol = env.subst("$UPLOAD_PROTOCOL") def before_fuses(source, target, env): print("before_fuses") fuses_section = "fuses" board = env.BoardConfig() lfuse = board.get("%s.lfuse" % fuses_section, "") hfuse = board.get("%s.hfuse" % fuses_section, "") efuse = board.get("%...
import('env') upload_protocol = env.subst('$UPLOAD_PROTOCOL') def before_fuses(source, target, env): print('before_fuses') fuses_section = 'fuses' board = env.BoardConfig() lfuse = board.get('%s.lfuse' % fuses_section, '') hfuse = board.get('%s.hfuse' % fuses_section, '') efuse = board.get('%s....
ROOT_SCOPE_METHOD( MD( 'ConsumeMap', 'CONSUME_MAP_FACTORY_single()' ) ) TEST( """ ConsumeMap @ ( Integer ) [ 1 2 3 ] next value == 2 """ ) TEST( """ ConsumeMap @ ( Grouping @ ( . [ ( Word ) ( Integer ) ] flatten () ) ) [ a 1 b 2 c 3 ] next value next value == 2 """ ) TEST( """ ConsumeMap @ ( Or @ ( . [ ( Plus @ ( R...
root_scope_method(md('ConsumeMap', 'CONSUME_MAP_FACTORY_single()')) test(' ConsumeMap @ ( Integer ) [ 1 2 3 ] next value == 2 ') test(' ConsumeMap @ ( Grouping @ ( . [ ( Word ) ( Integer ) ] flatten () ) ) [ a 1 b 2 c 3 ] next value next value == 2 ') test(' ConsumeMap @ ( Or @ ( . [ ( Plus @ ( RangeType @ 0 9 ) ) ( Pl...
"""Tests for vcs: testanimate test_anim_mesh testboxfill test_color_pick testcolor testcontinents testdisplayplot test_fillarea_update testge testhardcopy testisofill testisoline test_line_update test_marker_update testmeshfill testorientation testoutfill testoutline test_primitives_proj testprimitives test_ratio tests...
"""Tests for vcs: testanimate test_anim_mesh testboxfill test_color_pick testcolor testcontinents testdisplayplot test_fillarea_update testge testhardcopy testisofill testisoline test_line_update test_marker_update testmeshfill testorientation testoutfill testoutline test_primitives_proj testprimitives test_ratio tests...
def echo_default(default='hello'): # pragma: nocover return default def echo_back(): # pragma: nocover return 'howdy all'
def echo_default(default='hello'): return default def echo_back(): return 'howdy all'
# # @lc app=leetcode id=316 lang=python3 # # [316] Remove Duplicate Letters # # @lc code=start class Solution: def removeDuplicateLetters(self, s): # with first and last idx of each char if not s: return "" ls = list(s) stack = [] stack.append(ls.pop(0)) ...
class Solution: def remove_duplicate_letters(self, s): if not s: return '' ls = list(s) stack = [] stack.append(ls.pop(0)) while len(ls) > 0: item = ls.pop(0) if item not in stack: while len(stack) > 0 and item < stack[-1]:...
# A linked list is given such that each node contains an additional # random pointer which could point to any node in the list or null. # Return a deep copy of the list. # Example 1: # Input: # {"$id":"1","next":{"$id":"2","next":null,"random":{"$ref":"2"},"val":2},"random":{"$ref":"2"},"val":1} # Explanation: # Node...
class Node(object): def __init__(self, val, next, random): self.val = val self.next = next self.random = random class Solution(object): def copy_random_list(self, head): """ :type head: Node :rtype: Node """ if not head: return None ...
""" URL: https://codeforces.com/problemset/problem/200/B Author: Safiul Kabir [safiulanik at gmail.com] Tags: implementation, math, *800 """ n = int(input()) print(sum(map(int, input().split()))/n)
""" URL: https://codeforces.com/problemset/problem/200/B Author: Safiul Kabir [safiulanik at gmail.com] Tags: implementation, math, *800 """ n = int(input()) print(sum(map(int, input().split())) / n)
'''3. Write a Python program to insert a given string at the beginning of all items in a list. Sample list : [1,2,3,4], string : emp Expected output : ['emp1', 'emp2', 'emp3', 'emp4'] ''' def add_string(lst1, str1): lst2 = [] str(lst1) for i in lst1: var = str1 + str(i) lst2.append(var) ...
"""3. Write a Python program to insert a given string at the beginning of all items in a list. Sample list : [1,2,3,4], string : emp Expected output : ['emp1', 'emp2', 'emp3', 'emp4'] """ def add_string(lst1, str1): lst2 = [] str(lst1) for i in lst1: var = str1 + str(i) lst2.append(var) ...
ftp_details = { # FTP Credentials "host":"ftpupload.net", "username":"epiz_22913338", "password":"", "port":21 } default_control_directory = "/htdocs/control/" execution_filename = "python.execute" output_filename = "python.output"
ftp_details = {'host': 'ftpupload.net', 'username': 'epiz_22913338', 'password': '', 'port': 21} default_control_directory = '/htdocs/control/' execution_filename = 'python.execute' output_filename = 'python.output'
# -*- coding: utf-8 -*- """ Created on Tue Dec 29 12:59 2020 Introduction to Computation and Programming Using Python. John V. Guttag, 2016, 2nd ed Book Chapter 5 Structured types, Mutability and Higher-Order Functions Dictionaries The View Object Hashable types as keys @author: Atanas Kozarev - github.com/ultraasi...
""" Created on Tue Dec 29 12:59 2020 Introduction to Computation and Programming Using Python. John V. Guttag, 2016, 2nd ed Book Chapter 5 Structured types, Mutability and Higher-Order Functions Dictionaries The View Object Hashable types as keys @author: Atanas Kozarev - github.com/ultraasi-atanas """ months = {'...
""" --> Minimum Adjacent Swaps to Reach the Kth Smallest Number --> Medium use Find_k_permutation_greater_number in practice """
""" --> Minimum Adjacent Swaps to Reach the Kth Smallest Number --> Medium use Find_k_permutation_greater_number in practice """
''' pandas box plots While pandas can plot multiple columns of data in a single figure, making plots that share the same x and y axes, there are cases where two columns cannot be plotted together because their units do not match. The .plot() method can generate subplots for each column being plotted. Here, each plot w...
""" pandas box plots While pandas can plot multiple columns of data in a single figure, making plots that share the same x and y axes, there are cases where two columns cannot be plotted together because their units do not match. The .plot() method can generate subplots for each column being plotted. Here, each plot w...
class control_options: position = 1 #moves to x,y position, only forward pose = 2 #moves to x,y position and then turn to th, only forward momentum = 3 #not implemented angular_pose= 4 #turn to th direct_speeds = 5 #override control actions pose_line = 6 #moves to x,y position and turn to ...
class Control_Options: position = 1 pose = 2 momentum = 3 angular_pose = 4 direct_speeds = 5 pose_line = 6 special_movements = 7
# -*- coding: utf-8 -*- # Copyright 2019 Cohesity Inc. class CategoryNotificationRuleEnum(object): """Implementation of the 'Category_NotificationRule' enum. TODO: type enum description here. Attributes: KDISK: TODO: type description here. KNODE: TODO: type description here. KCLU...
class Categorynotificationruleenum(object): """Implementation of the 'Category_NotificationRule' enum. TODO: type enum description here. Attributes: KDISK: TODO: type description here. KNODE: TODO: type description here. KCLUSTER: TODO: type description here. KNODEHEALTH: T...
id_1 = "#4" average_grade_1 = "A" test_score_1 = 90 id_2 = "#5" average_grade_2 = "A" test_score_2 = 70 no_duplicates = id_1 != id_2 print("No duplicates entries:") print(no_duplicates) same_average = average_grade_1 == average_grade_2 print("Same average grade:") print(same_average) higher_score = test_score_1 > t...
id_1 = '#4' average_grade_1 = 'A' test_score_1 = 90 id_2 = '#5' average_grade_2 = 'A' test_score_2 = 70 no_duplicates = id_1 != id_2 print('No duplicates entries:') print(no_duplicates) same_average = average_grade_1 == average_grade_2 print('Same average grade:') print(same_average) higher_score = test_score_1 > test_...
positive = [] negative = [] sum = 0 numbers = int(input()) for i in range(0, numbers): num = int(input()) if num >= 0: positive.append(num) else: negative.append(num) for num in negative: sum += num print(positive) print(negative) print(f"Count of positives: {len(positive)}. Sum of nega...
positive = [] negative = [] sum = 0 numbers = int(input()) for i in range(0, numbers): num = int(input()) if num >= 0: positive.append(num) else: negative.append(num) for num in negative: sum += num print(positive) print(negative) print(f'Count of positives: {len(positive)}. Sum of negat...
def selectionSort(nlist): for fillslot in range(len(nlist)-1,0,-1): maxpos=0 for location in range(1,fillslot+1): if nlist[location]>nlist[maxpos]: maxpos = location temp = nlist[fillslot] nlist[fillslot] = nlist[maxpos] nlist[maxpos] = temp ...
def selection_sort(nlist): for fillslot in range(len(nlist) - 1, 0, -1): maxpos = 0 for location in range(1, fillslot + 1): if nlist[location] > nlist[maxpos]: maxpos = location temp = nlist[fillslot] nlist[fillslot] = nlist[maxpos] nlist[maxpos] =...
class Solution: def romanToInt(self, s): """ :type s: str :rtype: int """ sum = 0 for i, char in enumerate(s): # print(i, char, sum) if char in ('V', 'X') and i-1 >= 0 and s[i-1] == 'I': sum += { 'V': 3, 'X': 8, }.get(char) elif char in ('L', 'C') and i-1 >= 0 and s[i-1] == 'X': ...
class Solution: def roman_to_int(self, s): """ :type s: str :rtype: int """ sum = 0 for (i, char) in enumerate(s): if char in ('V', 'X') and i - 1 >= 0 and (s[i - 1] == 'I'): sum += {'V': 3, 'X': 8}.get(char) elif char in ('L', 'C') and i - 1 >=...
# -*- coding: utf-8 -*- # AtCoder Beginner Contest def main(): s = input() # See: # https://beta.atcoder.jp/contests/abc028/submissions/1915254 values = [s.count(si) for si in 'ABCDEF'] print(' '.join(map(str, values))) if __name__ == '__main__': main()
def main(): s = input() values = [s.count(si) for si in 'ABCDEF'] print(' '.join(map(str, values))) if __name__ == '__main__': main()
name = input("Enter the file name :") file = open(name) count = 0 for line in file: if line.startswith("From"): words = line.split() count = count + 1 sender = words[1] print(sender) print('There were lines in the file with From as the first word', count)
name = input('Enter the file name :') file = open(name) count = 0 for line in file: if line.startswith('From'): words = line.split() count = count + 1 sender = words[1] print(sender) print('There were lines in the file with From as the first word', count)
''' BenJek Program Mengelola pangkalan data akun driver BenJek. ''' drivers = {} BenJek_income = 0 class BenJekDriver(object): ''' Kelas yang merupakan driver BenJek. ''' def __init__(self, driver_name, service_type): ''' Membuat sebuah instance dari BenJekDriver. ...
""" BenJek Program Mengelola pangkalan data akun driver BenJek. """ drivers = {} ben_jek_income = 0 class Benjekdriver(object): """ Kelas yang merupakan driver BenJek. """ def __init__(self, driver_name, service_type): """ Membuat sebuah instance dari BenJekDriver. """ ...
def even_odd(command): numbers = [int(x) for x in input().split()] if command == 'Odd': odd = [x for x in numbers if x % 2 == 1] result = sum(odd) * len(numbers) print(result) elif command == 'Even': even = [x for x in numbers if x % 2 == 0] result = sum(even)...
def even_odd(command): numbers = [int(x) for x in input().split()] if command == 'Odd': odd = [x for x in numbers if x % 2 == 1] result = sum(odd) * len(numbers) print(result) elif command == 'Even': even = [x for x in numbers if x % 2 == 0] result = sum(even) * len(n...
def unique_subsets(super_set, constraint): """ This finds the minimum subset of a list of lists. Args: super_set (list<list>): The list to whittle down. constraint (list): The constraint set. Returns: all_encompassing (list): The minified list of lists. constraint (list...
def unique_subsets(super_set, constraint): """ This finds the minimum subset of a list of lists. Args: super_set (list<list>): The list to whittle down. constraint (list): The constraint set. Returns: all_encompassing (list): The minified list of lists. constraint (list...
# gets the largest range of numbers contained in the array def largestRange(arr): nums = {x:0 for x in arr} #creating hashmap for elements in arr left = right = 0 for num in arr: if nums[num] == 0: left_count = num - 1 right_count = num + 1 while left_count in nums: ...
def largest_range(arr): nums = {x: 0 for x in arr} left = right = 0 for num in arr: if nums[num] == 0: left_count = num - 1 right_count = num + 1 while left_count in nums: nums[left_count] = 1 left_count -= 1 left_count ...
class Point: """Point object""" def __init__(self, coords=None): if coords is None: coords = [0, 0] self.x = coords[0] self.y = coords[1] def coord(self): return [self.x, self.y] class Triangle: """Triangle object""" def __init__(self, points=None): ...
class Point: """Point object""" def __init__(self, coords=None): if coords is None: coords = [0, 0] self.x = coords[0] self.y = coords[1] def coord(self): return [self.x, self.y] class Triangle: """Triangle object""" def __init__(self, points=None): ...
class GetStateError(Exception): pass class UnhandledAction(Exception): pass class GameTreeFailure(Exception): pass
class Getstateerror(Exception): pass class Unhandledaction(Exception): pass class Gametreefailure(Exception): pass
""" from ctapipe.flow.gui.main_window import ModuleApplication from ctapipe.flow.gui.graphwidget import GraphWidget from ctapipe.flow.gui.infolabel import * from ctapipe.flow.gui.guiconnection import * all = ['GraphWidget', 'Ui_MainWindow', 'ModuleApplication', 'GuiConnexion', 'StagerRep', 'ProducerRep', 'Co...
""" from ctapipe.flow.gui.main_window import ModuleApplication from ctapipe.flow.gui.graphwidget import GraphWidget from ctapipe.flow.gui.infolabel import * from ctapipe.flow.gui.guiconnection import * all = ['GraphWidget', 'Ui_MainWindow', 'ModuleApplication', 'GuiConnexion', 'StagerRep', 'ProducerRep', 'Con...
class Solution: def trapRainWater(self, heightMap): """ :type heightMap: List[List[int]] :rtype: int """ if __name__ == '__main__': S = Solution() print(S.makesquare([1,1,2,2,2]))
class Solution: def trap_rain_water(self, heightMap): """ :type heightMap: List[List[int]] :rtype: int """ if __name__ == '__main__': s = solution() print(S.makesquare([1, 1, 2, 2, 2]))
""" @author: David Lei @since: 11/08/2017 @modified: Given a value and denomination of coins, what it the maximum number of unique ways to make up the value. Validate results with: https://prismoskills.appspot.com/lessons/Dynamic_Programming/Chapter_03_-_Max_ways_in_which_coins_can_make_a_sum.jsp Also can submit o...
""" @author: David Lei @since: 11/08/2017 @modified: Given a value and denomination of coins, what it the maximum number of unique ways to make up the value. Validate results with: https://prismoskills.appspot.com/lessons/Dynamic_Programming/Chapter_03_-_Max_ways_in_which_coins_can_make_a_sum.jsp Also can submit o...
def vigenereencoder(w, k): encrypt = [] for i in range(len(w)): x = (ord(w[i]) + ord(k[i])) % 26 x += ord('A') encrypt.append(chr(x)) return "".join(encrypt).lower() def vigeneredecoder(w, k): decrypt = [] for i in range(len(w)): x = (ord(w[i]) - ord(k[i]) + 26) % 2...
def vigenereencoder(w, k): encrypt = [] for i in range(len(w)): x = (ord(w[i]) + ord(k[i])) % 26 x += ord('A') encrypt.append(chr(x)) return ''.join(encrypt).lower() def vigeneredecoder(w, k): decrypt = [] for i in range(len(w)): x = (ord(w[i]) - ord(k[i]) + 26) % 26...
def StringValidator(string_data): is_array = [False, False, False, False, False] for s in string_data: if s.isalnum() and is_array[0] is False: is_array[0] = True if s.isalpha() and is_array[1] is False: is_array[1] = True if s.isdigit() and is_array[2] is False...
def string_validator(string_data): is_array = [False, False, False, False, False] for s in string_data: if s.isalnum() and is_array[0] is False: is_array[0] = True if s.isalpha() and is_array[1] is False: is_array[1] = True if s.isdigit() and is_array[2] is False:...
class Community(object): # def __init__(self, name, proportion, time_befor, time_after): # self.name = name # self.proportion = proportion # self.time_before = time_befor # self.time_after = time_after @property def name(self): return self._name @name.setter ...
class Community(object): @property def name(self): return self._name @name.setter def name(self, value): self._name = value @property def proportion(self): return self._proportion @proportion.setter def proportion(self, value): self._proportion = value...
d=dict() e=dict() i=1 while True: s=input().split() if len(s)==1: d=dict(sorted(d.items(),key=lambda item: len(item[0]),reverse=True)) #d=dict(sorted(d.items(),key=lambda item: item[1])) e=dict(sorted(e.items(),key=lambda item: (item[1],item[0]))) for i,j in e.items(): ...
d = dict() e = dict() i = 1 while True: s = input().split() if len(s) == 1: d = dict(sorted(d.items(), key=lambda item: len(item[0]), reverse=True)) e = dict(sorted(e.items(), key=lambda item: (item[1], item[0]))) for (i, j) in e.items(): print(i) print() for ...
ANTENNAS = {'m000': 'm000, -30:42:39.8, 21:26:38.0, 1035.0, 13.5, -8.254 -207.2925 1.209 5875.794 5877.025, -0:00:39.7 0 -0:04:04.4 -0:04:53.0 0:00:57.8 -0:00:13.9 0:13:45.2 0:00:59.8, 1.22', 'm001': 'm001, -30:42:39.8, 21:26:38.0, 1035.0, 13.5, 1.1275 -171.7635 1.0565 5869.964 5870.974, -0:42:08.0 0 0:01...
antennas = {'m000': 'm000, -30:42:39.8, 21:26:38.0, 1035.0, 13.5, -8.254 -207.2925 1.209 5875.794 5877.025, -0:00:39.7 0 -0:04:04.4 -0:04:53.0 0:00:57.8 -0:00:13.9 0:13:45.2 0:00:59.8, 1.22', 'm001': 'm001, -30:42:39.8, 21:26:38.0, 1035.0, 13.5, 1.1275 -171.7635 1.0565 5869.964 5870.974, -0:42:08.0 0 0:01:...
def hanoi(scheiben, start, hilfe, ziel): def start_hanoi(scheiben, start, hilfe, ziel): if scheiben > 1: yield from start_hanoi(scheiben - 1, start, ziel, hilfe) yield start, ziel yield from start_hanoi(scheiben - 1, hilfe, start, ziel) else: yield sta...
def hanoi(scheiben, start, hilfe, ziel): def start_hanoi(scheiben, start, hilfe, ziel): if scheiben > 1: yield from start_hanoi(scheiben - 1, start, ziel, hilfe) yield (start, ziel) yield from start_hanoi(scheiben - 1, hilfe, start, ziel) else: yield ...
raw_digits = [ """11111 1...1 1...1 1...1 11111""", """..1.. ..1.. ..1.. ..1.. ..1..""", """11111 ....1 11111 1.... 11111""", """11111 ....1 11111 ....1 11111""", """1...1 1...1...
raw_digits = ['11111\n 1...1\n 1...1\n 1...1\n 11111', '..1..\n ..1..\n ..1..\n ..1..\n ..1..', '11111\n ....1\n 11111\n 1....\n 11111', '11111\n ....1\n 11111\n ....1\n 11111', '1...1\n 1...1\n 11111\n ......
#!/usr/bin/python3 def replace_in_list(my_list, idx, element): if idx < 0 or (len(my_list) - 1) < idx: return (my_list) my_list[idx] = element return (my_list)
def replace_in_list(my_list, idx, element): if idx < 0 or len(my_list) - 1 < idx: return my_list my_list[idx] = element return my_list
"""This problem was asked by Quora. Given a string, find the palindrome that can be made by inserting the fewest number of characters as possible anywhere in the word. If there is more than one palindrome of minimum length that can be made, return the lexicographically earliest one (the first one alphabetically). Fo...
"""This problem was asked by Quora. Given a string, find the palindrome that can be made by inserting the fewest number of characters as possible anywhere in the word. If there is more than one palindrome of minimum length that can be made, return the lexicographically earliest one (the first one alphabetically). Fo...
class OutputOptions: def __init__(self, file_name=None, over_write=False): self.file_name = file_name self.over_write = over_write
class Outputoptions: def __init__(self, file_name=None, over_write=False): self.file_name = file_name self.over_write = over_write
#!/usr/bin/env python3 # -*- coding: utf-8 -*- if __name__ == "__main__": # open the newfile.txt in read mode. causes error if no such file exists. fileptr = open("newfile.txt", "x") print(fileptr) if fileptr: print("File created successfully") # closes the opened file fileptr.close()
if __name__ == '__main__': fileptr = open('newfile.txt', 'x') print(fileptr) if fileptr: print('File created successfully') fileptr.close()
''' Created on Sep 16, 2012 @author: Chris ''' FLIGHT= "Flight Move" NAVAL = "Naval Move" FOOT = "Foot Move"
""" Created on Sep 16, 2012 @author: Chris """ flight = 'Flight Move' naval = 'Naval Move' foot = 'Foot Move'
# Given a string S and a character C, return an array of integers # representing the shortest distance from the character C in the string. # S string length is in [1, 10000]. # C is a single character, and guaranteed to be in string S. # All letters in S and C are lowercase. class Solution(object): def shortestToCha...
class Solution(object): def shortest_to_char(self, S, C): prev = float('-inf') distance_to_chars = [] for (i, char) in enumerate(S): if char == C: prev = i distance_to_chars.append(i - prev) prev = float('inf') for i in reversed(xrange...