content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Solution:
"""
@param nums: The integer array.
@param target: Target to find.
@return: The first position of target. Position starts from 0.
"""
def binarySearch(self, nums, target):
left = 0
right = len(nums) - 1
while right != left:
mi... | class Solution:
"""
@param nums: The integer array.
@param target: Target to find.
@return: The first position of target. Position starts from 0.
"""
def binary_search(self, nums, target):
left = 0
right = len(nums) - 1
while right != left:
mid = (left + righ... |
'''
This solution worked out because it has a time complexity of O(N)
'''
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
# write your code in Python 3.6
lengthy = len(A)
if (lengthy == 0 or lengthy == 1):
return 0
diffies... | """
This solution worked out because it has a time complexity of O(N)
"""
def solution(A):
lengthy = len(A)
if lengthy == 0 or lengthy == 1:
return 0
diffies = []
maxy = sum(A)
tempy = 0
for i in range(0, lengthy - 1, 1):
tempy = tempy + A[i]
diffies.append(abs(maxy - te... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
i... | class Solution(object):
def binary_tree_paths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return ''
paths = []
self.binaryTreePathsHelper(root, paths, [])
return paths
def binary_tree_paths_helper(self, ro... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# =============================================================================
#
# =============================================================================
__author__ = 'Chet Coenen'
__copyright__ = 'Copyright 2020'
__credits__ = ['Chet Coenen']
__license__ = '/LICE... | __author__ = 'Chet Coenen'
__copyright__ = 'Copyright 2020'
__credits__ = ['Chet Coenen']
__license__ = '/LICENSE'
__version__ = '1.0'
__maintainer__ = 'Chet Coenen'
__email__ = 'chet.m.coenen@icloud.com'
__socials__ = '@Denimbeard'
__status__ = 'Complete'
__description__ = 'et of code to convert a whole number from ba... |
# coding: utf-8
"""
https://leetcode.com/problems/min-stack/
"""
class MinStack:
def __init__(self):
self.array = []
def push(self, x: int) -> None:
self.array.append(x)
def pop(self) -> None:
self.array.pop()
def top(self) -> int:
return self.array[-1]
def getM... | """
https://leetcode.com/problems/min-stack/
"""
class Minstack:
def __init__(self):
self.array = []
def push(self, x: int) -> None:
self.array.append(x)
def pop(self) -> None:
self.array.pop()
def top(self) -> int:
return self.array[-1]
def get_min(self) -> int... |
# vim:tw=50
"""Tuples
You have already seen one kind of sequence: the
string. Strings are a sequence of one-character
strings - they're strings all the way down. They
are also **immutable**: once you have defined one,
it can never change.
Another immutable seqeunce type in Python is the
**tuple**. You define a tupl... | """Tuples
You have already seen one kind of sequence: the
string. Strings are a sequence of one-character
strings - they're strings all the way down. They
are also **immutable**: once you have defined one,
it can never change.
Another immutable seqeunce type in Python is the
**tuple**. You define a tuple by separati... |
"""
# COMBINATION SUM II
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.
Each number in candidates may only be used once in the combination.
Note: The solution set must not contain duplicate comb... | """
# COMBINATION SUM II
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.
Each number in candidates may only be used once in the combination.
Note: The solution set must not contain duplicate comb... |
# EASY
# find all multiples less than n
# ex Input 6
# arr = [1:True, 2:True ,3:True ,4:True ,5:True ]
# start from 2, mark 2*2, 2*3, 2*4 ... False
# Time O(N^2) Space O(N)
class Solution:
def countPrimes(self, n: int) -> int:
arr = [1 for _ in range(n)]
count = 0
... | class Solution:
def count_primes(self, n: int) -> int:
arr = [1 for _ in range(n)]
count = 0
for i in range(2, n):
j = 2
while arr[i] and i * j < n:
arr[i * j] = 0
j += 1
for i in range(2, n):
if arr[i]:
... |
class ViewModel:
current_model = None
def __init__(self, view):
self.view = view
def switch(self, model):
self.clear_annotation()
self.current_model = model
self.view.show(model)
def get_current_id(self):
return self.current_model.identifier
def clear_ann... | class Viewmodel:
current_model = None
def __init__(self, view):
self.view = view
def switch(self, model):
self.clear_annotation()
self.current_model = model
self.view.show(model)
def get_current_id(self):
return self.current_model.identifier
def clear_anno... |
var1 = "Hello World"
var2 = 100
# while something is true do stuff
while(var2 < 110):
print("still less than 110!")
var2 += 1
else:
print(f"Not less than 110: var2 = {var2}") | var1 = 'Hello World'
var2 = 100
while var2 < 110:
print('still less than 110!')
var2 += 1
else:
print(f'Not less than 110: var2 = {var2}') |
def sort_carries(carries):
sorted_results = {"loss": [], "no_gain": [], "short_gain": [], "med_gain": [], "big_gain": []}
for carry in carries:
if carry < 0:
sorted_results["loss"].append(carry)
elif carry == 0:
sorted_results["no_gain"].append(carry)
elif 0 < c... | def sort_carries(carries):
sorted_results = {'loss': [], 'no_gain': [], 'short_gain': [], 'med_gain': [], 'big_gain': []}
for carry in carries:
if carry < 0:
sorted_results['loss'].append(carry)
elif carry == 0:
sorted_results['no_gain'].append(carry)
elif 0 < car... |
#
# PySNMP MIB module CXPhysicalInterfaceManager-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXPhysicalInterfaceManager-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:17:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, single_value_constraint, value_range_constraint, constraints_intersection) ... |
def df_to_lower(data, cols=None):
'''Convert all string values to lowercase
data : pandas dataframe
The dataframe to be cleaned
cols : str, list, or None
If None, an attempt will be made to turn
all string columns into lowercase.
'''
if isinstance(cols, str):
cols... | def df_to_lower(data, cols=None):
"""Convert all string values to lowercase
data : pandas dataframe
The dataframe to be cleaned
cols : str, list, or None
If None, an attempt will be made to turn
all string columns into lowercase.
"""
if isinstance(cols, str):
cols =... |
def exercise_1():
a_word = "hello world"
f = open("exo1.txt",'a')
f.write(a_word)
f.close()
def save_list2file(sentences, filename):
f = open(filename,"w")
f.close()
| def exercise_1():
a_word = 'hello world'
f = open('exo1.txt', 'a')
f.write(a_word)
f.close()
def save_list2file(sentences, filename):
f = open(filename, 'w')
f.close() |
'''
The .pivot_table() method has several useful arguments, including fill_value and margins.
fill_value replaces missing values with a real value (known as imputation). What to replace missing values with is a topic big enough to have its own course (Dealing with Missing Data in Python), but the simplest thing to... | """
The .pivot_table() method has several useful arguments, including fill_value and margins.
fill_value replaces missing values with a real value (known as imputation). What to replace missing values with is a topic big enough to have its own course (Dealing with Missing Data in Python), but the simplest thing to... |
def matrix_rank(x):
"""
Returns the rank of a Galois field matrix.
References
----------
* https://numpy.org/doc/stable/reference/generated/numpy.linalg.matrix_rank.html
Examples
--------
.. ipython:: python
GF = galois.GF(31)
A = GF.Identity(4); A
np.linalg.ma... | def matrix_rank(x):
"""
Returns the rank of a Galois field matrix.
References
----------
* https://numpy.org/doc/stable/reference/generated/numpy.linalg.matrix_rank.html
Examples
--------
.. ipython:: python
GF = galois.GF(31)
A = GF.Identity(4); A
np.linalg.ma... |
def make_differences(arr):
diff_arr = [0] * (len(arr) - 1)
for i in range(1, len(arr)):
diff_arr[i - 1] = arr[i] - arr[i - 1]
return diff_arr
def paths_reconstruction(arr):
num_paths_arr = [0] * len(arr)
num_paths_arr[-1] = 1
for i in range(len(arr) - 2, -1, -1):
... | def make_differences(arr):
diff_arr = [0] * (len(arr) - 1)
for i in range(1, len(arr)):
diff_arr[i - 1] = arr[i] - arr[i - 1]
return diff_arr
def paths_reconstruction(arr):
num_paths_arr = [0] * len(arr)
num_paths_arr[-1] = 1
for i in range(len(arr) - 2, -1, -1):
num_paths = 0
... |
class EmptyDicomSeriesException(Exception):
"""
Exception that is raised when the given folder does not contain dcm-files.
"""
def __init__(self, *args):
if not args:
args = ('The specified path does not contain dcm-files. Please ensure that '
'the path points to... | class Emptydicomseriesexception(Exception):
"""
Exception that is raised when the given folder does not contain dcm-files.
"""
def __init__(self, *args):
if not args:
args = ('The specified path does not contain dcm-files. Please ensure that the path points to a folder containing a ... |
#DictExample8.py
student = {"name":"sumit","college":"stanford","grade":"A"}
#this will prints whole key and values pairs using items()
for x in student.items():
print(x)
print("-----------------------------------------------------")
#you can also store key and value in two differnet variable li... | student = {'name': 'sumit', 'college': 'stanford', 'grade': 'A'}
for x in student.items():
print(x)
print('-----------------------------------------------------')
for (x, y) in student.items():
print(x, '-', y) |
# -*- coding: utf-8 -*-
def uninstall(portal, reinstall=False):
"""
launch uninstall profile
"""
setup_tool = portal.portal_setup
setup_tool.runAllImportStepsFromProfile(
'profile-Products.PloneGlossary:uninstall')
| def uninstall(portal, reinstall=False):
"""
launch uninstall profile
"""
setup_tool = portal.portal_setup
setup_tool.runAllImportStepsFromProfile('profile-Products.PloneGlossary:uninstall') |
class config:
global auth; auth = "YOUR TOKEN" # Enter your discord token for Auto-Login.
global prefix; prefix = "$" # Enter your prefix for selfbot.
global nitro_sniper; nitro_sniper = "true" # 'true' to enable nitro sniper, 'false' to disable.
global giveaway_sniper; giveaway_sniper = "true" # 't... | class Config:
global auth
auth = 'YOUR TOKEN'
global prefix
prefix = '$'
global nitro_sniper
nitro_sniper = 'true'
global giveaway_sniper
giveaway_sniper = 'true' |
#
# PySNMP MIB module HUAWEI-IMA-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/HUAWEI-IMA-MIB
# Produced by pysmi-0.0.7 at Sun Jul 3 11:25:20 2016
# On host localhost.localdomain platform Linux version 3.10.0-229.7.2.el7.x86_64 by user root
# Using Python version 2.7.5 (default, Jun 24 201... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, constraints_intersection, value_size_constraint, value_range_constraint) ... |
def sort_a_little_bit(items, begin_index, end_index):
left_index = begin_index
pivot_index = end_index
pivot_value = items[pivot_index]
while pivot_index != left_index:
item = items[left_index]
if item <= pivot_value:
left_index += 1
continue
items[left_... | def sort_a_little_bit(items, begin_index, end_index):
left_index = begin_index
pivot_index = end_index
pivot_value = items[pivot_index]
while pivot_index != left_index:
item = items[left_index]
if item <= pivot_value:
left_index += 1
continue
items[left_in... |
@auth.requires_membership('admin')
def album():
grid = SQLFORM.grid(db.t_mtalbum)
return dict(grid=grid)
@auth.requires_membership('admin')
def dataset():
grid = SQLFORM.grid(db.t_mtdataset)
return dict(grid=grid)
@auth.requires_membership('admin')
def item():
grid = SQLFORM.grid(db.t_mtitem)
... | @auth.requires_membership('admin')
def album():
grid = SQLFORM.grid(db.t_mtalbum)
return dict(grid=grid)
@auth.requires_membership('admin')
def dataset():
grid = SQLFORM.grid(db.t_mtdataset)
return dict(grid=grid)
@auth.requires_membership('admin')
def item():
grid = SQLFORM.grid(db.t_mtitem)
... |
n = int(input().strip())
value1 = 0
value2 = 0
for i in range(n):
a_t = [int(a_temp) for a_temp in input().strip().split(' ')]
value1 += a_t[i]
value2 += a_t[-1-i]
print(abs(value2-value1))
| n = int(input().strip())
value1 = 0
value2 = 0
for i in range(n):
a_t = [int(a_temp) for a_temp in input().strip().split(' ')]
value1 += a_t[i]
value2 += a_t[-1 - i]
print(abs(value2 - value1)) |
def test(): # noqa
assert 1 + 1 == 2
def test_multi_line_args(math_fixture, *args, **kwargs): # noqa
assert 1 + 1 == 2
| def test():
assert 1 + 1 == 2
def test_multi_line_args(math_fixture, *args, **kwargs):
assert 1 + 1 == 2 |
def checkio(str_number, radix):
try:
return int(str_number,radix)
except:
return -1
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio("AF", 16) == 175, "Hex"
assert checkio("101", 2) == 5, "B... | def checkio(str_number, radix):
try:
return int(str_number, radix)
except:
return -1
if __name__ == '__main__':
assert checkio('AF', 16) == 175, 'Hex'
assert checkio('101', 2) == 5, 'Bin'
assert checkio('101', 5) == 26, '5 base'
assert checkio('Z', 36) == 35, 'Z base'
assert ... |
async def _asyncWrapWith(res, wrapper_fn):
result = await res
return wrapper_fn(result["id"])
def wrapWith(res, wrapper_fn):
if isinstance(res, dict):
return wrapper_fn(res)
else:
return _asyncWrapWith(res, wrapper_fn)
| async def _asyncWrapWith(res, wrapper_fn):
result = await res
return wrapper_fn(result['id'])
def wrap_with(res, wrapper_fn):
if isinstance(res, dict):
return wrapper_fn(res)
else:
return _async_wrap_with(res, wrapper_fn) |
#!/usr/bin/env python
# encoding: utf-8
def run(whatweb, pluginname):
whatweb.recog_from_file(pluginname, "themes\default\Wikiwyg\Wikiwy\Phpwiki.js", "phpwiki")
| def run(whatweb, pluginname):
whatweb.recog_from_file(pluginname, 'themes\\default\\Wikiwyg\\Wikiwy\\Phpwiki.js', 'phpwiki') |
__author__ = "Prikly Grayp"
__license__ = "MIT"
__version__ = "1.0.0"
__email__ = "priklygrayp@gmail.com"
__status__ = "Development"
def first(iterable):
iterator = iter(iterable)
try:
return next(iterator)
except StopIteration:
raise ValueError('iterable is empty')
first(['Spring', 'Summ... | __author__ = 'Prikly Grayp'
__license__ = 'MIT'
__version__ = '1.0.0'
__email__ = 'priklygrayp@gmail.com'
__status__ = 'Development'
def first(iterable):
iterator = iter(iterable)
try:
return next(iterator)
except StopIteration:
raise value_error('iterable is empty')
first(['Spring', 'Summe... |
# https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/submissions/
class Solution:
def kidsWithCandies(self, candies: [int], extraCandies: int) -> [bool]:
maxCandies = max(candies, default=0)
return [True if v + extraCandies >= maxCandies else False for v in candies] | class Solution:
def kids_with_candies(self, candies: [int], extraCandies: int) -> [bool]:
max_candies = max(candies, default=0)
return [True if v + extraCandies >= maxCandies else False for v in candies] |
# Alternating Characters
# Developer: Murillo Grubler
# Link: https://www.hackerrank.com/challenges/alternating-characters/problem
# Time complexity: O(n)
def alternatingCharacters(s):
sumChars = 0
for i in range(len(s)):
if i == 0 or tempChar != s[i]:
tempChar = s[i]
continue
... | def alternating_characters(s):
sum_chars = 0
for i in range(len(s)):
if i == 0 or tempChar != s[i]:
temp_char = s[i]
continue
if tempChar == s[i]:
sum_chars += 1
return sumChars
q = int(input().strip())
for a0 in range(q):
print(alternating_characters(... |
# A simple use of user defined functions in python
def greet_user(name):
print(f"Hi {name}!")
print("Welcome Aboard!")
print("Start")
greet_user("Kwadwo")
greet_user("Sammy")
print("finish")
| def greet_user(name):
print(f'Hi {name}!')
print('Welcome Aboard!')
print('Start')
greet_user('Kwadwo')
greet_user('Sammy')
print('finish') |
#!/usr/bin/env python3
""" binary_tree contains methods to search a binary tree
"""
def is_valid_binary_search_tree(node):
"""
Traverses tree depth first in order
"""
return is_valid_bst(node, float('-inf'), float('inf'))
def is_valid_bst(node, value_min, value_max):
"""
Traverses tree depth... | """ binary_tree contains methods to search a binary tree
"""
def is_valid_binary_search_tree(node):
"""
Traverses tree depth first in order
"""
return is_valid_bst(node, float('-inf'), float('inf'))
def is_valid_bst(node, value_min, value_max):
"""
Traverses tree depth first in order
Note ... |
"""
In a given grid, each cell can have one of three values:
- the value 0 representing an empty cell;
- the value 1 representing a fresh orange;
- the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) to a
rotten orange becomes ... | """
In a given grid, each cell can have one of three values:
- the value 0 representing an empty cell;
- the value 1 representing a fresh orange;
- the value 2 representing a rotten orange.
Every minute, any fresh orange that is adjacent (4-directionally) to a
rotten orange becomes ... |
"""
A proxy provides a surrogate or place holder to provide
access to an object.
Ex1:
Use an extra level of indirection to support distributed,
controlled, or conditional access.
"""
class SubjectInterface:
"""
Define the common interface for RealSubject and Proxy so that a
Proxy can be used anywh... | """
A proxy provides a surrogate or place holder to provide
access to an object.
Ex1:
Use an extra level of indirection to support distributed,
controlled, or conditional access.
"""
class Subjectinterface:
"""
Define the common interface for RealSubject and Proxy so that a
Proxy can be used anywh... |
"""
30 Dec 2015.
code interpretation by Dealga McArdle of this paper.
http://www.cc.gatech.edu/~jarek/graphics/papers/04PolygonBooleansMargalit.pdf
It's the first thing that came up after a 'polygon unions' Google search. This repo
is an attempt at getting that psuedo code into a working state. It might be over my... | """
30 Dec 2015.
code interpretation by Dealga McArdle of this paper.
http://www.cc.gatech.edu/~jarek/graphics/papers/04PolygonBooleansMargalit.pdf
It's the first thing that came up after a 'polygon unions' Google search. This repo
is an attempt at getting that psuedo code into a working state. It might be over my... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
dummyHead = ListNode(float('-inf'), head)
currentNode = dummyHead.next
... | class Solution:
def insertion_sort_list(self, head: ListNode) -> ListNode:
dummy_head = list_node(float('-inf'), head)
current_node = dummyHead.next
while currentNode and currentNode.next:
if currentNode.val <= currentNode.next.val:
current_node = currentNode.nex... |
def Factorial_Head(n):
# Base Case: 0! = 1
if(n == 0):
return 1
# Recursion
result1 = Factorial_Head(n-1)
result2 = n * result1
return result2
def Factorial_Tail(n, accumulator):
# Base Case: 0! = 1
if( n == 0):
return accumulator
# Recursion
return ... | def factorial__head(n):
if n == 0:
return 1
result1 = factorial__head(n - 1)
result2 = n * result1
return result2
def factorial__tail(n, accumulator):
if n == 0:
return accumulator
return factorial__tail(n - 1, n * accumulator)
n = 5
head = factorial__head(n)
print(f'Factorial {... |
class palin:
def __init__(self,string):
self.string=string
s=self.string
a=[]
for i in s:
a.append(i)
b=[]
for i in range(len(a)-1,-1,-1):
b.append(a[i])
if(a==b):
print('True')
else:
print('False')
# if __name__=='__main__':
# obj=palin('kaif')
# obj.check() | class Palin:
def __init__(self, string):
self.string = string
s = self.string
a = []
for i in s:
a.append(i)
b = []
for i in range(len(a) - 1, -1, -1):
b.append(a[i])
if a == b:
print('True')
else:
print... |
class UnboundDataPullException(Exception):
pass
class DataPullInProgressError(Exception):
pass
| class Unbounddatapullexception(Exception):
pass
class Datapullinprogresserror(Exception):
pass |
print("To define a new function, you use 'def+<your_function_name>+(+<your_params_comma_separated>+)', example: 'def myFunction(param1, param2, ..., paramn)'")
# Creating a simple function and calling it
print("Creating simple function and calling it")
def sayHello(name):
print("Hello",name)
sayHello("balam909")
# D... | print("To define a new function, you use 'def+<your_function_name>+(+<your_params_comma_separated>+)', example: 'def myFunction(param1, param2, ..., paramn)'")
print('Creating simple function and calling it')
def say_hello(name):
print('Hello', name)
say_hello('balam909')
print('Creating a simple function with def... |
ecn_show_config_output="""\
Profile: AZURE_LOSSLESS
----------------------- -------
red_max_threshold 2097152
wred_green_enable true
ecn ecn_all
green_min_threshold 1048576
red_min_threshold 1048576
wred_yellow_enable true
yellow_min_threshold 1048576
green_max_... | ecn_show_config_output = 'Profile: AZURE_LOSSLESS\n----------------------- -------\nred_max_threshold 2097152\nwred_green_enable true\necn ecn_all\ngreen_min_threshold 1048576\nred_min_threshold 1048576\nwred_yellow_enable true\nyellow_min_threshold 1048576\ngre... |
# package org.apache.helix.store
#from org.apache.helix.store import *
class HelixPropertyListener:
def onDataChange(self, path):
"""
Returns void
Parameters:
path: String
"""
pass
def onDataCreate(self, path):
"""
Returns void
Pa... | class Helixpropertylistener:
def on_data_change(self, path):
"""
Returns void
Parameters:
path: String
"""
pass
def on_data_create(self, path):
"""
Returns void
Parameters:
path: String
"""
pass
de... |
class Credentials:
"""
Class that generates new instances of credentials.
"""
credentials_list = [] #empty user list
def __init__(self,account,username,password):
self.account = account
self.username = username
self.password = password
def save_credentials(self):
... | class Credentials:
"""
Class that generates new instances of credentials.
"""
credentials_list = []
def __init__(self, account, username, password):
self.account = account
self.username = username
self.password = password
def save_credentials(self):
"""
... |
class Solution:
def brokenCalc(self, X: int, Y: int) -> int:
count = 0
while Y>X:
if Y%2==0:
Y //= 2
else:
Y += 1
count += 1
return count + X - Y
| class Solution:
def broken_calc(self, X: int, Y: int) -> int:
count = 0
while Y > X:
if Y % 2 == 0:
y //= 2
else:
y += 1
count += 1
return count + X - Y |
s = float(input('What is the salary of the functionary? $'))
if s > 1250.00:
t = s + s * 0.10
print(f'His salary increased by 10% and is now {t:.2f}')
else:
f = s + s * 0.15
print(f'His salary increased by 15% and is now {f:.2f}')
| s = float(input('What is the salary of the functionary? $'))
if s > 1250.0:
t = s + s * 0.1
print(f'His salary increased by 10% and is now {t:.2f}')
else:
f = s + s * 0.15
print(f'His salary increased by 15% and is now {f:.2f}') |
condition_table_true = ["lt", "gt", "eq"]
condition_table_false = ["ge", "le", "ne"]
trap_condition_table = {
1: "lgt",
2: "llt",
4: "eq",
5: "lge",
8: "gt",
12: "ge",
16: "lt",
20: "le",
31: "u"
}
spr_table = {
8: "lr",
9: "ctr"
}
def decodeI(value):
return (value >> ... | condition_table_true = ['lt', 'gt', 'eq']
condition_table_false = ['ge', 'le', 'ne']
trap_condition_table = {1: 'lgt', 2: 'llt', 4: 'eq', 5: 'lge', 8: 'gt', 12: 'ge', 16: 'lt', 20: 'le', 31: 'u'}
spr_table = {8: 'lr', 9: 'ctr'}
def decode_i(value):
return (value >> 2 & 16777215, value >> 1 & 1, value & 1)
def dec... |
__version__ = "2.2.3"
__title__ = "taxidTools"
__description__ = "A Python Toolkit for Taxonomy"
__author__ = "Gregoire Denay"
__author_email__ = 'gregoire.denay@cvua-rrw.de'
__licence__ = 'BSD License'
__url__ = "https://github.com/CVUA-RRW/taxidTools"
| __version__ = '2.2.3'
__title__ = 'taxidTools'
__description__ = 'A Python Toolkit for Taxonomy'
__author__ = 'Gregoire Denay'
__author_email__ = 'gregoire.denay@cvua-rrw.de'
__licence__ = 'BSD License'
__url__ = 'https://github.com/CVUA-RRW/taxidTools' |
#!/usr/bin/python3.3
S1 = 'abc'
S2 = 'xyz123'
z = zip(S1, S2)
print(list(z))
print(list(zip([1, 2, 3], [2, 3, 4, 5])))
print(list(map(abs, [-2, -1, 0, 1, 2])))
print(list(map(pow, [1, 2, 3], [2, 3, 4, 5])))
print(list(map(lambda x, y: x+y, open('script2.py'), open('script2.py'))))
print([x+y for (x, y) in zip(ope... | s1 = 'abc'
s2 = 'xyz123'
z = zip(S1, S2)
print(list(z))
print(list(zip([1, 2, 3], [2, 3, 4, 5])))
print(list(map(abs, [-2, -1, 0, 1, 2])))
print(list(map(pow, [1, 2, 3], [2, 3, 4, 5])))
print(list(map(lambda x, y: x + y, open('script2.py'), open('script2.py'))))
print([x + y for (x, y) in zip(open('script2.py'), open('... |
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
ns = ''
for ch in s:
if ch.isalnum():
ns += ch.lower()
return ns == ns[::-1]
| class Solution(object):
def is_palindrome(self, s):
"""
:type s: str
:rtype: bool
"""
ns = ''
for ch in s:
if ch.isalnum():
ns += ch.lower()
return ns == ns[::-1] |
class LPGeneralException(Exception):
"""Raised when generic exceptions when using 'LPData' class"""
def __init__(self, msg):
self.msg = msg
class LPOptimizationFailedException(Exception):
"""Raised when optimization fails when using LPData class"""
pass
| class Lpgeneralexception(Exception):
"""Raised when generic exceptions when using 'LPData' class"""
def __init__(self, msg):
self.msg = msg
class Lpoptimizationfailedexception(Exception):
"""Raised when optimization fails when using LPData class"""
pass |
def make_singleton(class_):
def __new__(cls, *args, **kwargs):
raise Exception('class', cls.__name__, 'is a singleton')
class_.__new__ = __new__
| def make_singleton(class_):
def __new__(cls, *args, **kwargs):
raise exception('class', cls.__name__, 'is a singleton')
class_.__new__ = __new__ |
def main():
a = int(input("Insira a idade do nadador: "))
if(a <= 5):
print("Categoria: Bebe")
elif(a > 5 and a <= 7):
print("Categoria: Infantil A")
elif(a >= 8 and a <= 10):
print("Categoria: Infantil B")
elif(a >= 11 and a <= 13):
print("Categoria: Juvenil... | def main():
a = int(input('Insira a idade do nadador: '))
if a <= 5:
print('Categoria: Bebe')
elif a > 5 and a <= 7:
print('Categoria: Infantil A')
elif a >= 8 and a <= 10:
print('Categoria: Infantil B')
elif a >= 11 and a <= 13:
print('Categoria: Juvenil A')
elif... |
#Contains an (x,y) point, usually in projected coords.
class Point:
def __init__(self, x:float, y:float):
self.x = x
self.y = y
def __repr__(self):
return "Point(%f,%f)" % (self.x, self.y)
def __str__(self):
return "(%f,%f)" % (self.x, self.y)
#Contains a (lat/lng) location, usually as +/- rat... | class Point:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def __repr__(self):
return 'Point(%f,%f)' % (self.x, self.y)
def __str__(self):
return '(%f,%f)' % (self.x, self.y)
class Location:
def __init__(self, lat: float, lng: float):
self.lat... |
class Node:
pass
class BinaryNode(Node):
def __init__(self, des, src1, src2):
self.des=des
self.src1=src1
self.src2=src2
class AdduNode(BinaryNode):
def __str__(self):
return f'addu {self.des}, {self.src1}, {self.src2}'
class MuloNode(BinaryNode):
def __str__(... | class Node:
pass
class Binarynode(Node):
def __init__(self, des, src1, src2):
self.des = des
self.src1 = src1
self.src2 = src2
class Addunode(BinaryNode):
def __str__(self):
return f'addu {self.des}, {self.src1}, {self.src2}'
class Mulonode(BinaryNode):
def __str__(... |
n, m = map(int, input().split())
connected = []
seeds = []
for i in range(0, n):
connected.append([])
for i in range(0, m):
a, b = map(int, input().split())
if (b not in connected[a-1]):
connected[a-1].append(b)
if (a not in connected[b-1]):
connected[b-1].append(a)
print(connected)
# for each pasture
fo... | (n, m) = map(int, input().split())
connected = []
seeds = []
for i in range(0, n):
connected.append([])
for i in range(0, m):
(a, b) = map(int, input().split())
if b not in connected[a - 1]:
connected[a - 1].append(b)
if a not in connected[b - 1]:
connected[b - 1].append(a)
print(connect... |
class Rule:
def __init__(self, rule_id):
self.rule_id = rule_id
def __eq__(self, other):
return self.rule_id == other.rule_id
class RuleSet:
def __init__(self, **kwargs):
self.rules = {}
for k, v in kwargs.items():
self.rules[k] = Rule(v)
def __getattr__(s... | class Rule:
def __init__(self, rule_id):
self.rule_id = rule_id
def __eq__(self, other):
return self.rule_id == other.rule_id
class Ruleset:
def __init__(self, **kwargs):
self.rules = {}
for (k, v) in kwargs.items():
self.rules[k] = rule(v)
def __getattr_... |
class Solution(object):
def validPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
l, r = 0, len(s)-1
count = 0
def get_result(l,r,s,count,forward=True):
while l < r:
if s[l] == s[r]:
l += 1; r -= 1
... | class Solution(object):
def valid_palindrome(self, s):
"""
:type s: str
:rtype: bool
"""
(l, r) = (0, len(s) - 1)
count = 0
def get_result(l, r, s, count, forward=True):
while l < r:
if s[l] == s[r]:
l += 1
... |
#! /usr/bin/python
# -*- coding: iso-8859-15 -*-
def sc(n):
if n > 1:
r = sc(n - 1) + n ** 3
else:
r = 1
return r
a = int(input("Desde: "))
b = int(input("Hasta: "))
for i in range(a, b+1):
if sc(i):
print ("Numero primo: ",i) | def sc(n):
if n > 1:
r = sc(n - 1) + n ** 3
else:
r = 1
return r
a = int(input('Desde: '))
b = int(input('Hasta: '))
for i in range(a, b + 1):
if sc(i):
print('Numero primo: ', i) |
sum(
1,
2, 3,
5,
)
sum(
1,
2, 3,
5)
| sum(1, 2, 3, 5)
sum(1, 2, 3, 5) |
class AccountError(Exception):
"""
Raised when the API can't locate any accounts for the user
"""
pass
| class Accounterror(Exception):
"""
Raised when the API can't locate any accounts for the user
"""
pass |
class BackendError(Exception):
pass
class FieldError(Exception):
pass
| class Backenderror(Exception):
pass
class Fielderror(Exception):
pass |
def read_spreadsheet():
file_name = "Data/day2.txt"
file = open(file_name, "r")
spreadsheet = []
for line in file:
line = list(map(int, line.split()))
spreadsheet.append(line)
return spreadsheet
def checksum(spreadsheet):
total = 0
for row in... | def read_spreadsheet():
file_name = 'Data/day2.txt'
file = open(file_name, 'r')
spreadsheet = []
for line in file:
line = list(map(int, line.split()))
spreadsheet.append(line)
return spreadsheet
def checksum(spreadsheet):
total = 0
for row in spreadsheet:
total += ma... |
#!/usr/bin/env python3
# recherche empirique
aiguille = list()
for t in range(0, 43200):
h = t / 120
m = (t / 10) % 360
if abs(abs(h - m) - 90) < 0.05 or abs(abs(h - m) - 270) < 0.05:
if len(aiguille) > 0 and (t - aiguille[-1][0]) < 2:
del aiguille[-1]
hh, mm = int(h / 30), int(... | aiguille = list()
for t in range(0, 43200):
h = t / 120
m = t / 10 % 360
if abs(abs(h - m) - 90) < 0.05 or abs(abs(h - m) - 270) < 0.05:
if len(aiguille) > 0 and t - aiguille[-1][0] < 2:
del aiguille[-1]
(hh, mm) = (int(h / 30), int(m / 6))
aiguille.append((t, f'{hh:02d}:... |
"""
Given a string S, find the longest palindromic substring in S.
Substring of string S:
S[i...j] where 0 <= i <= j < len(S)
Palindrome string:
A string which reads the same backwards. More formally, S is palindrome if reverse(S) = S.
Incase of conflict, return the substring which occurs first ( with the least st... | """
Given a string S, find the longest palindromic substring in S.
Substring of string S:
S[i...j] where 0 <= i <= j < len(S)
Palindrome string:
A string which reads the same backwards. More formally, S is palindrome if reverse(S) = S.
Incase of conflict, return the substring which occurs first ( with the least st... |
"""
Constants and methods used in testing
"""
class Colors():
WHITE = 'rgba(255, 255, 255, 1)'
RED_ERROR = 'rgba(220, 53, 69, 1)'
users = {
'valid_user': {'first_name':'Shinji',
'last_name': 'Ikari',
'user_name': 'sikari',
'address1': '123 Main St.',
... | """
Constants and methods used in testing
"""
class Colors:
white = 'rgba(255, 255, 255, 1)'
red_error = 'rgba(220, 53, 69, 1)'
users = {'valid_user': {'first_name': 'Shinji', 'last_name': 'Ikari', 'user_name': 'sikari', 'address1': '123 Main St.', 'country': 'United States', 'state': 'California', 'zip': '123... |
# Iterate through the array and maintain the min_so_far value. at each step profit = max(profit, arr[i]-min_so_far)
class Solution:
def maxProfit(self, prices: List[int]) -> int:
i = 0
max_profit = 0
min_so_far = 99999
for i in range(len(prices)):
max_profit = m... | class Solution:
def max_profit(self, prices: List[int]) -> int:
i = 0
max_profit = 0
min_so_far = 99999
for i in range(len(prices)):
max_profit = max(max_profit, prices[i] - min_so_far)
min_so_far = min(min_so_far, prices[i])
return max_profit |
def f(xs):
ys = 'string'
for x in xs:
g(ys)
def g(x):
return x.lower()
| def f(xs):
ys = 'string'
for x in xs:
g(ys)
def g(x):
return x.lower() |
def get_standard_config_dictionary(values):
run_dict = {}
run_dict['Configuration Name'] = values['standard_name_input']
run_dict['Model file'] = values['standard_model_input']
var_values = list(filter(''.__ne__, values['standard_value_input'].split('\n')))
run_dict['Parameter values'] = list(map(la... | def get_standard_config_dictionary(values):
run_dict = {}
run_dict['Configuration Name'] = values['standard_name_input']
run_dict['Model file'] = values['standard_model_input']
var_values = list(filter(''.__ne__, values['standard_value_input'].split('\n')))
run_dict['Parameter values'] = list(map(la... |
A, B, C = input() .split()
A = float(A)
B = float(B)
C = float(C)
triangulo = float(A * C /2)
circulo = float(3.14159 * C**2)
trapezio = float(((A + B) * C) /2)
quadrado = float(B * B)
retangulo = float(A * B)
print("TRIANGULO: %0.3f" %triangulo)
print("CIRCULO: %0.3f" %circulo)
print("TRAPEZIO: %0.3f" %trapezio)
print... | (a, b, c) = input().split()
a = float(A)
b = float(B)
c = float(C)
triangulo = float(A * C / 2)
circulo = float(3.14159 * C ** 2)
trapezio = float((A + B) * C / 2)
quadrado = float(B * B)
retangulo = float(A * B)
print('TRIANGULO: %0.3f' % triangulo)
print('CIRCULO: %0.3f' % circulo)
print('TRAPEZIO: %0.3f' % trapezio)... |
__all__ = [
'TargetApiError',
'TargetApiParamsError',
'TargetApiBadRequestError',
'TargetApiUnauthorizedError',
'TargetApiNotFoundError',
'TargetApiMethodNotAllowedError',
'TargetApiServerError',
'TargetApiServiceUnavailableError',
'TargetApiParameterNotImplementedError',
'Target... | __all__ = ['TargetApiError', 'TargetApiParamsError', 'TargetApiBadRequestError', 'TargetApiUnauthorizedError', 'TargetApiNotFoundError', 'TargetApiMethodNotAllowedError', 'TargetApiServerError', 'TargetApiServiceUnavailableError', 'TargetApiParameterNotImplementedError', 'TargetApiUnknownError']
class Targetapierror(E... |
PAD = 0
UNK = 1
EOS = 2
BOS = 3
PAD_WORD = '<blank>'
UNK_WORD = '<unk>'
EOS_WORD = '<eos>'
BOS_WORD = '<bos>' | pad = 0
unk = 1
eos = 2
bos = 3
pad_word = '<blank>'
unk_word = '<unk>'
eos_word = '<eos>'
bos_word = '<bos>' |
#!/usr/bin/env python3
class Solution(object):
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
state = [{},
{'blank': 1, 'sign': 2, 'digit': 3, '.': 4},
{'digit': 3, '.': 4},
{'digit': 3, '.': 5, 'e': 6, 'blank': 9... | class Solution(object):
def is_number(self, s):
"""
:type s: str
:rtype: bool
"""
state = [{}, {'blank': 1, 'sign': 2, 'digit': 3, '.': 4}, {'digit': 3, '.': 4}, {'digit': 3, '.': 5, 'e': 6, 'blank': 9}, {'digit': 5}, {'digit': 5, 'e': 6, 'blank': 9}, {'sign': 7, 'digit': 8}... |
class File:
def __init__(self, name: str, kind: str, content=None, base64=False):
self.content = content
self.name = name
self.type = kind
self.base64 = base64
def save(self, path):
with open(path, 'wb') as f:
f.write(self.content)
def open(self, path):
... | class File:
def __init__(self, name: str, kind: str, content=None, base64=False):
self.content = content
self.name = name
self.type = kind
self.base64 = base64
def save(self, path):
with open(path, 'wb') as f:
f.write(self.content)
def open(self, path):... |
# README! #
# You can add your own maps, just follow the format:
# mapX = ("Name shown to the user", PUT THE THREE QUOTATION MARKS (""") HERE
# MAP GOES HERE, you can use any characters, but you can only define the map's borders
# PUT THREE QUOTATION MARKS (""") HERE
# #################################### #
# You MUS... | map1 = ('Tall', '\n############################################################\n# #\n# #\n# #\n# ... |
class Chain():
def __init__(self, val):
self.val = val
def add(self, b):
self.val += b
return self
def sub(self, b):
self.val -= b
return self
def mul(self, b):
self.val *= b
return self
print(Chain(5).add(5).sub(2).mul(10))
| class Chain:
def __init__(self, val):
self.val = val
def add(self, b):
self.val += b
return self
def sub(self, b):
self.val -= b
return self
def mul(self, b):
self.val *= b
return self
print(chain(5).add(5).sub(2).mul(10)) |
#passed Test Set 1 in py
# def romanToInt(s):
# translations = {
# "I": 1,
# "V": 5,
# "X": 10,
# "L": 50,
# "C": 100,
# "D": 500,
# "M": 1000
# }
# number = 0
# s = s.replace("IV", "IIII").replace("IX",... | def make_change(s):
s = s.replace('01', '2')
s = s.replace('12', '3')
s = s.replace('23', '4')
s = s.replace('34', '5')
s = s.replace('45', '6')
s = s.replace('56', '7')
s = s.replace('67', '8')
s = s.replace('78', '9')
s = s.replace('89', '0')
s = s.replace('90', '1')
return... |
EQUAL_ROWS_DATAFRAME_NAME = \
'dataframe_of_equal_rows'
NON_EQUAL_ROWS_DATAFRAME_NAME = \
'dataframe_of_non_equal_rows'
| equal_rows_dataframe_name = 'dataframe_of_equal_rows'
non_equal_rows_dataframe_name = 'dataframe_of_non_equal_rows' |
# HEAD
# Augmented Assignment Operators
# DESCRIPTION
# Describes basic usage of all the augmented operators available
# RESOURCES
#
foo = 40
# Addition augmented operator
foo += 1
print(foo)
# Subtraction augmented operator
foo -= 1
print(foo)
# Multiplication augmented operator
foo *= 1
print(foo)
# Division au... | foo = 40
foo += 1
print(foo)
foo -= 1
print(foo)
foo *= 1
print(foo)
foo /= 2
print(foo)
foo %= 3
print(foo)
foo //= 3
print(foo)
str_one = 'Testing'
list_one = [1, 2]
str_one += ' String'
print(strOne)
list_one *= 2
print(listOne) |
def test_client_can_get_avatars(client):
resp = client.get('/api/avatars')
assert resp.status_code == 200
def test_client_gets_correct_avatars_fields(client):
resp = client.get('/api/avatars')
assert 'offset' in resp.json
assert resp.json['offset'] is None
assert 'total' in resp.json
asser... | def test_client_can_get_avatars(client):
resp = client.get('/api/avatars')
assert resp.status_code == 200
def test_client_gets_correct_avatars_fields(client):
resp = client.get('/api/avatars')
assert 'offset' in resp.json
assert resp.json['offset'] is None
assert 'total' in resp.json
assert... |
"""
Question:
Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence
after sorting them alphabetically.
Suppose the following input is supplied to the program:
without,hello,bag,world
Then, the output should be:
bag,hello,without,world
"""
enter_st... | """
Question:
Write a program that accepts a comma separated sequence of words as input and prints the words in a comma-separated sequence
after sorting them alphabetically.
Suppose the following input is supplied to the program:
without,hello,bag,world
Then, the output should be:
bag,hello,without,world
"""
enter_st... |
# 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 diameterOfBinaryTree(self, root: TreeNode) -> int:
def helper(root):
if root is None... | class Solution:
def diameter_of_binary_tree(self, root: TreeNode) -> int:
def helper(root):
if root is None:
return (0, 0)
if root.left is None and root.right is None:
return (1, 1)
(l1, m1) = helper(root.left)
(l2, m2) = help... |
data_in: str = str()
balance: float = float()
deposit: float = float()
while True:
data_in = input()
if data_in == 'NoMoreMoney':
break
deposit = float(data_in)
if deposit < 0:
print('Invalid operation!')
break
print(f'Increase: {deposit:.2f}')
balance +=... | data_in: str = str()
balance: float = float()
deposit: float = float()
while True:
data_in = input()
if data_in == 'NoMoreMoney':
break
deposit = float(data_in)
if deposit < 0:
print('Invalid operation!')
break
print(f'Increase: {deposit:.2f}')
balance += deposit
print(f'... |
class Solution:
# # Track unsorted indexes using sets (Revisited), O(n*m) time, O(n) space
# def minDeletionSize(self, strs: List[str]) -> int:
# n, m = len(strs), len(strs[0])
# unsorted = set(range(n-1))
# res = 0
# for j in range(m):
# if any(strs[i][j] > strs[i+1]... | class Solution:
def min_deletion_size(self, A: List[str]) -> int:
(res, n, m) = (0, len(A), len(A[0]))
unsorted = set(range(n - 1))
for j in range(m):
if any((A[i][j] > A[i + 1][j] for i in unsorted)):
res += 1
else:
unsorted -= {i for... |
# code
t = int(input())
for _ in range(t):
n = int(input())
temp = list(map(int, input().split()))
l = [temp[i:i+n] for i in range(0, len(temp), n)]
del temp
weight = 1
for i in range(n):
l.append(list(map(int, input().split(','))))
row = 0
col = 0
suml = 0
while True:
... | t = int(input())
for _ in range(t):
n = int(input())
temp = list(map(int, input().split()))
l = [temp[i:i + n] for i in range(0, len(temp), n)]
del temp
weight = 1
for i in range(n):
l.append(list(map(int, input().split(','))))
row = 0
col = 0
suml = 0
while True:
... |
def Efrase(frase):
nums = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
if frase.count('.') == 1 and frase[len(frase) - 1] != '.' or frase == '.':
return False
elif frase.count('.') > 1:
return False
for j in range(0, 10):
if nums[j] in frase:
return False
... | def efrase(frase):
nums = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
if frase.count('.') == 1 and frase[len(frase) - 1] != '.' or frase == '.':
return False
elif frase.count('.') > 1:
return False
for j in range(0, 10):
if nums[j] in frase:
return False
re... |
#!/usr/bin/env python
outlinks_file = open('link_graph_ly.txt', 'r')
inlinks_file = open('link_graph_ly2.txt', 'w')
inlinks = {} # url -> list of inlinks in url
for line in outlinks_file.readlines():
urls = line.split()
if (len(urls)) < 1:
continue
url = urls[0]
inlinks[url] = []
outlinks_fi... | outlinks_file = open('link_graph_ly.txt', 'r')
inlinks_file = open('link_graph_ly2.txt', 'w')
inlinks = {}
for line in outlinks_file.readlines():
urls = line.split()
if len(urls) < 1:
continue
url = urls[0]
inlinks[url] = []
outlinks_file.seek(0)
for line in outlinks_file.readlines():
urls =... |
def init(cfg):
data = {'_logLevel': 'WARN', '_moduleLogLevel': 'WARN'}
if cfg['_stage'] == 'dev':
data.update({
'_logLevel': 'DEBUG',
'_moduleLogLevel': 'WARN',
'_logFormat': '%(levelname)s: %(message)s'
})
return data
| def init(cfg):
data = {'_logLevel': 'WARN', '_moduleLogLevel': 'WARN'}
if cfg['_stage'] == 'dev':
data.update({'_logLevel': 'DEBUG', '_moduleLogLevel': 'WARN', '_logFormat': '%(levelname)s: %(message)s'})
return data |
"""Common configs for plots"""
class Base():
font = {
'family': 'Times New Roman',
'size': 16,
}
class Legend(Base):
font = {**Base.font, 'weight': 'bold'}
class Tick(Base):
font = {**Base.font, 'size': 12}
| """Common configs for plots"""
class Base:
font = {'family': 'Times New Roman', 'size': 16}
class Legend(Base):
font = {**Base.font, 'weight': 'bold'}
class Tick(Base):
font = {**Base.font, 'size': 12} |
"""read()"""
f = open("./test_file2", 'r', encoding = 'utf-8')
# read a file line-by-line using a for loop
for line in f:
print(line, end='')
# read individual lines of a file
f5 = f.readline()
f6 = f.readline()
f7 = f.readline()
print("f5\n", f5)
print("f6\n", f6)
print("f7\n", f7)
# list of remaining lines of... | """read()"""
f = open('./test_file2', 'r', encoding='utf-8')
for line in f:
print(line, end='')
f5 = f.readline()
f6 = f.readline()
f7 = f.readline()
print('f5\n', f5)
print('f6\n', f6)
print('f7\n', f7)
f8 = f.readlines()
print('f8\n', f8) |
user1_input = int(input("Please enter number 1 : Rock or 2 : Scissors or 3 : Papers."))
user2_input = int(input("Please enter number 1 : Rock or 2 : Scissors or 3 : Papers."))
if user1_input == 1:
user1_input = 'Rock'
elif user1_input == 2:
user1_input = 'Scissors'
else:
user1_input = 'Papers'
if user2_... | user1_input = int(input('Please enter number 1 : Rock or 2 : Scissors or 3 : Papers.'))
user2_input = int(input('Please enter number 1 : Rock or 2 : Scissors or 3 : Papers.'))
if user1_input == 1:
user1_input = 'Rock'
elif user1_input == 2:
user1_input = 'Scissors'
else:
user1_input = 'Papers'
if user2_inpu... |
class AdvancedBoxScore:
def __init__(self, seconds_played, offensive_rating, defensive_rating,
teammate_assist_percentage, assist_to_turnover_ratio, assists_per_100_possessions,
offensive_rebound_percentage, defensive_rebound_percentage, turnovers_per_100_possessions,
... | class Advancedboxscore:
def __init__(self, seconds_played, offensive_rating, defensive_rating, teammate_assist_percentage, assist_to_turnover_ratio, assists_per_100_possessions, offensive_rebound_percentage, defensive_rebound_percentage, turnovers_per_100_possessions, effective_field_goal_percentage, true_shooting... |
def solution(A):
# write your code in Python 3.6
disks = []
for i,v in enumerate(A):
disks.append((i-v,1))
disks.append((i+v,0))
disks.sort(key=lambda x: (x[0], not x[1]))
active = 0
intersections = 0
for i,isBegin in disks:
if isBegin:
intersections += ac... | def solution(A):
disks = []
for (i, v) in enumerate(A):
disks.append((i - v, 1))
disks.append((i + v, 0))
disks.sort(key=lambda x: (x[0], not x[1]))
active = 0
intersections = 0
for (i, is_begin) in disks:
if isBegin:
intersections += active
active... |
"""
Given an integer array, adjust each integers so that the difference of every adjcent integers are not greater than a
given number target.
If the array before adjustment is A, the array after adjustment is B, you should minimize the sum of |A[i]-B[i]|
Note
You can assume each number in the array is a positive inte... | """
Given an integer array, adjust each integers so that the difference of every adjcent integers are not greater than a
given number target.
If the array before adjustment is A, the array after adjustment is B, you should minimize the sum of |A[i]-B[i]|
Note
You can assume each number in the array is a positive inte... |
def repeatedString(s, n):
total = s.count("a") * int(n/len(s))
total += s[:n % len(s)].count("a")
return total
s = "aba"
n = 10
n = int(n)
repeatedString(s, n)
| def repeated_string(s, n):
total = s.count('a') * int(n / len(s))
total += s[:n % len(s)].count('a')
return total
s = 'aba'
n = 10
n = int(n)
repeated_string(s, n) |
# ======================================================================
# Beverage Bandits
# Advent of Code 2018 Day 15 -- Eric Wastl -- https://adventofcode.com
#
# Python implementation by Dr. Dean Earl Wright III
# ======================================================================
# =========================... | """People and persons for the Advent of Code 2018 Day 15 puzzle"""
row_mult = 100
adjacent = [-100, -1, 1, 100]
def row_col_to_loc(row, col):
return row * ROW_MULT + col
def loc_to_row_col(loc):
return divmod(loc, ROW_MULT)
def distance(loc1, loc2):
(loc1row, loc1col) = loc_to_row_col(loc1)
(loc2row,... |
"""
here we produce visualization with excel
# one-time excel preparation
in cmder
xlwings addin install
open excel
enable Trust access to VBA
File > Options > Trust Center > Trust Center Settings > Macro Settings
# making the visualization workbook
in cmder
chdir this_directory
xlwings quickstart boo... | """
here we produce visualization with excel
# one-time excel preparation
in cmder
xlwings addin install
open excel
enable Trust access to VBA
File > Options > Trust Center > Trust Center Settings > Macro Settings
# making the visualization workbook
in cmder
chdir this_directory
xlwings quickstart boo... |
def Singleton(cls):
_instance = {}
def _singleton(*args, **kwargs):
if cls not in _instance:
_instance[cls] = cls(*args, *kwargs)
return _instance[cls]
return _singleton
@Singleton
class A(object):
def __init__(self, x):
self.x = x
if __name__ == '__main__':
... | def singleton(cls):
_instance = {}
def _singleton(*args, **kwargs):
if cls not in _instance:
_instance[cls] = cls(*args, *kwargs)
return _instance[cls]
return _singleton
@Singleton
class A(object):
def __init__(self, x):
self.x = x
if __name__ == '__main__':
a ... |
"""501. Find Mode in Binary Search Tree"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def findMode(self, root):
"""
:t... | """501. Find Mode in Binary Search Tree"""
class Solution(object):
def find_mode(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
nums = []
if not root:
return None
self.dfs(root, nums)
d = {}
for num in nums:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.