content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
# Space complexity O(amount)
# Time complexity O(amount * the number of coins)
# Using Dynamic programinig with bottom-up strategy
# First, allocate the storage
dp = [amount + 1] * (amount + 1)
... | class Solution:
def coin_change(self, coins: List[int], amount: int) -> int:
dp = [amount + 1] * (amount + 1)
dp[0] = 0
for num in range(amount + 1):
for coin in coins:
if num - coin >= 0:
dp[num] = min(dp[num], dp[num - coin] + 1)
if ... |
lis = [1, 3, 15, 26, 30, 37, 45, 56, ]
divisibles = list(filter(lambda x: (x % 15 == 0), lis))
print(divisibles)
| lis = [1, 3, 15, 26, 30, 37, 45, 56]
divisibles = list(filter(lambda x: x % 15 == 0, lis))
print(divisibles) |
# 2. Number Definer
# Write a program that reads a floating-point number and prints "zero" if the number is zero.
# Otherwise, print "positive" or "negative". Add "small" if the absolute value of the number is less than 1,
# or "large" if it exceeds 1 000 000.
number = float(input())
if number == 0:
print('zero')... | number = float(input())
if number == 0:
print('zero')
if number > 0:
if number > 1000000:
print('large positive')
elif number < 1:
print('small positive')
else:
print('positive')
if number < 0:
if abs(number) > 1000000:
print('large negative')
elif abs(number) < 1... |
# -*- coding: utf-8 -*-
DATE = 'Data'
TEMPERATURE = 'Temperatura do Ar Media (degC)'
MAX_TEMP = 'Temperatura do Ar Maxima (degC)'
MIN_TEMP = 'Temperatura do Ar Minima (degC)'
VARIATION_TEMP = 'Variacao da Temperatura do Ar (degC)'
HUMIDITY = 'Umidade relativa Media (%)'
MAX_HUMIDITY = 'Umidade relativa Maxima (%)'
MIN_... | date = 'Data'
temperature = 'Temperatura do Ar Media (degC)'
max_temp = 'Temperatura do Ar Maxima (degC)'
min_temp = 'Temperatura do Ar Minima (degC)'
variation_temp = 'Variacao da Temperatura do Ar (degC)'
humidity = 'Umidade relativa Media (%)'
max_humidity = 'Umidade relativa Maxima (%)'
min_humidity = 'Umidade rela... |
def swap(A, i, j):
temp = A[i]
A[i] = A[j]
A[j] = temp
def selectionSort(A):
for i in range(len(A) - 1):
min = i
for j in range(i + 1, len(A)):
if A[j] < A[min]:
min = j
swap(A, min, i)
if __name__ == '__main__':
A = [3, 5, 8, 4, 1, ... | def swap(A, i, j):
temp = A[i]
A[i] = A[j]
A[j] = temp
def selection_sort(A):
for i in range(len(A) - 1):
min = i
for j in range(i + 1, len(A)):
if A[j] < A[min]:
min = j
swap(A, min, i)
if __name__ == '__main__':
a = [3, 5, 8, 4, 1, 9, -2]
se... |
# should_error
# skip-if: '-x' in EXTRA_JIT_ARGS
# Syntax error to have a continue outside a loop.
def foo():
try: continue
finally: pass
| def foo():
try:
continue
finally:
pass |
class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
n = len(words)
res = []
row = [words[0]]
length = len(words[0]) # length including necessary space
lenwd = len(words[0]) # length of words in this row
numwd = 1 # number of words in t... | class Solution:
def full_justify(self, words: List[str], maxWidth: int) -> List[str]:
n = len(words)
res = []
row = [words[0]]
length = len(words[0])
lenwd = len(words[0])
numwd = 1
def postprocess(row, lenwd, numwd):
res = ''
if numw... |
# Dungeon problem statement
# the dungeon has a size of R x C and you start at cell 'S' and there's an exit at cell 'E'.
# a cell full of rock is indicated by a '#' and empty cells are represented by a '.'
# ------------C-------------
# | S . . # . . . |
# | . # . . . # . |
# R . # . . . ... | m = [['S', '.', '.', '#', '.', '.', '.'], ['.', '#', '.', '.', '.', '#', '.'], ['.', '#', '.', '.', '.', '.', '.'], ['.', '.', '#', '#', '.', '.', '.'], ['#', '.', '#', 'E', '.', '#', '.']]
r = len(m)
c = len(m[0])
sr = 0
sc = 0
dr = [-1, +1, 0, 0]
dc = [0, 0, +1, -1]
rq = []
cq = []
visited = [[False for i in range(C)... |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self) -> None:
self.root = None
def push(self, value) -> None:
if self.root is None:
self.root = Node(value)
else:
root_node = self.root
... | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Stack:
def __init__(self) -> None:
self.root = None
def push(self, value) -> None:
if self.root is None:
self.root = node(value)
else:
root_node = self.root
... |
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
n = 0
if len(nums) == 0: return 0
for i in range(1,len(nums)):
if nums[n] < nums[i]:
n += 1
nums[n] = nums[i]
return n+1
| class Solution:
def remove_duplicates(self, nums: List[int]) -> int:
n = 0
if len(nums) == 0:
return 0
for i in range(1, len(nums)):
if nums[n] < nums[i]:
n += 1
nums[n] = nums[i]
return n + 1 |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( str ) :
n = len ( str ) - 1
i = n
while ( i > 0 and str [ i - 1 ] <= str [ i ] ) :
i -= 1
i... | def f_gold(str):
n = len(str) - 1
i = n
while i > 0 and str[i - 1] <= str[i]:
i -= 1
if i <= 0:
return False
j = i - 1
while j + 1 <= n and str[j + 1] <= str[i - 1]:
j += 1
str = list(str)
temp = str[i - 1]
str[i - 1] = str[j]
str[j] = temp
str = ''.jo... |
class CaseChangingStream():
def __init__(self, stream, upper):
self._stream = stream
self._upper = upper
def __getattr__(self, name):
return self._stream.__getattribute__(name)
def LA(self, offset):
c = self._stream.LA(offset)
if c <= 0:
return c
return ord(chr(c).upper() if self._upper else chr(c).... | class Casechangingstream:
def __init__(self, stream, upper):
self._stream = stream
self._upper = upper
def __getattr__(self, name):
return self._stream.__getattribute__(name)
def la(self, offset):
c = self._stream.LA(offset)
if c <= 0:
return c
... |
fp = open("1.in", "r")
drift = 0
for line in iter(fp.readline, ''):
drift += int(line)
print(drift)
def findDup():
drift = 0
seen = set([0])
for _ in range(1000):
fp = open("input1.txt", "r")
for line in iter(fp.readline, ''):
drift += int(line)
if drift in s... | fp = open('1.in', 'r')
drift = 0
for line in iter(fp.readline, ''):
drift += int(line)
print(drift)
def find_dup():
drift = 0
seen = set([0])
for _ in range(1000):
fp = open('input1.txt', 'r')
for line in iter(fp.readline, ''):
drift += int(line)
if drift in seen... |
l1=[]
##Input number of elements in list
n=int(input())
##Input the elements in the list
l1=list(map(int,input().split()))
## Create a new list l2 to store the index(from 1 to number of elements in list1) of elements of list 1
l2=[i for i in range(1,n+1)]
##Run a for loop from 1 till the length of list 1(l1)
for i in ... | l1 = []
n = int(input())
l1 = list(map(int, input().split()))
l2 = [i for i in range(1, n + 1)]
for i in range(1, n + 1):
x = l1.index(i)
y = l2[x]
print(l2[l1.index(y)]) |
# Original version was a simple for loop incrementing counts. Refactored to a generic function using list comprehension.
def main(filepath):
depths = [int(x) for x in open(filepath,'r').read().split('\n')]
increases = lambda x,y: len([d for i,d in enumerate(x[1:]) if len(x[i+1:]) >= y and sum(x[i+1:i+y+1])... | def main(filepath):
depths = [int(x) for x in open(filepath, 'r').read().split('\n')]
increases = lambda x, y: len([d for (i, d) in enumerate(x[1:]) if len(x[i + 1:]) >= y and sum(x[i + 1:i + y + 1]) > sum(x[i:i + y])])
return (increases(depths, 1), increases(depths, 3))
print(main('01.txt')) |
class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack, indicesToRemove, result = [], set(), []
for i, c in enumerate(s):
if c not in ['(', ')']:
continue
if c == '(':
stack.append(i)
elif not stack:
in... | class Solution:
def min_remove_to_make_valid(self, s: str) -> str:
(stack, indices_to_remove, result) = ([], set(), [])
for (i, c) in enumerate(s):
if c not in ['(', ')']:
continue
if c == '(':
stack.append(i)
elif not stack:
... |
MFCSAM = {'children': 3, 'cats': 7, 'samoyeds': 2, 'pomeranians': 3, 'akitas': 0,
'vizslas': 0, 'goldfish': 5, 'trees': 3, 'cars': 2, 'perfumes': 1}
GREATER = ('cats', 'trees')
FEWER = ('pomeranians', 'goldfish')
sues = []
for row in open('input').read().splitlines():
sue_properties = {}
for info in ... | mfcsam = {'children': 3, 'cats': 7, 'samoyeds': 2, 'pomeranians': 3, 'akitas': 0, 'vizslas': 0, 'goldfish': 5, 'trees': 3, 'cars': 2, 'perfumes': 1}
greater = ('cats', 'trees')
fewer = ('pomeranians', 'goldfish')
sues = []
for row in open('input').read().splitlines():
sue_properties = {}
for info in row.split('... |
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
dp = [ [0] * (len(word2)+1) for _ in range(len(word1)+1) ]
for k in range(1, len(word2)+1):
dp[0][k] = k
for k in range(1, len(word1)+1):
dp[k][0] = k
for p in range(1, len(word1)+1):
... | class Solution:
def min_distance(self, word1: str, word2: str) -> int:
dp = [[0] * (len(word2) + 1) for _ in range(len(word1) + 1)]
for k in range(1, len(word2) + 1):
dp[0][k] = k
for k in range(1, len(word1) + 1):
dp[k][0] = k
for p in range(1, len(word1) + ... |
class Runner:
def __init__(self, graph):
self.graph = graph
self.cache = {}
def findValues(self, inputs):
self.cache = {}
for inputIndex in range(len(inputs)):
self.cache[(inputIndex + 1, 0)] = inputs[inputIndex]
if not self.__calculateValues(self.graph.nod... | class Runner:
def __init__(self, graph):
self.graph = graph
self.cache = {}
def find_values(self, inputs):
self.cache = {}
for input_index in range(len(inputs)):
self.cache[inputIndex + 1, 0] = inputs[inputIndex]
if not self.__calculateValues(self.graph.node... |
# Copyright (c) Moshe Zadka
# See LICENSE for details.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.viewcode',
'sphinx.ext.napoleon',
]
master_doc = 'index'
project = 'Symplectic'
copyright = '2017, Moshe Zadka'
author = 'Moshe Zadka'
version = '17.10'
release = '17.10'
| extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.napoleon']
master_doc = 'index'
project = 'Symplectic'
copyright = '2017, Moshe Zadka'
author = 'Moshe Zadka'
version = '17.10'
release = '17.10' |
'''
Created on 20 Jul 2015
@author: njohn
'''
if __name__ == '__main__':
pass | """
Created on 20 Jul 2015
@author: njohn
"""
if __name__ == '__main__':
pass |
# coding:utf-8
class Error(Exception):
def __str__(self):
return self.message
class SessionExpiredError(Error):
def __init__(self, message="Session has expired."):
super(SessionExpiredError, self).__init__()
self.message = message
class SessionInvalidError(Error):
def __init__(... | class Error(Exception):
def __str__(self):
return self.message
class Sessionexpirederror(Error):
def __init__(self, message='Session has expired.'):
super(SessionExpiredError, self).__init__()
self.message = message
class Sessioninvaliderror(Error):
def __init__(self, message='S... |
# 1. Complete the function by filling in the missing parts. The color_translator
# function receives the name of a color, then prints its hexadecimal value.
# Currently, it only supports the three addictive primary colors (red, green,
# blue), so it returns "unknown" for all other colors.
def color_translator... | def color_translator(color):
if color == 'red':
hex_color = '#ff0000'
elif color == 'green':
hex_color = '#00ff00'
elif color == 'blue':
hex_color = '#0000ff'
else:
hex_color = 'unknown'
return hex_color
print(color_translator('blue'))
print(color_translator('yellow')... |
# Joshua Nelson Gomes (Joshua)
# CIS 41A Spring 2020
# Take-Home Assignment I
class Square:
def __init__(self, side):
self.side = side
def getArea(self):
return self.side * self.side
class Cube(Square):
def __init__(self, side):
Square.__init__(self, side)
def getVolume(self):
return self.side * self.si... | class Square:
def __init__(self, side):
self.side = side
def get_area(self):
return self.side * self.side
class Cube(Square):
def __init__(self, side):
Square.__init__(self, side)
def get_volume(self):
return self.side * self.side * self.side
def calc_total(price, t... |
# The subroutine inserts the vector passed as the secondargument into row j of the matrix.
# It also inserts this vector into column j of the matrix.
# Insertion involves copying the vector into the corresponding row and column.
# If the value of j is out of range, the subroutine returns -1 and does not perform any ins... | def exercise(matrix, vector, N, j):
if j < 0 or j > N:
raise exception('j should be greater than 0 and smaller than N')
i = 0
while i < len(matrix):
element = vector[i]
matrix[j][i] = element
matrix[i][j] = element
i += 1
for row in matrix:
print(row)
if _... |
class HooksIter:
def __init__(self, items=None):
self.hooks = {}
if items:
for item in items:
self.hooks[item] = item.hooks
def __iter__(self):
for hooks in self.hooks.values():
for event in hooks:
for hook in event:
... | class Hooksiter:
def __init__(self, items=None):
self.hooks = {}
if items:
for item in items:
self.hooks[item] = item.hooks
def __iter__(self):
for hooks in self.hooks.values():
for event in hooks:
for hook in event:
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2019, Micah Hunsberger (@mhunsber)
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r'''
---
module: win_file_compression
short_description: Alters the compression of files and directories on NTFS pa... | documentation = "\n---\nmodule: win_file_compression\nshort_description: Alters the compression of files and directories on NTFS partitions.\ndescription:\n - This module sets the compressed attribute for files and directories on a filesystem that supports it like NTFS.\n - NTFS compression can be used to save disk s... |
class PopulationIsNotEvaluatedException(RuntimeError):
pass
class StopEvolution(Exception):
pass
| class Populationisnotevaluatedexception(RuntimeError):
pass
class Stopevolution(Exception):
pass |
#121
# Time: O(n)
# Space: O(1)
# Say you have an array for which the ith element is
# the price of a given stock on day i.
# If you were only permitted to complete at most one transaction
# (ie, buy one and sell one share of the stock),
# design an algorithm to find the maximum profit.
#
# Example 1:
# Input: [... | class Arraysol:
def best_time_sell_buy_i(self, prices):
(min_price, max_profit) = (float('Inf'), 0)
for price in prices:
min_price = min(min_price, price)
max_profit = max(max_profit, price - min_price)
return max_profit |
def partition(nums, low, high):
pivot = nums[(low + high) // 2]
i = low - 1
j = high + 1
while True:
i += 1
while nums[i] < pivot:
i += 1
j -= 1
while nums[j] > pivot:
j -= 1
if i >= j:
return j
nums[i], nums[j] = nums... | def partition(nums, low, high):
pivot = nums[(low + high) // 2]
i = low - 1
j = high + 1
while True:
i += 1
while nums[i] < pivot:
i += 1
j -= 1
while nums[j] > pivot:
j -= 1
if i >= j:
return j
(nums[i], nums[j]) = (num... |
h, w = map(int, input().split())
ans = 0
if h == 1 or w == 1:
ans = 1
else:
if w % 2 == 0:
ans += (w//2)*h
else:
if h % 2 == 0:
ans += (h//2)*(w//2*2+1)
else:
ans += (h//2)*(w//2*2+1)+(w//2+1)
print(max(1, ans))
| (h, w) = map(int, input().split())
ans = 0
if h == 1 or w == 1:
ans = 1
elif w % 2 == 0:
ans += w // 2 * h
elif h % 2 == 0:
ans += h // 2 * (w // 2 * 2 + 1)
else:
ans += h // 2 * (w // 2 * 2 + 1) + (w // 2 + 1)
print(max(1, ans)) |
### test examples for the rast_client.py file
def test_somefunction():
pass
| def test_somefunction():
pass |
def main():
#with open(filename, (open for reading 'r', #writing 'w' or reading and writing 'rw'))
word = input("What's your word? Enter it here: ")
print("Scrabble score: " + (str)(scrabble_value(word)));
#everything past here the file is closed
# scrabble_value("potato")
#three options:
# 1) write a program ... | def main():
word = input("What's your word? Enter it here: ")
print('Scrabble score: ' + str(scrabble_value(word)))
def scrabble_value(word):
score = 0
scrabble_dict = {'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 1... |
ALL_DRIVERS = ['chromedriver', 'geckodriver']
DEFAULT_DRIVERS = ['chromedriver', 'geckodriver']
CHROMEDRIVER_STORAGE_URL = 'https://chromedriver.storage.googleapis.com'
CHROMEDRIVER_LATEST_FILE = 'https://chromedriver.storage.googleapis.com/LATEST_RELEASE'
GECKODRIVER_LASTEST_URL = 'https://api.github.com/repos/mozi... | all_drivers = ['chromedriver', 'geckodriver']
default_drivers = ['chromedriver', 'geckodriver']
chromedriver_storage_url = 'https://chromedriver.storage.googleapis.com'
chromedriver_latest_file = 'https://chromedriver.storage.googleapis.com/LATEST_RELEASE'
geckodriver_lastest_url = 'https://api.github.com/repos/mozilla... |
# Ordering
# Create a program that allows entry of 10 numbers and then sorts them into ascending or descending order, based on user input.
def main():
isNumber = input('Do you want to enter numbers or a string: [N/S] ').upper()
if isNumber == 'N':
nums = [int(input('Enter a number: ')) for _ in range(10)]
... | def main():
is_number = input('Do you want to enter numbers or a string: [N/S] ').upper()
if isNumber == 'N':
nums = [int(input('Enter a number: ')) for _ in range(10)]
order = input('Do you want to order in ascending or descending order [A/D]: ').upper()
if order == 'A':
num... |
# This problem was recently asked by Twitter:
# Implement a class for a stack that supports all the regular functions (push, pop) and
# an additional function of max() which returns the maximum element in the stack (return None if the stack is empty)
# Each method should run in constant time.
class MaxStack:
def ... | class Maxstack:
def __init__(self):
self.items = []
def push(self, val):
self.items.append(val)
def pop(self):
return self.items.pop()
def max(self):
max_n = 0
if len(self.items) == 0:
return None
for i in self.items:
if i >= ma... |
coins = {
"Khan's Concentrated Magic": 80000,
"Luminous Cobalt Ingot": 800,
"Bright Reef Piece": 140,
"Great Ocean Dark Iron": 160,
"Cobalt Ingot": 150,
"Brilliant Rock Salt Ingot": 1600,
"Seaweed Stalk": 600,
"Enhanced Island Tree Coated Plywood": 80,
"Pure Pearl Crystal": 550,
"Cox Pirates' Artifact (Parley... | coins = {"Khan's Concentrated Magic": 80000, 'Luminous Cobalt Ingot': 800, 'Bright Reef Piece': 140, 'Great Ocean Dark Iron': 160, 'Cobalt Ingot': 150, 'Brilliant Rock Salt Ingot': 1600, 'Seaweed Stalk': 600, 'Enhanced Island Tree Coated Plywood': 80, 'Pure Pearl Crystal': 550, "Cox Pirates' Artifact (Parley Beginner)"... |
class Command:
def execute(self):
raise NotImplementedError
| class Command:
def execute(self):
raise NotImplementedError |
# Use a Q to keep recent timestamps. Whenever ping is called, add t to Q and remove all the expired ones. Return len(Q)
class RecentCounter:
def __init__(self):
self.Q = []
def ping(self, t: int) -> int:
self.Q.append(t)
while self.Q[0]<t-3000:
self.Q.pop(0)
... | class Recentcounter:
def __init__(self):
self.Q = []
def ping(self, t: int) -> int:
self.Q.append(t)
while self.Q[0] < t - 3000:
self.Q.pop(0)
return len(self.Q) |
class Html_Maker:
@classmethod
def read_text_file(cls, path: str):
ret = ''
with open(path, 'r') as f:
while True:
line = f.readline()
if not line:
break
line = line.replace(
'\t', '<span style="... | class Html_Maker:
@classmethod
def read_text_file(cls, path: str):
ret = ''
with open(path, 'r') as f:
while True:
line = f.readline()
if not line:
break
line = line.replace('\t', '<span style="white-space:pre">\t</... |
a = list(range(10))
print(a)
b = list("Pablo Fajardo")
print(b)
empty = []
print(empty)
nine = [0,1,2,3,4,5,6,7,8,9]
print(nine)
mixed = ['a',1,'b',2,'c',3,"Pablo",empty,True]
print(mixed)
#Add a single item to a list
mixed.append("Fajardo")
print(mixed)
#Add item with index
mixed.insert(2,"PALABRA")
print(mixed... | a = list(range(10))
print(a)
b = list('Pablo Fajardo')
print(b)
empty = []
print(empty)
nine = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(nine)
mixed = ['a', 1, 'b', 2, 'c', 3, 'Pablo', empty, True]
print(mixed)
mixed.append('Fajardo')
print(mixed)
mixed.insert(2, 'PALABRA')
print(mixed)
pies = ['cherry', 'cream', 'apple']
p... |
# This is a useful data structure for implementing
# a counter that counts the time.
class DFSTimeCounter:
def __init__(self):
self.count = 0
def reset(self):
self.count = 0
def increment(self):
self.count = self.count + 1
def get(self):
return self.count
class Undir... | class Dfstimecounter:
def __init__(self):
self.count = 0
def reset(self):
self.count = 0
def increment(self):
self.count = self.count + 1
def get(self):
return self.count
class Undirectedgraph:
def __init__(self, n):
self.n = n
self.adj_list = [s... |
class Obj(object):
def __init__(self, filename):
with open(filename) as f:
self.lines = f.read().splitlines()
self.vertices = []
self.vfaces = []
self.read()
def read(self):
for line in self.lines:
if line:
prefix, value = line.spl... | class Obj(object):
def __init__(self, filename):
with open(filename) as f:
self.lines = f.read().splitlines()
self.vertices = []
self.vfaces = []
self.read()
def read(self):
for line in self.lines:
if line:
(prefix, value) = line.... |
# Consider a row of n coins of values v1 . . . vn, where n is even.
# We play a game against an opponent by alternating turns. In each turn,
# a player selects either the first or last coin from the row, removes it
# from the row permanently, and receives the value of the coin. Determine the
# maximum possible amount o... | def find_max_val_recur(coins, l, r):
if l + 1 == r:
return max(coins[l], coins[r])
if l == r:
return coins[i]
left_choose = coins[l] + min(find_max_val_recur(coins, l + 1, r - 1), find_max_val_recur(coins, l + 2, r))
right_choose = coins[r] + min(find_max_val_recur(coins, l + 1, r - 1), ... |
'''
Example: Given an array of distinct integer values, count the number of pairs of integers that
have difference k. For example, given the array { 1, 7, 5, 9, 2, 12, 3 } and the difference
k = 2,there are four pairs with difference2: (1, 3), (3, 5), (5, 7), (7, 9).
'''
def pairs_of_difference(array, diff):
hash... | """
Example: Given an array of distinct integer values, count the number of pairs of integers that
have difference k. For example, given the array { 1, 7, 5, 9, 2, 12, 3 } and the difference
k = 2,there are four pairs with difference2: (1, 3), (3, 5), (5, 7), (7, 9).
"""
def pairs_of_difference(array, diff):
hash... |
numbers_count = int(input())
sum_number = 0
for counter in range(numbers_count):
current_number = int(input())
sum_number += current_number
print(sum_number)
| numbers_count = int(input())
sum_number = 0
for counter in range(numbers_count):
current_number = int(input())
sum_number += current_number
print(sum_number) |
# coding=utf-8
def test_common_stats_insert(session):
raise NotImplementedError
def test_duplicate_common_stats_error(session):
raise NotImplementedError
def test_common_stats_default_values(session):
raise NotImplementedError
def test_common_stats_negative_value_error(session):
raise NotImpleme... | def test_common_stats_insert(session):
raise NotImplementedError
def test_duplicate_common_stats_error(session):
raise NotImplementedError
def test_common_stats_default_values(session):
raise NotImplementedError
def test_common_stats_negative_value_error(session):
raise NotImplementedError
def test_... |
#common utilities for all module
def trap_exc_during_debug(*args):
# when app raises uncaught exception, print info
print(args) | def trap_exc_during_debug(*args):
print(args) |
# Copyright 2011 Nicholas Bray
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... | def do_nothing(node):
pass
class Cfgdfs(object):
def __init__(self, pre=doNothing, post=doNothing):
self.pre = pre
self.post = post
self.processed = set()
def process(self, node):
if node not in self.processed:
self.processed.add(node)
self.pre(node... |
def summation(number):
total = 0
for num in range(number + 1):
total += num
return total
if __name__ == "__main__":
print(summation(1000)) | def summation(number):
total = 0
for num in range(number + 1):
total += num
return total
if __name__ == '__main__':
print(summation(1000)) |
a = int(input('Informe um numero:'))
if a%2 == 0 :
print("Par!")
else:
print('Impar!') | a = int(input('Informe um numero:'))
if a % 2 == 0:
print('Par!')
else:
print('Impar!') |
class Piece:
def __init__(self, board, square, white):
self.square = square
self.row = square[0]
self.col = square[1]
self.is_clicked = False #dk if i need this
self._white = white
self.pinned = False
#self.letter
def move(self):
pass
def che... | class Piece:
def __init__(self, board, square, white):
self.square = square
self.row = square[0]
self.col = square[1]
self.is_clicked = False
self._white = white
self.pinned = False
def move(self):
pass
def check_move(self):
if self.is_click... |
print('please input the starting annual salary(annual_salary):')
annual_salary=float(input())
print('please input The portion of salary to be saved (portion_saved):')
portion_saved=float(input())
print("The cost of your dream home (total_cost):")
total_cost=float(input())
portion_down_payment=0.25
current_savings=0
nu... | print('please input the starting annual salary(annual_salary):')
annual_salary = float(input())
print('please input The portion of salary to be saved (portion_saved):')
portion_saved = float(input())
print('The cost of your dream home (total_cost):')
total_cost = float(input())
portion_down_payment = 0.25
current_savin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
mylist = [ "a", 2, 4.5 ]
myotherlist = mylist[ : ]
mylist[1] = "hello"
print(myotherlist)
mytext = "Hello world"
myothertext = mytext
mytext = "Hallo Welt!"
#print(myothertext)
print(mylist[ : ])
| mylist = ['a', 2, 4.5]
myotherlist = mylist[:]
mylist[1] = 'hello'
print(myotherlist)
mytext = 'Hello world'
myothertext = mytext
mytext = 'Hallo Welt!'
print(mylist[:]) |
'''
Pig Latin: Rules
if word starts with a vowel, add 'ay' to end
if word does not start with a vowel, put first letter at the end, then add 'ay'
word -> ordway
apple -> appleay
'''
def pig_latin(word):
initial_letter = word[0]
if initial_letter in 'aeiou':
translated_word = word + 'ay'
else:
translated_word... | """
Pig Latin: Rules
if word starts with a vowel, add 'ay' to end
if word does not start with a vowel, put first letter at the end, then add 'ay'
word -> ordway
apple -> appleay
"""
def pig_latin(word):
initial_letter = word[0]
if initial_letter in 'aeiou':
translated_word = word + 'ay'
else:
... |
class Break:
def __init__(self, dbRow):
self.flinch = dbRow[0]
self.wound = dbRow[1]
self.sever = dbRow[2]
self.extract = dbRow[3]
self.name = dbRow[4]
def __repr__(self):
return f"{self.__dict__!r}" | class Break:
def __init__(self, dbRow):
self.flinch = dbRow[0]
self.wound = dbRow[1]
self.sever = dbRow[2]
self.extract = dbRow[3]
self.name = dbRow[4]
def __repr__(self):
return f'{self.__dict__!r}' |
# -*- coding: utf-8 -*-
empty_dict = dict()
print(empty_dict)
d = {}
print(type(d))
#zbiory definuje sie set
e = set()
print(type(e))
# klucze nie moga sie w slowniku powtarzac
#w slowniku uporzadkowanie nie jest istotne, i nie jest uporzadkowane
pol_to_eng = {'jeden':'one', 'dwa':'two', 'trzy': 'th... | empty_dict = dict()
print(empty_dict)
d = {}
print(type(d))
e = set()
print(type(e))
pol_to_eng = {'jeden': 'one', 'dwa': 'two', 'trzy': 'three'}
name_to_digit = {'Jeden': 1, 'dwa': 2, 'trzy': 3}
len(name_to_digit)
pol_to_eng['cztery'] = 'four'
pol_to_eng.clear()
pol_to_eng_copied = pol_to_eng.copy()
pol_to_eng.keys()
... |
class WordDictionary:
def __init__(self, cache=True):
self.cache = cache
def train(self, data):
raise NotImplemented()
def predict(self, data):
raise NotImplemented()
def save(self, model_path):
raise NotImplemented()
def read(self, model_path):
raise NotI... | class Worddictionary:
def __init__(self, cache=True):
self.cache = cache
def train(self, data):
raise not_implemented()
def predict(self, data):
raise not_implemented()
def save(self, model_path):
raise not_implemented()
def read(self, model_path):
raise ... |
'''
Exercise 2: Odd Or Even
Ask the user for a number. Depending on whether the number is even or odd,
print out an appropriate message to the user. Hint: how does an even / odd
number react differently when divided by 2?
Extras:
If the number is a multiple of 4, print out a different message.
Ask the user for two nu... | """
Exercise 2: Odd Or Even
Ask the user for a number. Depending on whether the number is even or odd,
print out an appropriate message to the user. Hint: how does an even / odd
number react differently when divided by 2?
Extras:
If the number is a multiple of 4, print out a different message.
Ask the user for two nu... |
#!/usr/bin/env python
# Copyright (c) 2019 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: BSD-2 License
# The full license information can be found in LICENSE.txt
# in the root directory of this project.
SERVER_CONSTANTS = (
REQUEST_QUEUE_SIZE, PACKET_SIZE, ALLOW_REUSE_ADDRESS
) = (
100, 1024, Tr... | server_constants = (request_queue_size, packet_size, allow_reuse_address) = (100, 1024, True) |
class Stack:
def __init__(self, stack=[], lim=None):
self._stack = stack
self._lim = lim
def push(self, data):
if self._lim is not None and len(self._stack) == self._lim:
print("~~STACK OVERFLOW~~")
return
self._stack.append(int(data))
def pop(self):... | class Stack:
def __init__(self, stack=[], lim=None):
self._stack = stack
self._lim = lim
def push(self, data):
if self._lim is not None and len(self._stack) == self._lim:
print('~~STACK OVERFLOW~~')
return
self._stack.append(int(data))
def pop(self)... |
### Code is based on PySimpleAutomata (https://github.com/Oneiroe/PySimpleAutomata/)
# MIT License
# Copyright (c) 2017 Alessio Cecconi
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software with... | def _epsilon_closure(states, epsilon, transitions):
new_states = states
while new_states:
curr_states = set()
for state in new_states:
curr_states.update(transitions.get(state, {}).get(epsilon, set()))
new_states = curr_states - states
states.update(curr_states)
def ... |
def ab(b):
c=input("Term To Be Search:")
if c in b:
print ("Term Found")
else:
print ("Term Not Found")
a=[]
while True:
b=input("Enter Term(To terminate type Exit):")
if b=='Exit' or b=='exit':
break
else:
a.append(b)
ab(a)
| def ab(b):
c = input('Term To Be Search:')
if c in b:
print('Term Found')
else:
print('Term Not Found')
a = []
while True:
b = input('Enter Term(To terminate type Exit):')
if b == 'Exit' or b == 'exit':
break
else:
a.append(b)
ab(a) |
n = int(input())
def weird(n):
string = str(n)
while n != 1:
if n%2 == 0:
n = n//2
string += ' ' + str(n)
else:
n = n*3 + 1
string += ' ' + str(n)
return string
print(weird(n)) | n = int(input())
def weird(n):
string = str(n)
while n != 1:
if n % 2 == 0:
n = n // 2
string += ' ' + str(n)
else:
n = n * 3 + 1
string += ' ' + str(n)
return string
print(weird(n)) |
PRICES = [0.01, 0.02, 0.05, 0.10, 0.20, 0.50, 1, 2]
QUESTIONS = [
"Voer het aantal 1 centen in:\n",
"Voer het aantal 2 centen in: \n",
"Voer het aantal 5 centen in: \n",
"Voer het aantal 10 centen in: \n",
"Voer het aantal 20 centen in: \n"... | prices = [0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2]
questions = ['Voer het aantal 1 centen in:\n', 'Voer het aantal 2 centen in: \n', 'Voer het aantal 5 centen in: \n', 'Voer het aantal 10 centen in: \n', 'Voer het aantal 20 centen in: \n', 'Voer het aantal 50 centen in: \n', "Voer het aantal 1 euro's in: \n", "Voer het a... |
spec = {
'name' : "The devil's work...",
'external network name' : "exnet3",
'keypair' : "openstack_rsa",
'controller' : "r720",
'dns' : "10.30.65.200",
'credentials' : { 'user' : "nic", 'password' : "nic", 'project' : "nic" },
'Networks' : [
{ 'name' : "merlynctl" , "start": "172.1... | spec = {'name': "The devil's work...", 'external network name': 'exnet3', 'keypair': 'openstack_rsa', 'controller': 'r720', 'dns': '10.30.65.200', 'credentials': {'user': 'nic', 'password': 'nic', 'project': 'nic'}, 'Networks': [{'name': 'merlynctl', 'start': '172.16.1.2', 'end': '172.16.1.100', 'subnet': ' 172.16.1.0/... |
# coding: utf-8
# fields names
BITMAP = 'bitmap'
COLS = 'cols'
DATA = 'data'
EXTERIOR = 'exterior'
INTERIOR = 'interior'
MULTICHANNEL_BITMAP = 'multichannel_bitmap'
ORIGIN = 'origin'
POINTS = 'points'
ROWS = 'rows'
TYPE = 'type'
NODES = 'nodes'
EDGES = 'edges'
ENABLED = 'enabled'
LABEL = 'label'
COLOR = 'color'
TEMPL... | bitmap = 'bitmap'
cols = 'cols'
data = 'data'
exterior = 'exterior'
interior = 'interior'
multichannel_bitmap = 'multichannel_bitmap'
origin = 'origin'
points = 'points'
rows = 'rows'
type = 'type'
nodes = 'nodes'
edges = 'edges'
enabled = 'enabled'
label = 'label'
color = 'color'
template = 'template'
location = 'loca... |
# Data taken from the MathML 2.0 reference
data = '''
"(" form="prefix" fence="true" stretchy="true" lspace="0em" rspace="0em"
")" form="postfix" fence="true" stretchy="true" lspace="0em" rspace="0em"
"[" form="prefix... | data = '\n\n"(" form="prefix" fence="true" stretchy="true" lspace="0em" rspace="0em"\n")" form="postfix" fence="true" stretchy="true" lspace="0em" rspace="0em"\n"[" form="prefix" fence="true" stretchy="true" lspace="... |
# -*- coding: utf-8 -*-
# User role
USER = 0
ADMIN = 1
USER_ROLE = {
ADMIN: 'admin',
USER: 'user',
}
# User status
INACTIVE = 0
ACTIVE = 1
USER_STATUS = {
INACTIVE: 'inactive',
ACTIVE: 'active',
}
# Project progress
PR_CHALLENGE = -1
PR_NEW = 0
PR_RESEARCHED = 10
PR_SKETCHED = 20
PR_PROTOTYPED = 30
P... | user = 0
admin = 1
user_role = {ADMIN: 'admin', USER: 'user'}
inactive = 0
active = 1
user_status = {INACTIVE: 'inactive', ACTIVE: 'active'}
pr_challenge = -1
pr_new = 0
pr_researched = 10
pr_sketched = 20
pr_prototyped = 30
pr_launched = 40
pr_live = 50
project_progress = {PR_CHALLENGE: 'This is an idea or challenge d... |
q = int(input())
e = str(input()).split()
indq = 0
mini = int(e[0])
for i in range(1, len(e)):
if int(e[i]) > mini:
mini = int(e[i])
elif int(e[i]) < mini:
indq = i + 1
break
print(indq)
| q = int(input())
e = str(input()).split()
indq = 0
mini = int(e[0])
for i in range(1, len(e)):
if int(e[i]) > mini:
mini = int(e[i])
elif int(e[i]) < mini:
indq = i + 1
break
print(indq) |
__version__ = "1.8.0"
__all__ = ["epsonprinter","testpage"]
| __version__ = '1.8.0'
__all__ = ['epsonprinter', 'testpage'] |
class RequestExeption(Exception):
def __init__(self, request):
self.request = request
def badRequest(self):
self.message = "bad request url : %s" % self.request.url
return self
def __str__(self):
return self.message
| class Requestexeption(Exception):
def __init__(self, request):
self.request = request
def bad_request(self):
self.message = 'bad request url : %s' % self.request.url
return self
def __str__(self):
return self.message |
class Solution:
def dieSimulator(self, n: int, rollMax: List[int]) -> int:
# dp[i][j]: how many choices we have with i dices and the last face is j
# again dp[i][j] means the number of distinct sequences that can be obtained when rolling i times and ending with j
MOD = 10 ** 9 + 7
dp... | class Solution:
def die_simulator(self, n: int, rollMax: List[int]) -> int:
mod = 10 ** 9 + 7
dp = [[0] * 7 for i in range(n + 1)]
for i in range(6):
dp[1][i] = 1
dp[1][6] = 6
for i in range(2, n + 1):
total = 0
for j in range(6):
... |
n1 = int(input('Digite um valor: '))
n2 = int(input('Digite um valor: '))
n3 = int(input('Digite um valor: '))
menor = n1
maior = n2
if n2 < n1 and n2 < 3:
menor = n2
if n3 < n1 and n3 < n2:
menor = n3
if n1 > n2 and n1 > n3:
maior = n1
if n3 > n1 and n3 > n2:
maior = n3
print(f'O maior valor digitado f... | n1 = int(input('Digite um valor: '))
n2 = int(input('Digite um valor: '))
n3 = int(input('Digite um valor: '))
menor = n1
maior = n2
if n2 < n1 and n2 < 3:
menor = n2
if n3 < n1 and n3 < n2:
menor = n3
if n1 > n2 and n1 > n3:
maior = n1
if n3 > n1 and n3 > n2:
maior = n3
print(f'O maior valor digitado f... |
# a = ['a1','aa1','a2','aaa1']
# a.sort()
# print(a)
# print(2346/10)
def repeat_to_length(string_to_expand, length):
return (string_to_expand * (int(length/len(string_to_expand))+1))[:length]
for i in range(200):
if i > 10:
strnum = str(i)
tens = int(strnum[0:-1])
last = strnum[-1]
... | def repeat_to_length(string_to_expand, length):
return (string_to_expand * (int(length / len(string_to_expand)) + 1))[:length]
for i in range(200):
if i > 10:
strnum = str(i)
tens = int(strnum[0:-1])
last = strnum[-1]
print(strnum)
print(tens)
print(repeat_to_leng... |
'''
Given a binary string s (a string consisting only of '0's and '1's), we can split s into 3 non-empty strings s1, s2, s3 (s1+ s2+ s3 = s).
Return the number of ways s can be split such that the number of characters '1' is the same in s1, s2, and s3.
Since the answer may be too large, return it modulo 10^9 + 7.
... | """
Given a binary string s (a string consisting only of '0's and '1's), we can split s into 3 non-empty strings s1, s2, s3 (s1+ s2+ s3 = s).
Return the number of ways s can be split such that the number of characters '1' is the same in s1, s2, and s3.
Since the answer may be too large, return it modulo 10^9 + 7.
... |
arr = [2,3,5,8,1,8,0,9,11, 23, 51]
num = 0
def searchElement(arr, num):
n = len(arr)
for i in range(n):
if arr[i] == num:
print("From if block")
return i
elif arr[n-1] == num:
print("From else if block")
return n-1
n-=1
print(searchElement... | arr = [2, 3, 5, 8, 1, 8, 0, 9, 11, 23, 51]
num = 0
def search_element(arr, num):
n = len(arr)
for i in range(n):
if arr[i] == num:
print('From if block')
return i
elif arr[n - 1] == num:
print('From else if block')
return n - 1
n -= 1
prin... |
class MidiProtocol:
NON_REAL_TIME_HEADER = 0x7E
GENERAL_SYSTEM_INFORMATION = 0x06
DEVICE_IDENTITY_REQUEST = 0x01
@staticmethod
def device_identify_request(target=0x00):
TARGET_ID = target
SUB_ID_1 = MidiProtocol.GENERAL_SYSTEM_INFORMATION
SUB_ID_2 = MidiProtocol.DEVICE_IDE... | class Midiprotocol:
non_real_time_header = 126
general_system_information = 6
device_identity_request = 1
@staticmethod
def device_identify_request(target=0):
target_id = target
sub_id_1 = MidiProtocol.GENERAL_SYSTEM_INFORMATION
sub_id_2 = MidiProtocol.DEVICE_IDENTITY_REQUES... |
def get_chunks(start, value):
for each in range(start, 2000000001, value):
yield range(each, each+value)
def sum_xor_n(value):
mod_value = value&3
if mod_value == 3:
return 0
elif mod_value == 2:
return value+1
elif mod_value == 1:
return 1
elif mod_value == 0:
... | def get_chunks(start, value):
for each in range(start, 2000000001, value):
yield range(each, each + value)
def sum_xor_n(value):
mod_value = value & 3
if mod_value == 3:
return 0
elif mod_value == 2:
return value + 1
elif mod_value == 1:
return 1
elif mod_value =... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
VER_MAIN = '3'
VER_SUB = '5'
BUILD_SN = '160809'
| ver_main = '3'
ver_sub = '5'
build_sn = '160809' |
#4-9 Cube Comprehension
numberscube = [value ** 3 for value in range(1, 11)]
print(numberscube) | numberscube = [value ** 3 for value in range(1, 11)]
print(numberscube) |
#coding:utf-8
while True:
l_c = input().split()
x1 = int(l_c[0])
y1 = int(l_c[1])
x2 = int(l_c[2])
y2 = int(l_c[3])
if x1+x2+y1+y2 == 0:
break
else:
if (x1 == x2 and y1 == y2):
print(0)
elif ((x2-x1) == -(y2-y1) or -(x2-x1) == -(y2-y1)): ... | while True:
l_c = input().split()
x1 = int(l_c[0])
y1 = int(l_c[1])
x2 = int(l_c[2])
y2 = int(l_c[3])
if x1 + x2 + y1 + y2 == 0:
break
elif x1 == x2 and y1 == y2:
print(0)
elif x2 - x1 == -(y2 - y1) or -(x2 - x1) == -(y2 - y1):
print(1)
elif -(x2 - x1) == y2 -... |
# Definition for a binary tree node.
# class Node(object):
# def __init__(self, val=" ", left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def expTree(self, s: str) -> 'Node':
def process_op():
op = op_stack.pop()
... | class Solution:
def exp_tree(self, s: str) -> 'Node':
def process_op():
op = op_stack.pop()
rhs = val_stack.pop()
lhs = val_stack.pop()
node = node(val=op, left=lhs, right=rhs)
val_stack.append(node)
def priority(op):
if op i... |
# Practice problem 1 for chapter 4
# Function that takes an array and returns a comma-separated string
def make_string(array):
answer_string = ""
for i in array:
if array.index(i) == 0:
answer_string += str(i)
# Last index word finishes with "and" before it
elif array.index(... | def make_string(array):
answer_string = ''
for i in array:
if array.index(i) == 0:
answer_string += str(i)
elif array.index(i) == len(array) - 1:
answer_string += ', and ' + str(i)
else:
answer_string += ', ' + str(i)
print(answer_string)
my_arr = ... |
class RCListener:
def __iter__(self): raise NotImplementedError()
class Source:
def listener(self, *args, **kwargs):
raise NotImplementedError()
def query(self, start, end, *args, types=None, **kwargs):
raise NotImplementedError()
| class Rclistener:
def __iter__(self):
raise not_implemented_error()
class Source:
def listener(self, *args, **kwargs):
raise not_implemented_error()
def query(self, start, end, *args, types=None, **kwargs):
raise not_implemented_error() |
for _ in range(int(input())):
n,q = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
for _ in range(q):
k = int(input())
sum = 0
# if(k == 0):k = 1
for i in range(0,n,k + 1):
sum += a[i]
print(sum) | for _ in range(int(input())):
(n, q) = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
for _ in range(q):
k = int(input())
sum = 0
for i in range(0, n, k + 1):
sum += a[i]
print(sum) |
def front_back(s):
if len(s) > 1:
string = [s[-1]]
string.extend([i for i in s[1:-1]])
string.append(s[0])
return "".join(string)
else:
return s | def front_back(s):
if len(s) > 1:
string = [s[-1]]
string.extend([i for i in s[1:-1]])
string.append(s[0])
return ''.join(string)
else:
return s |
# twitter api data (replace yours here given are placeholder)
# if you have not yet, go for applying at: https://developer.twitter.com/
TWITTER_KEY=""
TWITTER_SECRET=""
TWITTER_APP_KEY=""
TWITTER_APP_SECRET=""
with open("twitter_keys.txt") as f:
for line in f:
tups=line.strip().split("=")
if tups[0] == "TWITTER_... | twitter_key = ''
twitter_secret = ''
twitter_app_key = ''
twitter_app_secret = ''
with open('twitter_keys.txt') as f:
for line in f:
tups = line.strip().split('=')
if tups[0] == 'TWITTER_KEY':
twitter_key = tups[1]
elif tups[0] == 'TWITTER_SECRET':
twitter_secret = tu... |
def maximum_subarray_1(coll):
n = len(coll)
max_result = 0
for i in xrange(1, n+1):
for j in range(n-i+1):
result = sum(coll[j: j+i])
if max_result < result:
max_result = result
return max_result
def maximum_subarray_2(coll):
n = len(coll)
max_... | def maximum_subarray_1(coll):
n = len(coll)
max_result = 0
for i in xrange(1, n + 1):
for j in range(n - i + 1):
result = sum(coll[j:j + i])
if max_result < result:
max_result = result
return max_result
def maximum_subarray_2(coll):
n = len(coll)
... |
lines = []
for i in xrange(3):
line = Line()
line.xValues = xrange(5)
line.yValues = [(i+1 / 2.0) * pow(x, i+1)
for x in line.xValues]
line.label = "Line %d" % (i + 1)
lines.append(line)
plot = Plot()
plot.add(lines[0])
inset = Plot()
inset.add(lines[1])
inset.hideTickLabels(... | lines = []
for i in xrange(3):
line = line()
line.xValues = xrange(5)
line.yValues = [(i + 1 / 2.0) * pow(x, i + 1) for x in line.xValues]
line.label = 'Line %d' % (i + 1)
lines.append(line)
plot = plot()
plot.add(lines[0])
inset = plot()
inset.add(lines[1])
inset.hideTickLabels()
inset.title = 'Ins... |
file = open('csv_data.txt', 'r')
lines = file.readlines()
file.close()
lines = [line.strip() for line in lines[1:]]
for line in lines:
person_data = line.split(',')
name = person_data[0].title()
age = person_data[1]
university = person_data[2].title()
degree = person_data[3].capitalize()
prin... | file = open('csv_data.txt', 'r')
lines = file.readlines()
file.close()
lines = [line.strip() for line in lines[1:]]
for line in lines:
person_data = line.split(',')
name = person_data[0].title()
age = person_data[1]
university = person_data[2].title()
degree = person_data[3].capitalize()
print(f... |
def media(n1, n2):
m = (n1 + n2)/2
return m
print(media(n1=10, n2=5))
def juros(preco, juros):
res = preco * (1 + juros/100)
return res
print(juros(preco=10, juros=50))
| def media(n1, n2):
m = (n1 + n2) / 2
return m
print(media(n1=10, n2=5))
def juros(preco, juros):
res = preco * (1 + juros / 100)
return res
print(juros(preco=10, juros=50)) |
def test_session_interruption(ui, ui_interrupted_session):
ui_interrupted_session.click()
interrupted_test = ui.driver.find_element_by_css_selector('.item.test')
css_classes = interrupted_test.get_attribute('class')
assert 'success' not in css_classes
assert 'fail' not in css_classes
interrupted... | def test_session_interruption(ui, ui_interrupted_session):
ui_interrupted_session.click()
interrupted_test = ui.driver.find_element_by_css_selector('.item.test')
css_classes = interrupted_test.get_attribute('class')
assert 'success' not in css_classes
assert 'fail' not in css_classes
interrupted... |
# 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 sortedArrayToBST(self, nums):
return self.recurse(nums,0,len(nums)-1)
def recurse(self,nums,start,en... | class Treenode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def sorted_array_to_bst(self, nums):
return self.recurse(nums, 0, len(nums) - 1)
def recurse(self, nums, start, end):
if end < star... |
Vivaldi = Goalkeeper('Juan Vivaldi', 83, 77, 72, 82)
Peillat = Outfield_Player('Gonzalo Peillat', 'DF', 70, 89, 78, 73, 79, 67)
Ortiz = Outfield_Player('Ignacio Ortiz', 'MF', 79, 78, 77, 80, 75, 81)
Rey = Outfield_Player('Matias Rey', 'MF', 81, 77, 74, 72, 87, 72)
Vila = Outfield_Player('Lucas Vila', 'FW', 87, 50, ... | vivaldi = goalkeeper('Juan Vivaldi', 83, 77, 72, 82)
peillat = outfield__player('Gonzalo Peillat', 'DF', 70, 89, 78, 73, 79, 67)
ortiz = outfield__player('Ignacio Ortiz', 'MF', 79, 78, 77, 80, 75, 81)
rey = outfield__player('Matias Rey', 'MF', 81, 77, 74, 72, 87, 72)
vila = outfield__player('Lucas Vila', 'FW', 87, 50, ... |
def factorial(x):
'''calculo de factorial
con una funcion recursiva'''
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 928
print('el factorial de: ', num ,'is ', factorial(num))
| def factorial(x):
"""calculo de factorial
con una funcion recursiva"""
if x == 1:
return 1
else:
return x * factorial(x - 1)
num = 928
print('el factorial de: ', num, 'is ', factorial(num)) |
# prompting user to enter the file name
fname = input('Enter file name: ')
d = dict()
# catching exceptions
try:
fhand = open(fname)
except:
print('File does not exist')
exit()
# reading the lines in the file
for line in fhand:
words = line.split()
# we only want email addresses
if ... | fname = input('Enter file name: ')
d = dict()
try:
fhand = open(fname)
except:
print('File does not exist')
exit()
for line in fhand:
words = line.split()
if len(words) < 2 or words[0] != 'From':
continue
else:
d[words[1]] = d.get(words[1], 0) + 1
print(d) |
# Copyright 2014 Google Inc.
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'skia_warnings_as_errors': 0,
},
'targets': [
{
'target_name': 'libpng',
'type': 'none',
'conditions': [
[ 'skia_android_framewor... | {'variables': {'skia_warnings_as_errors': 0}, 'targets': [{'target_name': 'libpng', 'type': 'none', 'conditions': [['skia_android_framework', {'dependencies': ['android_deps.gyp:png'], 'export_dependent_settings': ['android_deps.gyp:png']}, {'dependencies': ['libpng.gyp:libpng_static'], 'export_dependent_settings': ['l... |
_base_ = "./common_base.py"
# -----------------------------------------------------------------------------
# base model cfg for gdrn
# -----------------------------------------------------------------------------
MODEL = dict(
DEVICE="cuda",
WEIGHTS="",
# PIXEL_MEAN = [103.530, 116.280, 123.675] # bgr
... | _base_ = './common_base.py'
model = dict(DEVICE='cuda', WEIGHTS='', PIXEL_MEAN=[0, 0, 0], PIXEL_STD=[255.0, 255.0, 255.0], LOAD_DETS_TEST=False, CDPN=dict(NAME='GDRN', TASK='rot', USE_MTL=False, BACKBONE=dict(PRETRAINED='torchvision://resnet34', ARCH='resnet', NUM_LAYERS=34, INPUT_CHANNEL=3, INPUT_RES=256, OUTPUT_RES=6... |
#This app does your math
addition = input("Print your math sign, +, -, *, /: ")
if addition == "+":
a = int(input("First Number: "))
b = int(input("Seccond Number: "))
c = a + b
print(c)
elif addition == "-":
a = int(input("First Number: "))
b = int(input("Seccond Number: "))
c = a - b
... | addition = input('Print your math sign, +, -, *, /: ')
if addition == '+':
a = int(input('First Number: '))
b = int(input('Seccond Number: '))
c = a + b
print(c)
elif addition == '-':
a = int(input('First Number: '))
b = int(input('Seccond Number: '))
c = a - b
print(c)
elif addition == ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.